HevSocks5Tunnel Documentation

repository·main·Indexed 23 days ago

https://github.com/heiher/hev-socks5-tunnel

A lightweight, high-performance tun2socks tool that creates a tunnel over a Socks5 proxy, supporting IPv4, IPv6, and redirection of TCP and UDP traffic. It provides build instructions for Unix, Android, iOS, macOS, and Windows, as well as configuration guides via YAML and Docker Compose. The documentation includes a C API reference, JNI for Android, and detailed integration guides for the Wintun network adapter on Windows.

Tokens
5K
Snippets
10
Records
19
Agent score
34%

What's inside HevSocks5Tunnel

  1. Create and start a Wintun adapter session

    main

    Wintun operation follows a lifecycle of creating an adapter, configuring it, and starting a session. Adapters require a name (e.g., L"OfficeNet"), a type (e.g., L"Wintun"), and a fixed GUID.

    To start a session, use WintunStartSession with the adapter handle and a ring size (e.g., 0x400000).

  2. Build HevSocks5Tunnel for various platforms

    main

    You can build HevSocks5Tunnel from source for multiple operating systems using make or platform-specific scripts.

    Unix

    git clone --recursive https://github.com/heiher/hev-socks5-tunnel
    cd hev-socks5-tunnel
    make

    Android

    Requires NDK.

    mkdir hev-socks5-tunnel
    cd hev-socks5-tunnel
    git clone --recursive https://github.com/heiher/hev-socks5-tunnel jni
    ndk-build

    iOS and macOS

    Generates HevSocks5Tunnel.xcframework.

    git clone --recursive https://github.com/heiher/hev-socks5-tunnel
    cd hev-socks5-tunnel
    ./build-apple.sh

    Windows (MSYS2)

    export MSYS=winsymlinks:native
    git clone --recursive https://github.com/heiher/hev-socks5-tunnel
    cd hev-socks5-tunnel
    make

    Libraries

    To build as a static or shared library:

    git clone --recursive https://github.com/heiher/hev-socks5-tunnel
    cd hev-socks5-tunnel
    
    # Static library
    make static
    
    # Shared library
    make shared
    git clone --recursive https://github.com/heiher/hev-socks5-tunnel
    cd hev-socks5-tunnel
    make
  3. Run HevSocks5Tunnel on Linux

    main

    To run the tunnel on Linux, you must configure routing to bypass the upstream proxy and route traffic through the tun interface.

    Note: This example assumes socks5.mark is set to 438 in your config and the interface is tun0.

    1. Start the binary with your config.
    2. Disable reverse path filter.
    3. Add routing rules to bypass the proxy server.
    4. Route other traffic through the tunnel.
    # Set socks5.mark = 438
    bin/hev-socks5-tunnel conf/main.yml
    
    # Disable reverse path filter
    sudo sysctl -w net.ipv4.conf.all.rp_filter=0
    sudo sysctl -w net.ipv4.conf.tun0.rp_filter=0
    
    # Bypass upstream socks5 server
    sudo ip rule add fwmark 438 lookup main pref 10
    sudo ip -6 rule add fwmark 438 lookup main pref 10
    
    # Route others
    sudo ip route add default dev tun0 table 20
    sudo ip rule add lookup 20 pref 20
    sudo ip -6 route add default dev tun0 table 20
    sudo ip -6 rule add lookup 20 pref 20
  4. Run HevSocks5Tunnel on FreeBSD/macOS

    main

    On FreeBSD or macOS, you need to bypass the proxy server and then change the default gateway to the tunnel interface.

    Assumptions:

    • Socks5 server: 10.0.0.1
    • Default gateway: 10.0.2.2
    • Interface: tun0
    # Bypass upstream socks5 server
    sudo route add -net 10.0.0.1/32 10.0.2.2
    
    # Route others
    sudo route change -inet default -interface tun0
    sudo route change -inet6 default -interface tun0
  5. Run HevSocks5Tunnel on Windows

    main

    On Windows, use the route command to bypass the proxy and redirect traffic to the tunnel index.

    Assumptions:

    • Socks5 server: 10.0.0.1
    • Default gateway: 10.0.2.2
    • Tunnel index: tun-index
    # Bypass upstream socks5 server
    route add 10.0.0.1/32 10.0.2.2
    
    # Route others
    route change 0.0.0.0/0 0.0.0.0 if tun-index
    route change ::/0 :: if tun-index
  6. Integrate Wintun into a C/C++ project

    main

    To use Wintun in your project:

    1. Copy the wintun.h header file into your project directory.
    2. Dynamically load wintun.dll at runtime using the Windows API functions LoadLibraryEx() and GetProcAddress().
    3. Use the typedefs provided in wintun.h to resolve the function pointers.

    For a ready-to-use implementation of the initialization logic, you can copy the InitializeWintun function from the official example.c source.

  7. Configure HevSocks5Tunnel via YAML

    main

    The tunnel is configured using a YAML file. Key configuration sections include:

    • tunnel: Defines the virtual interface (name, mtu), IP addresses (ipv4, ipv6), and ICMP behavior (icmp).
    • socks5: Defines the proxy server connection (address, port), UDP relay mode (udp), and authentication (username, password).
    • mapdns: (Optional) Configures DNS mapping.
    • misc: Tuning parameters for performance and memory, such as task-stack-size, tcp-buffer-size, and max-session-count.

    For low-memory systems (like iOS), it is recommended to reduce task-stack-size, tcp-buffer-size, and max-session-count to prevent OOM issues.

    tunnel:
      name: tun0
      mtu: 8500
      multi-queue: false
      ipv4: 198.18.0.1
      ipv6: 'fc00::1'
      icmp: 'off'
    
    socks5:
      port: 1080
      address: 127.0.0.1
      udp: 'udp'
    
    misc:
      task-stack-size: 24576
      tcp-buffer-size: 4096
      max-session-count: 1200
  8. Run HevSocks5Tunnel via Docker Compose

    main

    You can run the tunnel in a Docker container. The tun service requires NET_ADMIN capabilities and access to /dev/net/tun. The client service uses network_mode: "service:tun" to route its traffic through the tunnel container.

    version: "3.9"
    
    services:
      client:
        image: alpine:latest # just for network testing
        tty: true # you can test network in terminal
        depends_on:
          tun:
            condition: service_healthy
        network_mode: "service:tun"
    
      tun:
        image: ghcr.io/heiher/hev-socks5-tunnel:latest # `latest` for the latest published version; `nightly` for the latest source build; `vX.Y.Z` for the specific version 
        cap_add:
          - NET_ADMIN # needed
        devices:
          - /dev/net/tun:/dev/net/tun # needed
        environment:
          TUN: tun0 # optional, tun interface name, default `tun0`
          MTU: 8500 # optional, MTU is MTU, default `8500`
          IPV4: 198.18.0.1 # optional, tun interface ip, default `198.18.0.1`
          IPV6: fc00::1 # optional, tun interface ip
          ICMP: off # optional, ICMP Echo mode, default `off`, other option `reply`
          TABLE: 20 # optional, ip route table id, default `20`
          MARK: 438 # optional, ip route rule mark, dec or hex format, default `438`
          SOCKS5_ADDR: a.b.c.d # socks5 proxy server address
          SOCKS5_PORT: 1080 # socks5 proxy server port
          SOCKS5_USERNAME: user # optional, socks5 proxy username, only set when need to auth
          SOCKS5_PASSWORD: pass # optional, socks5 proxy password, only set when need to auth
          SOCKS5_UDP_MODE: udp # optional, UDP relay mode, default `udp`, other option `tcp`
          SOCKS5_UDP_ADDR: a.b.c.d # optional, override the UDP address provided by the Socks5 server
          CONFIG_ROUTES: 1 # optional, set 0 to ignore TABLE, IPV4_INCLUDED_ROUTES and IPV4_EXCLUDED_ROUTES, with MARK defaults to 0
          IPV4_INCLUDED_ROUTES: 0.0.0.0/0 # optional, demo means proxy all traffic. for multiple network segments, join with `,` or `\n`
          IPV4_EXCLUDED_ROUTES: a.b.c.d # optional, demo means exclude traffic from the proxy itself. for multiple network segments, join with `,` or `\n`
          LOG_LEVEL: warn # optional, default `warn`, other option `debug`/`info`/`error`
        dns:
          - 8.8.8.8
  9. Send packets using Wintun

    main

    To send data through the tunnel, use a two-step process:

    1. Allocate a buffer using WintunAllocateSendPacket.
    2. Copy your data into that buffer and commit it using WintunSendPacket.

    If WintunAllocateSendPacket returns NULL, check GetLastError(). If it equals ERROR_BUFFER_OVERFLOW, the ring is full and you should consider dropping the packet or retrying later.

    BYTE *OutgoingPacket = WintunAllocateSendPacket(Session, PacketDataSize);
    if (OutgoingPacket)
    {
        memcpy(OutgoingPacket, PacketData, PacketDataSize);
        WintunSendPacket(Session, OutgoingPacket);
    }
    else if (GetLastError() != ERROR_BUFFER_OVERFLOW) // Silently drop packets if the ring is full
        Log(L"Packet write failed");
  10. Manage Wintun adapters

    main

    Wintun adapters represent the virtual network interfaces. You can create new adapters, open existing ones, or close them to release resources.

    • Create an adapter: Use WintunCreateAdapter to create a new interface. You must provide a Name, a TunnelType, and an optional RequestedGUID. If RequestedGUID is NULL, a random GUID is chosen.
    • Open an adapter: Use WintunOpenAdapter to access an existing interface by its Name.
    • Close an adapter: Use WintunCloseAdapter to release the handle. If the adapter was created via WintunCreateAdapter, this will also remove the adapter from the system.
    • Get LUID: Use WintunGetAdapterLuid to retrieve the adapter's Locally Unique Identifier (LUID).
  11. Send packets via a Wintun session

    main

    To transmit network traffic into the tunnel:

    1. Allocate memory: Call WintunAllocateSendPacket with the desired PacketSize. The size must be $\le$ WINTUN_MAX_IP_PACKET_SIZE (0xFFFF).
    2. Fill data: Copy your IPv4 or IPv6 packet data into the returned memory buffer.
    3. Send packet: Call WintunSendPacket with the buffer. This releases the internal buffer.

    Important: While WintunSendPacket is thread-safe, the order in which you call WintunAllocateSendPacket defines the actual packet sending order. The packet is not guaranteed to be sent immediately upon calling WintunSendPacket.