pseudotcp

package module
v0.0.0-...-acc069f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 28, 2025 License: BSD-3-Clause Imports: 21 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

PseudoTCP

Lint and Test GoDoc Go Report Card

A lightweight partial TCP stack for packet to stream interposition in Go

📖 What is PseudoTCP?

Many modern tunneling protocols, including IETF MASQUE, operate at a higher level of abstraction, dealing with flows rather than individual packets. However, this mismatch between the Android VPN interface and flow-based protocols poses a significant challenge for deploying MASQUE on Android devices.

PseudoTCP is an interposition stack that enables the use of unmodified applications and unmodified Android devices with a MASQUE-enabled Android VPN. It transparently handles translation between packets and flows as needed, making it possible for ordinary users to use a MASQUE-based Android VPN application as they would any other VPN or circumvention tool. The traffic is tunneled using our MASQUE stack as HTTPS traffic via the MASQUE-enabled infrastructure.

This project integrates with our INVISV masque stack, which is an implementation of the IETF MASQUE tunneling protocol, written in Go. INVISV masque provides the client-side functionality needed for running a Multi-Party Relay service to protect users' network privacy.

masque enables application code on the client to tunnel bytestream (TCP) and packet (UDP) traffic via a MASQUE-supporting proxy, such as the MASQUE service operated by Fastly.

🚀 Getting Started

Prerequisites
  • Go 1.23 or higher
  • Docker (for running integration tests)

🔧 Usage

PseudoTCP is intended to be used as part of an Android VPN app. We provide:

  1. A sample Android VPN app that demonstrates how to use this stack
  2. An example binary that binds the pseudotcp stack to a TUN interface for demonstration and evaluation

🧪 Testing

We have comprehensive integration tests that:

To run the integration tests:

$ go test -v ./tests/integration
Linting

We use golangci-lint for code quality checks. See the install instructions for comprehensive directions for your platform.

# Run linting
$ golangci-lint run

📊 Benchmarking

We include benchmarks that evaluate the performance of TCP connections over our stack with HTTP GET requests of various sizes, comparing them to direct HTTP GET requests:

# Run benchmarks
$ go test -bench=. -run='^#' -benchtime=20x ./tests/integration > bench-results.txt

# Analyze results
$ benchstat ./bench-results.txt

Sample benchmark results:

goos: linux
goarch: amd64
pkg: github.com/invisv-privacy/pseudotcp/tests/integration
cpu: Intel(R) Core(TM) i7-8665U CPU @ 1.90GHz
                                                  │ ./bench.txt  │
                                                  │    sec/op    │
Throughput/with-pseudotcp-payload-10000B-8          602.7µ ± ∞ ¹
Throughput/without-pseudotcp-payload-10000B-8       199.0µ ± ∞ ¹
Throughput/with-pseudotcp-payload-100000B-8         1.022m ± ∞ ¹
Throughput/without-pseudotcp-payload-100000B-8      665.0µ ± ∞ ¹
Throughput/with-pseudotcp-payload-1000000B-8        5.817m ± ∞ ¹
Throughput/without-pseudotcp-payload-1000000B-8     5.080m ± ∞ ¹
Throughput/with-pseudotcp-payload-10000000B-8       45.71m ± ∞ ¹
Throughput/without-pseudotcp-payload-10000000B-8    36.35m ± ∞ ¹
Throughput/with-pseudotcp-payload-100000000B-8      934.4m ± ∞ ¹
Throughput/without-pseudotcp-payload-100000000B-8   368.4m ± ∞ ¹
geomean                                             8.202m
¹ need >= 6 samples for confidence interval at level 0.95

Note: "with pseudotcp" vs "without pseudotcp" is an unfavorable comparison as "with pseudotcp" includes the overhead of not only our pseudotcp stack, but also the MASQUE connection overhead as well as the h2o proxy container and associated docker networking traversal.

📄 License

This project is licensed under the BSD 3-Clause License - see the LICENSE file.

Documentation

Index

Constants

View Source
const (
	// PROTO_ICMP is the IP protocol number for ICMP
	PROTO_ICMP byte = 1
	// PROTO_TCP is the IP protocol number for TCP
	PROTO_TCP byte = 6
	// PROTO_UDP is the IP protocol number for UDP
	PROTO_UDP byte = 17
)

IP protocol numbers for L4 headers.

View Source
const (
	IP_VERSION_IHL int = 0
	IP_LEN         int = 2
	IP_TTL         int = 8
	IP_PROTO       int = 9
	IP_CHECK       int = 10
	IP_SRC         int = 12
	IP_DST         int = 16
)

Byte offsets for IPv4 header fields.

