Hysteria 2

repository·master·Indexed 12 days ago

https://github.com/apernet/hysteria

A high-performance, censorship-resistant proxy tool built on a customized QUIC protocol that masquerades as HTTP/3 traffic. It supports multiple proxy modes including SOCKS5, HTTP, TCP/UDP forwarding, TProxy, and TUN, and is optimized for speed over lossy networks.

Tokens
14.7K
Snippets
51
Records
84
Agent score
98%

What's inside Hysteria

  1. Overview of Hysteria 2

    master

    Hysteria is a high-performance, censorship-resistant proxy designed to deliver fast speeds over unreliable and lossy networks. It uses a customized QUIC protocol that masquerades as standard HTTP/3 traffic to evade detection.

    Key Capabilities:

    • Multiple Proxy Modes: Supports SOCKS5, HTTP Proxy, TCP/UDP Forwarding, Linux TProxy, and TUN.
    • Performance: Optimized for high performance on lossy networks via customized QUIC.
    • Censorship Resistance: Mimics standard HTTP/3 traffic.
    • Extensibility: Built-in support for custom authentication, traffic statistics, and access control.
    • Cross-platform: Available for all major platforms and architectures.
  2. How Hysteria 2 Authentication Works

    master

    Authentication occurs during the initial HTTP/3 handshake. A Hysteria client MUST send a specific POST request to the server. If the server validates the credentials, it responds with a unique HTTP status code 233 HyOK.

    Client Authentication Request

    Method: POST
    Path: /auth
    Host: hysteria
    Required Headers:

    • Hysteria-Auth: The authentication credentials.
    • Hysteria-CC-RX: The client's maximum receive rate in bytes per second (use 0 if unknown).
    • Hysteria-Padding: (Optional) A random padding string to obfuscate request patterns.

    Server Authentication Response

    Status Code: 233 HyOK
    Required Headers:

    • Hysteria-UDP: true or false (indicates if the server supports UDP relay).
    • Hysteria-CC-RX: The server's maximum receive rate in bytes per second. Special values:
      • 0: Unlimited bandwidth.
      • auto: The server refuses to provide a value; the client must use its own congestion control.
    • Hysteria-Padding: (Optional) A random padding string.

    Note: If the status code is anything other than 233, the client MUST consider authentication failed and disconnect. To prevent active probing, it is recommended that Hysteria servers host actual content or act as a reverse proxy.

    // Client Request
    POST /auth HTTP/3
    Host: hysteria
    Hysteria-Auth: [your_credentials]
    Hysteria-CC-RX: 1000000
    Hysteria-Padding: [random_string]
    
    // Server Response
    HTTP/3 233 HyOK
    Hysteria-UDP: true
    Hysteria-CC-RX: auto
    Hysteria-Padding: [random_string]
  3. Understand "Salamander" Obfuscation

    master

    The "Salamander" layer is an optional obfuscation mechanism that encapsulates QUIC packets.

    Format

    [8 bytes Salt] + [Payload]

    Algorithm

    1. A random 8-byte salt is generated for each packet.
    2. A hash is calculated: hash = BLAKE2b-256(pre-shared-key + salt).
    3. The payload is obfuscated using XOR: payload[i] ^= hash[i % 32] for every byte in the payload.

    Any packet that fails deobfuscation (invalid hash/salt) MUST be discarded.

  4. Understand the Hysteria 2 Protocol Architecture

    master

    Hysteria 2 is a TCP and UDP proxy built on top of the QUIC transport protocol ([RFC 9000]) using the Unreliable Datagram Extension ([RFC 9221]).

    Key architectural features include:

    • HTTP/3 Masquerading: The server implements a standard HTTP/3 server ([RFC 9114]). To unauthorized observers, Hysteria traffic appears as normal HTTP/3 web traffic. Authentication is performed via a specific HTTP/3 POST request.
    • Multiplexing: TCP connections are handled via new QUIC bidirectional streams, while UDP traffic is encapsulated in QUIC unreliable datagrams.
    • Congestion Control: The protocol allows explicit exchange of upload/download rates via HTTP headers to optimize throughput.
    • Obfuscation: An optional layer called "Salamander" can be used to encapsulate QUIC packets with a salted BLAKE2b-256 hash to further resist detection.
  5. Use Hysteria 2 URIs for configuration

    master

    Hysteria 2 supports a custom URI scheme (hysteria2:// or hy2://) that can be used as the server address in a configuration file. This URI encapsulates the server address, authentication, obfuscation, and TLS settings.

    URI Structure: hysteria2://[user[:password]@]host[:port]/?obfs=[type]&obfs-password=[pass]&sni=[sni]&insecure=[0|1]&pinSHA256=[hash]&ech=[base64_ech]

  6. Configure Hysteria 2 client modes

    master

    The Hysteria client can operate in several modes depending on the configuration provided. You can enable one or multiple modes simultaneously:

    • SOCKS5 proxy: Listens for SOCKS5 connections. Supports username/password authentication and optional UDP disabling.
    • HTTP proxy: Listens for HTTP proxy connections. Supports username/password authentication and custom realm names.
    • TCP forwarding: Forwards specific TCP ports from a local address to a remote address.
    • UDP forwarding: Forwards specific UDP ports from a local address to a remote address with an optional timeout.
    • TCP transparent proxy (TProxy): Uses TProxy to intercept TCP traffic.
    • UDP transparent proxy (TProxy): Uses TProxy to intercept UDP traffic with an optional timeout.
    • TCP redirect: Listens for TCP connections and redirects them.
    • TUN: Creates a TUN interface to provide system-wide proxying.
  7. How Mimic works in Hysteria client

    master

    Mimic is a feature that must be initialized before the first packet is sent to the server. If Mimic is enabled in the client configuration, it must be attached to the client to ensure the server does not see plain UDP traffic and drop the connection.

    Mimic Configuration Options:

    • enabled: Boolean to activate Mimic.
    • interface: The network interface to use.
    • xdpMode: Enables XDP (eXpress Data Path) mode for high-performance packet processing.
    • path: The path used for Mimic.
    • extraArgs: Additional arguments for the Mimic instance.

    Mimic requires a resolved ip:port address (the server address) to function correctly for its filtering mechanism.

  8. Understand the Realm Port Mapping Lifecycle

    master

    The port mapping process follows a specific lifecycle to ensure reliable connectivity:

    1. Initialization: The PortMapper is created using the specified localPort and configuration. If initialization fails, the system logs a warning and continues using only STUN-discovered addresses (non-fatal).
    2. Renewal Loop: Once active, a background loop (realmPortMapLoop) manages the lease. It attempts to renew the mapping at an interval equal to half of the configured lifetime. If the lifetime is non-positive, it defaults to a 1-minute interval.
    3. Recovery: If a renewal fails, the system logs a warning. If a subsequent renewal succeeds, it logs a recovery message.
    4. Cleanup: When the context is cancelled (e.g., the application shuts down), the system attempts to remove the port mapping from the gateway via mapper.Close().
  9. Use MasqTCPServer for protocol masquerading

    master

    The MasqTCPServer struct allows you to run a standard web server (HTTP/HTTPS) alongside your QUIC service. This helps avoid suspicion by making the server appear as a legitimate web server that supports HTTP/3 via the Alt-Svc header.

    When a client connects via HTTP/HTTPS, the server uses the Alt-Svc header to inform the client that the service is also available via QUIC on the specified QUICPort. If ForceHTTPS is enabled, the server will automatically issue a 301 redirect from HTTP to HTTPS.

    server := &masq.MasqTCPServer{
    	QUICPort:   443, // The port where Hysteria/QUIC is running
    	HTTPSPort:  443, // The port for HTTPS
    	Handler:    myHandler, // Your standard http.Handler
    	TLSConfig:  myTLSConfig,
    	ForceHTTPS: true,
    }
    
    // Start the masquerade server
    err := server.ListenAndServeHTTPS(":443")
  10. Initialize a Realm Client

    master

    To interact with the Realm server, you must create a Client instance. You can do this using NewClient with a ClientConfig or NewClientFromAddr if you have an Addr object.

    Configuration Requirements:

    • BaseURL: Must use http or https scheme and include a host.
    • Token: A non-empty authentication token.
    • HTTPClient: An optional *http.Client. If nil, http.DefaultClient is used.
    // Using NewClient
    config := realm.ClientConfig{
        BaseURL:    url.Parse("https://example.com"),
        Token:      "your-secret-token",
        HTTPClient: nil, // uses default
    }
    client, err := realm.NewClient(config)
  11. Run the Hysteria CLI

    master

    The Hysteria application is a command-line interface (CLI) tool. The entrypoint executes the command logic defined in the cmd package. To use Hysteria, you typically run the compiled binary directly from your terminal to manage server or client configurations.

    # Example of running the compiled binary (assuming it is named 'hysteria')
    ./hysteria --help