Migrate tunnel related classes to tunnel/ Gradle module

Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
This commit is contained in:
Harsh Shandilya
2020-03-09 19:24:26 +05:30
parent fd573f6c1c
commit adc613d801
42 changed files with 76 additions and 44 deletions
@@ -0,0 +1,63 @@
/*
* Copyright © 2017-2019 WireGuard LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.wireguard.android.backend;
import com.wireguard.config.Config;
import java.util.Collection;
import java.util.Set;
import androidx.annotation.Nullable;
/**
* Interface for implementations of the WireGuard secure network tunnel.
*/
public interface Backend {
/**
* Enumerate names of currently-running tunnels.
*
* @return The set of running tunnel names.
*/
Set<String> getRunningTunnelNames();
/**
* Get the state of a tunnel.
*
* @param tunnel The tunnel to examine the state of.
* @return The state of the tunnel.
*/
Tunnel.State getState(Tunnel tunnel) throws Exception;
/**
* Get statistics about traffic and errors on this tunnel. If the tunnel is not running, the
* statistics object will be filled with zero values.
*
* @param tunnel The tunnel to retrieve statistics for.
* @return The statistics for the tunnel.
*/
Statistics getStatistics(Tunnel tunnel) throws Exception;
/**
* Determine version of underlying backend.
*
* @return The version of the backend.
* @throws Exception
*/
String getVersion() throws Exception;
/**
* Set the state of a tunnel, updating it's configuration. If the tunnel is already up, config
* may update the running configuration; config may be null when setting the tunnel down.
*
* @param tunnel The tunnel to control the state of.
* @param state The new state for this tunnel. Must be {@code UP}, {@code DOWN}, or
* {@code TOGGLE}.
* @param config The configuration for this tunnel, may be null if state is {@code DOWN}.
* @return The updated state of the tunnel.
*/
Tunnel.State setState(Tunnel tunnel, Tunnel.State state, @Nullable Config config) throws Exception;
}
@@ -0,0 +1,30 @@
/*
* Copyright © 2020 WireGuard LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.wireguard.android.backend;
public final class BackendException extends Exception {
public enum Reason {
UNKNOWN_KERNEL_MODULE_NAME,
WG_QUICK_CONFIG_ERROR_CODE,
TUNNEL_MISSING_CONFIG,
VPN_NOT_AUTHORIZED,
UNABLE_TO_START_VPN,
TUN_CREATION_ERROR,
GO_ACTIVATION_ERROR_CODE
}
private final Reason reason;
private final Object[] format;
public BackendException(final Reason reason, final Object ...format) {
this.reason = reason;
this.format = format;
}
public Reason getReason() {
return reason;
}
public Object[] getFormat() {
return format;
}
}
@@ -0,0 +1,292 @@
/*
* Copyright © 2017-2019 WireGuard LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.wireguard.android.backend;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import androidx.annotation.Nullable;
import androidx.collection.ArraySet;
import android.util.Log;
import com.wireguard.android.backend.BackendException.Reason;
import com.wireguard.android.backend.Tunnel.State;
import com.wireguard.android.util.SharedLibraryLoader;
import com.wireguard.config.Config;
import com.wireguard.config.InetNetwork;
import com.wireguard.config.Peer;
import com.wireguard.crypto.Key;
import com.wireguard.crypto.KeyFormatException;
import java.net.InetAddress;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java9.util.concurrent.CompletableFuture;
public final class GoBackend implements Backend {
private static final String TAG = "WireGuard/" + GoBackend.class.getSimpleName();
private static CompletableFuture<VpnService> vpnService = new CompletableFuture<>();
public interface AlwaysOnCallback {
void alwaysOnTriggered();
}
@Nullable private static AlwaysOnCallback alwaysOnCallback;
public static void setAlwaysOnCallback(AlwaysOnCallback cb) {
alwaysOnCallback = cb;
}
private final Context context;
@Nullable private Tunnel currentTunnel;
@Nullable private Config currentConfig;
private int currentTunnelHandle = -1;
public GoBackend(final Context context) {
SharedLibraryLoader.loadSharedLibrary(context, "wg-go");
this.context = context;
}
private static native String wgGetConfig(int handle);
private static native int wgGetSocketV4(int handle);
private static native int wgGetSocketV6(int handle);
private static native void wgTurnOff(int handle);
private static native int wgTurnOn(String ifName, int tunFd, String settings);
private static native String wgVersion();
@Override
public Set<String> getRunningTunnelNames() {
if (currentTunnel != null) {
final Set<String> runningTunnels = new ArraySet<>();
runningTunnels.add(currentTunnel.getName());
return runningTunnels;
}
return Collections.emptySet();
}
@Override
public State getState(final Tunnel tunnel) {
return currentTunnel == tunnel ? State.UP : State.DOWN;
}
@Override
public Statistics getStatistics(final Tunnel tunnel) {
final Statistics stats = new Statistics();
if (tunnel != currentTunnel) {
return stats;
}
final String config = wgGetConfig(currentTunnelHandle);
Key key = null;
long rx = 0, tx = 0;
for (final String line : config.split("\\n")) {
if (line.startsWith("public_key=")) {
if (key != null)
stats.add(key, rx, tx);
rx = 0;
tx = 0;
try {
key = Key.fromHex(line.substring(11));
} catch (final KeyFormatException ignored) {
key = null;
}
} else if (line.startsWith("rx_bytes=")) {
if (key == null)
continue;
try {
rx = Long.parseLong(line.substring(9));
} catch (final NumberFormatException ignored) {
rx = 0;
}
} else if (line.startsWith("tx_bytes=")) {
if (key == null)
continue;
try {
tx = Long.parseLong(line.substring(9));
} catch (final NumberFormatException ignored) {
tx = 0;
}
}
}
if (key != null)
stats.add(key, rx, tx);
return stats;
}
@Override
public String getVersion() {
return wgVersion();
}
@Override
public State setState(final Tunnel tunnel, State state, @Nullable final Config config) throws Exception {
final State originalState = getState(tunnel);
if (state == State.TOGGLE)
state = originalState == State.UP ? State.DOWN : State.UP;
if (state == originalState && tunnel == currentTunnel && config == currentConfig)
return originalState;
if (state == State.UP) {
final Config originalConfig = currentConfig;
final Tunnel originalTunnel = currentTunnel;
if (currentTunnel != null)
setStateInternal(currentTunnel, null, State.DOWN);
try {
setStateInternal(tunnel, config, state);
} catch(final Exception e) {
if (originalTunnel != null)
setStateInternal(originalTunnel, originalConfig, State.UP);
throw e;
}
} else if (state == State.DOWN && tunnel == currentTunnel) {
setStateInternal(tunnel, null, State.DOWN);
}
return getState(tunnel);
}
private void setStateInternal(final Tunnel tunnel, @Nullable final Config config, final State state)
throws Exception {
Log.i(TAG, "Bringing tunnel " + tunnel.getName() + " " + state);
if (state == State.UP) {
if (config == null)
throw new BackendException(Reason.TUNNEL_MISSING_CONFIG);
if (VpnService.prepare(context) != null)
throw new BackendException(Reason.VPN_NOT_AUTHORIZED);
final VpnService service;
if (!vpnService.isDone())
startVpnService();
try {
service = vpnService.get(2, TimeUnit.SECONDS);
} catch (final TimeoutException e) {
final Exception be = new BackendException(Reason.UNABLE_TO_START_VPN);
be.initCause(e);
throw be;
}
service.setOwner(this);
if (currentTunnelHandle != -1) {
Log.w(TAG, "Tunnel already up");
return;
}
// Build config
final String goConfig = config.toWgUserspaceString();
// Create the vpn tunnel with android API
final VpnService.Builder builder = service.getBuilder();
builder.setSession(tunnel.getName());
for (final String excludedApplication : config.getInterface().getExcludedApplications())
builder.addDisallowedApplication(excludedApplication);
for (final InetNetwork addr : config.getInterface().getAddresses())
builder.addAddress(addr.getAddress(), addr.getMask());
for (final InetAddress addr : config.getInterface().getDnsServers())
builder.addDnsServer(addr.getHostAddress());
for (final Peer peer : config.getPeers()) {
for (final InetNetwork addr : peer.getAllowedIps())
builder.addRoute(addr.getAddress(), addr.getMask());
}
builder.setMtu(config.getInterface().getMtu().orElse(1280));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
builder.setMetered(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
service.setUnderlyingNetworks(null);
builder.setBlocking(true);
try (final ParcelFileDescriptor tun = builder.establish()) {
if (tun == null)
throw new BackendException(Reason.TUN_CREATION_ERROR);
Log.d(TAG, "Go backend v" + wgVersion());
currentTunnelHandle = wgTurnOn(tunnel.getName(), tun.detachFd(), goConfig);
}
if (currentTunnelHandle < 0)
throw new BackendException(Reason.GO_ACTIVATION_ERROR_CODE, currentTunnelHandle);
currentTunnel = tunnel;
currentConfig = config;
service.protect(wgGetSocketV4(currentTunnelHandle));
service.protect(wgGetSocketV6(currentTunnelHandle));
} else {
if (currentTunnelHandle == -1) {
Log.w(TAG, "Tunnel already down");
return;
}
wgTurnOff(currentTunnelHandle);
currentTunnel = null;
currentTunnelHandle = -1;
currentConfig = null;
}
tunnel.onStateChange(state);
}
private void startVpnService() {
Log.d(TAG, "Requesting to start VpnService");
context.startService(new Intent(context, VpnService.class));
}
public static class VpnService extends android.net.VpnService {
@Nullable private GoBackend owner;
public void setOwner(final GoBackend owner) {
this.owner = owner;
}
public Builder getBuilder() {
return new Builder();
}
@Override
public void onCreate() {
vpnService.complete(this);
super.onCreate();
}
@Override
public void onDestroy() {
if (owner != null) {
final Tunnel tunnel = owner.currentTunnel;
if (tunnel != null) {
if (owner.currentTunnelHandle != -1)
wgTurnOff(owner.currentTunnelHandle);
owner.currentTunnel = null;
owner.currentTunnelHandle = -1;
owner.currentConfig = null;
tunnel.onStateChange(State.DOWN);
}
}
vpnService = vpnService.newIncompleteFuture();
super.onDestroy();
}
@Override
public int onStartCommand(@Nullable final Intent intent, final int flags, final int startId) {
vpnService.complete(this);
if (intent == null || intent.getComponent() == null || !intent.getComponent().getPackageName().equals(getPackageName())) {
Log.d(TAG, "Service started by Always-on VPN feature");
if (alwaysOnCallback != null)
alwaysOnCallback.alwaysOnTriggered();
}
return super.onStartCommand(intent, flags, startId);
}
}
}
@@ -0,0 +1,62 @@
/*
* Copyright © 2020 WireGuard LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.wireguard.android.backend;
import android.os.SystemClock;
import android.util.Pair;
import com.wireguard.crypto.Key;
import java.util.HashMap;
import java.util.Map;
public class Statistics {
private long lastTouched = SystemClock.elapsedRealtime();
private final Map<Key, Pair<Long, Long>> peerBytes = new HashMap<>();
Statistics() { }
void add(final Key key, final long rx, final long tx) {
peerBytes.put(key, Pair.create(rx, tx));
lastTouched = SystemClock.elapsedRealtime();
}
public boolean isStale() {
return SystemClock.elapsedRealtime() - lastTouched > 900;
}
public Key[] peers() {
return peerBytes.keySet().toArray(new Key[0]);
}
public long peerRx(final Key peer) {
if (!peerBytes.containsKey(peer))
return 0;
return peerBytes.get(peer).first;
}
public long peerTx(final Key peer) {
if (!peerBytes.containsKey(peer))
return 0;
return peerBytes.get(peer).second;
}
public long totalRx() {
long rx = 0;
for (final Pair<Long, Long> val : peerBytes.values()) {
rx += val.first;
}
return rx;
}
public long totalTx() {
long tx = 0;
for (final Pair<Long, Long> val : peerBytes.values()) {
tx += val.second;
}
return tx;
}
}
@@ -0,0 +1,46 @@
/*
* Copyright © 2020 WireGuard LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.wireguard.android.backend;
import java.util.regex.Pattern;
/**
* Represents a WireGuard tunnel.
*/
public interface Tunnel {
enum State {
DOWN,
TOGGLE,
UP;
public static State of(final boolean running) {
return running ? UP : DOWN;
}
}
int NAME_MAX_LENGTH = 15;
Pattern NAME_PATTERN = Pattern.compile("[a-zA-Z0-9_=+.-]{1,15}");
static boolean isNameInvalid(final CharSequence name) {
return !NAME_PATTERN.matcher(name).matches();
}
/**
* Get the name of the tunnel, which should always pass the !isNameInvalid test.
*
* @return The name of the tunnel.
*/
String getName();
/**
* React to a change in state of the tunnel. Should only be directly called by Backend.
*
* @param newState The new state of the tunnel.
* @return The new state of the tunnel.
*/
void onStateChange(State newState);
}
@@ -0,0 +1,158 @@
/*
* Copyright © 2017-2019 WireGuard LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.wireguard.android.backend;
import androidx.annotation.Nullable;
import android.content.Context;
import android.util.Log;
import com.wireguard.android.backend.BackendException.Reason;
import com.wireguard.android.backend.Tunnel.State;
import com.wireguard.android.util.RootShell;
import com.wireguard.android.util.ToolsInstaller;
import com.wireguard.config.Config;
import com.wireguard.crypto.Key;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.HashMap;
import java9.util.stream.Collectors;
import java9.util.stream.Stream;
/**
* WireGuard backend that uses {@code wg-quick} to implement tunnel configuration.
*/
public final class WgQuickBackend implements Backend {
private static final String TAG = "WireGuard/" + WgQuickBackend.class.getSimpleName();
private final RootShell rootShell;
private final ToolsInstaller toolsInstaller;
private final File localTemporaryDir;
private final Map<Tunnel, Config> runningConfigs = new HashMap<>();
public WgQuickBackend(final Context context, final RootShell rootShell, final ToolsInstaller toolsInstaller) {
localTemporaryDir = new File(context.getCacheDir(), "tmp");
this.rootShell = rootShell;
this.toolsInstaller = toolsInstaller;
}
@Override
public Set<String> getRunningTunnelNames() {
final List<String> output = new ArrayList<>();
// Don't throw an exception here or nothing will show up in the UI.
try {
toolsInstaller.ensureToolsAvailable();
if (rootShell.run(output, "wg show interfaces") != 0 || output.isEmpty())
return Collections.emptySet();
} catch (final Exception e) {
Log.w(TAG, "Unable to enumerate running tunnels", e);
return Collections.emptySet();
}
// wg puts all interface names on the same line. Split them into separate elements.
return Stream.of(output.get(0).split(" ")).collect(Collectors.toUnmodifiableSet());
}
@Override
public State getState(final Tunnel tunnel) {
return getRunningTunnelNames().contains(tunnel.getName()) ? State.UP : State.DOWN;
}
@Override
public Statistics getStatistics(final Tunnel tunnel) {
final Statistics stats = new Statistics();
final Collection<String> output = new ArrayList<>();
try {
if (rootShell.run(output, String.format("wg show '%s' transfer", tunnel.getName())) != 0)
return stats;
} catch (final Exception ignored) {
return stats;
}
for (final String line : output) {
final String[] parts = line.split("\\t");
if (parts.length != 3)
continue;
try {
stats.add(Key.fromBase64(parts[0]), Long.parseLong(parts[1]), Long.parseLong(parts[2]));
} catch (final Exception ignored) {
}
}
return stats;
}
@Override
public String getVersion() throws Exception {
final List<String> output = new ArrayList<>();
if (rootShell.run(output, "cat /sys/module/wireguard/version") != 0 || output.isEmpty())
throw new BackendException(Reason.UNKNOWN_KERNEL_MODULE_NAME);
return output.get(0);
}
@Override
public State setState(final Tunnel tunnel, State state, @Nullable final Config config) throws Exception {
final State originalState = getState(tunnel);
final Config originalConfig = runningConfigs.get(tunnel);
if (state == State.TOGGLE)
state = originalState == State.UP ? State.DOWN : State.UP;
if ((state == State.UP && originalState == State.UP && originalConfig != null && originalConfig == config) ||
(state == State.DOWN && originalState == State.DOWN))
return originalState;
if (state == State.UP) {
toolsInstaller.ensureToolsAvailable();
if (originalState == State.UP)
setStateInternal(tunnel, originalConfig == null ? config : originalConfig, State.DOWN);
try {
setStateInternal(tunnel, config, State.UP);
} catch(final Exception e) {
if (originalState == State.UP && originalConfig != null)
setStateInternal(tunnel, originalConfig, State.UP);
throw e;
}
} else if (state == State.DOWN) {
setStateInternal(tunnel, originalConfig == null ? config : originalConfig, State.DOWN);
}
return state;
}
private void setStateInternal(final Tunnel tunnel, @Nullable final Config config, final State state) throws Exception {
Log.i(TAG, "Bringing tunnel " + tunnel.getName() + " " + state);
Objects.requireNonNull(config, "Trying to set state up with a null config");
final File tempFile = new File(localTemporaryDir, tunnel.getName() + ".conf");
try (final FileOutputStream stream = new FileOutputStream(tempFile, false)) {
stream.write(config.toWgQuickString().getBytes(StandardCharsets.UTF_8));
}
String command = String.format("wg-quick %s '%s'",
state.toString().toLowerCase(Locale.ENGLISH), tempFile.getAbsolutePath());
if (state == State.UP)
command = "cat /sys/module/wireguard/version && " + command;
final int result = rootShell.run(null, command);
// noinspection ResultOfMethodCallIgnored
tempFile.delete();
if (result != 0)
throw new BackendException(Reason.WG_QUICK_CONFIG_ERROR_CODE, result);
if (state == State.UP)
runningConfigs.put(tunnel, config);
else
runningConfigs.remove(tunnel);
tunnel.onStateChange(state);
}
}