public class VpnService extends Service
Letting applications intercept packets raises huge security concerns. A VPN application can easily break the network. Besides, two of them may conflict with each other. The system takes several actions to address these issues. Here are some key points:
There are two primary methods in this class: prepare(android.content.Context)
and
VpnService.Builder.establish()
. The former deals with user action and stops
the VPN connection created by another application. The latter creates
a VPN interface using the parameters supplied to the VpnService.Builder
.
An application must call prepare(android.content.Context)
to grant the right to use
other methods in this class, and the right can be revoked at any time.
Here are the general steps to create a VPN connection:
prepare(android.content.Context)
and launch the returned intent, if non-null.VpnService.Builder
and create a VPN
interface by calling VpnService.Builder.establish()
.onRevoke()
is invoked, close the file descriptor and
shut down the tunnel gracefully.Services extended this class need to be declared with appropriate
permission and intent filter. Their access must be secured by
android.Manifest.permission#BIND_VPN_SERVICE
permission, and
their intent filter must match SERVICE_INTERFACE
action. Here
is an example of declaring a VPN service in AndroidManifest.xml
:
<service android:name=".ExampleVpnService" android:permission="android.permission.BIND_VPN_SERVICE"> <intent-filter> <action android:name="android.net.VpnService"/> </intent-filter> </service>
VpnService.Builder
Modifier and Type | Class and Description |
---|---|
class |
VpnService.Builder
Helper class to create a VPN interface.
|
Service.StartArgFlags, Service.StartResult, Service.StopForegroundFlags
Context.BindServiceFlags, Context.CreatePackageOptions, Context.ServiceName
Modifier and Type | Field and Description |
---|---|
static String |
SERVICE_INTERFACE
The action must be matched by the intent filter of this service.
|
START_CONTINUATION_MASK, START_FLAG_REDELIVERY, START_FLAG_RETRY, START_NOT_STICKY, START_REDELIVER_INTENT, START_STICKY, START_STICKY_COMPATIBILITY, START_TASK_REMOVED_COMPLETE, STOP_FOREGROUND_DETACH, STOP_FOREGROUND_REMOVE
ACCESSIBILITY_SERVICE, ACCOUNT_SERVICE, ACTIVITY_SERVICE, ALARM_SERVICE, APP_OPS_SERVICE, APPWIDGET_SERVICE, AUDIO_SERVICE, BACKUP_SERVICE, BATTERY_SERVICE, BIND_ABOVE_CLIENT, BIND_ADJUST_WITH_ACTIVITY, BIND_ALLOW_OOM_MANAGEMENT, BIND_ALLOW_WHITELIST_MANAGEMENT, BIND_AUTO_CREATE, BIND_DEBUG_UNBIND, BIND_EXTERNAL_SERVICE, BIND_FOREGROUND_SERVICE, BIND_FOREGROUND_SERVICE_WHILE_AWAKE, BIND_IMPORTANT, BIND_NOT_FOREGROUND, BIND_NOT_VISIBLE, BIND_SHOWING_UI, BIND_TREAT_LIKE_ACTIVITY, BIND_VISIBLE, BIND_WAIVE_PRIORITY, BLUETOOTH_SERVICE, CAMERA_SERVICE, CAPTIONING_SERVICE, CARRIER_CONFIG_SERVICE, CLIPBOARD_SERVICE, CONNECTIVITY_SERVICE, CONSUMER_IR_SERVICE, CONTEXT_CREDENTIAL_PROTECTED_STORAGE, CONTEXT_DEVICE_PROTECTED_STORAGE, CONTEXT_IGNORE_SECURITY, CONTEXT_INCLUDE_CODE, CONTEXT_REGISTER_PACKAGE, CONTEXT_RESTRICTED, CONTEXTHUB_SERVICE, COUNTRY_DETECTOR, DEVICE_IDLE_CONTROLLER, DEVICE_POLICY_SERVICE, DISPLAY_SERVICE, DOWNLOAD_SERVICE, DROPBOX_SERVICE, ETHERNET_SERVICE, FINGERPRINT_SERVICE, GATEKEEPER_SERVICE, HARDWARE_PROPERTIES_SERVICE, HDMI_CONTROL_SERVICE, INPUT_METHOD_SERVICE, INPUT_SERVICE, JOB_SCHEDULER_SERVICE, KEYGUARD_SERVICE, LAUNCHER_APPS_SERVICE, LAYOUT_INFLATER_SERVICE, LOCATION_SERVICE, MEDIA_PROJECTION_SERVICE, MEDIA_ROUTER_SERVICE, MEDIA_SESSION_SERVICE, MIDI_SERVICE, MODE_APPEND, MODE_ENABLE_WRITE_AHEAD_LOGGING, MODE_MULTI_PROCESS, MODE_NO_LOCALIZED_COLLATORS, MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE, NETWORK_POLICY_SERVICE, NETWORK_SCORE_SERVICE, NETWORK_STATS_SERVICE, NETWORKMANAGEMENT_SERVICE, NFC_SERVICE, NOTIFICATION_SERVICE, NSD_SERVICE, PERSISTENT_DATA_BLOCK_SERVICE, POWER_SERVICE, PRINT_SERVICE, RADIO_SERVICE, RECOVERY_SERVICE, RESTRICTIONS_SERVICE, SEARCH_SERVICE, SENSOR_SERVICE, SERIAL_SERVICE, SHORTCUT_SERVICE, SIP_SERVICE, SOUND_TRIGGER_SERVICE, STATUS_BAR_SERVICE, STORAGE_SERVICE, SYSTEM_HEALTH_SERVICE, TELECOM_SERVICE, TELEPHONY_SERVICE, TELEPHONY_SUBSCRIPTION_SERVICE, TEXT_SERVICES_MANAGER_SERVICE, TRUST_SERVICE, TV_INPUT_SERVICE, UI_MODE_SERVICE, UPDATE_LOCK_SERVICE, USAGE_STATS_SERVICE, USB_SERVICE, USER_SERVICE, VIBRATOR_SERVICE, VOICE_INTERACTION_MANAGER_SERVICE, WALLPAPER_SERVICE, WIFI_NAN_SERVICE, WIFI_P2P_SERVICE, WIFI_RTT_SERVICE, WIFI_SCANNING_SERVICE, WIFI_SERVICE, WINDOW_SERVICE
TRIM_MEMORY_BACKGROUND, TRIM_MEMORY_COMPLETE, TRIM_MEMORY_MODERATE, TRIM_MEMORY_RUNNING_CRITICAL, TRIM_MEMORY_RUNNING_LOW, TRIM_MEMORY_RUNNING_MODERATE, TRIM_MEMORY_UI_HIDDEN
Constructor and Description |
---|
VpnService() |
Modifier and Type | Method and Description |
---|---|
boolean |
addAddress(InetAddress address,
int prefixLength)
Adds a network address to the VPN interface.
|
IBinder |
onBind(Intent intent)
Return the communication interface to the service.
|
void |
onRevoke()
Invoked when the application is revoked.
|
static Intent |
prepare(Context context)
Prepare to establish a VPN connection.
|
static void |
prepareAndAuthorize(Context context)
Version of
prepare(Context) which does not require user consent. |
boolean |
protect(DatagramSocket socket)
Convenience method to protect a
DatagramSocket from VPN
connections. |
boolean |
protect(int socket)
Protect a socket from VPN connections.
|
boolean |
protect(Socket socket)
Convenience method to protect a
Socket from VPN connections. |
boolean |
removeAddress(InetAddress address,
int prefixLength)
Removes a network address from the VPN interface.
|
boolean |
setUnderlyingNetworks(Network[] networks)
Sets the underlying networks used by the VPN for its upstream connections.
|
attach, dump, getApplication, onConfigurationChanged, onCreate, onDestroy, onLowMemory, onRebind, onStart, onStartCommand, onTaskRemoved, onTrimMemory, onUnbind, setForeground, startForeground, stopForeground, stopForeground, stopSelf, stopSelf, stopSelfResult
attachBaseContext, bindService, bindServiceAsUser, canStartActivityForResult, checkCallingOrSelfPermission, checkCallingOrSelfUriPermission, checkCallingPermission, checkCallingUriPermission, checkPermission, checkPermission, checkSelfPermission, checkUriPermission, checkUriPermission, checkUriPermission, clearWallpaper, createApplicationContext, createConfigurationContext, createCredentialProtectedStorageContext, createDeviceProtectedStorageContext, createDisplayContext, createPackageContext, createPackageContextAsUser, databaseList, deleteDatabase, deleteFile, deleteSharedPreferences, enforceCallingOrSelfPermission, enforceCallingOrSelfUriPermission, enforceCallingPermission, enforceCallingUriPermission, enforcePermission, enforceUriPermission, enforceUriPermission, fileList, getApplicationContext, getApplicationInfo, getAssets, getBaseContext, getBasePackageName, getCacheDir, getClassLoader, getCodeCacheDir, getContentResolver, getDatabasePath, getDataDir, getDir, getDisplay, getDisplayAdjustments, getExternalCacheDir, getExternalCacheDirs, getExternalFilesDir, getExternalFilesDirs, getExternalMediaDirs, getFilesDir, getFileStreamPath, getMainLooper, getNoBackupFilesDir, getObbDir, getObbDirs, getOpPackageName, getPackageCodePath, getPackageManager, getPackageName, getPackageResourcePath, getResources, getSharedPreferences, getSharedPreferences, getSharedPreferencesPath, getSystemService, getSystemServiceName, getTheme, getThemeResId, getUserId, getWallpaper, getWallpaperDesiredMinimumHeight, getWallpaperDesiredMinimumWidth, grantUriPermission, isCredentialProtectedStorage, isDeviceProtectedStorage, isRestricted, moveDatabaseFrom, moveSharedPreferencesFrom, openFileInput, openFileOutput, openOrCreateDatabase, openOrCreateDatabase, peekWallpaper, registerReceiver, registerReceiver, registerReceiverAsUser, removeStickyBroadcast, removeStickyBroadcastAsUser, revokeUriPermission, sendBroadcast, sendBroadcast, sendBroadcast, sendBroadcast, sendBroadcastAsUser, sendBroadcastAsUser, sendBroadcastAsUser, sendBroadcastMultiplePermissions, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcastAsUser, sendOrderedBroadcastAsUser, sendOrderedBroadcastAsUser, sendStickyBroadcast, sendStickyBroadcastAsUser, sendStickyBroadcastAsUser, sendStickyOrderedBroadcast, sendStickyOrderedBroadcastAsUser, setTheme, setWallpaper, setWallpaper, startActivities, startActivities, startActivitiesAsUser, startActivity, startActivity, startActivityAsUser, startActivityAsUser, startActivityForResult, startInstrumentation, startIntentSender, startIntentSender, startService, startServiceAsUser, stopService, stopServiceAsUser, unbindService, unregisterReceiver
bindServiceAsUser, createCredentialEncryptedStorageContext, createDeviceEncryptedStorageContext, getColor, getColorStateList, getDrawable, getSharedPrefsFile, getString, getString, getSystemService, getText, isCredentialEncryptedStorage, isDeviceEncryptedStorage, migrateDatabaseFrom, migrateSharedPreferencesFrom, obtainStyledAttributes, obtainStyledAttributes, obtainStyledAttributes, obtainStyledAttributes, registerComponentCallbacks, unregisterComponentCallbacks
public static final String SERVICE_INTERFACE
android.Manifest.permission#BIND_VPN_SERVICE
permission so that other applications cannot abuse it.public static Intent prepare(Context context)
null
if the VPN application is already prepared or if the user has previously
consented to the VPN application. Otherwise, it returns an
Intent
to a system activity. The application should launch the
activity using Activity.startActivityForResult(android.content.Intent, int)
to get itself
prepared. The activity may pop up a dialog to require user action, and
the result will come back via its Activity.onActivityResult(int, int, android.content.Intent)
.
If the result is Activity.RESULT_OK
, the application becomes
prepared and is granted to use other methods in this class.
Only one application can be granted at the same time. The right
is revoked when another application is granted. The application
losing the right will be notified via its onRevoke()
. Unless
it becomes prepared again, subsequent calls to other methods in this
class will fail.
The user may disable the VPN at any time while it is activated, in which case this method will return an intent the next time it is executed to obtain the user's consent again.
onRevoke()
public static void prepareAndAuthorize(Context context)
prepare(Context)
which does not require user consent.
Requires android.Manifest.permission#CONTROL_VPN
and should generally not be
used. Only acceptable in situations where user consent has been obtained through other means.
Once this is run, future preparations may be done with the standard prepare method as this will authorize the package to prepare the VPN without consent in the future.
public boolean protect(int socket)
The socket is NOT closed by this method.
true
on success.public boolean protect(Socket socket)
Socket
from VPN connections.true
on success.protect(int)
public boolean protect(DatagramSocket socket)
DatagramSocket
from VPN
connections.true
on success.protect(int)
public boolean addAddress(InetAddress address, int prefixLength)
address
- The IP address (IPv4 or IPv6) to assign to the VPN interface.prefixLength
- The prefix length of the address.true
on success.IllegalArgumentException
- if the address is invalid.VpnService.Builder.addAddress(java.net.InetAddress, int)
public boolean removeAddress(InetAddress address, int prefixLength)
address
- The IP address (IPv4 or IPv6) to assign to the VPN interface.prefixLength
- The prefix length of the address.true
on success.IllegalArgumentException
- if the address is invalid.public boolean setUnderlyingNetworks(Network[] networks)
Used by the system to know the actual networks that carry traffic for apps affected by this VPN in order to present this information to the user (e.g., via status bar icons).
This method only needs to be called if the VPN has explicitly bound its underlying
communications channels — such as the socket(s) passed to protect(int)
—
to a Network
using APIs such as Network.bindSocket(Socket)
or
Network.bindSocket(DatagramSocket)
. The VPN should call this method every time
the set of Network
s it is using changes.
networks
is one of the following:
Network
s, in
decreasing preference order. For example, if this VPN uses both wifi and mobile (cellular)
networks to carry app traffic, but prefers or uses wifi more than mobile, wifi should appear
first in the array.bindSocket
or bindDatagramSocket
APIs mentioned above to send traffic over specific channels.This call will succeed only if the VPN is currently established. For setting this value
when the VPN has not yet been established, see VpnService.Builder.setUnderlyingNetworks(android.net.Network[])
.
networks
- An array of networks the VPN uses to tunnel traffic to/from its servers.true
on success.public IBinder onBind(Intent intent)
null
on Intent
s other than SERVICE_INTERFACE
action. Applications overriding this method must identify the intent
and return the corresponding interface accordingly.onBind
in class Service
intent
- The Intent that was used to bind to this service,
as given to Context.bindService
. Note that any extras that were included with
the Intent at that point will not be seen here.Service.onBind(android.content.Intent)
public void onRevoke()
Service.stopSelf()
.
Calls to this method may not happen on the main thread of the process.
prepare(android.content.Context)