View Source
const (
	TCP_SRC_PORT int = 0
	TCP_DST_PORT int = 2
	TCP_SEQ_NUM  int = 4
	TCP_ACK_NUM  int = 8
	TCP_DATA_OFF int = 12
	TCP_FLAGS    int = 13
	TCP_WINDOW   int = 14
	TCP_CHECK    int = 16
	TCP_OPTIONS  int = 20
)

Byte offsets for TCP header fields.

View Source
const (
	FLAG_BIT_URG byte = 0x20
	FLAG_BIT_ACK byte = 0x10
	FLAG_BIT_PSH byte = 0x08
	FLAG_BIT_RST byte = 0x04
	FLAG_BIT_SYN byte = 0x02
	FLAG_BIT_FIN byte = 0x01
)

TCP flag bits.

View Source
const (
	UDP_SRC_PORT int = 0
	UDP_DST_PORT int = 2
	UDP_LEN      int = 4
	UDP_CHECK    int = 6
)

Byte offsets for UDP header fields.

View Source
const (
	ICMP_TYPE         int = 0
	ICMP_CODE         int = 1
	ICMP_CHECK        int = 2
	ICMP_NEXT_HOP_MTU     = 6
)

Byte offsets for ICMP header fields.

View Source
const (
	// DEFAULT_IP_HDR_SIZE is the size of a standard IPv4 header
	DEFAULT_IP_HDR_SIZE int = 20
	// DEFAULT_TCP_HDR_SIZE is the size of a standard TCP header
	DEFAULT_TCP_HDR_SIZE int = 20
	// DEFAULT_UDP_HDR_SIZE is the size of a standard UDP header
	DEFAULT_UDP_HDR_SIZE int = 8
	// DEFAULT_ICMP_UNREACHABLE_HDR_SIZE is the size of an ICMP unreachable message header
	DEFAULT_ICMP_UNREACHABLE_HDR_SIZE int = 8
	// SYNACK_SIZE is the total size of a SYN-ACK packet
	SYNACK_SIZE = DEFAULT_IP_HDR_SIZE + DEFAULT_TCP_HDR_SIZE + 4
	// RST_SIZE is the total size of a RST packet
	RST_SIZE = DEFAULT_IP_HDR_SIZE + DEFAULT_TCP_HDR_SIZE
	// ACK_SIZE is the total size of an ACK packet
	ACK_SIZE = DEFAULT_IP_HDR_SIZE + DEFAULT_TCP_HDR_SIZE
	// ICMP_UNREACHABLE_SIZE is the total size of an ICMP unreachable message
	ICMP_UNREACHABLE_SIZE = DEFAULT_IP_HDR_SIZE + DEFAULT_ICMP_UNREACHABLE_HDR_SIZE + (DEFAULT_IP_HDR_SIZE + 8)
)

Header size constants.

View Source
const (
	// TUN_MTU is the Maximum Transmission Unit of the TUN interface we're using, has to match Android.
	TUN_MTU = 32000

	// INTERNET_MTU is the standard Maximum Transmission Unit for Internet connections.
	INTERNET_MTU = 1500

	// DNS_CACHE_TIMEOUT_SECONDS is the time in seconds that DNS responses are cached.
	DNS_CACHE_TIMEOUT_SECONDS = 300

	// DEFAULT_PROXY_PORT is the default port used for proxy connections.
	DEFAULT_PROXY_PORT = "443"
)
View Source
const (
	WAKEUP_PACKET_IP_PORT  string = "10.10.10.10:1234" // Invalid destination for the wakeup packet.
	WAKEUP_PACKET_IP_VALUE byte   = 10
)

Variables

View Source
var DEFAULT_DOH_SERVER_ADDRS = []string{"1.1.1.1:443", "1.0.0.1:443", "1.1.1.2:443", "1.0.0.2:443"}

The default DNS-over-HTTPS server to use for DNS queries.

View Source
var DEFAULT_POPULAR_DNS_NAMES []string = []string{"api.invisv.com"}

Functions

This section is empty.

Types

type DNSResponse

type DNSResponse struct {
	// Answer contains the DNS records returned in the response
	Answer []struct {
		// Name is the domain name for this record
		Name string `json:"name"`
		// Type is the DNS record type (1 for A, 28 for AAAA, etc.)
		Type int `json:"type"`
		// TTL is the time-to-live for this record in seconds
		TTL int `json:"ttl"`
		// Data is the record data (IP address for A/AAAA records, etc.)
		Data string `json:"data"`
	} `json:"Answer"`
}

DNSResponse represents the structure of a DNS-over-HTTPS response in JSON format.

type ProxyClient

