blob: 870d8b1b7c226d70cccfe1da5bae554fc7a9b271 [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
Irina Dumitrescu5155a2d2019-02-20 18:17:06 +000022import android.annotation.NonNull;
Varun Anand6e81d012019-02-28 23:40:56 -080023import android.annotation.Nullable;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060024import android.annotation.RequiresPermission;
Jeff Davidson9a1da682014-11-11 13:52:58 -080025import android.annotation.SystemApi;
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010026import android.annotation.UnsupportedAppUsage;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070027import android.app.Activity;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070028import android.app.PendingIntent;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070029import android.app.Service;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070030import android.content.Context;
31import android.content.Intent;
Paul Jensen0784eea2014-08-19 16:00:24 -040032import android.content.pm.IPackageManager;
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -070033import android.content.pm.PackageManager;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070034import android.os.Binder;
35import android.os.IBinder;
36import android.os.Parcel;
37import android.os.ParcelFileDescriptor;
38import android.os.RemoteException;
39import android.os.ServiceManager;
Paul Jensen0784eea2014-08-19 16:00:24 -040040import android.os.UserHandle;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070041
42import com.android.internal.net.VpnConfig;
43
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070044import java.net.DatagramSocket;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070045import java.net.Inet4Address;
46import java.net.Inet6Address;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070047import java.net.InetAddress;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070048import java.net.Socket;
49import java.util.ArrayList;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070050import java.util.List;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070051
52/**
53 * VpnService is a base class for applications to extend and build their
54 * own VPN solutions. In general, it creates a virtual network interface,
55 * configures addresses and routing rules, and returns a file descriptor
56 * to the application. Each read from the descriptor retrieves an outgoing
57 * packet which was routed to the interface. Each write to the descriptor
58 * injects an incoming packet just like it was received from the interface.
59 * The interface is running on Internet Protocol (IP), so packets are
60 * always started with IP headers. The application then completes a VPN
61 * connection by processing and exchanging packets with the remote server
62 * over a tunnel.
63 *
64 * <p>Letting applications intercept packets raises huge security concerns.
65 * A VPN application can easily break the network. Besides, two of them may
66 * conflict with each other. The system takes several actions to address
67 * these issues. Here are some key points:
68 * <ul>
Jeff Davidson6d6ea3b2014-09-11 14:13:22 -070069 * <li>User action is required the first time an application creates a VPN
70 * connection.</li>
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070071 * <li>There can be only one VPN connection running at the same time. The
72 * existing interface is deactivated when a new one is created.</li>
73 * <li>A system-managed notification is shown during the lifetime of a
74 * VPN connection.</li>
75 * <li>A system-managed dialog gives the information of the current VPN
76 * connection. It also provides a button to disconnect.</li>
77 * <li>The network is restored automatically when the file descriptor is
78 * closed. It also covers the cases when a VPN application is crashed
79 * or killed by the system.</li>
80 * </ul>
81 *
82 * <p>There are two primary methods in this class: {@link #prepare} and
83 * {@link Builder#establish}. The former deals with user action and stops
84 * the VPN connection created by another application. The latter creates
85 * a VPN interface using the parameters supplied to the {@link Builder}.
86 * An application must call {@link #prepare} to grant the right to use
87 * other methods in this class, and the right can be revoked at any time.
88 * Here are the general steps to create a VPN connection:
89 * <ol>
Jeff Davidson6d6ea3b2014-09-11 14:13:22 -070090 * <li>When the user presses the button to connect, call {@link #prepare}
91 * and launch the returned intent, if non-null.</li>
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070092 * <li>When the application becomes prepared, start the service.</li>
93 * <li>Create a tunnel to the remote server and negotiate the network
94 * parameters for the VPN connection.</li>
95 * <li>Supply those parameters to a {@link Builder} and create a VPN
96 * interface by calling {@link Builder#establish}.</li>
97 * <li>Process and exchange packets between the tunnel and the returned
98 * file descriptor.</li>
99 * <li>When {@link #onRevoke} is invoked, close the file descriptor and
100 * shut down the tunnel gracefully.</li>
101 * </ol>
102 *
Benjamin Miller28a3e852017-07-14 17:17:12 +0200103 * <p>Services extending this class need to be declared with an appropriate
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700104 * permission and intent filter. Their access must be secured by
105 * {@link android.Manifest.permission#BIND_VPN_SERVICE} permission, and
106 * their intent filter must match {@link #SERVICE_INTERFACE} action. Here
107 * is an example of declaring a VPN service in {@code AndroidManifest.xml}:
108 * <pre>
109 * &lt;service android:name=".ExampleVpnService"
110 * android:permission="android.permission.BIND_VPN_SERVICE"&gt;
111 * &lt;intent-filter&gt;
112 * &lt;action android:name="android.net.VpnService"/&gt;
113 * &lt;/intent-filter&gt;
114 * &lt;/service&gt;</pre>
115 *
Benjamin Miller28a3e852017-07-14 17:17:12 +0200116 * <p> The Android system starts a VPN in the background by calling
117 * {@link android.content.Context#startService startService()}. In Android 8.0
118 * (API level 26) and higher, the system places VPN apps on the temporary
119 * whitelist for a short period so the app can start in the background. The VPN
120 * app must promote itself to the foreground after it's launched or the system
121 * will shut down the app.
122 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700123 * @see Builder
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700124 */
125public class VpnService extends Service {
126
127 /**
128 * The action must be matched by the intent filter of this service. It also
129 * needs to require {@link android.Manifest.permission#BIND_VPN_SERVICE}
130 * permission so that other applications cannot abuse it.
131 */
132 public static final String SERVICE_INTERFACE = VpnConfig.SERVICE_INTERFACE;
133
134 /**
Charles He36738632017-05-15 17:07:18 +0100135 * Key for boolean meta-data field indicating whether this VpnService supports always-on mode.
136 *
137 * <p>For a VPN app targeting {@link android.os.Build.VERSION_CODES#N API 24} or above, Android
138 * provides users with the ability to set it as always-on, so that VPN connection is
139 * persisted after device reboot and app upgrade. Always-on VPN can also be enabled by device
140 * owner and profile owner apps through
141 * {@link android.app.admin.DevicePolicyManager#setAlwaysOnVpnPackage}.
142 *
143 * <p>VPN apps not supporting this feature should opt out by adding this meta-data field to the
144 * {@code VpnService} component of {@code AndroidManifest.xml}. In case there is more than one
145 * {@code VpnService} component defined in {@code AndroidManifest.xml}, opting out any one of
146 * them will opt out the entire app. For example,
147 * <pre> {@code
148 * <service android:name=".ExampleVpnService"
149 * android:permission="android.permission.BIND_VPN_SERVICE">
150 * <intent-filter>
151 * <action android:name="android.net.VpnService"/>
152 * </intent-filter>
153 * <meta-data android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
154 * android:value=false/>
155 * </service>
156 * } </pre>
157 *
Charles Hec57a01c2017-08-15 15:30:22 +0100158 * <p>This meta-data field defaults to {@code true} if absent. It will only have effect on
159 * {@link android.os.Build.VERSION_CODES#O_MR1} or higher.
Charles He36738632017-05-15 17:07:18 +0100160 */
Charles Hec57a01c2017-08-15 15:30:22 +0100161 public static final String SERVICE_META_DATA_SUPPORTS_ALWAYS_ON =
Charles He36738632017-05-15 17:07:18 +0100162 "android.net.VpnService.SUPPORTS_ALWAYS_ON";
163
164 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700165 * Use IConnectivityManager since those methods are hidden and not
166 * available in ConnectivityManager.
167 */
168 private static IConnectivityManager getService() {
169 return IConnectivityManager.Stub.asInterface(
170 ServiceManager.getService(Context.CONNECTIVITY_SERVICE));
171 }
172
173 /**
174 * Prepare to establish a VPN connection. This method returns {@code null}
Jeff Davidson6d6ea3b2014-09-11 14:13:22 -0700175 * if the VPN application is already prepared or if the user has previously
176 * consented to the VPN application. Otherwise, it returns an
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700177 * {@link Intent} to a system activity. The application should launch the
178 * activity using {@link Activity#startActivityForResult} to get itself
179 * prepared. The activity may pop up a dialog to require user action, and
180 * the result will come back via its {@link Activity#onActivityResult}.
181 * If the result is {@link Activity#RESULT_OK}, the application becomes
182 * prepared and is granted to use other methods in this class.
183 *
184 * <p>Only one application can be granted at the same time. The right
185 * is revoked when another application is granted. The application
186 * losing the right will be notified via its {@link #onRevoke}. Unless
187 * it becomes prepared again, subsequent calls to other methods in this
188 * class will fail.
189 *
Jeff Davidson6d6ea3b2014-09-11 14:13:22 -0700190 * <p>The user may disable the VPN at any time while it is activated, in
191 * which case this method will return an intent the next time it is
192 * executed to obtain the user's consent again.
193 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700194 * @see #onRevoke
195 */
196 public static Intent prepare(Context context) {
197 try {
Jeff Sharkeyad357d12018-02-02 13:25:31 -0700198 if (getService().prepareVpn(context.getPackageName(), null, context.getUserId())) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700199 return null;
200 }
201 } catch (RemoteException e) {
202 // ignore
203 }
204 return VpnConfig.getIntentForConfirmation();
205 }
206
207 /**
Jeff Davidson9a1da682014-11-11 13:52:58 -0800208 * Version of {@link #prepare(Context)} which does not require user consent.
209 *
210 * <p>Requires {@link android.Manifest.permission#CONTROL_VPN} and should generally not be
211 * used. Only acceptable in situations where user consent has been obtained through other means.
212 *
213 * <p>Once this is run, future preparations may be done with the standard prepare method as this
214 * will authorize the package to prepare the VPN without consent in the future.
215 *
216 * @hide
217 */
218 @SystemApi
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -0600219 @RequiresPermission(android.Manifest.permission.CONTROL_VPN)
Jeff Davidson9a1da682014-11-11 13:52:58 -0800220 public static void prepareAndAuthorize(Context context) {
221 IConnectivityManager cm = getService();
222 String packageName = context.getPackageName();
223 try {
224 // Only prepare if we're not already prepared.
Jeff Sharkeyad357d12018-02-02 13:25:31 -0700225 int userId = context.getUserId();
Robin Lee3b3dd942015-05-12 18:14:58 +0100226 if (!cm.prepareVpn(packageName, null, userId)) {
227 cm.prepareVpn(null, packageName, userId);
Jeff Davidson9a1da682014-11-11 13:52:58 -0800228 }
Robin Lee3b3dd942015-05-12 18:14:58 +0100229 cm.setVpnPackageAuthorization(packageName, userId, true);
Jeff Davidson9a1da682014-11-11 13:52:58 -0800230 } catch (RemoteException e) {
231 // ignore
232 }
233 }
234
235 /**
Chad Brubakerbcf12b32014-02-11 14:18:56 -0800236 * Protect a socket from VPN connections. After protecting, data sent
237 * through this socket will go directly to the underlying network,
238 * so its traffic will not be forwarded through the VPN.
239 * This method is useful if some connections need to be kept
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700240 * outside of VPN. For example, a VPN tunnel should protect itself if its
241 * destination is covered by VPN routes. Otherwise its outgoing packets
242 * will be sent back to the VPN interface and cause an infinite loop. This
243 * method will fail if the application is not prepared or is revoked.
244 *
245 * <p class="note">The socket is NOT closed by this method.
246 *
247 * @return {@code true} on success.
248 */
249 public boolean protect(int socket) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400250 return NetworkUtils.protectFromVpn(socket);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700251 }
252
253 /**
254 * Convenience method to protect a {@link Socket} from VPN connections.
255 *
256 * @return {@code true} on success.
257 * @see #protect(int)
258 */
259 public boolean protect(Socket socket) {
260 return protect(socket.getFileDescriptor$().getInt$());
261 }
262
263 /**
264 * Convenience method to protect a {@link DatagramSocket} from VPN
265 * connections.
266 *
267 * @return {@code true} on success.
268 * @see #protect(int)
269 */
270 public boolean protect(DatagramSocket socket) {
271 return protect(socket.getFileDescriptor$().getInt$());
272 }
273
274 /**
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700275 * Adds a network address to the VPN interface.
276 *
277 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
278 * address is already in use or cannot be assigned to the interface for any other reason.
279 *
Sreeram Ramachandran13846052014-07-10 12:35:23 -0700280 * Adding an address implicitly allows traffic from that address family (i.e., IPv4 or IPv6) to
281 * be routed over the VPN. @see Builder#allowFamily
282 *
Robin Lee1472c922015-07-29 17:25:06 +0100283 * @throws IllegalArgumentException if the address is invalid.
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700284 *
285 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
286 * @param prefixLength The prefix length of the address.
287 *
288 * @return {@code true} on success.
289 * @see Builder#addAddress
Sreeram Ramachandrana1e06802014-09-11 14:08:25 -0700290 *
291 * @hide
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700292 */
293 public boolean addAddress(InetAddress address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700294 check(address, prefixLength);
295 try {
296 return getService().addVpnAddress(address.getHostAddress(), prefixLength);
297 } catch (RemoteException e) {
298 throw new IllegalStateException(e);
299 }
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700300 }
301
302 /**
303 * Removes a network address from the VPN interface.
304 *
305 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
306 * address is not assigned to the VPN interface, or if it is the only address assigned (thus
307 * cannot be removed), or if the address cannot be removed for any other reason.
308 *
Sreeram Ramachandran13846052014-07-10 12:35:23 -0700309 * After removing an address, if there are no addresses, routes or DNS servers of a particular
310 * address family (i.e., IPv4 or IPv6) configured on the VPN, that <b>DOES NOT</b> block that
311 * family from being routed. In other words, once an address family has been allowed, it stays
312 * allowed for the rest of the VPN's session. @see Builder#allowFamily
313 *
Robin Lee1472c922015-07-29 17:25:06 +0100314 * @throws IllegalArgumentException if the address is invalid.
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700315 *
316 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
317 * @param prefixLength The prefix length of the address.
318 *
319 * @return {@code true} on success.
Sreeram Ramachandrana1e06802014-09-11 14:08:25 -0700320 *
321 * @hide
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700322 */
323 public boolean removeAddress(InetAddress address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700324 check(address, prefixLength);
325 try {
326 return getService().removeVpnAddress(address.getHostAddress(), prefixLength);
327 } catch (RemoteException e) {
328 throw new IllegalStateException(e);
329 }
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700330 }
331
332 /**
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800333 * Sets the underlying networks used by the VPN for its upstream connections.
334 *
Sreeram Ramachandran9e956e92014-12-03 10:53:35 -0800335 * <p>Used by the system to know the actual networks that carry traffic for apps affected by
336 * this VPN in order to present this information to the user (e.g., via status bar icons).
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800337 *
Sreeram Ramachandran9e956e92014-12-03 10:53:35 -0800338 * <p>This method only needs to be called if the VPN has explicitly bound its underlying
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800339 * communications channels &mdash; such as the socket(s) passed to {@link #protect(int)} &mdash;
Jeff Sharkey88d2a3c2014-11-22 16:49:34 -0800340 * to a {@code Network} using APIs such as {@link Network#bindSocket(Socket)} or
341 * {@link Network#bindSocket(DatagramSocket)}. The VPN should call this method every time
342 * the set of {@code Network}s it is using changes.
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800343 *
Sreeram Ramachandran9e956e92014-12-03 10:53:35 -0800344 * <p>{@code networks} is one of the following:
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800345 * <ul>
346 * <li><strong>a non-empty array</strong>: an array of one or more {@link Network}s, in
347 * decreasing preference order. For example, if this VPN uses both wifi and mobile (cellular)
348 * networks to carry app traffic, but prefers or uses wifi more than mobile, wifi should appear
349 * first in the array.</li>
350 * <li><strong>an empty array</strong>: a zero-element array, meaning that the VPN has no
351 * underlying network connection, and thus, app traffic will not be sent or received.</li>
352 * <li><strong>null</strong>: (default) signifies that the VPN uses whatever is the system's
353 * default network. I.e., it doesn't use the {@code bindSocket} or {@code bindDatagramSocket}
Sreeram Ramachandran9e956e92014-12-03 10:53:35 -0800354 * APIs mentioned above to send traffic over specific channels.</li>
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800355 * </ul>
356 *
Sreeram Ramachandran9e956e92014-12-03 10:53:35 -0800357 * <p>This call will succeed only if the VPN is currently established. For setting this value
358 * when the VPN has not yet been established, see {@link Builder#setUnderlyingNetworks}.
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800359 *
360 * @param networks An array of networks the VPN uses to tunnel traffic to/from its servers.
361 *
362 * @return {@code true} on success.
363 */
364 public boolean setUnderlyingNetworks(Network[] networks) {
365 try {
366 return getService().setUnderlyingNetworksForVpn(networks);
367 } catch (RemoteException e) {
368 throw new IllegalStateException(e);
369 }
370 }
371
372 /**
Pavel Grafovcb3b8952018-12-14 13:51:07 +0000373 * Returns whether the service is running in always-on VPN mode.
374 */
375 public final boolean isAlwaysOn() {
376 try {
377 return getService().isCallerCurrentAlwaysOnVpnApp();
378 } catch (RemoteException e) {
379 throw e.rethrowFromSystemServer();
380 }
381 }
382
383 /**
384 * Returns whether the service is running in always-on VPN mode blocking connections without
385 * VPN.
386 */
387 public final boolean isLockdownEnabled() {
388 try {
389 return getService().isCallerCurrentAlwaysOnVpnLockdownApp();
390 } catch (RemoteException e) {
391 throw e.rethrowFromSystemServer();
392 }
393 }
394
395 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700396 * Return the communication interface to the service. This method returns
397 * {@code null} on {@link Intent}s other than {@link #SERVICE_INTERFACE}
398 * action. Applications overriding this method must identify the intent
399 * and return the corresponding interface accordingly.
400 *
401 * @see Service#onBind
402 */
403 @Override
404 public IBinder onBind(Intent intent) {
405 if (intent != null && SERVICE_INTERFACE.equals(intent.getAction())) {
406 return new Callback();
407 }
408 return null;
409 }
410
411 /**
412 * Invoked when the application is revoked. At this moment, the VPN
413 * interface is already deactivated by the system. The application should
414 * close the file descriptor and shut down gracefully. The default
415 * implementation of this method is calling {@link Service#stopSelf()}.
416 *
417 * <p class="note">Calls to this method may not happen on the main thread
418 * of the process.
419 *
420 * @see #prepare
421 */
422 public void onRevoke() {
423 stopSelf();
424 }
425
426 /**
427 * Use raw Binder instead of AIDL since now there is only one usage.
428 */
429 private class Callback extends Binder {
430 @Override
431 protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
432 if (code == IBinder.LAST_CALL_TRANSACTION) {
433 onRevoke();
434 return true;
435 }
436 return false;
437 }
438 }
439
440 /**
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700441 * Private method to validate address and prefixLength.
442 */
443 private static void check(InetAddress address, int prefixLength) {
444 if (address.isLoopbackAddress()) {
445 throw new IllegalArgumentException("Bad address");
446 }
447 if (address instanceof Inet4Address) {
448 if (prefixLength < 0 || prefixLength > 32) {
449 throw new IllegalArgumentException("Bad prefixLength");
450 }
451 } else if (address instanceof Inet6Address) {
452 if (prefixLength < 0 || prefixLength > 128) {
453 throw new IllegalArgumentException("Bad prefixLength");
454 }
455 } else {
456 throw new IllegalArgumentException("Unsupported family");
457 }
458 }
459
460 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700461 * Helper class to create a VPN interface. This class should be always
462 * used within the scope of the outer {@link VpnService}.
463 *
464 * @see VpnService
465 */
466 public class Builder {
467
468 private final VpnConfig mConfig = new VpnConfig();
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100469 @UnsupportedAppUsage
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700470 private final List<LinkAddress> mAddresses = new ArrayList<LinkAddress>();
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100471 @UnsupportedAppUsage
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700472 private final List<RouteInfo> mRoutes = new ArrayList<RouteInfo>();
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700473
474 public Builder() {
475 mConfig.user = VpnService.this.getClass().getName();
476 }
477
478 /**
479 * Set the name of this session. It will be displayed in
480 * system-managed dialogs and notifications. This is recommended
481 * not required.
482 */
Varun Anand6e81d012019-02-28 23:40:56 -0800483 @NonNull
484 public Builder setSession(@NonNull String session) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700485 mConfig.session = session;
486 return this;
487 }
488
489 /**
490 * Set the {@link PendingIntent} to an activity for users to
491 * configure the VPN connection. If it is not set, the button
492 * to configure will not be shown in system-managed dialogs.
493 */
Varun Anand6e81d012019-02-28 23:40:56 -0800494 @NonNull
495 public Builder setConfigureIntent(@NonNull PendingIntent intent) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700496 mConfig.configureIntent = intent;
497 return this;
498 }
499
500 /**
501 * Set the maximum transmission unit (MTU) of the VPN interface. If
502 * it is not set, the default value in the operating system will be
503 * used.
504 *
505 * @throws IllegalArgumentException if the value is not positive.
506 */
Varun Anand6e81d012019-02-28 23:40:56 -0800507 @NonNull
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700508 public Builder setMtu(int mtu) {
509 if (mtu <= 0) {
510 throw new IllegalArgumentException("Bad mtu");
511 }
512 mConfig.mtu = mtu;
513 return this;
514 }
515
516 /**
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000517 * Sets an HTTP proxy for the VPN network. This proxy is only a recommendation
518 * and it is possible that some apps will ignore it.
519 */
Varun Anand6e81d012019-02-28 23:40:56 -0800520 @NonNull
Irina Dumitrescu5155a2d2019-02-20 18:17:06 +0000521 public Builder setHttpProxy(@NonNull ProxyInfo proxyInfo) {
Irina Dumitrescu044a4362018-12-05 16:19:47 +0000522 mConfig.proxyInfo = proxyInfo;
523 return this;
524 }
525
526 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700527 * Add a network address to the VPN interface. Both IPv4 and IPv6
528 * addresses are supported. At least one address must be set before
529 * calling {@link #establish}.
530 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700531 * Adding an address implicitly allows traffic from that address family
532 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
533 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700534 * @throws IllegalArgumentException if the address is invalid.
535 */
Varun Anand6e81d012019-02-28 23:40:56 -0800536 @NonNull
537 public Builder addAddress(@NonNull InetAddress address, int prefixLength) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700538 check(address, prefixLength);
539
540 if (address.isAnyLocalAddress()) {
541 throw new IllegalArgumentException("Bad address");
542 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700543 mAddresses.add(new LinkAddress(address, prefixLength));
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700544 mConfig.updateAllowedFamilies(address);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700545 return this;
546 }
547
548 /**
549 * Convenience method to add a network address to the VPN interface
550 * using a numeric address string. See {@link InetAddress} for the
551 * definitions of numeric address formats.
552 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700553 * Adding an address implicitly allows traffic from that address family
554 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
555 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700556 * @throws IllegalArgumentException if the address is invalid.
557 * @see #addAddress(InetAddress, int)
558 */
Varun Anand6e81d012019-02-28 23:40:56 -0800559 @NonNull
560 public Builder addAddress(@NonNull String address, int prefixLength) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700561 return addAddress(InetAddress.parseNumericAddress(address), prefixLength);
562 }
563
564 /**
565 * Add a network route to the VPN interface. Both IPv4 and IPv6
566 * routes are supported.
567 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700568 * Adding a route implicitly allows traffic from that address family
569 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
570 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700571 * @throws IllegalArgumentException if the route is invalid.
572 */
Varun Anand6e81d012019-02-28 23:40:56 -0800573 @NonNull
574 public Builder addRoute(@NonNull InetAddress address, int prefixLength) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700575 check(address, prefixLength);
576
577 int offset = prefixLength / 8;
578 byte[] bytes = address.getAddress();
579 if (offset < bytes.length) {
580 for (bytes[offset] <<= prefixLength % 8; offset < bytes.length; ++offset) {
581 if (bytes[offset] != 0) {
582 throw new IllegalArgumentException("Bad address");
583 }
584 }
585 }
Lorenzo Colittib2053112015-01-20 13:40:58 +0900586 mRoutes.add(new RouteInfo(new IpPrefix(address, prefixLength), null));
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700587 mConfig.updateAllowedFamilies(address);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700588 return this;
589 }
590
591 /**
592 * Convenience method to add a network route to the VPN interface
593 * using a numeric address string. See {@link InetAddress} for the
594 * definitions of numeric address formats.
595 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700596 * Adding a route implicitly allows traffic from that address family
597 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
598 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700599 * @throws IllegalArgumentException if the route is invalid.
600 * @see #addRoute(InetAddress, int)
601 */
Varun Anand6e81d012019-02-28 23:40:56 -0800602 @NonNull
603 public Builder addRoute(@NonNull String address, int prefixLength) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700604 return addRoute(InetAddress.parseNumericAddress(address), prefixLength);
605 }
606
607 /**
608 * Add a DNS server to the VPN connection. Both IPv4 and IPv6
609 * addresses are supported. If none is set, the DNS servers of
610 * the default network will be used.
611 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700612 * Adding a server implicitly allows traffic from that address family
613 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
614 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700615 * @throws IllegalArgumentException if the address is invalid.
616 */
Varun Anand6e81d012019-02-28 23:40:56 -0800617 @NonNull
618 public Builder addDnsServer(@NonNull InetAddress address) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700619 if (address.isLoopbackAddress() || address.isAnyLocalAddress()) {
620 throw new IllegalArgumentException("Bad address");
621 }
622 if (mConfig.dnsServers == null) {
623 mConfig.dnsServers = new ArrayList<String>();
624 }
625 mConfig.dnsServers.add(address.getHostAddress());
626 return this;
627 }
628
629 /**
630 * Convenience method to add a DNS server to the VPN connection
631 * using a numeric address string. See {@link InetAddress} for the
632 * definitions of numeric address formats.
633 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700634 * Adding a server implicitly allows traffic from that address family
635 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
636 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700637 * @throws IllegalArgumentException if the address is invalid.
638 * @see #addDnsServer(InetAddress)
639 */
Varun Anand6e81d012019-02-28 23:40:56 -0800640 @NonNull
641 public Builder addDnsServer(@NonNull String address) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700642 return addDnsServer(InetAddress.parseNumericAddress(address));
643 }
644
645 /**
646 * Add a search domain to the DNS resolver.
647 */
Varun Anand6e81d012019-02-28 23:40:56 -0800648 @NonNull
649 public Builder addSearchDomain(@NonNull String domain) {
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700650 if (mConfig.searchDomains == null) {
651 mConfig.searchDomains = new ArrayList<String>();
652 }
653 mConfig.searchDomains.add(domain);
654 return this;
655 }
656
657 /**
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700658 * Allows traffic from the specified address family.
659 *
660 * By default, if no address, route or DNS server of a specific family (IPv4 or IPv6) is
661 * added to this VPN, then all outgoing traffic of that family is blocked. If any address,
662 * route or DNS server is added, that family is allowed.
663 *
664 * This method allows an address family to be unblocked even without adding an address,
665 * route or DNS server of that family. Traffic of that family will then typically
666 * fall-through to the underlying network if it's supported.
667 *
668 * {@code family} must be either {@code AF_INET} (for IPv4) or {@code AF_INET6} (for IPv6).
669 * {@link IllegalArgumentException} is thrown if it's neither.
670 *
671 * @param family The address family ({@code AF_INET} or {@code AF_INET6}) to allow.
672 *
673 * @return this {@link Builder} object to facilitate chaining of method calls.
674 */
Varun Anand6e81d012019-02-28 23:40:56 -0800675 @NonNull
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700676 public Builder allowFamily(int family) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700677 if (family == AF_INET) {
678 mConfig.allowIPv4 = true;
679 } else if (family == AF_INET6) {
680 mConfig.allowIPv6 = true;
681 } else {
682 throw new IllegalArgumentException(family + " is neither " + AF_INET + " nor " +
683 AF_INET6);
684 }
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700685 return this;
686 }
687
Paul Jensen0784eea2014-08-19 16:00:24 -0400688 private void verifyApp(String packageName) throws PackageManager.NameNotFoundException {
689 IPackageManager pm = IPackageManager.Stub.asInterface(
690 ServiceManager.getService("package"));
691 try {
692 pm.getApplicationInfo(packageName, 0, UserHandle.getCallingUserId());
693 } catch (RemoteException e) {
694 throw new IllegalStateException(e);
695 }
696 }
697
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700698 /**
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700699 * Adds an application that's allowed to access the VPN connection.
700 *
701 * If this method is called at least once, only applications added through this method (and
702 * no others) are allowed access. Else (if this method is never called), all applications
Robert Greenwaltfc4f7212014-08-25 12:41:08 -0700703 * are allowed by default. If some applications are added, other, un-added applications
704 * will use networking as if the VPN wasn't running.
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700705 *
706 * A {@link Builder} may have only a set of allowed applications OR a set of disallowed
707 * ones, but not both. Calling this method after {@link #addDisallowedApplication} has
708 * already been called, or vice versa, will throw an {@link UnsupportedOperationException}.
709 *
710 * {@code packageName} must be the canonical name of a currently installed application.
711 * {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
712 *
Robin Lee1472c922015-07-29 17:25:06 +0100713 * @throws PackageManager.NameNotFoundException If the application isn't installed.
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700714 *
715 * @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
716 *
717 * @return this {@link Builder} object to facilitate chaining method calls.
718 */
Varun Anand6e81d012019-02-28 23:40:56 -0800719 @NonNull
720 public Builder addAllowedApplication(@NonNull String packageName)
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700721 throws PackageManager.NameNotFoundException {
Paul Jensen0784eea2014-08-19 16:00:24 -0400722 if (mConfig.disallowedApplications != null) {
723 throw new UnsupportedOperationException("addDisallowedApplication already called");
724 }
725 verifyApp(packageName);
726 if (mConfig.allowedApplications == null) {
727 mConfig.allowedApplications = new ArrayList<String>();
728 }
729 mConfig.allowedApplications.add(packageName);
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700730 return this;
731 }
732
733 /**
734 * Adds an application that's denied access to the VPN connection.
735 *
736 * By default, all applications are allowed access, except for those denied through this
Robert Greenwaltfc4f7212014-08-25 12:41:08 -0700737 * method. Denied applications will use networking as if the VPN wasn't running.
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700738 *
739 * A {@link Builder} may have only a set of allowed applications OR a set of disallowed
740 * ones, but not both. Calling this method after {@link #addAllowedApplication} has already
741 * been called, or vice versa, will throw an {@link UnsupportedOperationException}.
742 *
743 * {@code packageName} must be the canonical name of a currently installed application.
744 * {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
745 *
Robin Lee1472c922015-07-29 17:25:06 +0100746 * @throws PackageManager.NameNotFoundException If the application isn't installed.
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700747 *
748 * @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
749 *
750 * @return this {@link Builder} object to facilitate chaining method calls.
751 */
Varun Anand6e81d012019-02-28 23:40:56 -0800752 @NonNull
753 public Builder addDisallowedApplication(@NonNull String packageName)
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700754 throws PackageManager.NameNotFoundException {
Paul Jensen0784eea2014-08-19 16:00:24 -0400755 if (mConfig.allowedApplications != null) {
756 throw new UnsupportedOperationException("addAllowedApplication already called");
757 }
758 verifyApp(packageName);
759 if (mConfig.disallowedApplications == null) {
760 mConfig.disallowedApplications = new ArrayList<String>();
761 }
762 mConfig.disallowedApplications.add(packageName);
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700763 return this;
764 }
765
766 /**
Sreeram Ramachandrana9294eb2014-07-09 21:43:03 -0700767 * Allows all apps to bypass this VPN connection.
768 *
769 * By default, all traffic from apps is forwarded through the VPN interface and it is not
770 * possible for apps to side-step the VPN. If this method is called, apps may use methods
Paul Jensen72db88e2015-03-10 10:54:12 -0400771 * such as {@link ConnectivityManager#bindProcessToNetwork} to instead send/receive
Sreeram Ramachandrana9294eb2014-07-09 21:43:03 -0700772 * directly over the underlying network or any other network they have permissions for.
773 *
774 * @return this {@link Builder} object to facilitate chaining of method calls.
775 */
Varun Anand6e81d012019-02-28 23:40:56 -0800776 @NonNull
Sreeram Ramachandrana9294eb2014-07-09 21:43:03 -0700777 public Builder allowBypass() {
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700778 mConfig.allowBypass = true;
Sreeram Ramachandrana9294eb2014-07-09 21:43:03 -0700779 return this;
780 }
781
782 /**
Sreeram Ramachandrancc26b4c2014-07-18 16:41:25 -0700783 * Sets the VPN interface's file descriptor to be in blocking/non-blocking mode.
784 *
785 * By default, the file descriptor returned by {@link #establish} is non-blocking.
786 *
787 * @param blocking True to put the descriptor into blocking mode; false for non-blocking.
788 *
789 * @return this {@link Builder} object to facilitate chaining method calls.
790 */
Varun Anand6e81d012019-02-28 23:40:56 -0800791 @NonNull
Sreeram Ramachandrancc26b4c2014-07-18 16:41:25 -0700792 public Builder setBlocking(boolean blocking) {
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700793 mConfig.blocking = blocking;
Sreeram Ramachandrancc26b4c2014-07-18 16:41:25 -0700794 return this;
795 }
796
797 /**
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800798 * Sets the underlying networks used by the VPN for its upstream connections.
799 *
800 * @see VpnService#setUnderlyingNetworks
801 *
802 * @param networks An array of networks the VPN uses to tunnel traffic to/from its servers.
803 *
804 * @return this {@link Builder} object to facilitate chaining method calls.
805 */
Varun Anand6e81d012019-02-28 23:40:56 -0800806 @NonNull
807 public Builder setUnderlyingNetworks(@Nullable Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800808 mConfig.underlyingNetworks = networks != null ? networks.clone() : null;
809 return this;
810 }
811
812 /**
Varun Anand1215f092019-01-14 11:45:33 -0800813 * Marks the VPN network as metered. A VPN network is classified as metered when the user is
814 * sensitive to heavy data usage due to monetary costs and/or data limitations. In such
815 * cases, you should set this to {@code true} so that apps on the system can avoid doing
816 * large data transfers. Otherwise, set this to {@code false}. Doing so would cause VPN
817 * network to inherit its meteredness from its underlying networks.
818 *
819 * <p>VPN apps targeting {@link android.os.Build.VERSION_CODES#Q} or above will be
820 * considered metered by default.
821 *
822 * @param isMetered {@code true} if VPN network should be treated as metered regardless of
823 * underlying network meteredness
824 * @return this {@link Builder} object to facilitate chaining method calls
825 * @see #setUnderlyingNetworks(Networks[])
826 * @see ConnectivityManager#isActiveNetworkMetered()
827 */
Varun Anand6e81d012019-02-28 23:40:56 -0800828 @NonNull
Varun Anand1215f092019-01-14 11:45:33 -0800829 public Builder setMetered(boolean isMetered) {
830 mConfig.isMetered = isMetered;
831 return this;
832 }
833
834 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700835 * Create a VPN interface using the parameters supplied to this
836 * builder. The interface works on IP packets, and a file descriptor
837 * is returned for the application to access them. Each read
838 * retrieves an outgoing packet which was routed to the interface.
839 * Each write injects an incoming packet just like it was received
840 * from the interface. The file descriptor is put into non-blocking
841 * mode by default to avoid blocking Java threads. To use the file
842 * descriptor completely in native space, see
843 * {@link ParcelFileDescriptor#detachFd()}. The application MUST
844 * close the file descriptor when the VPN connection is terminated.
845 * The VPN interface will be removed and the network will be
846 * restored by the system automatically.
847 *
848 * <p>To avoid conflicts, there can be only one active VPN interface
849 * at the same time. Usually network parameters are never changed
850 * during the lifetime of a VPN connection. It is also common for an
851 * application to create a new file descriptor after closing the
852 * previous one. However, it is rare but not impossible to have two
853 * interfaces while performing a seamless handover. In this case, the
854 * old interface will be deactivated when the new one is created
855 * successfully. Both file descriptors are valid but now outgoing
856 * packets will be routed to the new interface. Therefore, after
857 * draining the old file descriptor, the application MUST close it
858 * and start using the new file descriptor. If the new interface
859 * cannot be created, the existing interface and its file descriptor
860 * remain untouched.
861 *
862 * <p>An exception will be thrown if the interface cannot be created
863 * for any reason. However, this method returns {@code null} if the
864 * application is not prepared or is revoked. This helps solve
865 * possible race conditions between other VPN applications.
866 *
867 * @return {@link ParcelFileDescriptor} of the VPN interface, or
868 * {@code null} if the application is not prepared.
869 * @throws IllegalArgumentException if a parameter is not accepted
870 * by the operating system.
871 * @throws IllegalStateException if a parameter cannot be applied
872 * by the operating system.
873 * @throws SecurityException if the service is not properly declared
874 * in {@code AndroidManifest.xml}.
875 * @see VpnService
876 */
Varun Anand6e81d012019-02-28 23:40:56 -0800877 @Nullable
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700878 public ParcelFileDescriptor establish() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700879 mConfig.addresses = mAddresses;
880 mConfig.routes = mRoutes;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700881
882 try {
883 return getService().establishVpn(mConfig);
884 } catch (RemoteException e) {
885 throw new IllegalStateException(e);
886 }
887 }
888 }
889}