blob: e43b0b6fa63583de91fc4cbbefab050ceb4003cc [file] [log] [blame]
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001/*
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 static android.system.OsConstants.AF_INET;
20import static android.system.OsConstants.AF_INET6;
21
22import android.annotation.NonNull;
23import android.annotation.Nullable;
24import android.annotation.RequiresPermission;
25import android.annotation.SystemApi;
26import android.app.Activity;
27import android.app.PendingIntent;
28import android.app.Service;
29import android.app.admin.DevicePolicyManager;
30import android.compat.annotation.UnsupportedAppUsage;
31import android.content.ComponentName;
32import android.content.Context;
33import android.content.Intent;
34import android.content.pm.IPackageManager;
35import android.content.pm.PackageManager;
36import android.os.Binder;
37import android.os.IBinder;
38import android.os.Parcel;
39import android.os.ParcelFileDescriptor;
40import android.os.RemoteException;
41import android.os.ServiceManager;
42import android.os.UserHandle;
43
44import com.android.internal.net.VpnConfig;
45
46import java.net.DatagramSocket;
47import java.net.Inet4Address;
48import java.net.Inet6Address;
49import java.net.InetAddress;
50import java.net.Socket;
51import java.util.ArrayList;
52import java.util.List;
53import java.util.Set;
54
55/**
56 * VpnService is a base class for applications to extend and build their
57 * own VPN solutions. In general, it creates a virtual network interface,
58 * configures addresses and routing rules, and returns a file descriptor
59 * to the application. Each read from the descriptor retrieves an outgoing
60 * packet which was routed to the interface. Each write to the descriptor
61 * injects an incoming packet just like it was received from the interface.
62 * The interface is running on Internet Protocol (IP), so packets are
63 * always started with IP headers. The application then completes a VPN
64 * connection by processing and exchanging packets with the remote server
65 * over a tunnel.
66 *
67 * <p>Letting applications intercept packets raises huge security concerns.
68 * A VPN application can easily break the network. Besides, two of them may
69 * conflict with each other. The system takes several actions to address
70 * these issues. Here are some key points:
71 * <ul>
72 * <li>User action is required the first time an application creates a VPN
73 * connection.</li>
74 * <li>There can be only one VPN connection running at the same time. The
75 * existing interface is deactivated when a new one is created.</li>
76 * <li>A system-managed notification is shown during the lifetime of a
77 * VPN connection.</li>
78 * <li>A system-managed dialog gives the information of the current VPN
79 * connection. It also provides a button to disconnect.</li>
80 * <li>The network is restored automatically when the file descriptor is
81 * closed. It also covers the cases when a VPN application is crashed
82 * or killed by the system.</li>
83 * </ul>
84 *
85 * <p>There are two primary methods in this class: {@link #prepare} and
86 * {@link Builder#establish}. The former deals with user action and stops
87 * the VPN connection created by another application. The latter creates
88 * a VPN interface using the parameters supplied to the {@link Builder}.
89 * An application must call {@link #prepare} to grant the right to use
90 * other methods in this class, and the right can be revoked at any time.
91 * Here are the general steps to create a VPN connection:
92 * <ol>
93 * <li>When the user presses the button to connect, call {@link #prepare}
94 * and launch the returned intent, if non-null.</li>
95 * <li>When the application becomes prepared, start the service.</li>
96 * <li>Create a tunnel to the remote server and negotiate the network
97 * parameters for the VPN connection.</li>
98 * <li>Supply those parameters to a {@link Builder} and create a VPN
99 * interface by calling {@link Builder#establish}.</li>
100 * <li>Process and exchange packets between the tunnel and the returned
101 * file descriptor.</li>
102 * <li>When {@link #onRevoke} is invoked, close the file descriptor and
103 * shut down the tunnel gracefully.</li>
104 * </ol>
105 *
106 * <p>Services extending this class need to be declared with an appropriate
107 * permission and intent filter. Their access must be secured by
108 * {@link android.Manifest.permission#BIND_VPN_SERVICE} permission, and
109 * their intent filter must match {@link #SERVICE_INTERFACE} action. Here
110 * is an example of declaring a VPN service in {@code AndroidManifest.xml}:
111 * <pre>
112 * &lt;service android:name=".ExampleVpnService"
113 * android:permission="android.permission.BIND_VPN_SERVICE"&gt;
114 * &lt;intent-filter&gt;
115 * &lt;action android:name="android.net.VpnService"/&gt;
116 * &lt;/intent-filter&gt;
117 * &lt;/service&gt;</pre>
118 *
119 * <p> The Android system starts a VPN in the background by calling
120 * {@link android.content.Context#startService startService()}. In Android 8.0
121 * (API level 26) and higher, the system places VPN apps on the temporary
122 * allowlist for a short period so the app can start in the background. The VPN
123 * app must promote itself to the foreground after it's launched or the system
124 * will shut down the app.
125 *
126 * <h3>Developer's guide</h3>
127 *
128 * <p>To learn more about developing VPN apps, read the
129 * <a href="{@docRoot}guide/topics/connectivity/vpn">VPN developer's guide</a>.
130 *
131 * @see Builder
132 */
133public class VpnService extends Service {
134
135 /**
136 * The action must be matched by the intent filter of this service. It also
137 * needs to require {@link android.Manifest.permission#BIND_VPN_SERVICE}
138 * permission so that other applications cannot abuse it.
139 */
140 public static final String SERVICE_INTERFACE = VpnConfig.SERVICE_INTERFACE;
141
142 /**
143 * Key for boolean meta-data field indicating whether this VpnService supports always-on mode.
144 *
145 * <p>For a VPN app targeting {@link android.os.Build.VERSION_CODES#N API 24} or above, Android
146 * provides users with the ability to set it as always-on, so that VPN connection is
147 * persisted after device reboot and app upgrade. Always-on VPN can also be enabled by device
148 * owner and profile owner apps through
149 * {@link DevicePolicyManager#setAlwaysOnVpnPackage}.
150 *
151 * <p>VPN apps not supporting this feature should opt out by adding this meta-data field to the
152 * {@code VpnService} component of {@code AndroidManifest.xml}. In case there is more than one
153 * {@code VpnService} component defined in {@code AndroidManifest.xml}, opting out any one of
154 * them will opt out the entire app. For example,
155 * <pre> {@code
156 * <service android:name=".ExampleVpnService"
157 * android:permission="android.permission.BIND_VPN_SERVICE">
158 * <intent-filter>
159 * <action android:name="android.net.VpnService"/>
160 * </intent-filter>
161 * <meta-data android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
162 * android:value=false/>
163 * </service>
164 * } </pre>
165 *
166 * <p>This meta-data field defaults to {@code true} if absent. It will only have effect on
167 * {@link android.os.Build.VERSION_CODES#O_MR1} or higher.
168 */
169 public static final String SERVICE_META_DATA_SUPPORTS_ALWAYS_ON =
170 "android.net.VpnService.SUPPORTS_ALWAYS_ON";
171
172 /**
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900173 * Use IVpnManager since those methods are hidden and not available in VpnManager.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900174 */
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900175 private static IVpnManager getService() {
176 return IVpnManager.Stub.asInterface(
177 ServiceManager.getService(Context.VPN_MANAGEMENT_SERVICE));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900178 }
179
180 /**
181 * Prepare to establish a VPN connection. This method returns {@code null}
182 * if the VPN application is already prepared or if the user has previously
183 * consented to the VPN application. Otherwise, it returns an
184 * {@link Intent} to a system activity. The application should launch the
185 * activity using {@link Activity#startActivityForResult} to get itself
186 * prepared. The activity may pop up a dialog to require user action, and
187 * the result will come back via its {@link Activity#onActivityResult}.
188 * If the result is {@link Activity#RESULT_OK}, the application becomes
189 * prepared and is granted to use other methods in this class.
190 *
191 * <p>Only one application can be granted at the same time. The right
192 * is revoked when another application is granted. The application
193 * losing the right will be notified via its {@link #onRevoke}. Unless
194 * it becomes prepared again, subsequent calls to other methods in this
195 * class will fail.
196 *
197 * <p>The user may disable the VPN at any time while it is activated, in
198 * which case this method will return an intent the next time it is
199 * executed to obtain the user's consent again.
200 *
201 * @see #onRevoke
202 */
203 public static Intent prepare(Context context) {
204 try {
205 if (getService().prepareVpn(context.getPackageName(), null, context.getUserId())) {
206 return null;
207 }
208 } catch (RemoteException e) {
209 // ignore
210 }
211 return VpnConfig.getIntentForConfirmation();
212 }
213
214 /**
215 * Version of {@link #prepare(Context)} which does not require user consent.
216 *
217 * <p>Requires {@link android.Manifest.permission#CONTROL_VPN} and should generally not be
218 * used. Only acceptable in situations where user consent has been obtained through other means.
219 *
220 * <p>Once this is run, future preparations may be done with the standard prepare method as this
221 * will authorize the package to prepare the VPN without consent in the future.
222 *
223 * @hide
224 */
225 @SystemApi
226 @RequiresPermission(android.Manifest.permission.CONTROL_VPN)
227 public static void prepareAndAuthorize(Context context) {
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900228 IVpnManager vm = getService();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900229 String packageName = context.getPackageName();
230 try {
231 // Only prepare if we're not already prepared.
232 int userId = context.getUserId();
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900233 if (!vm.prepareVpn(packageName, null, userId)) {
234 vm.prepareVpn(null, packageName, userId);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900235 }
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900236 vm.setVpnPackageAuthorization(packageName, userId, VpnManager.TYPE_VPN_SERVICE);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900237 } catch (RemoteException e) {
238 // ignore
239 }
240 }
241
242 /**
243 * Protect a socket from VPN connections. After protecting, data sent
244 * through this socket will go directly to the underlying network,
245 * so its traffic will not be forwarded through the VPN.
246 * This method is useful if some connections need to be kept
247 * outside of VPN. For example, a VPN tunnel should protect itself if its
248 * destination is covered by VPN routes. Otherwise its outgoing packets
249 * will be sent back to the VPN interface and cause an infinite loop. This
250 * method will fail if the application is not prepared or is revoked.
251 *
252 * <p class="note">The socket is NOT closed by this method.
253 *
254 * @return {@code true} on success.
255 */
256 public boolean protect(int socket) {
257 return NetworkUtils.protectFromVpn(socket);
258 }
259
260 /**
261 * Convenience method to protect a {@link Socket} from VPN connections.
262 *
263 * @return {@code true} on success.
264 * @see #protect(int)
265 */
266 public boolean protect(Socket socket) {
267 return protect(socket.getFileDescriptor$().getInt$());
268 }
269
270 /**
271 * Convenience method to protect a {@link DatagramSocket} from VPN
272 * connections.
273 *
274 * @return {@code true} on success.
275 * @see #protect(int)
276 */
277 public boolean protect(DatagramSocket socket) {
278 return protect(socket.getFileDescriptor$().getInt$());
279 }
280
281 /**
282 * Adds a network address to the VPN interface.
283 *
284 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
285 * address is already in use or cannot be assigned to the interface for any other reason.
286 *
287 * Adding an address implicitly allows traffic from that address family (i.e., IPv4 or IPv6) to
288 * be routed over the VPN. @see Builder#allowFamily
289 *
290 * @throws IllegalArgumentException if the address is invalid.
291 *
292 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
293 * @param prefixLength The prefix length of the address.
294 *
295 * @return {@code true} on success.
296 * @see Builder#addAddress
297 *
298 * @hide
299 */
300 public boolean addAddress(InetAddress address, int prefixLength) {
301 check(address, prefixLength);
302 try {
303 return getService().addVpnAddress(address.getHostAddress(), prefixLength);
304 } catch (RemoteException e) {
305 throw new IllegalStateException(e);
306 }
307 }
308
309 /**
310 * Removes a network address from the VPN interface.
311 *
312 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
313 * address is not assigned to the VPN interface, or if it is the only address assigned (thus
314 * cannot be removed), or if the address cannot be removed for any other reason.
315 *
316 * After removing an address, if there are no addresses, routes or DNS servers of a particular
317 * address family (i.e., IPv4 or IPv6) configured on the VPN, that <b>DOES NOT</b> block that
318 * family from being routed. In other words, once an address family has been allowed, it stays
319 * allowed for the rest of the VPN's session. @see Builder#allowFamily
320 *
321 * @throws IllegalArgumentException if the address is invalid.
322 *
323 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
324 * @param prefixLength The prefix length of the address.
325 *
326 * @return {@code true} on success.
327 *
328 * @hide
329 */
330 public boolean removeAddress(InetAddress address, int prefixLength) {
331 check(address, prefixLength);
332 try {
333 return getService().removeVpnAddress(address.getHostAddress(), prefixLength);
334 } catch (RemoteException e) {
335 throw new IllegalStateException(e);
336 }
337 }
338
339 /**
340 * Sets the underlying networks used by the VPN for its upstream connections.
341 *
342 * <p>Used by the system to know the actual networks that carry traffic for apps affected by
343 * this VPN in order to present this information to the user (e.g., via status bar icons).
344 *
345 * <p>This method only needs to be called if the VPN has explicitly bound its underlying
346 * communications channels &mdash; such as the socket(s) passed to {@link #protect(int)} &mdash;
347 * to a {@code Network} using APIs such as {@link Network#bindSocket(Socket)} or
348 * {@link Network#bindSocket(DatagramSocket)}. The VPN should call this method every time
349 * the set of {@code Network}s it is using changes.
350 *
351 * <p>{@code networks} is one of the following:
352 * <ul>
353 * <li><strong>a non-empty array</strong>: an array of one or more {@link Network}s, in
354 * decreasing preference order. For example, if this VPN uses both wifi and mobile (cellular)
355 * networks to carry app traffic, but prefers or uses wifi more than mobile, wifi should appear
356 * first in the array.</li>
357 * <li><strong>an empty array</strong>: a zero-element array, meaning that the VPN has no
358 * underlying network connection, and thus, app traffic will not be sent or received.</li>
359 * <li><strong>null</strong>: (default) signifies that the VPN uses whatever is the system's
360 * default network. I.e., it doesn't use the {@code bindSocket} or {@code bindDatagramSocket}
361 * APIs mentioned above to send traffic over specific channels.</li>
362 * </ul>
363 *
364 * <p>This call will succeed only if the VPN is currently established. For setting this value
365 * when the VPN has not yet been established, see {@link Builder#setUnderlyingNetworks}.
366 *
367 * @param networks An array of networks the VPN uses to tunnel traffic to/from its servers.
368 *
369 * @return {@code true} on success.
370 */
371 public boolean setUnderlyingNetworks(Network[] networks) {
372 try {
373 return getService().setUnderlyingNetworksForVpn(networks);
374 } catch (RemoteException e) {
375 throw new IllegalStateException(e);
376 }
377 }
378
379 /**
380 * Returns whether the service is running in always-on VPN mode. In this mode the system ensures
381 * that the service is always running by restarting it when necessary, e.g. after reboot.
382 *
383 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
384 */
385 public final boolean isAlwaysOn() {
386 try {
387 return getService().isCallerCurrentAlwaysOnVpnApp();
388 } catch (RemoteException e) {
389 throw e.rethrowFromSystemServer();
390 }
391 }
392
393 /**
394 * Returns whether the service is running in always-on VPN lockdown mode. In this mode the
395 * system ensures that the service is always running and that the apps aren't allowed to bypass
396 * the VPN.
397 *
398 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
399 */
400 public final boolean isLockdownEnabled() {
401 try {
402 return getService().isCallerCurrentAlwaysOnVpnLockdownApp();
403 } catch (RemoteException e) {
404 throw e.rethrowFromSystemServer();
405 }
406 }
407
408 /**
409 * Return the communication interface to the service. This method returns
410 * {@code null} on {@link Intent}s other than {@link #SERVICE_INTERFACE}
411 * action. Applications overriding this method must identify the intent
412 * and return the corresponding interface accordingly.
413 *
414 * @see Service#onBind
415 */
416 @Override
417 public IBinder onBind(Intent intent) {
418 if (intent != null && SERVICE_INTERFACE.equals(intent.getAction())) {
419 return new Callback();
420 }
421 return null;
422 }
423
424 /**
425 * Invoked when the application is revoked. At this moment, the VPN
426 * interface is already deactivated by the system. The application should
427 * close the file descriptor and shut down gracefully. The default
428 * implementation of this method is calling {@link Service#stopSelf()}.
429 *
430 * <p class="note">Calls to this method may not happen on the main thread
431 * of the process.
432 *
433 * @see #prepare
434 */
435 public void onRevoke() {
436 stopSelf();
437 }
438
439 /**
440 * Use raw Binder instead of AIDL since now there is only one usage.
441 */
442 private class Callback extends Binder {
443 @Override
444 protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
445 if (code == IBinder.LAST_CALL_TRANSACTION) {
446 onRevoke();
447 return true;
448 }
449 return false;
450 }
451 }
452
453 /**
454 * Private method to validate address and prefixLength.
455 */
456 private static void check(InetAddress address, int prefixLength) {
457 if (address.isLoopbackAddress()) {
458 throw new IllegalArgumentException("Bad address");
459 }
460 if (address instanceof Inet4Address) {
461 if (prefixLength < 0 || prefixLength > 32) {
462 throw new IllegalArgumentException("Bad prefixLength");
463 }
464 } else if (address instanceof Inet6Address) {
465 if (prefixLength < 0 || prefixLength > 128) {
466 throw new IllegalArgumentException("Bad prefixLength");
467 }
468 } else {
469 throw new IllegalArgumentException("Unsupported family");
470 }
471 }
472
473 /**
474 * Helper class to create a VPN interface. This class should be always
475 * used within the scope of the outer {@link VpnService}.
476 *
477 * @see VpnService
478 */
479 public class Builder {
480
481 private final VpnConfig mConfig = new VpnConfig();
482 @UnsupportedAppUsage
483 private final List<LinkAddress> mAddresses = new ArrayList<LinkAddress>();
484 @UnsupportedAppUsage
485 private final List<RouteInfo> mRoutes = new ArrayList<RouteInfo>();
486
487 public Builder() {
488 mConfig.user = VpnService.this.getClass().getName();
489 }
490
491 /**
492 * Set the name of this session. It will be displayed in
493 * system-managed dialogs and notifications. This is recommended
494 * not required.
495 */
496 @NonNull
497 public Builder setSession(@NonNull String session) {
498 mConfig.session = session;
499 return this;
500 }
501
502 /**
503 * Set the {@link PendingIntent} to an activity for users to
504 * configure the VPN connection. If it is not set, the button
505 * to configure will not be shown in system-managed dialogs.
506 */
507 @NonNull
508 public Builder setConfigureIntent(@NonNull PendingIntent intent) {
509 mConfig.configureIntent = intent;
510 return this;
511 }
512
513 /**
514 * Set the maximum transmission unit (MTU) of the VPN interface. If
515 * it is not set, the default value in the operating system will be
516 * used.
517 *
518 * @throws IllegalArgumentException if the value is not positive.
519 */
520 @NonNull
521 public Builder setMtu(int mtu) {
522 if (mtu <= 0) {
523 throw new IllegalArgumentException("Bad mtu");
524 }
525 mConfig.mtu = mtu;
526 return this;
527 }
528
529 /**
530 * Sets an HTTP proxy for the VPN network. This proxy is only a recommendation
531 * and it is possible that some apps will ignore it.
532 */
533 @NonNull
534 public Builder setHttpProxy(@NonNull ProxyInfo proxyInfo) {
535 mConfig.proxyInfo = proxyInfo;
536 return this;
537 }
538
539 /**
540 * Add a network address to the VPN interface. Both IPv4 and IPv6
541 * addresses are supported. At least one address must be set before
542 * calling {@link #establish}.
543 *
544 * Adding an address implicitly allows traffic from that address family
545 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
546 *
547 * @throws IllegalArgumentException if the address is invalid.
548 */
549 @NonNull
550 public Builder addAddress(@NonNull InetAddress address, int prefixLength) {
551 check(address, prefixLength);
552
553 if (address.isAnyLocalAddress()) {
554 throw new IllegalArgumentException("Bad address");
555 }
556 mAddresses.add(new LinkAddress(address, prefixLength));
557 mConfig.updateAllowedFamilies(address);
558 return this;
559 }
560
561 /**
562 * Convenience method to add a network address to the VPN interface
563 * using a numeric address string. See {@link InetAddress} for the
564 * definitions of numeric address formats.
565 *
566 * Adding an address implicitly allows traffic from that address family
567 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
568 *
569 * @throws IllegalArgumentException if the address is invalid.
570 * @see #addAddress(InetAddress, int)
571 */
572 @NonNull
573 public Builder addAddress(@NonNull String address, int prefixLength) {
574 return addAddress(InetAddress.parseNumericAddress(address), prefixLength);
575 }
576
577 /**
578 * Add a network route to the VPN interface. Both IPv4 and IPv6
579 * routes are supported.
580 *
581 * Adding a route implicitly allows traffic from that address family
582 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
583 *
584 * @throws IllegalArgumentException if the route is invalid.
585 */
586 @NonNull
587 public Builder addRoute(@NonNull InetAddress address, int prefixLength) {
588 check(address, prefixLength);
589
590 int offset = prefixLength / 8;
591 byte[] bytes = address.getAddress();
592 if (offset < bytes.length) {
593 for (bytes[offset] <<= prefixLength % 8; offset < bytes.length; ++offset) {
594 if (bytes[offset] != 0) {
595 throw new IllegalArgumentException("Bad address");
596 }
597 }
598 }
599 mRoutes.add(new RouteInfo(new IpPrefix(address, prefixLength), null));
600 mConfig.updateAllowedFamilies(address);
601 return this;
602 }
603
604 /**
605 * Convenience method to add a network route to the VPN interface
606 * using a numeric address string. See {@link InetAddress} for the
607 * definitions of numeric address formats.
608 *
609 * Adding a route implicitly allows traffic from that address family
610 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
611 *
612 * @throws IllegalArgumentException if the route is invalid.
613 * @see #addRoute(InetAddress, int)
614 */
615 @NonNull
616 public Builder addRoute(@NonNull String address, int prefixLength) {
617 return addRoute(InetAddress.parseNumericAddress(address), prefixLength);
618 }
619
620 /**
621 * Add a DNS server to the VPN connection. Both IPv4 and IPv6
622 * addresses are supported. If none is set, the DNS servers of
623 * the default network will be used.
624 *
625 * Adding a server implicitly allows traffic from that address family
626 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
627 *
628 * @throws IllegalArgumentException if the address is invalid.
629 */
630 @NonNull
631 public Builder addDnsServer(@NonNull InetAddress address) {
632 if (address.isLoopbackAddress() || address.isAnyLocalAddress()) {
633 throw new IllegalArgumentException("Bad address");
634 }
635 if (mConfig.dnsServers == null) {
636 mConfig.dnsServers = new ArrayList<String>();
637 }
638 mConfig.dnsServers.add(address.getHostAddress());
639 return this;
640 }
641
642 /**
643 * Convenience method to add a DNS server to the VPN connection
644 * using a numeric address string. See {@link InetAddress} for the
645 * definitions of numeric address formats.
646 *
647 * Adding a server implicitly allows traffic from that address family
648 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
649 *
650 * @throws IllegalArgumentException if the address is invalid.
651 * @see #addDnsServer(InetAddress)
652 */
653 @NonNull
654 public Builder addDnsServer(@NonNull String address) {
655 return addDnsServer(InetAddress.parseNumericAddress(address));
656 }
657
658 /**
659 * Add a search domain to the DNS resolver.
660 */
661 @NonNull
662 public Builder addSearchDomain(@NonNull String domain) {
663 if (mConfig.searchDomains == null) {
664 mConfig.searchDomains = new ArrayList<String>();
665 }
666 mConfig.searchDomains.add(domain);
667 return this;
668 }
669
670 /**
671 * Allows traffic from the specified address family.
672 *
673 * By default, if no address, route or DNS server of a specific family (IPv4 or IPv6) is
674 * added to this VPN, then all outgoing traffic of that family is blocked. If any address,
675 * route or DNS server is added, that family is allowed.
676 *
677 * This method allows an address family to be unblocked even without adding an address,
678 * route or DNS server of that family. Traffic of that family will then typically
679 * fall-through to the underlying network if it's supported.
680 *
681 * {@code family} must be either {@code AF_INET} (for IPv4) or {@code AF_INET6} (for IPv6).
682 * {@link IllegalArgumentException} is thrown if it's neither.
683 *
684 * @param family The address family ({@code AF_INET} or {@code AF_INET6}) to allow.
685 *
686 * @return this {@link Builder} object to facilitate chaining of method calls.
687 */
688 @NonNull
689 public Builder allowFamily(int family) {
690 if (family == AF_INET) {
691 mConfig.allowIPv4 = true;
692 } else if (family == AF_INET6) {
693 mConfig.allowIPv6 = true;
694 } else {
695 throw new IllegalArgumentException(family + " is neither " + AF_INET + " nor " +
696 AF_INET6);
697 }
698 return this;
699 }
700
701 private void verifyApp(String packageName) throws PackageManager.NameNotFoundException {
702 IPackageManager pm = IPackageManager.Stub.asInterface(
703 ServiceManager.getService("package"));
704 try {
705 pm.getApplicationInfo(packageName, 0, UserHandle.getCallingUserId());
706 } catch (RemoteException e) {
707 throw new IllegalStateException(e);
708 }
709 }
710
711 /**
712 * Adds an application that's allowed to access the VPN connection.
713 *
714 * If this method is called at least once, only applications added through this method (and
715 * no others) are allowed access. Else (if this method is never called), all applications
716 * are allowed by default. If some applications are added, other, un-added applications
717 * will use networking as if the VPN wasn't running.
718 *
719 * A {@link Builder} may have only a set of allowed applications OR a set of disallowed
720 * ones, but not both. Calling this method after {@link #addDisallowedApplication} has
721 * already been called, or vice versa, will throw an {@link UnsupportedOperationException}.
722 *
723 * {@code packageName} must be the canonical name of a currently installed application.
724 * {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
725 *
726 * @throws PackageManager.NameNotFoundException If the application isn't installed.
727 *
728 * @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
729 *
730 * @return this {@link Builder} object to facilitate chaining method calls.
731 */
732 @NonNull
733 public Builder addAllowedApplication(@NonNull String packageName)
734 throws PackageManager.NameNotFoundException {
735 if (mConfig.disallowedApplications != null) {
736 throw new UnsupportedOperationException("addDisallowedApplication already called");
737 }
738 verifyApp(packageName);
739 if (mConfig.allowedApplications == null) {
740 mConfig.allowedApplications = new ArrayList<String>();
741 }
742 mConfig.allowedApplications.add(packageName);
743 return this;
744 }
745
746 /**
747 * Adds an application that's denied access to the VPN connection.
748 *
749 * By default, all applications are allowed access, except for those denied through this
750 * method. Denied applications will use networking as if the VPN wasn't running.
751 *
752 * A {@link Builder} may have only a set of allowed applications OR a set of disallowed
753 * ones, but not both. Calling this method after {@link #addAllowedApplication} has already
754 * been called, or vice versa, will throw an {@link UnsupportedOperationException}.
755 *
756 * {@code packageName} must be the canonical name of a currently installed application.
757 * {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
758 *
759 * @throws PackageManager.NameNotFoundException If the application isn't installed.
760 *
761 * @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
762 *
763 * @return this {@link Builder} object to facilitate chaining method calls.
764 */
765 @NonNull
766 public Builder addDisallowedApplication(@NonNull String packageName)
767 throws PackageManager.NameNotFoundException {
768 if (mConfig.allowedApplications != null) {
769 throw new UnsupportedOperationException("addAllowedApplication already called");
770 }
771 verifyApp(packageName);
772 if (mConfig.disallowedApplications == null) {
773 mConfig.disallowedApplications = new ArrayList<String>();
774 }
775 mConfig.disallowedApplications.add(packageName);
776 return this;
777 }
778
779 /**
780 * Allows all apps to bypass this VPN connection.
781 *
782 * By default, all traffic from apps is forwarded through the VPN interface and it is not
783 * possible for apps to side-step the VPN. If this method is called, apps may use methods
784 * such as {@link ConnectivityManager#bindProcessToNetwork} to instead send/receive
785 * directly over the underlying network or any other network they have permissions for.
786 *
787 * @return this {@link Builder} object to facilitate chaining of method calls.
788 */
789 @NonNull
790 public Builder allowBypass() {
791 mConfig.allowBypass = true;
792 return this;
793 }
794
795 /**
796 * Sets the VPN interface's file descriptor to be in blocking/non-blocking mode.
797 *
798 * By default, the file descriptor returned by {@link #establish} is non-blocking.
799 *
800 * @param blocking True to put the descriptor into blocking mode; false for non-blocking.
801 *
802 * @return this {@link Builder} object to facilitate chaining method calls.
803 */
804 @NonNull
805 public Builder setBlocking(boolean blocking) {
806 mConfig.blocking = blocking;
807 return this;
808 }
809
810 /**
811 * Sets the underlying networks used by the VPN for its upstream connections.
812 *
813 * @see VpnService#setUnderlyingNetworks
814 *
815 * @param networks An array of networks the VPN uses to tunnel traffic to/from its servers.
816 *
817 * @return this {@link Builder} object to facilitate chaining method calls.
818 */
819 @NonNull
820 public Builder setUnderlyingNetworks(@Nullable Network[] networks) {
821 mConfig.underlyingNetworks = networks != null ? networks.clone() : null;
822 return this;
823 }
824
825 /**
826 * Marks the VPN network as metered. A VPN network is classified as metered when the user is
827 * sensitive to heavy data usage due to monetary costs and/or data limitations. In such
828 * cases, you should set this to {@code true} so that apps on the system can avoid doing
829 * large data transfers. Otherwise, set this to {@code false}. Doing so would cause VPN
830 * network to inherit its meteredness from its underlying networks.
831 *
832 * <p>VPN apps targeting {@link android.os.Build.VERSION_CODES#Q} or above will be
833 * considered metered by default.
834 *
835 * @param isMetered {@code true} if VPN network should be treated as metered regardless of
836 * underlying network meteredness
837 * @return this {@link Builder} object to facilitate chaining method calls
838 * @see #setUnderlyingNetworks(Network[])
839 * @see ConnectivityManager#isActiveNetworkMetered()
840 */
841 @NonNull
842 public Builder setMetered(boolean isMetered) {
843 mConfig.isMetered = isMetered;
844 return this;
845 }
846
847 /**
848 * Create a VPN interface using the parameters supplied to this
849 * builder. The interface works on IP packets, and a file descriptor
850 * is returned for the application to access them. Each read
851 * retrieves an outgoing packet which was routed to the interface.
852 * Each write injects an incoming packet just like it was received
853 * from the interface. The file descriptor is put into non-blocking
854 * mode by default to avoid blocking Java threads. To use the file
855 * descriptor completely in native space, see
856 * {@link ParcelFileDescriptor#detachFd()}. The application MUST
857 * close the file descriptor when the VPN connection is terminated.
858 * The VPN interface will be removed and the network will be
859 * restored by the system automatically.
860 *
861 * <p>To avoid conflicts, there can be only one active VPN interface
862 * at the same time. Usually network parameters are never changed
863 * during the lifetime of a VPN connection. It is also common for an
864 * application to create a new file descriptor after closing the
865 * previous one. However, it is rare but not impossible to have two
866 * interfaces while performing a seamless handover. In this case, the
867 * old interface will be deactivated when the new one is created
868 * successfully. Both file descriptors are valid but now outgoing
869 * packets will be routed to the new interface. Therefore, after
870 * draining the old file descriptor, the application MUST close it
871 * and start using the new file descriptor. If the new interface
872 * cannot be created, the existing interface and its file descriptor
873 * remain untouched.
874 *
875 * <p>An exception will be thrown if the interface cannot be created
876 * for any reason. However, this method returns {@code null} if the
877 * application is not prepared or is revoked. This helps solve
878 * possible race conditions between other VPN applications.
879 *
880 * @return {@link ParcelFileDescriptor} of the VPN interface, or
881 * {@code null} if the application is not prepared.
882 * @throws IllegalArgumentException if a parameter is not accepted
883 * by the operating system.
884 * @throws IllegalStateException if a parameter cannot be applied
885 * by the operating system.
886 * @throws SecurityException if the service is not properly declared
887 * in {@code AndroidManifest.xml}.
888 * @see VpnService
889 */
890 @Nullable
891 public ParcelFileDescriptor establish() {
892 mConfig.addresses = mAddresses;
893 mConfig.routes = mRoutes;
894
895 try {
896 return getService().establishVpn(mConfig);
897 } catch (RemoteException e) {
898 throw new IllegalStateException(e);
899 }
900 }
901 }
902}