Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(client/linux): revamp the Linux VPN routing logic #2291

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions client/electron/debian/after_install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,22 @@

# Dependencies:
# - libcap2-bin: setcap
# - patchelf: patchelf

set -eux

# Capabilitites will disable LD_LIBRARY_PATH, and $ORIGIN evaluation in binary's
# rpath. So we need to set the rpath to an absolute path. (for libffmpeg.so)
# This command will also reset capabilitites, so we need to run this before setcap.
/usr/bin/patchelf --add-rpath /opt/Outline /opt/Outline/Outline

# Grant specific capabilities so Outline can run without root permisssion
# - cap_net_admin: configure network interfaces, set up routing tables, etc.
# - cap_dac_override: modify network configuration files owned by root
/usr/sbin/setcap cap_net_admin,cap_dac_override+eip /opt/Outline/Outline

# From electron's hint:
# > The SUID sandbox helper binary was found, but is not configured correctly.
# > Rather than run without sandboxing I'm aborting now. You need to make sure
# > that /opt/Outline/chrome-sandbox is owned by root and has mode 4755.
/usr/bin/chmod 4755 /opt/Outline/chrome-sandbox
7 changes: 1 addition & 6 deletions client/electron/electron-builder.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"deb": {
"depends": [
"gconf2", "gconf-service", "libnotify4", "libappindicator1", "libxtst6", "libnss3",
"libcap2-bin"
"libcap2-bin", "patchelf"
],
"afterInstall": "client/electron/debian/after_install.sh"
},
Expand All @@ -36,11 +36,6 @@
"icon": "client/electron/icons/png",
"maintainer": "Jigsaw LLC",
"target": [{
"arch": [
"x64"
],
"target": "AppImage"
}, {
"arch": "x64",
"target": "deb"
}]
Expand Down
6 changes: 3 additions & 3 deletions client/electron/go_plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {pathToBackendLibrary} from './app_paths';

let invokeGoAPIFunc: Function | undefined;

export type GoApiName = 'FetchResource';
export type GoApiName = 'FetchResource' | 'EstablishVPN' | 'CloseVPN';