type ProxyClient interface {
	// Connect establishes a connection to the proxy server.
	Connect() error

	// CurrentProxyIP returns the IP address of the currently connected proxy.
	CurrentProxyIP() string

	// CreateTCPStream creates a TCP stream to the specified address through the proxy.
	CreateTCPStream(string) (io.ReadWriteCloser, error)

	// CreateUDPStream creates a UDP stream to the specified address through the proxy.
	CreateUDPStream(string) (io.ReadWriteCloser, error)

	// Close terminates the connection to the proxy server.
	Close() error
}

ProxyClient defines the interface for a client that can connect to a proxy server and create TCP and UDP streams through that proxy.

type PseudoTCP

type PseudoTCP struct {
	// contains filtered or unexported fields
}

PseudoTCP is the main structure that handles the interposition between packet-based VPN interfaces and stream-based proxy connections.

func NewPseudoTCP

func NewPseudoTCP(config *PseudoTCPConfig) *PseudoTCP

NewPseudoTCP creates a new PseudoTCP instance with the provided configuration. It initializes internal data structures but does not start processing packets. Call Init() after creating a PseudoTCP instance to start processing.

func (*PseudoTCP) ConfigureProtect

func (t *PseudoTCP) ConfigureProtect(protect SocketProtector)

ConfigureProtect sets up a socket protect function to be used by PseudoTCP. This function is used to prevent VPN traffic from being routed through the VPN itself, which would create a loop. On Android, this typically calls VpnService.protect().

func (*PseudoTCP) CurrentProxyIP

func (t *PseudoTCP) CurrentProxyIP() string

CurrentProxyIP returns the IP of the proxy server we are connected to. If PseudoTCP is not active, returns empty string.

func (*PseudoTCP) Init

func (t *PseudoTCP) Init() error

Init initializes the userspace network stack module. This must be called before any other UserStack function. It sets up internal data structures, connects to the proxy, and initializes the DNS client. Returns an error if initialization fails.

func (*PseudoTCP) ReconnectToProxy

func (t *PseudoTCP) ReconnectToProxy() error

ReconnectToProxy attempts to reconnect to the proxy server. This is useful when the network connection changes, such as when Android detects that a network interface has come back up. It resets all active flows and establishes a new connection to the proxy.

func (*PseudoTCP) ResolveDOHJSON

func (t *PseudoTCP) ResolveDOHJSON(host string) (string, error)

func (*PseudoTCP) Send

func (t *PseudoTCP) Send(packetData []byte)

Send processes an IP packet from the TUN interface. This is the main entry point for packets coming from the device.

func (*PseudoTCP) SetLogger

func (t *PseudoTCP) SetLogger(l *slog.Logger)

SetLogger updates the logger used by PseudoTCP. This can be used to change logging behavior after initialization.

func (*PseudoTCP) Shutdown

func (t *PseudoTCP) Shutdown()

Shutdown gracefully terminates PseudoTCP operation. It closes all active flows and disconnects from the proxy.

func (*PseudoTCP) UserStackIPProcessPacket

func (t *PseudoTCP) UserStackIPProcessPacket(p []byte)

UserStackIPProcessPacket processes an IPv4 packet and emits the generated reply to Linux and/or MASQUE.

type PseudoTCPConfig

type PseudoTCPConfig struct {
	// Logger is the structured logger to use for logging messages.
	// If nil, logging will be discarded.
	Logger *slog.Logger

	// ProxyClient is the client that will be used to connect to the proxy server.
	// This must implement the ProxyClient interface.
	ProxyClient ProxyClient

	// SendPacket is the function that will be called to send packets to the TUN interface.
	SendPacket SendPacket

	// ProhibitDisallowedIPPorts determines whether to block packets to disallowed IP/port combinations.
	// When true, packets to private IP ranges will be blocked with ICMP host unreachable.
	ProhibitDisallowedIPPorts bool
}

PseudoTCPConfig contains the configuration options for creating a new PseudoTCP instance.

type SendPacket

type SendPacket func(packet []byte, length int) error

SendPacket is a function type for sending packets to the TUN interface. It takes a packet buffer and its length, and returns an error if the send fails.

type SocketProtector

type SocketProtector func(fileDescriptor int) error

SocketProtector is a function type that overrides Android's VpnService.protect() It takes a system file descriptor and protects it from being routed through the VPN. This is necessary to prevent loops when the VPN itself needs to make network connections.

type TCPFlow

type TCPFlow struct {
	// contains filtered or unexported fields
}

TCPFlow tracks the state of a virtual TCP connection between Android and the MASQUE proxy.

type UDPFlow

type UDPFlow struct {
	// contains filtered or unexported fields
}

UDPFlow tracks the state of a MASQUE connection to a _destination IP/port_ (different from TCP).

type UDPFlowKey

type UDPFlowKey struct {
	// contains filtered or unexported fields
}

UDPFlowKey keys the activeUDPFlows map with the client (src) IP/port and server (dst) IP/port.

Directories

Path Synopsis
example
tun command
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址