/**
* Calls a Go function by invoking the `InvokeGoAPI` function in the native backend library.
Expand Down Expand Up @@ -58,9 +58,9 @@ export async function invokeGoApi(
);
}

console.debug('[Backend] - calling InvokeGoAPI ...');
console.debug(`[Backend] - calling InvokeGoAPI "${api}" ...`);
const result = await invokeGoAPIFunc(api, input);
console.debug('[Backend] - InvokeGoAPI returned', result);
console.debug(`[Backend] - GoAPI ${api} returned`, result);
if (result.ErrorJson) {
throw Error(result.ErrorJson);
}
Expand Down
22 changes: 17 additions & 5 deletions client/electron/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {GoApiName, invokeGoApi} from './go_plugin';
import {GoVpnTunnel} from './go_vpn_tunnel';
import {installRoutingServices, RoutingDaemon} from './routing_service';
import {TunnelStore} from './tunnel_store';
import {closeVpn, establishVpn} from './vpn_service';
import {VpnTunnel} from './vpn_tunnel';
import * as config from '../src/www/app/outline_server_repository/config';
import {
Expand All @@ -56,7 +57,7 @@ declare const APP_VERSION: string;
// Run-time environment variables:
const debugMode = process.env.OUTLINE_DEBUG === 'true';

const isLinux = os.platform() === 'linux';
const IS_LINUX = os.platform() === 'linux';

// Used for the auto-connect feature. There will be a tunnel in store
// if the user was connected at shutdown.
Expand Down Expand Up @@ -158,7 +159,7 @@ function setupWindow(): void {
//
// The ideal solution would be: either electron-builder supports the app icon; or we add
// dpi-aware features to this app.
if (isLinux) {
if (IS_LINUX) {
mainWindow.setIcon(
path.join(
app.getAppPath(),
Expand Down Expand Up @@ -251,7 +252,7 @@ function updateTray(status: TunnelStatus) {
{type: 'separator'} as MenuItemConstructorOptions,
{label: localizedStrings['quit'], click: quitApp},
];
if (isLinux) {
if (IS_LINUX) {
// Because the click event is never fired on Linux, we need an explicit open option.
menuTemplate = [
{
Expand Down Expand Up @@ -309,7 +310,7 @@ function interceptShadowsocksLink(argv: string[]) {
async function setupAutoLaunch(request: StartRequestJson): Promise<void> {
try {
await tunnelStore.save(request);
if (isLinux) {
if (IS_LINUX) {
if (process.env.APPIMAGE) {
const outlineAutoLauncher = new autoLaunch({
name: 'OutlineClient',
Expand All @@ -327,7 +328,7 @@ async function setupAutoLaunch(request: StartRequestJson): Promise<void> {

async function tearDownAutoLaunch() {
try {
if (isLinux) {
if (IS_LINUX) {
const outlineAutoLauncher = new autoLaunch({
name: 'OutlineClient',
});
Expand Down Expand Up @@ -368,6 +369,12 @@ async function createVpnTunnel(

// Invoked by both the start-proxying event handler and auto-connect.
async function startVpn(request: StartRequestJson, isAutoConnect: boolean) {
if (IS_LINUX) {
await establishVpn(request);
setUiTunnelStatus(TunnelStatus.CONNECTED, request.id);
return;
}

if (currentTunnel) {
throw new Error('already connected');
}
Expand Down Expand Up @@ -401,6 +408,11 @@ async function startVpn(request: StartRequestJson, isAutoConnect: boolean) {

// Invoked by both the stop-proxying event and quit handler.
async function stopVpn() {
if (IS_LINUX) {
await Promise.all([closeVpn(), tearDownAutoLaunch()]);
return;
}

if (!currentTunnel) {
return;
}
Expand Down
45 changes: 45 additions & 0 deletions client/electron/vpn_service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Copyright 2024 The Outline Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import {invokeGoApi} from './go_plugin';
import {StartRequestJson} from '../src/www/app/outline_server_repository/vpn';

interface VpnConfig {
interfaceName: string;
ipAddress: string;
dnsServers: string[];
routingTableId: number;
protectionMark: number;
transport: string;
}

export async function establishVpn(request: StartRequestJson) {
const config: VpnConfig = {
interfaceName: 'outline-tun0',
ipAddress: '10.0.85.5',
dnsServers: ['8.8.4.4'],
routingTableId: 13579,
protectionMark: 24680,
transport: JSON.stringify(request.config.transport),
};
const connectionJson = await invokeGoApi(
'EstablishVPN',
JSON.stringify(config)
);
console.info(JSON.parse(connectionJson));
}

export async function closeVpn(): Promise<void> {
await invokeGoApi('CloseVPN', '');
}
30 changes: 18 additions & 12 deletions client/go/outline/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,23 +42,29 @@ type NewClientResult struct {

// NewClient creates a new Outline client from a configuration string.
func NewClient(transportConfig string) *NewClientResult {
config, err := parseConfigFromJSON(transportConfig)
client, err := NewClientWithBaseDialers(transportConfig, net.Dialer{KeepAlive: -1}, net.Dialer{})
return &NewClientResult{
Client: client,
Error: platerrors.ToPlatformError(err),
}
}

func NewClientWithBaseDialers(transportConfig string, tcpDialer, udpDialer net.Dialer) (*Client, error) {
conf, err := parseConfigFromJSON(transportConfig)
if err != nil {
return &NewClientResult{Error: platerrors.ToPlatformError(err)}
return nil, err
}
prefixBytes, err := ParseConfigPrefixFromString(config.Prefix)
prefixBytes, err := ParseConfigPrefixFromString(conf.Prefix)
if err != nil {
return &NewClientResult{Error: platerrors.ToPlatformError(err)}
return nil, err
}

client, err := newShadowsocksClient(config.Host, int(config.Port), config.Method, config.Password, prefixBytes)
return &NewClientResult{
Client: client,
Error: platerrors.ToPlatformError(err),
}
return newShadowsocksClient(conf.Host, int(conf.Port), conf.Method, conf.Password, prefixBytes, tcpDialer, udpDialer)
}

func newShadowsocksClient(host string, port int, cipherName, password string, prefix []byte) (*Client, error) {
func newShadowsocksClient(
host string, port int, cipherName, password string, prefix []byte, tcpDialer, udpDialer net.Dialer,
) (*Client, error) {
if err := validateConfig(host, port, cipherName, password); err != nil {
return nil, err
}
Expand All @@ -74,7 +80,7 @@ func newShadowsocksClient(host string, port int, cipherName, password string, pr

// We disable Keep-Alive as per https://datatracker.ietf.org/doc/html/rfc1122#page-101, which states that it should only be
// enabled in server applications. This prevents the device from unnecessarily waking up to send keep alives.
streamDialer, err := shadowsocks.NewStreamDialer(&transport.TCPEndpoint{Address: proxyAddress, Dialer: net.Dialer{KeepAlive: -1}}, cryptoKey)
streamDialer, err := shadowsocks.NewStreamDialer(&transport.TCPEndpoint{Address: proxyAddress, Dialer: tcpDialer}, cryptoKey)
if err != nil {
return nil, platerrors.PlatformError{
Code: platerrors.SetupTrafficHandlerFailed,
Expand All @@ -88,7 +94,7 @@ func newShadowsocksClient(host string, port int, cipherName, password string, pr
streamDialer.SaltGenerator = shadowsocks.NewPrefixSaltGenerator(prefix)
}

packetListener, err := shadowsocks.NewPacketListener(&transport.UDPEndpoint{Address: proxyAddress}, cryptoKey)
packetListener, err := shadowsocks.NewPacketListener(&transport.UDPEndpoint{Address: proxyAddress, Dialer: udpDialer}, cryptoKey)
if err != nil {
return nil, platerrors.PlatformError{
Code: platerrors.SetupTrafficHandlerFailed,
Expand Down
24 changes: 24 additions & 0 deletions client/go/outline/electron/go_plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,19 @@ const (
// - Input: the URL string of the resource to fetch
// - Output: the content in raw string of the fetched resource
FetchResourceAPI = "FetchResource"

// EstablishVPNAPI initiates a VPN connection and directs all network traffic through Outline.
//
// - Input: a JSON string of [VPNConfig].
// - Output: a JSON string of [VPNConnection].
EstablishVPNAPI = "EstablishVPN"

// CloseVPNAPI closes an existing VPN connection and restores network traffic to the default
// network interface.
//
// - Input: null
// - Output: null
CloseVPNAPI = "CloseVPN"
)

// InvokeGoAPI is the unified entry point for TypeScript to invoke various Go functions.
Expand All @@ -69,6 +82,17 @@ func InvokeGoAPI(api *C.char, input *C.char) C.InvokeGoAPIResult {
ErrorJson: marshalCGoErrorJson(platerrors.ToPlatformError(res.Error)),
}

case EstablishVPNAPI:
res, err := EstablishVPN(C.GoString(input))
return C.InvokeGoAPIResult{
Output: newCGoString(res),
ErrorJson: marshalCGoErrorJson(err),
}

case CloseVPNAPI:
err := CloseVPN()
return C.InvokeGoAPIResult{ErrorJson: marshalCGoErrorJson(err)}

default:
err := &platerrors.PlatformError{
Code: platerrors.InternalError,
Expand Down
98 changes: 98 additions & 0 deletions client/go/outline/electron/outline_device.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// Copyright 2024 The Outline Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
"log/slog"
"net"
"syscall"

"github.com/Jigsaw-Code/outline-apps/client/go/outline"
"github.com/Jigsaw-Code/outline-apps/client/go/outline/platerrors"
"github.com/Jigsaw-Code/outline-sdk/network"
"github.com/Jigsaw-Code/outline-sdk/network/dnstruncate"
"github.com/Jigsaw-Code/outline-sdk/network/lwip2transport"
)

type outlineDevice struct {
network.IPDevice
network.DelegatePacketProxy

remote, fallback network.PacketProxy
}

func configureOutlineDevice(transportConfig string, sockmark int) (*outlineDevice, *platerrors.PlatformError) {
var err error
dev := &outlineDevice{}

tcpDialer := net.Dialer{
Control: func(network, address string, c syscall.RawConn) error {
return c.Control(func(fd uintptr) {
slog.Debug("Setting SO_MARK to TCP connection", "SO_MARK", sockmark)
syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, sockmark)

Check failure on line 44 in client/go/outline/electron/outline_device.go

View workflow job for this annotation

GitHub Actions / Windows Debug Build

cannot use int(fd) (value of type int) as syscall.Handle value in argument to syscall.SetsockoptInt

Check failure on line 44 in client/go/outline/electron/outline_device.go

View workflow job for this annotation

GitHub Actions / Windows Debug Build

undefined: syscall.SO_MARK

Check failure on line 44 in client/go/outline/electron/outline_device.go

View workflow job for this annotation

GitHub Actions / Windows Debug Build

cannot use int(fd) (value of type int) as syscall.Handle value in argument to syscall.SetsockoptInt

Check failure on line 44 in client/go/outline/electron/outline_device.go

View workflow job for this annotation

GitHub Actions / Windows Debug Build

undefined: syscall.SO_MARK
})
},
}
udpDialer := net.Dialer{
Control: func(network, address string, c syscall.RawConn) error {
return c.Control(func(fd uintptr) {
slog.Debug("Setting SO_MARK to UDP connection", "SO_MARK", sockmark)
syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, sockmark)

Check failure on line 52 in client/go/outline/electron/outline_device.go

View workflow job for this annotation

GitHub Actions / Windows Debug Build

cannot use int(fd) (value of type int) as syscall.Handle value in argument to syscall.SetsockoptInt

Check failure on line 52 in client/go/outline/electron/outline_device.go

View workflow job for this annotation

GitHub Actions / Windows Debug Build

undefined: syscall.SO_MARK

Check failure on line 52 in client/go/outline/electron/outline_device.go

View workflow job for this annotation

GitHub Actions / Windows Debug Build

cannot use int(fd) (value of type int) as syscall.Handle value in argument to syscall.SetsockoptInt

Check failure on line 52 in client/go/outline/electron/outline_device.go

View workflow job for this annotation

GitHub Actions / Windows Debug Build

undefined: syscall.SO_MARK
})
},
}

c, err := outline.NewClientWithBaseDialers(transportConfig, tcpDialer, udpDialer)
if err != nil {
return nil, platerrors.ToPlatformError(err)
}

dev.remote, err = network.NewPacketProxyFromPacketListener(c.PacketListener)
if err != nil {
return nil, &platerrors.PlatformError{
Code: platerrors.SetupTrafficHandlerFailed,
Message: "failed to create datagram handler",
Cause: platerrors.ToPlatformError(err),
}
}

if dev.fallback, err = dnstruncate.NewPacketProxy(); err != nil {
return nil, &platerrors.PlatformError{
Code: platerrors.SetupTrafficHandlerFailed,
Message: "failed to create datagram handler for DNS fallback",
Cause: platerrors.ToPlatformError(err),
}
}

if dev.DelegatePacketProxy, err = network.NewDelegatePacketProxy(dev.remote); err != nil {
return nil, &platerrors.PlatformError{
Code: platerrors.SetupTrafficHandlerFailed,
Message: "failed to combine datagram handlers",
Cause: platerrors.ToPlatformError(err),
}
}

dev.IPDevice, err = lwip2transport.ConfigureDevice(c.StreamDialer, dev)
if err != nil {
return nil, &platerrors.PlatformError{
Code: platerrors.SetupTrafficHandlerFailed,
Message: "failed to configure network stack",
Cause: platerrors.ToPlatformError(err),
}
}

slog.Info("successfully configured outline device")
return dev, nil
}
Loading
Loading