Preface

The proxy ecosystem is broad and fragmented. Proxy Wiki exists to document the Chimera projects as one coherent stack and to make their relationships easier to understand.

The projects draw inspiration from several established open-source projects:

  • Chimera_Client builds on ideas from clash-rs, with broader Clash/Mihomo-style compatibility as a long-term direction.
  • Chimera is inspired by clash-nyanpasu, while prioritizing first-class support for the Chimera_Client engine and related cores.
  • Chimera_Server explores a Rust server stack influenced by xray-core and shoes, with xray-core compatibility as a long-term goal.

These statements describe project direction, not a guarantee that every upstream feature is already implemented. Current gaps and unresolved compatibility questions are tracked in Open Questions.

Introduction

This documentation set covers the Chimera proxy ecosystem as implemented across the local source repositories:

  • Chimera_Client: the Rust Clash-family client core.
  • Chimera: the Tauri + React desktop control application.
  • Chimera_Service: the privileged local service used for service-mode core lifecycle and selected privileged operations.
  • AChimera: the Android application that owns the Android VPN/TUN lifecycle and embeds the Chimera client core through UniFFI.
  • Chimera_Server: the Rust server core focused on Xray-style inbound configuration, transports, security wrappers, and protocol handlers.

These projects target different layers of the system. A configuration or protocol feature should therefore be attributed to the component that actually parses and executes it rather than to the GUI that exposes the setting.

How to Use This Wiki

There are three complementary reading paths:

  • Architecture and operators: start with System Topology, then read the component pages for desktop, Android, service mode, client, and server behavior.
  • Implementation and compatibility: use Implementation Status and Source Evidence to see which capabilities are parsed, implemented, feature-gated, tested, or explicitly rejected in the current source.
  • Proxy protocols: use Proxy Protocol Reference for proxy handshakes, destination requests, wire formats, and TCP/UDP relay semantics. See Transport Reference for byte-stream delivery and Transport Security Reference for TLS/REALITY handshakes; each layer has its own configuration and failure boundaries.

Protocol specification and implementation status are deliberately separate. An upstream protocol can define a field that Chimera does not yet implement, while Chimera can also parse compatibility fields that are not applied by its runtime.

Documentation Source Policy

For current implementation claims, this Wiki uses the following evidence order:

  1. executable/runtime path,
  2. integration or interoperability tests,
  3. typed configuration and validation,
  4. repository README or planning text.

This prevents a broad README statement such as “Xray compatible” or “Clash compatible” from hiding an explicit runtime rejection or a parsed-only field.

For public protocol wire behavior, protocol specifications, RFCs, and current upstream implementations remain the preferred sources.

Documentation Status

The low-level protocol reference is mature for the currently documented core protocols, but the wider project documentation is maintained continuously against source changes. The implementation-status page records the audited source snapshot so readers can tell when a capability table may need to be rechecked.

Remaining source-verified documentation and implementation gaps are tracked in Open Questions. That page should contain real unresolved work, not items that have already been answered by the source tree.

System Topology

The Chimera ecosystem is split across multiple repositories with different runtime responsibilities. The desktop application, Android application, client core, privileged service, and server core are related, but they are not one shared process.

Ecosystem Overview

flowchart LR
    Apps["Desktop applications"] --> Local["HTTP / SOCKS / mixed / TUN entry"]
    GUI["Chimera desktop"] --> Core["Chimera_Client or another selected Clash-family core"]
    GUI --> Service["Chimera_Service"]
    Service --> Core
    Local --> Core

    AndroidApps["Android applications"] --> ATun["Android VpnService / TUN"]
    AUI["AChimera"] --> ATun
    ATun --> UniFFI["UniFFI bridge"]
    UniFFI --> Embedded["embedded Chimera client core"]

    Core --> Remote["Remote proxy endpoint"]
    Embedded --> Remote
    Remote --> Server["Chimera_Server or compatible server"]
    Server --> Internet["Target services / internet"]

The desktop and Android paths are sibling client applications. They normally do not sit in series.

Component Responsibilities

ComponentRuntime rolePrimary source anchors
ChimeraDesktop control plane: profile/runtime generation, core selection and update, foreground process management, service-mode IPC, system integration.backend/tauri/src/config, backend/tauri/src/core/clash, backend/tauri/src/core/service
Chimera_ClientClash-family client core: local listeners, DNS, rules, TUN/transparent paths, outbound proxy handlers, controller APIs.clash-lib/src/config, clash-lib/src/app, clash-lib/src/proxy
AChimeraAndroid control/platform layer: VpnService, TUN ownership, profile lifecycle, UniFFI bridge, controller-backed traffic/memory/connection UI.app/src/main/java/rs/chimera/android/backend, service/TunService.kt, ffi
Chimera_ServerServer/inbound core: Xray-oriented config validation, listeners/transports/security wrappers, inbound protocol handlers, forwarding/runtime/traffic state.chimera_server_lib/src/config, beginning, handler, reality

For a source-audited feature matrix, see Implementation Status and Source Evidence.

Desktop Data Flow

A typical desktop forwarding path is:

application
    |
    v
HTTP / SOCKS / mixed / TUN / transparent entry
    |
    v
Chimera_Client
    |
    +--> DNS resolution / Fake-IP handling
    +--> rule evaluation
    +--> outbound selection
    |
    v
proxy protocol + optional transport/security layers
    |
    v
Chimera_Server or another compatible server
    |
    v
target

Chimera does not terminate the remote proxy protocol itself. It prepares and controls the selected core.

Desktop Control Flow

The control path is separate from packet forwarding:

profile / application settings
        |
        v
Chimera config + enhance pipeline
        |
        v
generated runtime config
        |
        +-----------------------+
        |                       |
        v                       v
foreground child          Chimera_Service
        |                       |
        +-----------+-----------+
                    v
              selected core

The desktop source currently supports multiple Clash-family core types, including Chimera Client. The generated configuration and selected core type are therefore separate compatibility dimensions: a field can exist in the generated YAML even when a selected core handles it differently.

Android Data and Control Flow

Android has an additional OS VPN boundary:

application traffic
       |
       v
Android VpnService / TUN
       |
       v
AChimera TunService
       |
       v
UniFFI
       |
       v
embedded Rust client core
       |
       +--> protect(remote socket fd)
       |
       v
physical network / remote proxy

The protect(fd) callback is essential because the proxy core’s own remote sockets must bypass the VPN capture path rather than re-entering the TUN.

See AChimera Android Client for the lifecycle details.

Server Inbound Flow

A useful Server mental model is:

listen socket / UDP / QUIC
        |
        v
transport acceptance
        |
        +--> WebSocket / XHTTP / gRPC / HTTPUpgrade
        |
        v
TLS / REALITY where configured
        |
        v
inbound proxy handler
        |
        v
outbound/session forwarding

Transport success and inner-protocol success are separate states. For example, a REALITY handshake can succeed while VLESS authentication or request parsing still fails afterward.

Configuration Ownership

Keep these ownership boundaries explicit in documentation:

  • Chimera owns desktop application settings, profile orchestration, generated runtime config, and core lifecycle decisions.
  • Chimera_Service owns privileged service/process management, not proxy-rule semantics.
  • AChimera owns Android VPN/profile/UI concerns; the embedded core owns proxy forwarding semantics.
  • Chimera_Client owns Clash-style client runtime behavior.
  • Chimera_Server owns server inbound/runtime behavior.

A bug should be assigned to the layer that actually owns the failing state, rather than to the repository whose UI happens to expose it.

Implementation Status and Source Evidence

This page is the implementation-facing index for the Chimera ecosystem. It is intentionally different from the protocol reference: protocol pages describe what a protocol means on the wire, while this page records what the local Chimera source trees actually parse, construct, execute, and test.

Evidence Levels

Use the following terms consistently across this Wiki:

LevelMeaning
ParsedA typed configuration path accepts the option or protocol. This alone does not prove runtime support.
ConstructedRuntime code can build/register the relevant handler, listener, transport, or outbound.
ImplementedA real forwarding/data path exists for the advertised direction.
Integration-testedThe repository contains a network/integration test exercising the implementation.
Interop-testedA test exercises Chimera against another implementation, or exercises two Chimera components together.
Parsed-onlyConfiguration is accepted for compatibility, but the runtime explicitly does not apply the option.
RejectedThe parser/builder deliberately rejects the option because the runtime does not support it yet.

A protocol must not be described simply as “supported” when the available evidence only reaches Parsed or Constructed.

Source Checkout Snapshot

The table records the repository heads and working-tree states observed on 2026-10-12 while maintaining this page. It is provenance, not a claim that every feature below was re-audited at these revisions. Protocol claims should be verified against the relevant source and tests; dirty working trees can contain uncommitted changes beyond the listed commit.

RepositoryHEAD observedWorking tree observedPrimary role
Chimera_Client8fc9b2b3CleanClash-family client core and local proxy runtime
Chimera_Serverc600d2fCleanXray-oriented inbound/server core
Chimeraf5f0d036CleanDesktop control plane and core lifecycle manager
Chimera_Service938490bDirtyPrivileged local service and core process manager
AChimerad6b4af73DirtyAndroid application embedding the Chimera client core through UniFFI

This is a documentation checkout marker, not a release compatibility promise or a complete feature audit. Re-check the relevant source and tests before relying on a capability claim after protocol or runtime changes.

For the concrete tests behind interoperability claims, see Test Evidence and Interoperability Matrix.

Client and Server Protocol Matrix

The matrix is deliberately directional. Chimera_Client is primarily a client core, while Chimera_Server is primarily an inbound/server core.

Protocol / layerChimera_Client evidenceChimera_Server evidenceImportant boundary
SOCKS5Local inbound and outbound code existInbound code existsClient SOCKS inbound UDP currently returns unsupported; do not infer complete UDP ASSOCIATE parity from outbound support.
HTTP proxyLocal HTTP inbound existsHTTP inbound existsTreat HTTP proxying separately from HTTP-based transports such as XHTTP.
Mixed HTTP/SOCKSLocal mixed listener existsMixed inbound existsClient mixed UDP is explicitly unsupported.
ShadowsocksInbound/outbound modules; TCP and UDP integration work exists behind shadowsocks featureInbound TCP/UDP implementation behind shadowsocks featureServer currently rejects/does not implement some cipher/config variants, including xchacha20-poly1305; the protocol page separates classic AEAD and AEAD-2022.
AnyTLSInbound/outbound implementation behind anytls; TCP/UDP integration tests existNo AnyTLS server protocol in the current server protocol enumSeveral Client options are Parsed-only; current Chimera uses one logical stream ID per underlying connection and UoT v2 for UDP.
VLESSOutbound implementation with stream, datagram, Vision, REALITY and XHTTP pathsInbound implementation behind vlessServer Vision direct mode is explicitly not implemented yet.
TrojanOutbound implementation behind trojanInbound and UDP handling behind trojanServer fallback support has explicit restrictions; unsupported fallback types are rejected.
Hysteria 2Outbound implementation behind hysteriaQUIC inbound implementation behind hysteriaServer behavior has dedicated recent compatibility work; verify exact transport/version assumptions in tests.
VMessNo VMess outbound variant in the current Client outbound enumAEAD VMess inbound implementation behind vmessServer outbound routing does not imply a VMess outbound client implementation.
TUIC v5No TUIC outbound variant in the current Client outbound enumQUIC inbound implementation behind tuic with E2E testsKeep TUIC version-specific behavior tied to the current server implementation.
XHTTPClient transport implementation used by VLESSServer XHTTP transport with protocol/security matrix testsServer deliberately rejects several Xray XHTTP fields that are not implemented yet, including downloadSettings.
WebSocketTransport module behind wsTransport module behind wsA transport is not a proxy protocol by itself.
gRPC transportNot present as a current Client outbound transport moduleServer transport behind grpc_transport; Xray-client VLESS/gRPC external E2E existsSingle-stream Hunk mode is implemented; multiMode is explicitly rejected. Management-gRPC compatibility tests are separate evidence and must not be confused with proxy-transport tests.
HTTPUpgradeNo current Client outbound transport moduleServer transport behind httpupgrade; handler unit tests and Xray-client external E2E existHTTP/1.1 GET/101 preface then raw stream, not WebSocket framing; acceptProxyProtocol and ed are explicitly rejected.
Dokodemo-doorNot a current Client remote outbound protocolTCP/UDP forwarding inbound with fixed-target and Linux original-destination modes; tests/examples existNo proxy handshake/header of its own; followRedirect is Linux-only and UDP rejects stream security layers.
TLSShared client transport/security supportServer security wrapper behind tlsTLS is a security/transport layer, not an identity-bearing proxy protocol.
REALITYClient implementation under proxy/transport/realityServer implementation under reality plus inbound wrappersCross-project REALITY/Vision E2E and negative tests exist in the Server repository.

Source Anchors

Chimera_Client

The most important capability anchors are:

  • clash-lib/src/config/internal/proxy.rs: outbound protocol enum and protocol configuration structures.
  • clash-lib/src/app/outbound/manager.rs: runtime outbound registration.
  • clash-lib/src/proxy/: concrete inbound, outbound, and transport modules.
  • clash-lib/Cargo.toml: build-feature gates.
  • clash-lib/tests/anytls_integration_tests.rs and clash-lib/tests/shadowsocks_integration_tests.rs: integration evidence.

The current default build enables core/TLS/TUN/port/REALITY functionality, while anytls, shadowsocks, trojan, hysteria, and ws are separate Cargo features. Documentation must distinguish “implemented in source” from “present in this binary build”.

Chimera_Server

The most important capability anchors are:

  • chimera_server_lib/src/config/mod.rs: protocol and stream-setting schema.
  • chimera_server_lib/src/config/server_config/: validation and conversion into runtime configuration.
  • chimera_server_lib/src/beginning/: socket/QUIC/XHTTP/gRPC transport entry points.
  • chimera_server_lib/src/handler/: protocol handlers.
  • chimera_server_lib/Cargo.toml: feature matrix; the current default is full.
  • chimera_server_app/tests/: cross-implementation and matrix E2E coverage.

Important explicit rejection points currently include unsupported SOCKS fields, parts of Trojan/VLESS fallback behavior, XHTTP fields, gRPC multiMode, HTTPUpgrade compatibility options, non-zero REALITY xver, and selected Shadowsocks/Vision modes. These should remain visible in user-facing docs rather than being hidden behind a blanket “Xray compatible” statement.

Application and Control-Plane Matrix

ComponentSource-backed responsibilityWhat it does not own
ChimeraProfile/runtime generation, core selection/update, foreground core lifecycle, service-mode IPC, desktop system integrationRemote proxy wire protocols themselves
Chimera_ServicePrivileged service lifecycle, local IPC, start/stop/restart/status of the selected core, selected privileged network operationsProxy protocol parsing/forwarding
AChimeraAndroid VpnService, profile lifecycle, config verification/download, TUN ownership, UniFFI bridge, controller-backed traffic/memory/connection viewsA separate proxy protocol engine; forwarding is delegated to the embedded Rust core

Maintenance Rule

When implementation and documentation disagree, update the Wiki from this order of evidence:

  1. executable/runtime path,
  2. integration or interoperability tests,
  3. typed configuration and validation,
  4. repository README or planning text.

A README claim must not override code that explicitly rejects a field or leaves it parsed-only.

Test Evidence and Interoperability Matrix

This page records what has actually been exercised by tests, not merely what the parser or runtime can construct. It complements Implementation Status and Source Evidence: implementation status answers “does code exist?”, while this page answers “which peer/direction/behavior has test evidence?”.

The matrix was audited from the current local Chimera_Client and Chimera_Server source trees. Test names are deliberately included because capability names are not always visible in filenames: several important protocol interoperability cases live inside a shared xray_client_proxy_e2e.rs suite.

Evidence Classes

ClassMeaning
UnitExercises a parser, codec, state transition, or handler in-process.
Self-integrationStarts Chimera components/instances on both sides without an independent peer implementation.
Cross-projectExercises two different Chimera repositories together, such as Chimera Client → Chimera Server.
External interoperabilityExercises Chimera against an independent implementation such as Xray.
Negative interoperabilityVerifies expected rejection/fallback/failure against a real peer or full process stack.
Example/build validationProves a configuration example parses/builds, but does not prove network interoperability.

These levels are cumulative only when the specific path is actually covered. A protocol with an external TCP test does not automatically have external UDP, TLS, fallback, multiplexing, or every cipher/transport variant tested.

Default Tests vs Explicit E2E

Many Chimera_Server process-level interoperability tests carry #[ignore] because they launch Chimera and another binary such as Xray. This means:

  • the test is real executable interoperability evidence;
  • it is not necessarily part of the default fast cargo test run;
  • maintainers must run the ignored suite explicitly when changing the covered protocol path.

Do not translate “ignored” into “not useful” or “not implemented”. It means the test belongs to an explicit, slower/environment-dependent verification tier.

Client-side Integration Matrix

The following tests live in Chimera_Client/clash-lib/tests.

CapabilityDirection / peerEvidenceWhat it proves
AnyTLS TCPChimera Client local SOCKS → Chimera AnyTLS outbound → Chimera AnyTLS inbound → targetanytls_integration_tests.rs::integration_test_anytls_tcpClient AnyTLS TCP outbound and inbound interoperate through a real local socket path.
AnyTLS UDPChimera Client local SOCKS UDP → AnyTLS UoT v2 outbound → Chimera AnyTLS inbound → UDP targetanytls_integration_tests.rs::integration_test_anytls_udpCurrent UDP-over-TCP v2 framing and session path work end to end within Client implementations.
Shadowsocks TCPChimera Client local SOCKS → Shadowsocks outbound → Chimera Shadowsocks inbound → targetshadowsocks_integration_tests.rs::integration_test_shadowsocks_tcpClient-side Shadowsocks TCP inbound/outbound integration.
Shadowsocks UDPLocal SOCKS UDP → Shadowsocks outbound/inbound → UDP targetintegration_test_shadowsocks_udpBasic Client Shadowsocks UDP relay.
Shadowsocks UDP multi-targetOne client path to multiple UDP targetsintegration_test_shadowsocks_udp_multi_targetDestination/session handling does not collapse all UDP traffic into one target.
Shadowsocks UDP isolationMultiple logical clients/sessionsintegration_test_shadowsocks_udp_session_isolationUDP session state remains isolated.
Direct UDP multi-targetLocal UDP path → directdirect_udp_integration_tests.rs::ref_compat_udp_one_client_preserves_multiple_destinationsDirect UDP preserves per-datagram destinations.
Direct UDP client isolationMultiple clients → direct UDPref_compat_udp_sessions_are_isolated_by_clientSession keys distinguish client state.
TUN + Fake-IPTUN/Fake-IP → direct and SOCKS-style proxy path → real network targetstun_fake_ip_real_tests.rs::tun_fake_ip_routes_direct_and_proxy_with_real_networkTUN/Fake-IP routing can drive both direct and proxied real network traffic.
DNS listenerReal UDP/TCP DNS queries → Client DNS listenerdns_real_traffic_tests.rsDNS listener handles real UDP/TCP query traffic and concurrency.

These are primarily self-integration or real-network integration tests. They do not prove compatibility with Xray for AnyTLS or Shadowsocks Server behavior.

Chimera Client → Chimera Server REALITY/Vision

Chimera_Server/chimera_server_app/tests/chimera_client_reality_vision_e2e.rs is the dedicated cross-project suite for Chimera Client → Chimera Server.

Positive coverage includes:

  • basic TCP and large payloads;
  • payload/framing boundaries;
  • domain targets;
  • TLS 1.3 application-data transition;
  • sequential and concurrent connections;
  • multiple configured REALITY server names;
  • multiple short IDs;
  • exact client version bounds.

The companion chimera_client_reality_vision_negative_e2e.rs verifies rejection for cases including:

  • client version below an explicit minimum;
  • client version above an explicit maximum;
  • wrong short ID;
  • wrong server name;
  • wrong REALITY public key;
  • wrong VLESS UUID;
  • missing required Vision flow;
  • Vision flow presented to a plain VLESS account.

These tests are marked ignored because they launch both project binaries. They are nevertheless the strongest evidence for the exact Chimera Client ↔ Chimera Server REALITY/Vision combination.

Xray Client → Chimera Server Matrix

The shared ignored suite Chimera_Server/chimera_server_app/tests/xray_client_proxy_e2e.rs contains several protocol cases. The filename is generic, so the individual test function is the important evidence anchor.

CapabilityDirectionTestCoverage
VLESS + REALITY + VisionXray client → Chimera Serverxray_client_can_proxy_tcp_through_chimera_reality_visionTCP proxying through REALITY/Vision.
VLESS + TLS + VisionXray client → Chimera Serverxray_client_can_proxy_tcp_through_chimera_tls_visionTLS-wrapped Vision TCP.
Shadowsocks classic AEADXray client → Chimera Serverxray_client_can_proxy_tcp_through_chimera_shadowsocksLegacy/current classic AEAD TCP methods exercised by the loop in the test.
Shadowsocks multi-user classicTwo Xray clients → one Chimera inboundxray_clients_can_use_multiple_legacy_shadowsocks_usersMultiple configured classic users select/authenticate independently.
Shadowsocks 2022 EIHTwo Xray clients → one Chimera inboundxray_clients_can_use_shadowsocks_2022_eih_usersAEAD-2022 multi-user EIH user selection.
Shadowsocks 2022 TCP + AES UDPXray client → Chimera Serverxray_client_can_proxy_tcp_and_aes_udp_through_chimera_shadowsocks_20222022 TCP plus AES-2022 UDP interoperability.
VLESS over gRPC transportXray client → Chimera Serverxray_client_can_proxy_tcp_through_chimera_grpcXray VLESS gRPC/h2c client can traverse Chimera’s proxy gRPC transport.
VLESS over HTTPUpgradeXray client → Chimera Serverxray_client_can_proxy_tcp_through_chimera_httpupgradeXray VLESS HTTPUpgrade request/101/raw-stream path interoperates with Chimera.
Hysteria 2Xray client → Chimera Serverxray_client_can_proxy_tcp_and_udp_through_chimera_hysteria2Both TCP and UDP proxying through the Server Hysteria 2 implementation.

The same file also contains HTTP/Mixed inbound process-level coverage using direct HTTP CONNECT/forward-proxy/SOCKS clients rather than relying on an Xray proxy protocol for those local-proxy semantics.

Fallback and Negative Process Tests

xray_client_proxy_e2e.rs also exercises full-process fallback behavior that is easy to miss in a simple protocol matrix:

CaseEvidence
Unauthenticated plain TCP reaches VLESS fallbackunauthenticated_plain_tcp_reaches_vless_fallback
TLS payload reaches VLESS Vision fallbackunauthenticated_tls_payload_reaches_vless_vision_fallback
Trojan TLS fallback rule selectionunauthenticated_tls_payload_reaches_trojan_fallback_rules
REALITY SNI mismatch reaches destination fallbackplain_tls_client_falls_back_to_reality_dest_on_sni_mismatch
Wrong REALITY short ID falls backxray_client_with_wrong_reality_short_id_falls_back_to_dest
Wrong REALITY SNI falls backxray_client_with_wrong_reality_sni_falls_back_to_dest

Fallback evidence matters because “invalid auth is rejected” and “invalid auth is safely routed to the configured fallback” are different runtime behaviors.

REALITY/Vision Xray Baseline Matrix

The Server also has dedicated ignored Xray-baseline suites:

  • reality_vision_matrix_e2e.rs;
  • reality_vision_negative_e2e.rs.

They cover uTLS fingerprints, payload boundaries, domain/IPv6 targets, TLS 1.3 transitions, repeated sessions, half-close behavior, concurrency, multiple server names/short IDs, version bounds, and authentication/flow rejection cases.

These suites compare behavior with an Xray-oriented baseline and are stronger evidence for subtle REALITY/Vision state transitions than a single happy-path connection test.

XHTTP Interoperability Matrix

xhttp_matrix_e2e.rs starts Chimera Server and Xray and generates a matrix of XHTTP cases. The matrix covers combinations including:

  • stream-one, packet-up, stream-up, and auto modes;
  • POST/GET/PATCH/PUT uplink methods where allowed;
  • session ID placement in path/header/query/cookie;
  • sequence placement variants;
  • body/header/cookie uplink data placement;
  • header-size limits;
  • padding obfuscation placements and methods;
  • noGRPCHeader / noSSEHeader variants.

These cases are ignored explicit E2E tests because they launch both Chimera and Xray.

xhttp_security_matrix_e2e.rs separately verifies XHTTP with:

  • no security wrapper;
  • TLS;
  • REALITY.

xhttp_protocol_matrix_e2e.rs is primarily Chimera process-level behavioral/negative coverage for host/path rejection, padding validation, packet sequencing, body-size limits, duplicate stream-up, mode conflicts, CORS/options, and padding placement.

gRPC: Proxy Transport vs Management API

The repository contains two unrelated features that both use gRPC terminology:

  1. proxy gRPC transport — beginning/grpc_transport.rs, which wraps an inner proxy byte stream as Xray-style Hunk messages;
  2. management gRPC API — Xray-compatible control-plane services for stats, handlers, routing, observatory, and related operations.

Use these evidence anchors correctly:

TestWhat it proves
xray_client_proxy_e2e.rs::xray_client_can_proxy_tcp_through_chimera_grpcProxy transport interoperability.
beginning/grpc_transport.rs unit testsHunk codec/incomplete-buffer behavior.
grpc_all_interfaces_e2e.rsManagement API behavior across many exposed interfaces.
grpc_external_integration.rsExternal management API process integration.
grpc_xray_compat_e2e.rsManagement API behavioral comparison with Xray, including generated reports.

Do not cite the management API tests as proof that VLESS/gRPC proxy transport works. Conversely, a successful VLESS/gRPC proxy test says nothing about StatsService or HandlerService compatibility.

SOCKS and HTTP/Mixed Evidence

Chimera_Server/chimera_server_app/tests/socks_external_integration.rs contains external-process SOCKS tests for:

  • no-auth TCP round trip;
  • username/password TCP round trip.

xray_client_proxy_e2e.rs::http_and_mixed_inbounds_proxy_tcp starts real Chimera HTTP and mixed listeners and exercises:

  • authenticated HTTP CONNECT;
  • absolute-form HTTP forwarding;
  • transparent-style HTTP request forwarding where enabled;
  • HTTP through mixed inbound;
  • SOCKS5 through mixed inbound.

This is process-level protocol evidence even though it does not use Xray as the client for those local proxy requests.

TUIC Evidence

chimera_server_lib/src/handler/tuic/e2e_tests.rs::udp_stream_and_datagram_roundtrips_record_stats exercises the current TUIC handler over QUIC and verifies:

  • UDP stream relay;
  • QUIC datagram relay;
  • traffic-stat accounting.

This is strong in-repository E2E evidence for the implemented TUIC data path, but it is not external TUIC interoperability evidence with an independent client. Keep that distinction visible until such a test is added.

Dokodemo-door Evidence

Dokodemo-door has no client wire protocol to compare against an external peer, so the relevant evidence is handler/socket/routing behavior rather than a protocol handshake.

Current tests include:

  • handler/dokodemo.rs::follow_redirect_uses_original_destination;
  • handler/dokodemo.rs::follow_redirect_rejects_missing_original_destination;
  • Linux original-destination extraction tests in the listener path;
  • beginning/udp.rs::dokodemo_udp_follow_redirect_routes_by_original_destination;
  • dokodemo_udp_relay_forwards_datagrams;
  • dokodemo_udp_reuses_session_for_same_flow;
  • dokodemo_udp_session_forwards_multiple_responses;
  • Xray-compatible TCP/UDP example parsing/building in tests/xray_compatible_examples.rs.

These tests validate the forwarding machinery; a real transparent deployment still depends on Linux firewall/policy-routing configuration outside the Rust process.

What Is Not Yet Proven

The current test tree does not justify the following blanket claims:

  • AnyTLS interoperability with Chimera_Server — the Server has no AnyTLS inbound;
  • Chimera Client gRPC or HTTPUpgrade outbound interoperability — those outbound transport modules are not currently present;
  • external TUIC interoperability with an independent TUIC client;
  • every Shadowsocks cipher parsed by Client is accepted by Server;
  • every XHTTP field parsed from Xray-shaped configuration is implemented;
  • every ignored E2E runs in default CI simply because the source file exists.

Absence from this list does not necessarily mean a feature is broken. It means the Wiki should not upgrade a capability claim to “interop-tested” without a concrete test anchor.

Running the Evidence Suites

From Chimera_Client, focused protocol integration tests can be run with commands such as:

cargo test -p clash-lib --test anytls_integration_tests
cargo test -p clash-lib --test shadowsocks_integration_tests

From Chimera_Server, the explicit ignored E2E tier can be exercised with:

cargo test --workspace -- --ignored

A focused external proxy suite can be run with:

cargo test -p chimera_server_app --test xray_client_proxy_e2e -- --ignored --nocapture

These process-level tests may require the expected peer binaries/test assets in the locations resolved by the repository’s test harness. A test that cannot start its external dependency is an infrastructure failure, not evidence that the protocol itself failed.

Maintenance Rule

When a protocol or transport changes:

  1. identify the exact parser/runtime path that changed;
  2. locate the strongest existing test that traverses that path;
  3. update or add a positive test;
  4. add a negative test when authentication, bounds, fallback, replay, or malformed input is involved;
  5. run the relevant ignored external/cross-project suite when applicable;
  6. only then update this Wiki’s interoperability label.

If one test file contains several unrelated subsystems, cite the test function, not just the filename. The gRPC management/transport distinction and the shared xray_client_proxy_e2e.rs suite are the canonical examples of why this matters.

End-to-End Troubleshooting

Proxy failures become much easier to diagnose when the Chimera stack is treated as a sequence of independently testable layers. Do not start by changing UUIDs, DNS, TLS fingerprints, routes, and transport modes at the same time. First identify the first layer that is observably wrong.

The practical path is:

application
  ↓
local listener / Android TUN / desktop system proxy
  ↓
Chimera_Client DNS + rule selection
  ↓
selected outbound protocol
  ↓
transport / TLS / REALITY / QUIC
  ↓
Chimera_Server listener / transport wrapper
  ↓
server-side proxy authentication + request parsing
  ↓
server routing / outbound
  ↓
target DNS + target socket
  ↓
target application

A failure at one layer often produces symptoms in the layer above it. The goal of this page is to stop at the first failing boundary instead of debugging every layer at once.

For implementation claims and concrete interoperability tests, use Implementation Status and Source Evidence and Test Evidence and Interoperability Matrix together with this page.

First Question: Which Boundary Fails?

Use this symptom table before changing configuration:

SymptomFirst boundary to inspect
Local proxy port refuses connectionlistener startup / bind / selected binary feature
Local proxy accepts, but controller shows no connectionapplication proxy settings, listener protocol, allow-LAN/source policy
Connection appears, but rule/outbound is unexpectedDNS result, rule order, provider state, selector/group choice
Correct outbound selected, remote TCP never establishesrouting/firewall/server address/port
TCP establishes, TLS immediately failsSNI, certificate trust, ALPN, TLS version, REALITY parameters
TLS/transport succeeds, proxy auth failsUUID/password/key/method/flow/protocol request
Proxy auth succeeds, target cannot connectserver DNS/routing/outbound/target firewall
TCP works but UDP does notprotocol-specific UDP support, session model, MTU, QUIC/datagram path
Only service mode failsDesktop → Chimera_Service IPC, privileges, config path, managed core process
Only Android failsVPN permission, TUN FD, protect(fd), Android routes/DNS, embedded-core state
One Xray peer works but Chimera peer failsexact implementation/feature/interoperability matrix, not the public protocol alone

The phrase “proxy does not work” is not yet a useful diagnosis. Convert it into one row of this table first.

Step 0: Validate Configuration Before Network Debugging

A process that rejected configuration has no meaningful network path to debug.

For Chimera_Server, the current CLI has a validation-only mode:

cargo run --package chimera_server_app -- --config path/to/config.json5 --check

A successful check exits without starting the server. Validation can catch unsupported fields such as Server gRPC multiMode, HTTPUpgrade acceptProxyProtocol/ed, unsupported XHTTP fields, non-zero REALITY xver, and other builder-level restrictions before any packet is sent.

For Chimera_Client, distinguish these cases:

  1. YAML parses;
  2. the outbound/listener is constructible in the current build;
  3. the required Cargo feature was compiled;
  4. runtime initialization succeeds.

A field being accepted by serde does not prove that it is active runtime behavior. AnyTLS currently has explicit Parsed-only compatibility fields, and several Server Xray-shaped fields are deliberately rejected rather than silently applied.

Step 1: Prove the Local Ingress

Before debugging a remote protocol, prove that the application can reach the local Client ingress.

For a SOCKS listener, test the exact listener address/port configured in the active runtime. A useful external check is:

curl --socks5-hostname 127.0.0.1:7891 https://example.com/

For an HTTP proxy listener:

curl --proxy http://127.0.0.1:7890 https://example.com/

Use the actual configured ports rather than assuming Clash-family defaults.

If the connection is refused, stay at the listener layer. Check:

  • whether the current binary contains the required inbound feature;
  • whether another process already owns the port;
  • whether the listener bound loopback, LAN, IPv4, or IPv6 as expected;
  • source-address/allow-LAN policy;
  • listener startup logs.

Current Client logs include messages such as tcp listen failed, udp listen failed, listener stopped warnings, and source-address rejection. Do not move to TLS or remote authentication until the local listener is demonstrably reachable.

Step 2: Use the Chimera_Client Controller as an Observation Point

When the Client controller is enabled, it is a much better observation point than guessing from an application timeout.

The current Client exposes controller surfaces including:

/connections
/proxies
/configs
/dns/query
/traffic
/memory
/logs        WebSocket

The TCP controller uses bearer-token authentication when a secret is configured:

Authorization: Bearer <secret>

The current Client refuses an unsafe non-loopback TCP API configuration without a secret, and also requires valid CORS origins for a non-loopback API listener.

Useful questions are:

  • Does /connections show the application flow?
  • Which proxy chain/group was selected?
  • Does /proxies show the expected selector state?
  • Does /configs reflect the runtime configuration you think is active?
  • Does /dns/query resolve the same name the application is using?
  • Do /traffic or connection counters move when the application sends data?
  • What is the first warning/error on /logs?

If no connection appears at all, debug ingress. If a connection appears with the wrong chain, debug DNS/rules/group selection. If the right chain appears and then fails, move outward to the outbound/transport layer.

Step 3: Separate DNS from Rule Selection

DNS and routing are related but not interchangeable.

A rule can behave differently depending on whether the Client sees:

  • the original domain name;
  • a locally resolved IP;
  • a Fake-IP address that can be reverse-mapped;
  • a failed/no DNS result.

Current Client logs have explicit paths for failed to resolve destination and failed Fake-IP reverse lookup. Use the controller DNS query surface and the DNS module page before blaming the remote protocol.

A useful isolation sequence is:

  1. resolve the destination through the Client’s configured resolver path;
  2. confirm the expected domain/IP reaches the rule engine;
  3. confirm the selected rule and proxy group;
  4. only then inspect the remote dial.

If a profile works with a literal IP but not a domain, that is strong evidence to inspect DNS/rule behavior before protocol cryptography.

See DNS Module and Rule Types and Their Effects.

Step 4: Confirm the Outbound Exists in This Binary

A common source of confusion is documentation/source support versus artifact support.

Current Chimera_Client source contains optional features such as:

anytls
shadowsocks
trojan
hysteria
ws

These are not all part of the default feature set. A valid profile can therefore fail during handler construction when the distributed/local binary was built without the required feature.

Client outbound-manager logs identify failures such as:

failed to load socks5 outbound ...
failed to load anytls outbound ...
failed to load trojan outbound ...
failed to load vless outbound ...

Before packet capture, confirm the expected handler was actually constructed. See Chimera_Client for the current feature matrix.

Step 5: Prove Remote TCP/UDP Reachability Before Protocol Parsing

For TCP-based transports, determine whether a TCP connection to the remote listener can be established at all.

If SYN packets receive no response, proxy credentials are irrelevant. Check:

  • server process/listener state;
  • destination IP/port;
  • local and server firewall;
  • NAT/port forwarding;
  • IPv4/IPv6 selection;
  • cloud/security-group policy;
  • routing to the server.

On the Server, listener-level failures appear before protocol handlers. Current Server logs include Accept failed, TCP server stopped with error, UDP server stopped with error, xhttp accept failed, and gRPC transport accept failed.

For QUIC protocols such as Hysteria 2 and TUIC, a successful TCP check on the same port proves nothing about UDP reachability. Test the actual UDP path and inspect both directions in a packet capture.

Step 6: Split Security Handshake from Proxy Protocol Handshake

TLS/REALITY success and proxy authentication success are distinct events.

For TLS-based stacks, validate:

  • SNI/server name;
  • certificate chain/trust or intentional private CA;
  • ALPN required by the transport (h2 for the current Server gRPC/TLS path);
  • client certificate/key when mTLS is configured;
  • system clock where protocol/security checks depend on time.

For REALITY, additionally verify:

  • public/private key pair;
  • short ID;
  • accepted server name;
  • client version bounds when configured;
  • VLESS UUID/flow separately from the REALITY handshake.

The Server test suite intentionally contains cases where REALITY/transport state and VLESS account/flow state fail independently. Treat them as separate layers in logs and captures.

See REALITY and Test Evidence and Interoperability Matrix.

Step 7: Validate the Transport Wrapper

A transport can fail after TCP/TLS succeeds but before the inner proxy parser sees a byte.

XHTTP

Check mode, path, Host, session/sequence placement, upload method, data placement, padding metadata, body/header size limits, and whether the configured field is actually implemented by the Server.

Server logs contain transport-specific anchors such as:

xhttp request rejected by host/padding validation
xhttp request rejected by path validation
xhttp packet-up write failed
xhttp logical stream ... failed

See XHTTP Transport.

gRPC transport

Check in this order:

HTTP/2 / h2 or h2c
POST /<serviceName>/Tun
Content-Type: application/grpc
compressed flag = 0
Hunk protobuf field 1
inner proxy bytes

A grpc-status: 12 response usually means method/path/content-type mismatch. Do not use management-gRPC API tests or endpoints to diagnose the proxy gRPC transport; they are separate subsystems.

See gRPC Transport.

HTTPUpgrade

The current Server expects HTTP/1.1 GET, matching path/optional Host, Connection: Upgrade, and Upgrade: websocket, then returns 101 and switches to a raw byte stream.

Do not apply WebSocket data framing after 101. That mistake makes the transport handshake look successful while the inner proxy parser receives invalid bytes.

See HTTPUpgrade Transport.

WebSocket

WebSocket is a different transport. After its HTTP upgrade it still has WebSocket frame boundaries, opcodes, masking rules, control frames, and close semantics. Keep it separate from HTTPUpgrade in packet analysis.

Step 8: Validate Proxy Authentication and Request Fields

Only after the transport/security layer is proven should you debug protocol credentials and request encoding.

Examples of protocol-layer checks:

ProtocolHigh-value fields/state
SOCKS5method selection, RFC 1929 account, command, ATYP/destination
Shadowsocksclassic vs 2022 method, key length, salt/session replay, timestamp, EIH user
AnyTLSSHA-256 password token, padding length, SETTINGS/SYN/PSH ordering, stream ID
Trojanpassword hash line, CRLF framing, command/address, fallback behavior
VLESSUUID, request version, command/address, flow, optional Encryption
VMessAuthID time/replay, AEAD request header, security mode, record framing
Hysteria 2QUIC/TLS, HTTP auth request, bandwidth/UDP/session state
TUICQUIC/TLS, UUID/password token, command/session/association IDs

At this layer, a transport capture may show a healthy connection even though the server immediately closes the inner stream.

Use the corresponding protocol chapter rather than changing transport settings blindly.

Step 9: Separate Server Inbound Success from Target Success

A server can successfully authenticate the proxy client and still fail to reach the requested target.

After inbound parsing, inspect:

  • target domain resolution on the Server;
  • routing/outbound policy;
  • blackhole/reject selection;
  • target IP/port reachability;
  • IPv4/IPv6 choice;
  • target-side firewall;
  • source-address restrictions at the target.

Current Hysteria 2 logs, for example, explicitly distinguish authentication failures from failed to connect to <target>. Similar separation should be preserved when reading other protocol logs.

For Dokodemo-door fixed-target mode, there is no proxy request header at all, so target configuration/resolution is especially important. For followRedirect, prove Linux original-destination interception before debugging routing.

See Dokodemo-door.

Step 10: Treat UDP as a Separate Data Plane

“TCP works” is weak evidence for UDP.

Different protocols use very different UDP models:

  • SOCKS5 uses UDP ASSOCIATE plus a SOCKS UDP header;
  • Shadowsocks encrypts packet-oriented destination + payload records and AEAD-2022 adds session/packet state;
  • AnyTLS currently uses UDP-over-TCP v2, so datagrams inherit TCP ordering/head-of-line blocking;
  • Hysteria 2 and TUIC use QUIC-oriented UDP/session semantics;
  • Dokodemo-door forwards raw UDP to a fixed/original target;
  • some local Client listeners currently do not provide UDP even when the remote outbound can.

For UDP failure, record:

  1. client/source address;
  2. logical target;
  3. chosen outbound;
  4. protocol session/association ID where applicable;
  5. packet/datagram size;
  6. whether the server emitted a response;
  7. whether that response reached the original client.

Also check MTU, NAT timeout, firewall UDP policy, QUIC datagram support, and whether the implementation uses stream fallback versus native datagrams.

Service Mode: Separate Four Processes/Boundaries

When foreground mode works but service mode does not, stop debugging the remote protocol first.

The service-mode chain is:

Chimera desktop
  ↓
local IPC
  ↓
Chimera_Service
  ↓
managed core process
  ↓
proxy network path

Check these independently:

  1. Is chimera-service installed/running?
  2. Can the desktop query /status through the local IPC client?
  3. Does /core/start receive the intended CoreType and generated config path?
  4. Can the service account read the config and execute the selected core?
  5. Does the managed core itself start its listeners?

A healthy service process does not prove a healthy core, and a healthy core does not prove remote protocol success.

See Service Mode Configuration.

Android: Separate VPN Lifecycle from Proxy Core

For AChimera, the path is:

VpnService permission
  ↓
TUN creation / detached FD
  ↓
UniFFI core start
  ↓
socket protect(fd)
  ↓
DNS / rules / outbound

High-value failure boundaries are:

  • VpnService.prepare(...) never succeeds;
  • TUN FD is missing/invalid;
  • profile verification fails before core start;
  • the Rust core starts but its own sockets are not protected and re-enter the VPN;
  • Android route/DNS settings do not send expected traffic into the TUN;
  • controller traffic/connection state remains empty.

If the same profile works in desktop Chimera_Client but fails only on Android, inspect Android VPN/TUN/protection state before changing the remote protocol.

See AChimera Android Client.

Packet Capture Strategy

Capture at the boundary you are trying to prove, not only at the Internet-facing NIC.

A useful sequence is:

  1. application → local listener;
  2. Client → remote server address;
  3. server listener → target;
  4. UDP response path back to the client where relevant.

Useful display/filter concepts include:

tcp.port == <port>
udp.port == <port>
tls
http2
http
quic

For encrypted transports, packet capture proves reachability, direction, timing, retransmissions, close/reset behavior, and ciphertext sizes unless you have session keys or in-process traces. Do not claim a UUID/password/address is wrong merely because encrypted bytes are opaque.

Protocol pages contain the post-decryption wire anchors for SOCKS5, HTTP CONNECT, Shadowsocks, AnyTLS, Trojan, Hysteria 2, TUIC, VMess, VLESS, XHTTP, gRPC transport, HTTPUpgrade, REALITY, and Dokodemo-door.

Build a Minimal Reproduction by Removing Layers

When a production stack contains many layers, reduce it deliberately.

A useful order is:

1. target reachable directly from server
2. minimal server inbound without optional transport
3. matching minimal client outbound
4. local SOCKS/HTTP ingress
5. add TLS/REALITY
6. add XHTTP/gRPC/HTTPUpgrade/WebSocket
7. add DNS/Fake-IP/rules/groups
8. add TUN/service mode/Android VPN integration

Not every protocol allows every layer to be removed, but the principle is to replace one complex boundary at a time with a known-good simpler one.

Keep a minimal known-good profile in the repository/test environment. It is far more useful than editing a large subscription profile during an incident.

Error Strings Are Layer Markers

Treat log strings as hints about where failure occurred, not just as messages to search online.

Examples from current source include:

Client listener:   tcp listen failed / udp listen failed
Client DNS:        failed to resolve destination
Client outbound:   failed to load <protocol> outbound
AnyTLS:            missing SYN before PSH / alert
Shadowsocks:       failed to perform Shadowsocks handshake
Server listener:   Accept failed / UDP server stopped with error
XHTTP:             request rejected by path or host/padding validation
Hysteria2:         auth rejected / failed to connect to target
TUIC:              Authentication timeout / Connection failed

If the first error says “failed to load outbound”, packet capture is premature. If the first Server error is target connect failure, changing the client UUID is unlikely to help.

Compare Against the Strongest Existing Test

When a failure resembles an already-tested combination, reproduce the repository test before inventing a new configuration.

Examples:

  • Chimera Client → Chimera Server REALITY/Vision: dedicated cross-project E2E;
  • Xray → Chimera Server VLESS/gRPC: xray_client_can_proxy_tcp_through_chimera_grpc;
  • Xray → Chimera Server HTTPUpgrade: xray_client_can_proxy_tcp_through_chimera_httpupgrade;
  • Xray → Chimera Server Shadowsocks 2022: dedicated TCP/AES-UDP test;
  • XHTTP: matrix and security-matrix E2E;
  • AnyTLS/Shadowsocks Client behavior: dedicated Client integration tests.

See Test Evidence and Interoperability Matrix for commands and exact test names.

If the known test passes but the deployment fails, compare configuration/build/platform differences. If the known test fails on the same checkout, investigate implementation/regression before blaming deployment.

Incident Capture Checklist

For a useful bug report or incident note, record:

  • exact repository commit/version for Client and Server;
  • binary build features where optional protocols are involved;
  • operating system and service/foreground/Android mode;
  • sanitized active runtime configuration, not only the source subscription;
  • local ingress protocol and address/port;
  • selected rule/proxy chain;
  • remote server IP/port and transport/security mode;
  • first relevant Client warning/error;
  • first relevant Server warning/error;
  • whether TCP/UDP reachability is proven;
  • packet capture around the failing boundary when useful;
  • exact existing E2E/integration test that most closely matches the deployment.

Do not include private keys, raw passwords, bearer secrets, subscription URLs, or reusable authentication tokens in public reports.

Stop Conditions

Stop expanding the search when you have identified the first failing boundary and can reproduce it independently.

Examples:

  • listener does not bind → fix listener/build/config first;
  • rule selects wrong outbound → fix DNS/rule/group state first;
  • TLS certificate fails → fix TLS trust/SNI first;
  • gRPC returns status 12 → fix transport method/path/content type first;
  • proxy auth succeeds but target connect fails → fix server routing/target first;
  • only service mode fails → fix IPC/privilege/core lifecycle first.

Changing downstream layers before the upstream failure is resolved makes the incident harder to reason about and can erase useful evidence.

Source Anchors

The concrete observation/error paths used in this guide were checked against:

  • Chimera_Client/clash-lib/src/app/api/runner.rs and app/api/handlers;
  • Chimera_Client/clash-lib/src/app/dispatcher/dispatcher_impl.rs;
  • Chimera_Client/clash-lib/src/app/inbound and app/outbound/manager.rs;
  • Chimera_Client/clash-lib/src/app/dns;
  • Chimera_Client/clash-lib/src/proxy;
  • Chimera_Server/chimera_server_app/src/main.rs;
  • Chimera_Server/chimera_server_lib/src/beginning;
  • Chimera_Server/chimera_server_lib/src/handler;
  • Chimera_Server/chimera_server_lib/src/reality;
  • the cross-project and external E2E tests catalogued in Test Evidence and Interoperability Matrix.

This page should be updated when a failure boundary, controller endpoint, feature gate, or test path changes in source.

Deployment Security and Threat Model

This page describes the security boundaries that matter when deploying the Chimera ecosystem. It is not a claim that one configuration is universally secure; it is a checklist for understanding which component trusts whom, which secrets cross which boundary, and what an attacker can reach if one layer is exposed.

Protocol cryptography is only one part of the system. A correctly encrypted VLESS/REALITY or Shadowsocks connection can still be undermined by an unauthenticated LAN listener, leaked controller secret, unsafe fallback target, DNS/TUN leak, over-privileged service, or logs containing reusable credentials.

Use this page together with End-to-End Troubleshooting, Implementation Status and Source Evidence, and the protocol-specific security sections.

Trust Boundaries

A typical desktop deployment crosses these boundaries:

local application
   ↓
local HTTP/SOCKS/mixed/TUN ingress
   ↓
Chimera_Client process
   ↓
remote encrypted/authenticated proxy transport
   ↓
Chimera_Server process
   ↓
server DNS/routing/outbound
   ↓
target network/service

Service mode inserts another privileged boundary:

Chimera desktop user process
   ↓ local IPC
Chimera_Service privileged process
   ↓ process/config control
managed proxy core

Android inserts a VPN boundary:

Android applications
   ↓
VpnService/TUN
   ↓
AChimera + embedded Rust core
   ↓ protect(fd)
remote network

Each arrow can have a different attacker and different authentication model. Do not treat “the proxy connection is encrypted” as protection for every arrow.

Assets to Protect

Treat these as security-sensitive assets:

  • Shadowsocks passwords/PSKs and AEAD-2022 raw keys;
  • AnyTLS passwords;
  • Trojan passwords;
  • VLESS/VMess user identifiers where they grant service access;
  • REALITY private keys, client public-key configuration, and short IDs;
  • Hysteria 2 credentials;
  • TUIC UUID/password material;
  • TLS private keys and client certificates;
  • Chimera controller/API bearer secrets;
  • subscription URLs containing access tokens;
  • generated runtime configuration when it contains credentials;
  • service IPC/control capability;
  • DNS/routing policy when it reveals or controls user traffic.

A value does not need to be a conventional password to be reusable authentication material.

Threat Actors

Useful threat categories include:

ActorTypical capability
Local unprivileged user/processConnect to local listeners/APIs, read world-readable files, influence local DNS or environment.
LAN peerReach listeners accidentally bound to LAN, probe unauthenticated SOCKS/HTTP/Dokodemo endpoints.
On-path network observerSee IPs, ports, timing, sizes, plaintext protocols without TLS, and possibly HTTP metadata.
Malicious proxy clientSend malformed/replayed/authentication-failing traffic and consume server resources.
Malicious/compromised proxy serverObserve target destinations and plaintext after proxy decryption, return malicious content, manipulate DNS/routing behavior under its control.
Reverse proxy/CDN/logging infrastructureObserve HTTP/XHTTP/gRPC metadata that is outside end-to-end encrypted inner payloads.
Privileged local attackerControl service/core lifecycle, routes, DNS, TUN, process memory, and configuration; protocol cryptography cannot protect against full local privilege compromise.

The appropriate mitigation depends on which actor is in scope.

Local Proxy Listeners Are Security Boundaries

SOCKS5, local HTTP proxy, and mixed listeners are often plaintext application-facing interfaces. If exposed beyond the intended host, they can become open proxies or leak credentials/traffic metadata.

For local-only desktop use:

  • prefer loopback binding unless LAN access is intentionally required;
  • verify allow-lan/source policy and actual bind address;
  • use listener authentication where the implementation and deployment require shared access;
  • firewall LAN/WAN access even when the application configuration appears restrictive;
  • do not assume remote-protocol authentication protects the local listener.

A LAN peer that can use your local SOCKS listener does not need to know your remote VLESS UUID or Shadowsocks key; your Client will authenticate to the remote server on its behalf.

Chimera_Client Controller/API

The Client controller is a control and observation surface, not a public application proxy.

Current TCP API behavior requires a bearer token when a secret is configured, and the Client rejects unsafe non-loopback TCP API exposure without a secret. Non-loopback API exposure also requires explicit valid CORS origins.

Security guidance:

  • keep the controller on loopback unless remote administration is genuinely needed;
  • configure a high-entropy secret before non-loopback exposure;
  • restrict it with host firewall rules in addition to application authentication;
  • do not put bearer secrets in screenshots, logs, shell history, or bug reports;
  • remember that /connections, /proxies, /configs, DNS queries, logs, and traffic information can reveal sensitive operational metadata even without raw payloads.

A compromised controller can expose much more than a passive packet capture.

Service Mode and Privileged IPC

Chimera_Service can start, stop, and restart selected cores using supplied configuration paths, report runtime status, and perform supported privileged network operations such as DNS changes.

That makes the Desktop → Service IPC boundary security-sensitive.

Operational requirements include:

  • rely on the repository’s local IPC ACL/security mechanisms rather than exposing the service control endpoint broadly;
  • keep Desktop, Service, shared IPC types, and core binaries from trusted build/update sources;
  • treat a config path supplied to a privileged service as security-sensitive input;
  • avoid world-writable generated-config directories;
  • verify service-account file permissions and executable paths;
  • distinguish service-process compromise from proxy-core compromise in incident response.

Service mode increases operational privilege; it does not strengthen proxy protocol authentication by itself.

Android VPN/TUN Boundary

AChimera owns an Android VpnService and passes the TUN file descriptor to the embedded Rust core. The protect(fd) callback prevents the proxy core’s own remote sockets from being captured by the VPN again.

Security/reliability concerns include:

  • incorrect route or DNS configuration can leak traffic outside the intended VPN path;
  • failure to protect proxy sockets can create loops or unexpected routing;
  • per-app include/exclude policy changes which applications are inside the trust boundary;
  • profile files and remote subscription metadata remain sensitive application data;
  • Android VPN permission proves user authorization to create the VPN, not remote proxy identity.

When the same profile behaves differently on desktop and Android, do not immediately weaken TLS/protocol checks to make Android work. Prove the VPN/TUN/protection path first.

DNS Privacy and Routing Leaks

A proxy can carry application traffic while DNS still leaves through an unintended resolver.

Leak risks include:

  • application resolves locally before using a proxy;
  • system DNS bypasses the Client DNS listener;
  • TUN captures traffic but DNS hijack/routing does not match;
  • Fake-IP reverse mapping fails and routing falls back unexpectedly;
  • server-side domain resolution reveals destinations to the server’s resolver even when the client used remote-domain semantics.

Decide explicitly where names should be resolved and test that path. DNS privacy is not automatically provided by SOCKS5, HTTP CONNECT, or a remote encrypted proxy protocol.

TUN and Transparent Routing Risks

TUN, redir, TProxy, and Dokodemo followRedirect move policy into operating-system routing/firewall state.

Common risks are:

  • traffic bypass because a route/table/rule is missing;
  • routing loops;
  • DNS escaping through an interface not covered by policy;
  • accidentally capturing the proxy server connection itself;
  • exposing a transparent listener to networks that should never reach it;
  • assuming followRedirect creates interception rules when it only consumes original-destination metadata.

Treat OS routes/firewall state as part of the security configuration, not as an implementation detail outside the proxy.

Remote Listener Exposure

A server listener should expose only the protocol/transport actually intended for remote clients.

Controls include:

  • bind only required addresses/interfaces;
  • firewall only required TCP/UDP ports;
  • remove obsolete inbounds and fallback listeners;
  • avoid exposing management APIs on the same trust level as public proxy inbounds;
  • verify IPv6 exposure separately from IPv4;
  • treat QUIC/UDP reachability as a separate firewall surface from TCP.

A protocol’s authentication failure behavior matters only after the attacker can reach the listener.

TLS Security

For TLS-based transports/protocols:

  • keep certificate verification enabled on clients unless there is a documented private trust model;
  • validate SNI/server names deliberately;
  • protect server private keys with restrictive file permissions;
  • rotate certificates/keys according to deployment policy;
  • provide client certificate/key together when mTLS is required;
  • keep ALPN aligned with the transport (h2 is required by the current Server gRPC/TLS path).

skip-cert-verify is a security downgrade, not a generic troubleshooting switch. If disabling it makes a connection work, fix the trust/SNI/certificate problem rather than leaving verification off.

REALITY Security Boundary

REALITY adds a transport-security/camouflage mechanism but does not replace the inner proxy account/flow checks.

Protect:

  • the REALITY private key;
  • expected server names;
  • short IDs;
  • VLESS UUID/flow configuration separately.

Current Server tests deliberately cover cases where wrong server name, short ID, public key, client version, VLESS UUID, or Vision flow fail independently.

Fallback behavior is part of the security design. A mismatch may route traffic to the configured REALITY destination rather than simply closing. Ensure that destination is safe to expose and that fallback cannot be abused to reach an unintended internal service.

Shadowsocks Security

For classic AEAD:

  • use modern AEAD methods supported by both peers;
  • protect passwords/master keys;
  • never reuse salt/nonce material deliberately;
  • keep replay defenses enabled.

For AEAD-2022:

  • the current Server treats configured Base64 material as raw PSK and enforces exact key length;
  • timestamp validation makes clock synchronization relevant;
  • session/packet replay windows are active security state;
  • multi-user EIH changes user selection and must use supported method combinations.

Do not advertise a Client-only cipher as Server-compatible without interoperability evidence.

AnyTLS Security

AnyTLS uses two distinct layers:

  1. TLS for encrypted transport/server identity;
  2. a deterministic 32-byte SHA256(password) authentication token inside TLS.

Use a high-entropy password and keep TLS certificate verification enabled. The password hash is not a substitute for server certificate authentication.

The current Client inbound can send unknown-password traffic to a configured fallback after TLS termination. That fallback receives decrypted TLS application bytes. Point it only at a service intentionally designed to receive such traffic.

Parsed-only fingerprint/idle-session fields must not be relied upon as active security controls in the current runtime.

Trojan Security

Trojan depends on TLS plus its password-based proxy authentication. Protect both layers independently.

Fallback rules are security-sensitive because unauthenticated or mismatched traffic can be intentionally routed elsewhere. Validate fallback destination, path/type rules, and which fields are actually implemented by Chimera Server.

A safe fallback target should not be an unauthenticated administrative or internal-only service merely because it is convenient for camouflage.

VLESS and VMess Security

A VLESS UUID identifies/authorizes a proxy user but basic VLESS does not by itself provide transport confidentiality. Use the intended VLESS Encryption and/or TLS/REALITY stack according to the deployment design.

Keep flow mode and transport compatibility explicit; changing Vision/plain flow to bypass an error can change the security and traffic-shaping model.

VMess AEAD provides its own authenticated/encrypted request/body records and anti-replay/time-related state. Protect user IDs and do not re-enable historical insecure modes merely for compatibility.

For both protocols, outer transport camouflage is separate from inner proxy authentication.

Hysteria 2 and TUIC Security

Hysteria 2 and TUIC build on QUIC/TLS and add their own proxy authentication/session semantics.

Security/resource considerations include:

  • UDP listener exposure and firewall policy;
  • credential protection;
  • QUIC handshake/resource cost under unauthenticated floods;
  • limits on concurrent streams/sessions/associations;
  • UDP amplification/resource abuse against reachable targets;
  • idle/session cleanup;
  • target-routing policy.

Do not apply TCP-only rate/connection assumptions to a public QUIC listener.

XHTTP Metadata Exposure

XHTTP can place session IDs, sequence numbers, padding metadata, and sometimes uplink data chunks in HTTP-visible structures such as paths, query strings, headers, or cookies depending on configuration.

Even when the inner proxy stream is encrypted/authenticated, infrastructure around the HTTP layer may log metadata:

  • reverse proxy access logs;
  • CDN/WAF logs;
  • HTTP header/query tracing;
  • browser/developer tooling in unusual deployments.

Avoid putting reusable secrets into configurable XHTTP metadata keys/values. Review logging retention and redaction when using header/cookie/query placement.

Host, path, padding, and session metadata are transport validation/camouflage, not a replacement for inner proxy authentication.

gRPC and HTTPUpgrade Metadata

gRPC transport exposes service path, HTTP/2 metadata, timing, and message sizes to any infrastructure that can see the HTTP layer. TLS/REALITY can protect this on the network, but a terminating reverse proxy can still observe HTTP metadata.

HTTPUpgrade’s Host, path, and Upgrade headers likewise provide transport matching/camouflage rather than cryptographic authentication. After 101, current Chimera HTTPUpgrade carries raw inner-protocol bytes rather than WebSocket frames.

Do not confuse “request reached the correct path” with “proxy user authenticated”.

Dokodemo-door Is Not an Authenticated Proxy

Dokodemo-door has no user-authentication handshake of its own.

A fixed-target Dokodemo listener exposed to an untrusted network can act as a direct port forward to the configured service. Protect it with bind scope, firewall policy, outer security where appropriate, and target-service authentication.

For Linux followRedirect, the OS interception rules determine which traffic enters the listener. A broad or incorrect redirect rule is a security policy bug even if the Rust handler behaves exactly as designed.

Fallback Safety

Fallback is not just a compatibility feature. It changes what unauthenticated, malformed, or camouflage traffic can reach.

For every fallback path, document:

  • triggering condition;
  • destination service;
  • whether bytes are raw encrypted transport bytes or already-decrypted application bytes;
  • whether original SNI/path metadata is preserved;
  • whether the target service requires its own authentication;
  • whether an attacker can intentionally trigger fallback repeatedly.

The Server E2E suite contains fallback cases because “reject” and “route to fallback” are materially different security outcomes.

UDP and Amplification/Resource Abuse

Public UDP/QUIC listeners need resource controls independent of TCP controls.

Threats include:

  • spoofed-source traffic where the network permits it;
  • high-rate unauthenticated QUIC handshakes;
  • creating many protocol associations/sessions;
  • sending traffic toward high-amplification targets;
  • retaining idle UDP state too long;
  • oversized datagrams or fragmentation pressure.

Use firewall/rate controls, protocol authentication, bounded session state, idle expiry, and routing restrictions appropriate to the deployment.

Current implementations already contain protocol-specific replay/session/timeout controls in several paths, but those do not replace network-level abuse controls.

Logging and Redaction

Logs are valuable for troubleshooting and can also become a data leak.

Do not log or publish:

  • raw passwords/PSKs/private keys;
  • controller bearer secrets;
  • full subscription URLs containing tokens;
  • complete generated configs without sanitization;
  • authentication tokens or deterministic password hashes when they can be reused;
  • sensitive DNS/target history beyond the required operational retention.

Be careful with structured logs containing target addresses, inbound tags, user identities, SNI, XHTTP metadata, and connection chains. Decide retention and access policy deliberately.

Configuration and File Permissions

Generated configuration often contains everything needed to authenticate as the user.

Protect:

  • profile directories;
  • generated runtime YAML/JSON5;
  • TLS/REALITY key files;
  • service data/config directories;
  • test fixtures containing real secrets;
  • backups and crash reports.

Use placeholders or dedicated test credentials in repository examples. Never copy production credentials into an interoperability test merely to make it realistic.

Updates and Build Provenance

The ecosystem can run different core binaries and optional Cargo feature sets. Security review must therefore identify the actual artifact, not only the repository source.

Record:

  • core type;
  • version/commit;
  • enabled optional protocol features;
  • update source/channel;
  • checksum/signature verification process where available.

A protocol implementation existing in source does not prove the deployed binary contains it, and a security fix in source does not protect an older deployed binary.

Deployment Baseline

A reasonable baseline for an Internet-facing deployment is:

  1. bind local Client/controller listeners to loopback unless remote access is required;
  2. firewall Server ports to only the required TCP/UDP surface;
  3. enable and validate protocol authentication;
  4. enable TLS/REALITY where the protocol/transport design requires it;
  5. keep certificate verification enabled;
  6. protect credentials and generated config files;
  7. verify DNS/TUN routing does not bypass policy;
  8. review all fallback destinations;
  9. bound UDP/QUIC/session resources;
  10. redact logs and bug reports;
  11. run the strongest relevant negative/interoperability tests after security-sensitive changes.

This baseline is intentionally layered. No single checkbox replaces the others.

Security Review Checklist

Before exposing a new inbound or client control surface, answer:

  • Who can connect to it at the network layer?
  • What authenticates that peer?
  • Is the channel encrypted, and who terminates encryption?
  • What metadata remains visible outside encryption?
  • What happens on authentication failure: close, drop, or fallback?
  • Can the caller choose an arbitrary destination?
  • Can UDP/QUIC behavior be abused for resource consumption or amplification?
  • Which secrets/config files are readable by the process and local users?
  • What is logged?
  • Which negative tests prove malformed/unauthorized traffic is handled as expected?

If any answer is unknown, treat it as an unresolved deployment risk rather than assuming a protocol name implies safety.

Source Anchors

The implementation-specific boundaries in this page are derived from the current source and documentation work around:

  • Chimera_Client listener/API authorization, DNS/TUN, optional protocol features, AnyTLS and Shadowsocks implementations;
  • Chimera_Service IPC/ACL and privileged core/network management;
  • AChimera VpnService, TUN ownership, and protect(fd) bridge;
  • Chimera_Server config validation, fallback handling, protocol/transport handlers, replay/session state, routing, and tests;
  • protocol chapters in this Wiki that document current wire/security behavior;
  • negative and interoperability suites catalogued in Test Evidence and Interoperability Matrix.

When a field moves from Parsed-only/Rejected to active runtime behavior, or when a new listener/control endpoint is added, re-evaluate the corresponding trust boundary here.

Chimera_Client

Role and Source of Truth

Chimera_Client is the Clash-compatible client runtime in the Chimera ecosystem. It parses Clash-style configuration, exposes local proxy listeners, performs DNS/rule dispatch, and creates remote outbound connections.

For implementation status, the source tree is authoritative. In particular:

  • clash-lib/src/config/internal/proxy.rs defines the current outbound protocol configuration enum.
  • clash-lib/src/app/outbound/manager.rs registers concrete outbound handlers.
  • clash-lib/src/proxy/ contains protocol, inbound, outbound, and transport implementations.
  • clash-lib/Cargo.toml determines which optional implementations are present in a given binary.

See Implementation Status and Source Evidence for the evidence terminology used by this Wiki.

Current Outbound Protocols

The current outbound configuration/runtime path contains:

OutboundBuild conditionNotes
directAlwaysDirect routing action, not a remote proxy protocol.
rejectAlwaysReject routing action, not a remote proxy protocol.
socks5AlwaysSOCKS5 client/outbound implementation.
vlessAlwaysIncludes stream/datagram paths and transport/security integration such as XHTTP, Vision, and REALITY where configured.
ss / Shadowsocksshadowsocks featureTCP and UDP implementation exists; integration tests are present.
anytlsanytls featureAnyTLS outbound implementation; the same feature also exposes AnyTLS inbound code.
trojantrojan featureTrojan outbound implementation. WebSocket wrapping additionally depends on ws.
hysteria2hysteria featureQUIC/Hysteria 2 outbound implementation.

VMess, TUIC, WireGuard, and SSH are not variants of the current outbound enum. They must not be documented as current Chimera_Client outbound capabilities until a runtime path actually exists.

Current Local Inbound Surface

The client also contains local inbound implementations, which are a different capability from remote outbounds:

  • HTTP proxy inbound,
  • SOCKS inbound,
  • mixed HTTP/SOCKS listener,
  • Shadowsocks inbound behind shadowsocks,
  • AnyTLS inbound behind anytls,
  • TUN, redir, and TProxy paths according to Cargo features and platform support.

Known boundaries should be stated explicitly:

  • the current SOCKS inbound path reports UDP as unsupported,
  • the mixed inbound path reports UDP as unsupported,
  • a protocol being implemented behind a Cargo feature does not mean it is present in the default binary.

Default Build vs Optional Features

The current default feature set enables:

  • zero_copy,
  • tls,
  • aws-lc-rs,
  • tun,
  • port,
  • reality,
  • extended-health-check.

The following protocol/transport implementations are separate features:

  • ws,
  • anytls,
  • shadowsocks,
  • trojan,
  • hysteria.

This distinction matters operationally. A profile can be syntactically valid for the project while a particular binary was built without the feature needed to instantiate its handler.

Parsed Compatibility Is Not Runtime Support

Some configuration fields intentionally exist only to accept ecosystem configuration shapes. The AnyTLS configuration is a concrete example: several fields are annotated in source as parsed for compatibility but currently not applied by the runtime.

Documentation should therefore distinguish:

  1. Parsed — serde accepts the field,
  2. Constructed — a handler can be built,
  3. Implemented — a forwarding path uses it,
  4. Tested — integration or interoperability tests exercise it.

Do not infer level 3 or 4 from level 1.

Architecture Overview

Internally, the client is organized into four broad layers:

  1. Configuration layer
    • Parses Clash-style YAML into typed Rust structures.
    • Applies defaults and validation.
    • Converts external configuration into runtime-specific forms.
  2. Inbound/controller layer
    • Owns local proxy listeners and TUN/transparent-entry paths.
    • Exposes management APIs for status, switching, traffic, and diagnostics.
  3. Policy and DNS layer
    • Evaluates rules with first-match semantics.
    • Provides system/enhanced DNS paths, Fake-IP behavior, resolver policy, and DNS-rule dispatch hooks.
  4. Outbound/transport layer
    • Selects the outbound handler.
    • Applies transport/security wrappers such as WebSocket, XHTTP, TLS, and REALITY where the selected protocol supports them.
    • Executes protocol handshakes and forwarding.

A useful mental model is:

local listener / TUN
        |
        v
metadata + DNS + rules
        |
        v
outbound manager
        |
        v
proxy protocol
        |
        v
optional transport/security wrapper
        |
        v
remote server

VLESS as a Current Client Capability

VLESS is a current outbound, not merely a planned target. The source contains configuration fields for network, XHTTP options, REALITY options, flow, client fingerprint, TLS settings, and UDP behavior, together with concrete VLESS stream/datagram and Vision modules.

When documenting a VLESS combination, keep the layers separate. For example:

VLESS identity / command
        |
     Vision flow      (optional protocol optimization)
        |
     XHTTP            (optional transport)
        |
     REALITY/TLS      (optional security layer)
        |
     TCP/HTTP stack

The presence of one layer does not automatically prove every combination of the others is tested.

Integration Evidence

The repository currently contains dedicated integration coverage including:

  • clash-lib/tests/anytls_integration_tests.rs,
  • clash-lib/tests/shadowsocks_integration_tests.rs,
  • direct UDP, DNS, TUN/Fake-IP, controller/API, connection-chain, and socket protection tests.

Use these tests as stronger evidence than README capability lists when updating this Wiki.

Module Guide

  • Ports and listeners: key mapping and local inbound support. See Ports and Listeners.
  • DNS module: Fake-IP vs real-IP models, resolver policy, and implementation status. See DNS Module.
  • TUN module: route-all/split-route semantics and platform considerations. See Tun Module.
  • Rules module: rule taxonomy, ordering, and provider-based policy. See Rule Types and Their Effects.

Relationship to Clash-rs and Mihomo

clash-rs and Mihomo remain important compatibility references, but they are not proof that an option is implemented in Chimera_Client.

  • clash-rs is a useful Rust architectural/configuration reference.
  • Mihomo is a broad ecosystem compatibility reference.
  • Chimera_Client source and tests determine what the current Chimera binary can actually do.

Migration documentation should explicitly call out fields that are parsed-only, feature-gated, rejected, or behaviorally different.

Deployment Guidance

For a new deployment:

  1. confirm the binary was built with the required Cargo features,
  2. validate the profile,
  3. start with a local HTTP/SOCKS listener before adding TUN,
  4. verify DNS/rule behavior,
  5. add the remote protocol and transport/security layers one at a time,
  6. use integration/interop-tested combinations where possible.

For CI, keep both a minimal profile and profiles that exercise the optional features enabled by the produced artifact.

Reference Repositories

Ports and Listeners

Purpose

Listeners define how local applications and operating-system traffic enter chimera_client. They are the first boundary between an application and the proxy core, so listener selection should be treated separately from outbound protocol selection.

For most deployments, start with an application-level listener such as SOCKS5 or HTTP before enabling transparent or TUN-based capture.

Listener Overview

Configuration keyRoleTypical useNotes
port / http-portHTTP proxy listenerBrowsers, system HTTP proxyPrimarily TCP proxy traffic
socks-portSOCKS5 listenerGeneral application proxyingGood baseline for local testing
mixed-portHTTP + SOCKS5 listenerOne shared application endpointConvenient when clients expose only one proxy field
redir-portTransparent redirect listenerLinux gateway/router setupsPrimarily TCP redirect workflows
tproxy-portTransparent proxy listenerLinux TCP/UDP interceptionRequires firewall and policy-routing integration
external-controllerManagement APIGUI, dashboards, automationBind to loopback unless remote access is intentional
dns.listenDNS listenerLocal DNS interception/resolutionUsually used with enhanced DNS or TUN

Availability can depend on build features, platform support, and the exact chimera_client revision. A configuration key being accepted does not by itself guarantee that the corresponding runtime path is enabled.

Listener Selection

SOCKS5

SOCKS5 is the safest starting point when validating a new profile. It does not require route changes and is supported by a wide range of applications.

bind_address: "127.0.0.1"
allow_lan: false
socks_port: 7891

Use SOCKS5 first when you want to separate proxy-core behavior from operating system routing and DNS interception issues.

The currently audited Client SOCKS inbound does not provide a complete UDP ASSOCIATE relay path: UDP requests on this local inbound currently return unsupported. Do not infer local SOCKS UDP support from the existence of SOCKS outbound UDP handling elsewhere in the codebase.

HTTP Proxy

An HTTP proxy listener is convenient for browsers and operating-system proxy settings. HTTPS traffic normally enters through HTTP CONNECT tunneling.

port: 7890

Mixed Listener

A mixed listener accepts both HTTP-proxy and SOCKS-style clients on one port. It is useful for desktop setups where exposing a single endpoint is simpler than managing separate HTTP and SOCKS ports.

mixed-port: 7892

The currently audited mixed listener is likewise a TCP-focused local entry for HTTP/SOCKS use; its UDP path is explicitly unsupported. Use the protocol/status matrix when a deployment requires local UDP ingress rather than assuming a mixed port provides SOCKS UDP parity.

Transparent Listeners

redir-port and tproxy-port are intended for routing-level interception, primarily on Linux. They should not be treated as drop-in replacements for SOCKS5 or HTTP listeners.

Transparent proxying normally also requires:

  • firewall rules,
  • loop-prevention rules,
  • policy routing for TProxy deployments,
  • and a DNS strategy that preserves enough domain information for rule matching.

For host-wide interception, also see Tun Module.

Controller and DNS Bindings

Management and DNS listeners deserve stricter exposure rules than ordinary local proxy listeners.

During development, prefer loopback-only bindings:

external-controller: 127.0.0.1:9090

dns:
  enable: true
  listen: 127.0.0.1:1053

Do not expose the controller or DNS listener to a LAN or public interface unless you have intentionally configured access controls and understand the security impact.

Example Local Profile

The following layout keeps all application-facing services local while making listener roles explicit:

bind_address: "127.0.0.1"
allow_lan: false

port: 7890
socks_port: 7891
mixed_port: 7892
external_controller: "127.0.0.1:9090"

dns:
  enable: false

Exact accepted key spelling can vary between compatibility layers. When importing Clash/Mihomo profiles, preserve the original profile where practical and verify the normalized runtime configuration produced by the client.

Platform and Compatibility Notes

  • Application-level HTTP and SOCKS listeners are the easiest paths to validate across platforms.
  • Transparent redirect and TProxy workflows are platform-specific and require operating-system network configuration outside the YAML file.
  • TUN support has its own privilege, routing, and DNS requirements; see Tun Module.
  • Listener availability may be gated by Cargo features or runtime build choices.
  • Controller behavior should be treated as an API surface rather than a proxy protocol endpoint.

Troubleshooting

When a local application cannot connect through the core, check the listener before debugging outbound protocols:

  1. Confirm the process is running and the expected port is listening.
  2. Verify the application points to the correct listener type and port.
  3. Confirm the listener is bound to the expected address (127.0.0.1, LAN IP, or wildcard address).
  4. Check whether allow_lan or equivalent exposure settings block remote clients.
  5. Test with a minimal SOCKS5 or HTTP profile before enabling TUN, Redir, or TProxy.
  6. If routing works by IP but domain rules fail, inspect the DNS path as well.

DNS Module

Purpose

DNS is part of the routing pipeline, not just a name-to-address lookup service. The resolver strategy affects whether domain rules remain usable, whether TUN traffic can be classified correctly, and whether DNS requests bypass the proxy unexpectedly.

A stable DNS setup should answer three questions clearly:

  1. Which resolver handles a query?
  2. Does the client keep the original domain identity for later rule matching?
  3. Does DNS traffic itself follow the intended proxy or direct path?

Operating Modes

ModeBest fitAdvantagesTrade-offs
System / DNS disabledSimple app-level proxyingLeast invasive, easiest to debugDepends on OS resolver behavior
Real-IP / redir-host styleConservative enhanced DNSApplications receive real addressesDomain identity can be harder to retain in transparent flows
Fake-IPTUN and domain-heavy routingPreserves domain intent for later connection matchingRequires exclusions and careful DNS integration

Start with the system resolver or real-IP behavior when validating a new setup. Introduce Fake-IP only when the routing model benefits from it.

Resolver Pipeline

A Clash-style enhanced resolver generally follows this conceptual sequence:

application query
      |
      v
hosts/cache lookup
      |
      v
policy/default resolver selection
      |
      v
upstream DNS query
      |
      +----> fallback / validation path when configured
      |
      v
cache + answer
      |
      v
rule engine / connection flow

The exact fallback and policy behavior depends on the current chimera_client implementation and should not be assumed to match every Mihomo edge case.

Conservative Configuration

For application-level SOCKS5 or HTTP proxying, keeping enhanced DNS disabled is a useful baseline:

dns:
  enable: false
  ipv6: false

If this works but an enhanced-DNS profile does not, the failure is probably in the DNS interception/resolver path rather than the outbound proxy itself.

Local DNS Listener

A local listener lets the operating system, TUN path, or other applications send queries directly to chimera_client:

dns:
  enable: true
  listen: 127.0.0.1:1053
  ipv6: false

During development, keep the listener on loopback. Binding DNS to a LAN or public interface can expose an unintended resolver service.

Fake-IP Example

dns:
  enable: true
  listen: 127.0.0.1:1053
  ipv6: false
  enhanced-mode: fake-ip
  fake-ip-range: 198.18.0.1/16
  fake-ip-filter:
    - "*.lan"
    - "*.local"

  default-nameserver:
    - 1.1.1.1
    - 8.8.8.8

  nameserver:
    - https://dns.alidns.com/dns-query
    - tls://1.1.1.1:853

Fake-IP exclusions should be kept small and understandable. Large copied filter lists can hide routing mistakes and make failures difficult to reproduce.

Policy and Fallback Example

dns:
  enable: true
  listen: 127.0.0.1:1053
  ipv6: false

  nameserver:
    - https://dns.alidns.com/dns-query

  fallback:
    - 9.9.9.9

  fallback-filter:
    geoip: true
    geoip-code: CN

The schema and resolver hooks for policy/fallback behavior exist in the current client documentation, but full behavioral parity with Mihomo should be verified before relying on unusual edge cases.

DNS and Rules

DNS mode directly affects the rule engine:

  • Domain-based rules need access to the original hostname or equivalent metadata.
  • IP rules depend on the resolved destination address.
  • Fake-IP is most useful when an application resolves first and connects later, because the client can map the synthetic address back to the original domain.
  • A DNS request that bypasses the intended resolver path can cause apparently random rule mismatches.

When debugging rules, inspect DNS before changing rule order blindly.

DNS and TUN

TUN deployments often combine three separate mechanisms:

  1. host traffic capture,
  2. DNS interception or resolver redirection,
  3. enhanced DNS such as Fake-IP.

dns-hijack in the TUN configuration does not replace a valid DNS configuration. It only controls how captured DNS traffic is redirected into the DNS path. See Tun Module for the routing side.

Upstream Resolver Guidance

When choosing upstreams:

  • keep at least one simple resolver path available while debugging;
  • verify that encrypted DNS endpoint hostnames can be bootstrapped;
  • avoid mixing many upstreams until the basic path is known to work;
  • consider whether DNS itself should be proxied or sent directly;
  • treat resolver latency, failure, and blocking as routing signals, not just DNS errors.

Compatibility Notes

The current documentation describes support or runtime hooks for:

  • the system resolver path,
  • a local DNS listener,
  • enhanced/Fake-IP resolution,
  • nameserver policy and fallback structures,
  • and respect-rules-style DNS dialing hooks.

These capabilities are aligned with the Clash family, but this Wiki should not claim blanket Mihomo parity. Configuration syntax can also differ between the external Clash-style form and the client’s normalized internal representation.

Troubleshooting

Use this order when DNS-related behavior looks wrong:

  1. Confirm ordinary network connectivity without enhanced DNS.

  2. Confirm the local DNS listener is actually reachable.

  3. Query the listener directly, for example:

    dig @127.0.0.1 -p 1053 example.com
    
  4. Check whether the OS or TUN path really sends DNS to that listener.

  5. Temporarily use one simple upstream resolver to isolate DoH/DoT problems.

  6. Inspect timeout, TLS, bootstrap, and validation errors in logs.

  7. If Fake-IP is enabled, verify that the affected domain is not unexpectedly included in the filter list.

  8. If rules are wrong, compare the domain seen by the rule engine with the final resolved IP.

Tun Module

Purpose

TUN mode captures IP traffic at the operating-system network layer and sends it into the proxy pipeline without requiring each application to configure an HTTP or SOCKS proxy.

It is the closest chimera_client mode to a host-wide proxy, but it is also the mode with the most external dependencies: interface creation, privileges, routes, loop prevention, DNS handling, and platform-specific behavior all need to work together.

For a new deployment, validate an application-level listener first. Only enable TUN after the core, outbound protocol, and basic rule set are already known to work.

Current Status

The current client documentation exposes a tun configuration block and carries TUN configuration into the internal runtime representation. Actual behavior is still dependent on:

  • whether the build includes the required TUN feature/runtime code,
  • the target operating system,
  • sufficient privileges,
  • route-management support,
  • and a compatible DNS configuration.

A successfully parsed tun block does not by itself prove that the host routing setup is active.

Core Configuration

tun:
  enable: true
  device-id: "dev://tun0"
  route-all: true
  gateway: "198.18.0.1/24"
  mtu: 1500
  dns-hijack: true

The exact set of accepted keys follows the current chimera_client/clash-rs configuration path rather than being a promise of full Mihomo key compatibility.

Key Fields

KeyPurposeOperational notes
enableEnables the TUN pathOther TUN fields are irrelevant while disabled
device-idSelects or identifies the TUN deviceMay be platform-specific
gatewayIPv4 address/prefix for the TUN interfaceCommonly uses a dedicated private/benchmark range
gateway-v6Optional IPv6 address/prefixNeeded when IPv6 is intentionally carried through TUN
route-allFull-tunnel routing switchBroadest and most invasive mode
routesPrefix list for split routingUsed when only selected networks should enter TUN
mtuInterface MTUUseful when diagnosing fragmentation or PMTU problems
so-markLinux packet markHelps integrate loop prevention and policy routing
route-tableLinux policy-routing tableAvoid conflicts with existing host route tables
dns-hijackRedirects captured DNS into the client DNS pathRequires a working DNS module configuration

Deployment Modes

Full Tunnel

A full-tunnel profile attempts to route most host traffic through the TUN interface:

tun:
  enable: true
  device-id: "dev://tun0"
  route-all: true
  gateway: "198.18.0.1/24"
  dns-hijack: true

Use this only after confirming that the core has a reliable path to its remote proxy server. Otherwise the proxy’s own outbound connection can be captured by TUN and form a routing loop.

Split Tunnel

A split-tunnel profile limits TUN routing to selected prefixes:

tun:
  enable: true
  device-id: "dev://tun0"
  route-all: false
  gateway: "198.18.0.1/24"
  routes:
    - 1.1.1.1/32
    - 8.8.8.8/32
  dns-hijack: false

Split routing is useful for staged rollout because it changes less of the host’s network behavior.

Device Selection

The inherited configuration path documents device identifiers such as:

  • dev://tun0 — named TUN device,
  • tun0 — plain device-name form,
  • dev://utun1989 — macOS-style utun device,
  • fd://3 — advanced file-descriptor handoff where supported by the runtime.

Do not assume every form is meaningful on every operating system. In ordinary desktop use, prefer the simplest platform-native device form supported by the selected build.

Routing Model

TUN introduces two traffic directions that must stay distinct:

application traffic
       |
       v
   TUN interface
       |
       v
 chimera_client
       |
       +---- rules / DNS ----+
       |                     |
       v                     v
 proxy outbound          DIRECT/reject
       |
       v
 physical network

The core’s own outbound traffic must reach the physical network without being captured back into the same TUN path. Linux deployments commonly use packet marks and policy routing for this purpose; other platforms use their own route management mechanisms.

DNS Interaction

TUN and DNS should be designed together.

A common failure mode is that application traffic enters TUN while DNS still uses an unrelated system path. This can cause:

  • domain rules to stop matching,
  • Fake-IP mappings to be bypassed,
  • DNS leaks,
  • or traffic to appear to work inconsistently between applications.

dns-hijack only controls interception of captured DNS traffic. It does not replace a valid dns: configuration.

For domain-heavy rule sets, verify the DNS flow described in DNS Module before assuming the TUN route itself is wrong.

Linux Notes

Linux TUN deployments may require root-equivalent privileges or capabilities such as CAP_NET_ADMIN, depending on how the process creates interfaces and routes.

When policy routing is involved, useful inspection commands include:

ip addr
ip rule
ip route
ip route show table 2468
ip -6 route

If so-mark or a dedicated route table is configured, make sure the values do not conflict with rules installed by another VPN, container runtime, firewall, or proxy application.

Windows and macOS Notes

On Windows and macOS, TUN behavior is still sensitive to privileges, route ownership, interface setup, and other networking software running on the host.

When troubleshooting these platforms:

  • check whether another VPN or proxy tool is already managing default routes;
  • verify the TUN interface was created successfully;
  • inspect route changes before and after enabling TUN;
  • disable competing network-filter or VPN software temporarily when isolating a problem;
  • and restore application-level SOCKS/HTTP proxying to confirm that the proxy core itself remains healthy.

MTU

MTU problems often look like partial connectivity: small requests work while larger TLS or QUIC transfers stall.

If that happens:

  1. keep the default MTU first;
  2. confirm the problem only appears through TUN;
  3. lower the MTU gradually if the network path requires it;
  4. re-test both TCP and UDP-based outbound protocols.

Avoid treating an arbitrary low MTU as a permanent fix without identifying the underlying path limitation.

Compatibility Notes

chimera_client inherits several TUN concepts from clash-rs, while Mihomo uses some different key names and routing abstractions. Similar functionality does not always mean configuration is interchangeable.

Examples of potential differences include:

  • device naming and file-descriptor handoff,
  • explicit gateway / gateway-v6 fields,
  • route-all and routes versus Mihomo-style auto-route controls,
  • route-table naming,
  • and Linux packet-mark configuration.

When migrating a Mihomo profile, translate TUN settings deliberately instead of copying the entire block and assuming semantic parity.

Use this sequence to reduce the number of variables being debugged at once:

  1. Start chimera_client with TUN disabled.
  2. Verify SOCKS5 or HTTP proxying works.
  3. Verify the intended outbound proxy and rule group work.
  4. Configure DNS and confirm direct queries to the client resolver succeed.
  5. Enable TUN without adding unnecessary custom routes or MTU overrides.
  6. Confirm the interface is created.
  7. Confirm host routes changed as expected.
  8. Confirm the core’s own outbound traffic is not looping back into TUN.
  9. Enable DNS hijacking/Fake-IP only after ordinary TUN traffic works.
  10. Add advanced split routes, packet marks, or custom route tables last.

Troubleshooting

If TUN is enabled but traffic fails, inspect the layers in order:

  1. Interface — was the TUN device created?
  2. Privileges — did route/interface operations succeed?
  3. Routes — is traffic actually pointed at TUN?
  4. Loop prevention — can the proxy core still reach its remote server?
  5. DNS — are queries using the intended resolver path?
  6. Rules — does the captured flow contain enough metadata for the expected rule?
  7. MTU — do only large packets or particular transports fail?
  8. Platform conflicts — is another VPN/proxy/firewall modifying the same routes?

If the problem remains unclear, return to SOCKS5/HTTP mode and re-enable TUN one piece at a time.

Rule Types and Their Effects

Purpose

Rules decide which outbound policy handles a connection. In the Clash-style model used by chimera_client, evaluation is ordered: rules are checked from top to bottom and the first matching rule wins.

That makes rule order just as important as rule syntax. A valid rule placed too late can be effectively unreachable because an earlier rule already captured the flow.

Rule Evaluation Model

A routing decision can use several kinds of metadata:

  • domain name, SNI, or HTTP host,
  • resolved destination IP,
  • source or destination port,
  • source subnet,
  • process identity when supported by the platform,
  • GeoIP/GeoSite datasets,
  • and external rule-provider sets.

The selected target is usually an outbound or policy group such as DIRECT, REJECT, Proxy, or Auto.

Domain Rules

DOMAIN

Matches one exact hostname.

rules:
  - DOMAIN,api.github.com,Proxy

Use this for the most precise domain-based exceptions.

DOMAIN-SUFFIX

Matches a domain suffix and its subdomains.

rules:
  - DOMAIN-SUFFIX,google.com,Proxy

This is usually preferable to a broad keyword when an entire domain tree should share the same policy.

DOMAIN-KEYWORD

Matches a substring in the domain name.

rules:
  - DOMAIN-KEYWORD,openai,Proxy

Keyword rules are easy to overmatch. Keep them below more precise domain rules unless broad matching is intentional.

IP and Network Rules

IP-CIDR

Matches an IPv4 destination prefix.

rules:
  - IP-CIDR,1.1.1.0/24,DIRECT

IP-CIDR6

Matches an IPv6 destination prefix.

rules:
  - IP-CIDR6,2606:4700::/32,DIRECT

SRC-IP-CIDR

Matches the source subnet. This is most useful when the client is acting as a router or gateway for multiple devices.

rules:
  - SRC-IP-CIDR,192.168.50.0/24,GameProxy

GEOIP

Matches an IP against a geographic database.

rules:
  - GEOIP,CN,DIRECT

GeoIP results are only as accurate as the installed dataset. Treat database freshness as part of the routing configuration.

GEOSITE

Matches a domain against a maintained category/list dataset.

rules:
  - GEOSITE,geolocation-!cn,Proxy

As with GeoIP, behavior depends on the data files actually available to the runtime.

Port and Process Rules

DST-PORT

Matches the remote destination port.

rules:
  - DST-PORT,443,Proxy

Port-only routing is broad. Place service-specific domain rules above it when possible.

SRC-PORT

Matches the local/source port.

rules:
  - SRC-PORT,60000-60100,DIRECT

PROCESS-NAME

Matches the executable name when process inspection is supported.

rules:
  - PROCESS-NAME,Telegram.exe,Proxy

PROCESS-PATH

Matches a full executable path.

rules:
  - PROCESS-PATH,/Applications/Discord.app/Contents/MacOS/Discord,Proxy

Process rules are platform-sensitive and can be affected by permissions, application launchers, sandboxing, and executable path changes. Validate them on every target operating system.

Rule Providers

RULE-SET delegates matching to a named rule provider.

rule-providers:
  streaming:
    type: http
    behavior: domain
    url: https://example.com/streaming.yaml
    interval: 86400
    path: ./ruleset/streaming.yaml

rules:
  - RULE-SET,streaming,Proxy

Rule providers make large policy sets easier to maintain, but introduce another runtime dependency. A stale, unavailable, or incompatible provider can make a routing policy behave differently from its source configuration.

For important providers, keep the source, update interval, expected behavior, and local cache path explicit.

Final Fallback

MATCH is the catch-all rule and should normally be last.

rules:
  - MATCH,DIRECT

Anything after MATCH is unreachable.

A practical rule set usually moves from narrow/high-priority decisions to broad fallbacks:

  1. explicit blocks and local/private bypass rules;
  2. exact domain or process exceptions;
  3. specific IP and port rules;
  4. provider/category rules such as RULE-SET and GEOSITE;
  5. broad heuristics such as DOMAIN-KEYWORD and GEOIP;
  6. final MATCH fallback.

This is a guideline rather than a mandatory ordering. The important property is that earlier rules intentionally take priority over later ones.

Example Policy

rules:
  - DOMAIN,internal.example.com,DIRECT
  - DOMAIN-SUFFIX,corp.example.com,DIRECT
  - PROCESS-NAME,Telegram.exe,Proxy
  - GEOSITE,category-ads-all,REJECT
  - GEOIP,CN,DIRECT
  - RULE-SET,streaming,Proxy
  - MATCH,Auto

Read the example from top to bottom: an exact corporate exception wins before a broader geographic or provider rule can see the same connection.

DNS Interaction

Many apparent rule failures are actually DNS-context failures.

  • Domain rules require the runtime to know the original hostname.
  • IP rules depend on the address returned by the resolver.
  • Fake-IP can help preserve domain intent through a later connection attempt.
  • Transparent and TUN traffic can lose domain context if DNS bypasses the client’s intended resolver path.

When a domain rule works through SOCKS5 but fails through TUN, compare the DNS path before changing the rule itself. See DNS Module.

Compatibility Notes

The core first-match model and common Clash rule syntax are intended to remain portable across chimera_client, clash-rs, and Mihomo. Exact support still varies by runtime feature and platform.

In particular:

  • process matching is platform-dependent;
  • GeoIP/GeoSite behavior depends on local datasets;
  • provider behavior depends on provider format and refresh success;
  • DNS mode and inbound type can change the metadata available to a rule;
  • newer Mihomo-only rule types should not be assumed to work unless they are explicitly implemented by the selected client core.

Troubleshooting

When a connection selects the wrong outbound, debug the decision in this order:

  1. Identify the first rule that actually matched, not the rule you expected to match.
  2. Check whether an earlier broad rule shadows the intended one.
  3. Confirm the policy/group named by the rule exists.
  4. For domain rules, verify that the runtime still knows the hostname.
  5. For IP/GeoIP rules, verify the resolved address and database state.
  6. For process rules, confirm the observed executable name/path on that OS.
  7. For RULE-SET, confirm the provider loaded and refreshed successfully.
  8. Temporarily reduce the rules to a few explicit entries plus MATCH to isolate the problem.

Chimera GUI

Design Goals

Chimera is the desktop control surface for the Chimera client ecosystem. It is built with Tauri, Rust, and React, and its job is to make daily proxy operation clearer: import profiles, switch nodes, select the proxy core, inspect runtime state, manage system integration, and keep the core/app updated.

The core design priorities of Chimera are:

  • stable cross-platform desktop behavior,
  • clear profile and subscription management,
  • first-class support for chimera-client while retaining compatibility with clash-rs and mihomo,
  • reliable core lifecycle management through child-process and service-mode paths,
  • practical diagnostics through logs, connection views, core status, and configuration-directory access.

Runtime Boundary

Chimera is a control application, not a proxy protocol engine. Protocol availability, transport behavior, and packet forwarding are provided by the selected core. This distinction is important when comparing features: a feature visible in the GUI is not necessarily implemented by every supported core, and a core capability may require additional UI integration before it is exposed in Chimera.

Runtime Responsibilities

Chimera manages local state and delegates packet/protocol handling to a selected core. The main responsibilities visible in the companion codebase are:

  • profile import, update, deletion, viewing, editing, and runtime patching,
  • Clash-style runtime YAML generation from app settings plus active profile,
  • core selection among sidecars such as mihomo, clash-rs, and chimera-client,
  • core start, stop, restart, recovery, version query, and update,
  • system proxy, deep link, notification, dialog, tray, and single-instance integration,
  • service-mode install, uninstall, start, stop, restart, and status workflows.

Currently Supported Platforms

First Tier

  • Windows
  • macOS
  • Linux

Second Tier

  • NixOS

Core-Dependent Protocol Surface

Chimera does not have one fixed protocol matrix of its own. The selected core is an explicit runtime choice, and the desktop source maps several Clash-family core types into the shared core-management layer, including Mihomo, clash-rs, and Chimera Client variants.

A generated profile can therefore contain a field that one selected core supports and another rejects or interprets differently. Protocol claims in this Wiki should be attached to the core implementation rather than to the desktop GUI.

For the current Chimera Client matrix, see Chimera_Client. For a source-audited cross-project view, see Implementation Status and Source Evidence.

Foreground and Service Runtime Paths

The desktop currently has two distinct core ownership paths:

foreground: Chimera -> child core
service:    Chimera -> local IPC -> Chimera_Service -> child core

Both paths use the desktop-generated runtime configuration. Service mode moves process ownership and privileged control into Chimera_Service; it does not move profile merge/rule semantics into the service.

See Service Mode Configuration for the actual IPC boundary and lifecycle.


Chimera Runtime Configuration: Inputs, Generation, and Loading

This page describes how Chimera prepares the configuration used by its core. At startup and during hot reload, the core uses a generated runtime file rather than reading profiles.yaml directly. The backend assembles the runtime configuration in memory, writes it to disk, and provides it to the core through startup arguments or the Clash API.

  • Upstream alignment: Needs assessment
  • Local maturity: In development

1. Inputs and Initialization

The runtime configuration draws on four kinds of input:

  1. Application settings — chimera-config.yaml, represented by IVerge and loaded through backend/tauri/src/config/chimera/mod.rs → IVerge::new(). These settings control field filtering, port strategy, TUN behavior, and system-proxy behavior.
  2. Clash Guard overrides — clash-guard-overrides.yaml, represented by IClashTemp and loaded through backend/tauri/src/config/clash/mod.rs → IClashTemp::new(). These values override selected fields such as mode, mixed-port, external-controller, and secret.
  3. Profile metadata — profiles.yaml, represented by Profiles and loaded through backend/tauri/src/config/profile/profiles.rs → Profiles::new(). It records the active profile (current) and the profile list (items).
  4. Profile content — app_config_dir/profiles/*.yaml, read through Profiles::current_mappings(). These files contain configuration such as proxies, rules, DNS, and TUN settings.

Startup initialization

backend/tauri/src/utils/init/mod.rs → init_config() creates the following files when they are missing:

  • clash-guard-overrides.yaml, using IClashTemp::template()
  • chimera-config.yaml, using IVerge::template()
  • profiles.yaml, with an empty or default configuration

backend/tauri/src/config/core.rs → Config::global() initializes Profiles::new(), IVerge::new(), IClashTemp::new(), and IRuntime::new(). IRuntime holds the in-memory runtime configuration; its config field is an Option<Mapping>.

2. Runtime Configuration Generation

The documented entry point is Config::generate() in backend/tauri/src/config/core.rs:

flowchart TD
  A["Start Config::generate"] --> B["Call enhance::enhance"]
  B --> C["Read YAML(s) of current profile"]
  C --> D["merge_profiles: merge configs"]
  D --> E["(Optional) whitelist-based field filtering"]
  E --> F["Override key fields (HANDLE_FIELDS)"]
  F --> G["Write into in-memory runtime config"]
  G --> H["Write out clash config YAML"]
  H --> I["Load at startup or hot-reload via PUT /configs"]

enhance::enhance() in backend/tauri/src/enhance/mod.rs performs these steps:

  1. Loads Clash Guard settings from Config::clash().latest().0.clone().
  2. Reads feature settings from IVerge, including enable_clash_fields.
  3. Loads the active profile content through Profiles::current_mappings(). This iterates over current, reads each profiles/<file>.yaml, and converts it to a Mapping.
  4. Calls process_chain(...) for profile-chain scripts. In the implementation described here, this is a placeholder and returns the original configuration unchanged.
  5. Calls merge_profiles(...) to combine profile configurations. The first configuration is merged in full with extend; later configurations append only their proxies to the existing proxies list.
  6. Optionally filters fields through use_whitelist_fields_filter(...). When enable_clash_fields = true, only keys in the valid and default field sets are retained.
  7. Copies the fields in HANDLE_FIELDS from IClashTemp into the final configuration so the client centrally controls these values.

HANDLE_FIELDS, defined in backend/tauri/src/enhance/field.rs, contains:

  • mode
  • port
  • socks-port
  • mixed-port
  • allow-lan
  • log-level
  • ipv6
  • secret
  • external-controller

If a profile also defines one of these fields, the corresponding value from clash-guard-overrides.yaml takes precedence.

3. Runtime File and Core Loading

Config::generate_file(ConfigType::Run) in backend/tauri/src/config/core.rs writes the runtime output to app_config_dir()/clash-config.yaml. In Check mode, it writes to temp_dir()/clash-config-check.yaml. If generation fails, Config::init_config() falls back to writing IClashTemp directly as the runtime configuration.

At startup

CoreManager::run_core() → Instance::try_new() in backend/tauri/src/core/clash/core.rs calls Config::generate_file(ConfigType::Run) and passes the resulting path to the core through CoreInstanceBuilder.config_path(config_path). The core then reads clash-config.yaml at startup.

During hot reload

CoreManager::update_config() follows this sequence:

  1. Config::generate().await? rebuilds the in-memory configuration.
  2. check_config().await? validates it using the check file.
  3. generate_file(Run) rewrites clash-config.yaml.
  4. The client sends PUT /configs with { "path": "<absolute path>" } to ask the core to reload it.

Relevant code is in backend/tauri/src/core/clash/core.rs → update_config() and backend/tauri/src/core/clash/api.rs → put_configs(...).

4. Operations That Trigger a Rebuild

Changing the active profile selection

The frontend calls commands.patchProfilesConfig, which reaches patch_profiles_config(...) in the backend. The backend applies a draft with Config::profiles().draft().apply(...), calls CoreManager::update_config(), then saves the profile state with Config::profiles().apply() and save_file() on success. On failure, it calls discard() to roll back.

Changing selected application settings

The frontend calls commands.patchVergeConfig, which reaches feat::patch_verge(...). It first writes an IVerge draft. Depending on the field, for example enable_tun_mode, the change may regenerate configuration and restart the core through Config::generate() + run_core(), or hot-update it through update_core_config().

Importing the first profile

After import_profile(...) succeeds, if no profile is active, Chimera sets ProfilesBuilder.current = [new_uid] and reuses patch_profiles_config(...) to trigger an update.

5. Runtime Details and Limitations

  • profiles.yaml stores profile metadata and the current pointer; it is not the final configuration consumed by the core.
  • Profile content files are not passed to the core verbatim. They become the runtime configuration after merging, filtering, and Clash Guard overrides.
  • prepare_external_controller_port() checks port availability according to policy and changes the external-controller port when necessary.
  • verge_mixed_port is primarily used by system-proxy logic. It is not written directly to the runtime YAML’s mixed-port. System-proxy logic uses verge_mixed_port first, then falls back to Config::clash().get_mixed_port().
  • get_runtime_yaml() returns the in-memory IRuntime.config. It is usually consistent with the recently written clash-config.yaml, but it does not reread the file on each call.

The implementation limitations recorded here are:

  • Profile-chain script execution is a placeholder; process_chain(...) does not yet rewrite the configuration.
  • Global chain processing remains commented out; only the scoped chain framework is present.
  • The patch_clash_config IPC is still todo!(), so the frontend will fail if it uses that IPC path.
  • Editing a profile file directly does not automatically trigger hot reload. save_profile_file(...) writes the file but does not call update_config().

6. Troubleshooting

If the core appears to be using the wrong configuration, check these items in order:

  1. Active profile: verify current in profiles.yaml.
  2. Profile content: inspect the relevant file under app_config_dir/profiles/.
  3. Clash Guard overrides: check whether fields in HANDLE_FIELDS from clash-guard-overrides.yaml replace the values you expected.
  4. Generated configuration: inspect clash-config.yaml, or call get_runtime_yaml() to view the in-memory configuration.
  5. Reload or restart: confirm that patch_profiles_config, patch_verge_config, or restart_sidecar ran, and check the logs for the result of PUT /configs.
  6. Port problems: check whether the port strategy changed external-controller.

Service Mode Configuration

Scope

Service mode changes who owns the client core process. It does not add proxy protocol features and it does not change rule, DNS, or outbound semantics.

In foreground mode the desktop application starts and owns the selected core process directly. In service mode the desktop application delegates core lifecycle to Chimera_Service over local IPC.

Foreground mode

Chimera desktop
      |
      +--> selected core process

Service mode

Chimera desktop
      |
      v
local IPC
      |
      v
chimera-service
      |
      +--> selected core process

Source Boundaries

The desktop-side integration lives primarily under:

  • Chimera/backend/tauri/src/core/clash/core.rs,
  • Chimera/backend/tauri/src/core/service/,
  • Chimera/backend/tauri/src/config/chimera/mod.rs.

The privileged service implementation lives in the Chimera_Service repository. Its IPC definitions and server routes are split between chimera_ipc and chimera_service.

Current IPC Surface

The inspected service source exposes these core operations:

EndpointPurpose
GET /statusRead service/runtime/core status.
POST /core/startStart a selected core using a supplied config path.
POST /core/stopStop the running core.
POST /core/restartRestart the managed core.
POST /network/set_dnsPerform the supported privileged DNS operation on platforms where that path is implemented.

The IPC crate also contains WebSocket event definitions and log-related API surfaces. Treat these as local control-plane interfaces, not as remote proxy protocols.

Foreground vs Service Mode

PropertyForegroundService mode
Core ownerDesktop processchimera-service
Lifecycle callsDirect child-process managementIPC requests to the service
Privilege boundaryDesktop/user processPrivileged service boundary
Config generationDesktopDesktop
Proxy protocol implementationSelected coreSelected core
GUI/controller roleDirectly manages coreSends requests and observes service/core state

The desktop still generates the runtime configuration in service mode. The service receives the core type and config path; it does not independently merge profiles or reinterpret proxy rules.

Start Flow

At a high level, service-mode startup is:

  1. Chimera selects the configured core type.
  2. Chimera builds or refreshes the generated runtime configuration.
  3. The desktop converts its core selection into chimera_utils::core::CoreType.
  4. Chimera checks/uses the service IPC client.
  5. A /core/start request is sent with the core type and generated config path.
  6. chimera-service creates and supervises the child core process.
  7. Status/events are used to reflect the resulting runtime state back to the desktop application.

The source also handles races where service/core status can change between a status check and a start request. Documentation should therefore avoid presenting service start as a single infallible toggle.

Restart and Configuration Changes

A runtime setting can fall into one of three categories:

  • handled through the selected core’s own controller/hot-reload path,
  • written into generated configuration and requiring core restart,
  • owned by Chimera or the OS and not part of core config at all.

Service mode does not change this classification. It changes the restart path from direct process management to /core/restart or a stop/start sequence through the service.

When documenting an individual setting, verify its actual update path before claiming that it is hot-reloadable.

Service Installation and Platform Managers

Chimera_Service uses platform service-manager integration to install, start, stop, query, and uninstall the privileged service. Windows also has dedicated Windows-service control code.

The exact operating-system registration details are an implementation concern of Chimera_Service; the desktop application should treat the service as a managed local control endpoint.

Do not assume GUI settings such as “start at boot”, “auto recover”, or “keep running after GUI exit” exist merely because they are common in other proxy applications. They should be documented only when the corresponding Chimera setting and service behavior are present in source.

Failure Model

Troubleshoot service mode by separating desktop, IPC, service, and core failures:

SymptomFirst boundary to inspect
Service is not installed or cannot startOS service manager / installation privileges
GUI cannot query statuslocal IPC endpoint, ACL/permissions, service process
/core/start failscore type, config path, executable availability, service-side process spawn
Service is healthy but proxy traffic failsselected core logs/config/protocol path
Config change appears ignoreddetermine whether the setting needs hot reload or core restart
Core exits unexpectedlyservice core-manager status and captured core output/logs

A healthy chimera-service process does not imply a healthy proxy core, and a healthy proxy core does not imply successful remote protocol negotiation.

Security Boundary

Service mode introduces a privileged local control plane. Operational guidance should therefore emphasize:

  • restrict local IPC access with the repository’s ACL/security mechanisms,
  • do not treat a user-supplied config path as harmless input,
  • keep the desktop, service, and shared IPC/types compatible,
  • inspect both service logs and core logs when diagnosing privilege-related networking failures.

Verification

Useful source-level checks are:

  • confirm /status reports the expected core state,
  • exercise start/stop/restart through the same IPC client used by Chimera,
  • verify the generated config path exists and is readable by the service,
  • verify the selected core executable matches the requested CoreType,
  • test privileged networking operations separately from proxy connectivity.

AChimera Android Client

Role in the Ecosystem

AChimera is the Android application layer for the Chimera client ecosystem. It is not a separate proxy protocol implementation. The Android app owns the platform-specific VPN lifecycle, profile storage, user interface, and telemetry presentation, while packet forwarding is delegated to the embedded Rust core through UniFFI.

The core runtime shape is:

Android UI / ViewModels
        |
        v
ChimeraBackend
        |
        +--> profile download / verification / persistence
        |
        v
Android VpnService (TunService)
        |
        +--> create and own Android TUN interface
        +--> protect core sockets from VPN recursion
        |
        v
UniFFI bridge
        |
        v
Chimera Rust client core
        |
        v
SOCKS / HTTP / mixed listeners, rules, DNS, outbound proxies

Source Anchors

The Android repository is easiest to understand through these files:

  • app/src/main/java/rs/chimera/android/backend/ChimeraBackend.kt: application backend contract.
  • app/src/main/java/rs/chimera/android/backend/ChimeraBackendImpl.kt: profile, runtime, controller, traffic, memory, and connection orchestration.
  • app/src/main/java/rs/chimera/android/service/TunService.kt: Android VpnService lifecycle and TUN ownership.
  • app/src/main/java/rs/chimera/android/ffi/ChimeraFfi.kt: UniFFI initialization and socket-protection bridge.
  • app/src/main/java/rs/chimera/android/ffi/Clash.kt: Rust core startup bridge.

VPN Startup Flow

A normal Android VPN start follows this sequence:

  1. The backend verifies that an active profile exists.
  2. Android VpnService.prepare(...) is used to request VPN permission when the user has not granted it yet.
  3. TunService is started as the Android VPN service.
  4. The service resolves and validates the active profile path.
  5. Android creates the TUN interface and detaches the file descriptor used by the Rust runtime.
  6. The profile and runtime overrides are passed through the UniFFI bridge to the Chimera client core.
  7. The core starts its local listeners and networking runtime.
  8. The service publishes runtime state and keeps ownership of the VPN/TUN lifecycle until shutdown.

A failure before the Rust core starts should be treated differently from a failure after the core starts: the former is normally an Android permission, profile, or TUN setup problem, while the latter belongs to runtime config, listener, DNS, rule, or outbound initialization.

Socket Protection

Android VPN applications must prevent their own outbound sockets from being captured by the VPN again. AChimera exposes a bridge from Rust back to VpnService.protect(fd).

Conceptually:

proxied application packet
        |
        v
Android TUN
        |
        v
Rust proxy core
        |
        +--> create remote socket
                 |
                 +--> VpnService.protect(fd)
                 |
                 v
              physical network

Without this protection, a remote proxy connection can recursively enter the same TUN path and fail or loop.

Profile Lifecycle

The current backend supports both local and remote profiles.

For local profiles it tracks metadata such as profile ID, display name, file path, active state, creation time, and size.

For remote profiles it additionally stores source URL and update metadata, and uses the Rust-side download helper for retrieval. A downloaded profile is not assumed valid merely because the HTTP request succeeded: configuration verification is exposed separately through the UniFFI layer.

Profile deletion is deliberately defensive. The repository contains policy objects for staging, persistence, deletion, and recovery so that an interrupted or failed delete operation does not silently corrupt the profile catalog.

Relevant tests include:

  • ProfileCatalogPolicyTest
  • ProfileDeletionPolicyTest
  • ProfileDeletionRecoveryPolicyTest
  • ProfileFilePolicyTest
  • ProfilePersistencePolicyTest
  • ProfileRemotePolicyTest

Runtime Settings

The Android app currently exposes runtime listener overrides for:

  • mixed port,
  • HTTP port,
  • SOCKS port.

These settings are application/runtime overrides. They do not define which remote proxy protocols are compiled into the embedded core. Protocol availability still follows the Chimera_Client build and configuration.

Observability

ChimeraBackendImpl polls the embedded controller and exposes application state for:

  • total traffic,
  • memory usage,
  • active connections,
  • service/runtime state,
  • runtime errors.

The Android UI therefore consumes controller state from the Rust core rather than maintaining a second independent accounting model.

Failure Boundaries

When troubleshooting Android, identify the failing layer before changing proxy protocol settings:

SymptomFirst layer to inspect
Android never asks for or receives VPN permissionVpnService.prepare / platform permission flow
Service starts but no TUN FD is availableTunService interface creation and detach path
Core startup fails immediatelyprofile verification, runtime overrides, Rust initialization
Proxy connects recursively or never leaves the devicesocket protect(fd) bridge
UI shows stale traffic or connectionscontroller polling/backend state collection
Remote profile update failsdownload helper, URL policy, temporary-file/persistence path

Relationship to Chimera Desktop

AChimera and the desktop Chimera application are sibling control surfaces, not two layers that normally run in one forwarding path.

The desktop application can choose and manage external core processes or Chimera_Service; Android embeds the client core in the application and passes its TUN file descriptor through UniFFI. Both ultimately depend on Chimera_Client behavior for Clash-style configuration and proxy forwarding.

Chimera_Server

Purpose and Scope

Chimera_Server is the inbound/server core of the Chimera ecosystem. Its configuration model intentionally follows Xray-style inbounds, streamSettings, transport wrappers, and security settings, but compatibility must be evaluated field by field and path by path rather than assumed from configuration shape alone.

The server source is organized around this data path:

JSON / JSON5 / YAML
        |
        v
config definitions
        |
        v
ServerConfig validation/conversion
        |
        v
beginning: listener / TCP / UDP / QUIC / XHTTP / gRPC
        |
        v
transport + security wrappers
        |
        v
protocol handler
        |
        v
outbound/session + traffic/runtime state

For the evidence terminology used below, see Implementation Status and Source Evidence.

Workspace Layout

CrateRole
chimera_server_appApplication entry point and integration-test surface.
chimera_server_libConfig parsing, runtime construction, listener/transport entry points, protocol handlers, routing/outbound state, traffic and control-plane services.
chimera_cliAdministrative helper CLI, including X25519 key utilities.
chimera_tcp_reality_serverFocused TCP/REALITY server crate used for a narrower runtime path.

Important source anchors are:

  • chimera_server_lib/src/config/mod.rs,
  • chimera_server_lib/src/config/server_config/,
  • chimera_server_lib/src/beginning/,
  • chimera_server_lib/src/handler/,
  • chimera_server_lib/src/reality/,
  • chimera_server_app/tests/.

Build Features

The current server library exposes protocol/transport features including:

  • hysteria,
  • http,
  • mixed,
  • httpupgrade,
  • grpc_transport,
  • trojan,
  • ws,
  • tls,
  • reality,
  • shadowsocks,
  • vless,
  • vmess,
  • tuic,
  • traffic,
  • api.

The current default is full, so the normal server build includes this feature set. Smaller application feature sets such as minimal-vless and minimal-vless-tls also exist and should be treated as different capability artifacts.

Current Protocol and Transport Surface

The typed protocol configuration currently includes:

  • VLESS,
  • VMess,
  • Hysteria 2,
  • Dokodemo-door,
  • Trojan,
  • TUIC v5,
  • XHTTP,
  • SOCKS,
  • HTTP,
  • Mixed,
  • Shadowsocks.

Transport/security code also includes WebSocket, HTTPUpgrade, gRPC transport, XHTTP, TLS, REALITY, TCP/UDP and QUIC entry paths.

This list means source/runtime paths exist. It is not a claim that every Xray field or every transport/protocol combination has parity.

Explicit Compatibility Boundaries

One of the most useful properties of the current server is that unsupported compatibility fields are often rejected deliberately instead of silently ignored. The Wiki should preserve these boundaries.

Current source includes explicit rejections or unimplemented paths such as:

AreaCurrent boundary
SOCKSsettings.ip is not supported yet.
SOCKSsettings.userLevel is not supported yet.
Trojan fallbackUnsupported fallback types and Unix-socket destinations are rejected.
VLESS fallbackUnsupported fallback types and Unix-socket destinations are rejected.
XHTTPheaders and several additional Xray fields are rejected when unsupported.
XHTTPdownloadSettings is not supported yet.
gRPC transportgrpcSettings.multiMode is not supported yet.
HTTPUpgradeacceptProxyProtocol and ed are not supported yet.
REALITYxver values other than 0 are not supported yet.
Shadowsocksxchacha20-poly1305 is not supported yet.
VLESS VisionVision direct mode is not implemented yet.
UDP outbound proxyingSome outbound protocol selections, including VMess in the inspected path, are rejected as unsupported.

These restrictions are more precise than saying “Xray compatible”. When a field is added upstream, the Server builder and runtime must both be checked before the Wiki marks it supported.

Configuration Model

A typical VLESS + REALITY inbound retains the familiar Xray-style shape:

{
  "inbounds": [
    {
      "tag": "vless-reality",
      "protocol": "vless",
      "listen": "0.0.0.0",
      "port": 443,
      "settings": {
        "clients": [
          { "id": "YOUR-UUID", "flow": "xtls-rprx-vision" }
        ]
      },
      "streamSettings": {
        "network": "tcp",
        "security": "reality",
        "realitySettings": {
          "dest": "example.com:443",
          "serverNames": ["example.com"],
          "privateKey": "YOUR-PRIVATE-KEY",
          "shortIds": ["0123456789abcdef"]
        }
      }
    }
  ]
}

Configuration compatibility has three distinct outcomes:

  1. accepted and applied,
  2. accepted only where explicitly documented as compatibility parsing,
  3. rejected early because the runtime path does not support the field.

Prefer early rejection over implying behavior that does not exist.

Listener and Handler Separation

The server architecture keeps transport acceptance separate from proxy semantics. For example:

TCP listener
  +-- optional TLS / REALITY
  +-- optional WebSocket / HTTPUpgrade / XHTTP / gRPC transport
  +-- VLESS / VMess / Trojan / SOCKS / HTTP / ... handler

QUIC entry paths similarly dispatch Hysteria 2 or TUIC to protocol-specific handlers.

This separation is important when debugging: a successful TLS/REALITY or HTTP transport handshake does not prove that the inner protocol authentication or request header succeeded.

Interoperability and E2E Evidence

The server repository contains dedicated tests that are stronger evidence than a capability list. Current examples include:

  • chimera_client_reality_vision_e2e.rs,
  • chimera_client_reality_vision_negative_e2e.rs,
  • reality_vision_matrix_e2e.rs,
  • reality_vision_negative_e2e.rs,
  • xhttp_matrix_e2e.rs,
  • xhttp_protocol_matrix_e2e.rs,
  • xhttp_security_matrix_e2e.rs,
  • grpc_xray_compat_e2e.rs,
  • grpc_external_integration.rs,
  • socks_external_integration.rs,
  • xray_client_proxy_e2e.rs,
  • TUIC E2E tests inside the handler module.

When describing a combination as interoperable, link the claim to one of these concrete tests or add a new test first.

Control Plane and Observability

The server data plane is intentionally separate from control-plane surfaces. The codebase includes:

  • runtime/service registry state,
  • traffic accounting,
  • gRPC API services when api is enabled,
  • MCP-related control/data push code,
  • tracing-based logs.

These should not be confused with the proxy gRPC transport. The API gRPC service is a management plane; grpc_transport is a forwarding transport for an inbound proxy protocol.

Running

From the Chimera_Server workspace:

cargo run --package chimera_server_app -- --config path/to/config.json5

To generate X25519 key material:

cargo run -p chimera_cli -- x25519 --count 1 --format base64

Development Checks

The repository guidance uses:

cargo build --all-features
cargo fmt --all
cargo clippy --all-targets --all-features -- -D warnings
cargo test

For documentation maintenance, protocol capability claims should be updated only after the relevant configuration/runtime path and its tests have been inspected.

Proxy Protocol Reference

A proxy protocol defines how a client identifies itself, requests a target, and exchanges proxied TCP or UDP traffic with an endpoint. This chapter covers those messages, authentication rules, framing, and failure behavior.

Transport wrappers and transport security have their own references: Transport Reference and Transport Security Reference. They are not additional proxy protocols.

What Belongs to a Proxy Protocol?

A protocol reference owns:

  • identity and proxy authentication (if the protocol defines them);
  • destination address, command, and response semantics;
  • TCP relay and UDP packet framing or association lifetime;
  • protocol-level encryption, replay checks, and error handling;
  • implementation evidence and compatibility limits for that protocol.

It does not define the HTTP path, gRPC service name, XHTTP session, TLS certificate, or REALITY short ID used by an outer layer. Refer to the relevant layer’s documentation instead of copying its configuration into every protocol page.

Protocols

ProtocolRoleProtocol-specific characteristics
SOCKS5Local/application proxyMethod negotiation, destination commands, and UDP ASSOCIATE
HTTP ProxyLocal/application proxyHTTP forwarding and CONNECT tunneling
ShadowsocksRemote proxyAEAD/AEAD-2022 encrypted TCP and UDP records
AnyTLSRemote proxyPassword authentication, framed logical streams, and UDP-over-TCP
TrojanRemote proxyShared-secret authentication and destination requests
Hysteria 2Remote proxyQUIC-based sessions with its own TCP/UDP framing
TUICRemote proxyQUIC-based connection authentication and TCP/UDP relay
VMessRemote proxyAEAD request authentication and encrypted body records
VLESSRemote proxyIdentity and destination dispatch; optional VLESS Encryption
Dokodemo-doorServer forwarding inboundFixed-target or original-destination forwarding, without its own proxy authentication handshake

Trojan wire format and Trojan traffic handling expand the Trojan protocol description without defining outer transport behavior.

Where the Layers Meet

For a stack that supports independently configurable layers, read it from the inner proxy messages outward:

Proxy protocol:    identity + destination + proxied bytes
Transport method:  delivery of those bytes (RAW / XHTTP / gRPC / ...)
Security layer:    outer channel protection (TLS / REALITY / ...)
Network:           TCP or UDP

This is a responsibility map, not a guarantee that any arbitrary combination works. See the Transport Reference for framing and HTTP wrappers, and the Transport Security Reference for outer-handshake responsibilities.

Some protocols intentionally bind these layers together:

  • Hysteria 2 and TUIC build their sessions on QUIC, including QUIC TLS. QUIC-specific details remain in the respective protocol chapters.
  • AnyTLS and baseline Trojan explicitly depend on TLS. Their protocol chapters describe that requirement without treating TLS configuration as a proxy command.
  • Shadowsocks and VMess include protocol-owned cryptographic framing; VLESS may use VLESS Encryption. None of those automatically implies a particular outer transport.

Choosing a Protocol

For a local application entrypoint, start with SOCKS5 or HTTP Proxy. For remote encrypted proxy semantics, compare Shadowsocks, AnyTLS, Trojan, and VMess. For QUIC-based remote sessions, compare Hysteria 2 and TUIC.

For Xray-style layered configurations, begin with VLESS or VMess, then select a supported transport and security mechanism from their separate chapters. Never infer support for a combination merely because its constituent parts appear in the source.

Implementation and Troubleshooting

Read Implementation Status and Source Evidence and Test Evidence and Interoperability Matrix for component-specific availability and verification. Configuration parsing alone is not proof of runtime or cross-project compatibility.

When debugging, check network reachability, then any outer security handshake, then transport framing/session setup, and only then proxy authentication, destination dispatch, and TCP/UDP relay behavior. See End-to-End Troubleshooting for the full procedure.

SOCKS5

Positioning

SOCKS5 is a general-purpose application proxy protocol standardized by RFC 1928. It can relay TCP connections and defines UDP ASSOCIATE for UDP traffic. Because SOCKS operates below HTTP semantics, applications can use it for many protocols without the proxy needing to understand the application payload.

For local Chimera deployments, SOCKS5 is usually the best baseline listener to validate before enabling TUN or transparent routing.

Standards

The main standards are:

  • RFC 1928 — SOCKS Protocol Version 5.
  • RFC 1929 — Username/Password Authentication for SOCKS V5.
  • RFC 1961 — GSS-API Authentication Method for SOCKS V5.
  • RFC 3089 — SOCKS-based IPv6/IPv4 Gateway operation.

Protocol Flow

Method negotiation

  1. The client opens a TCP connection to the SOCKS5 server.
  2. The client sends the authentication methods it supports.
  3. The server chooses one method.
  4. If required, the client performs the selected authentication exchange.

Proxy request

After negotiation, the client sends one of the SOCKS5 commands:

  • CONNECT — create an outbound TCP connection.
  • BIND — ask the proxy to accept a related incoming connection.
  • UDP ASSOCIATE — establish the control association for UDP relay.

The request can identify a destination by IPv4 address, IPv6 address, or domain name.

CONNECT

For the common TCP case:

  1. The client asks the proxy to connect to a destination.
  2. The proxy evaluates access and routing policy.
  3. The proxy returns a success or failure reply.
  4. After success, client and server relay the TCP byte stream.

UDP ASSOCIATE

UDP relay uses the TCP SOCKS connection as the lifetime/control channel. The proxy returns an address and UDP port where the client sends SOCKS-framed UDP datagrams. The association ends when the corresponding TCP control connection ends.

UDP support is therefore a separate capability from basic SOCKS5 TCP support; do not assume that every SOCKS5 implementation supports it equally well.

Wire-Level Interaction and State Machine

The most important difference between SOCKS5 and many modern proxy protocols is that SOCKS5 has a small explicit control protocol before raw forwarding begins. After the handshake completes, the proxy normally stops interpreting payload bytes.

TCP connection and negotiation

The TCP session between application and SOCKS server starts with a method selection exchange:

Client -> Server
+----+----------+----------------+
|VER | NMETHODS | METHODS        |
+----+----------+----------------+
|0x05| 1 byte   | N bytes        |
+----+----------+----------------+

Server -> Client
+----+--------+
|VER | METHOD |
+----+--------+
|0x05| 1 byte |
+----+--------+

METHOD determines the next state. Common values include:

  • 0x00 — no authentication.
  • 0x02 — username/password authentication defined by RFC 1929.
  • 0xff — no acceptable method.

Username/password authentication

When RFC 1929 authentication is selected, the exchange becomes:

Client -> Server
+----+------+----------+------+----------+
|VER | ULEN | UNAME    | PLEN | PASSWD   |
+----+------+----------+------+----------+

Server -> Client
+----+--------+
|VER | STATUS |
+----+--------+

The authentication layer only proves identity to the SOCKS server. It does not encrypt the TCP stream.

Request command frame

After authentication, the client sends:

+----+-----+------+----------+----------+
|VER | CMD | RSV  | ATYP     | DST.ADDR |
+----+-----+------+----------+----------+
|PORT|
+----+

Important fields:

  • CMD selects CONNECT, BIND, or UDP ASSOCIATE.
  • ATYP selects address encoding.
  • IPv4 uses 4 bytes.
  • IPv6 uses 16 bytes.
  • Domain names use one length byte followed by domain bytes.
  • DST.PORT is an unsigned 16-bit network-order value.

Server reply

The server returns:

+----+-----+------+----------+----------+
|VER | REP | RSV  | ATYP     | BND.ADDR |
+----+-----+------+----------+----------+
|BND.PORT|
+---------+

REP communicates the result. RFC 1928 defines these one-byte values:

REPMeaning
0x00succeeded
0x01general SOCKS server failure
0x02connection not allowed by ruleset
0x03network unreachable
0x04host unreachable
0x05connection refused
0x06TTL expired
0x07command not supported
0x08address type not supported
0x09-0xffunassigned

For a failed request, RFC 1928 requires the SOCKS server to close the TCP connection shortly after sending the reply. A client should therefore treat a non-zero REP as terminal for that request instead of waiting for a later application payload.

After a successful CONNECT, the state machine changes from control protocol to transparent byte relay:

Application TCP bytes
        |
        v
 SOCKS5 server
        |
        v
 Destination TCP socket

The SOCKS server does not parse HTTP, TLS, SSH, or application protocols after this transition.

BIND: two replies, not one

BIND is unusual because one request can produce two successful server replies. It was designed for protocols in which the proxied application expects a peer to connect back to it.

Client -> SOCKS server
    BIND request(target identity)

SOCKS server -> Client
    Reply #1: BND.ADDR/BND.PORT where the server is listening

Remote peer -> SOCKS server
    inbound TCP connection

SOCKS server -> Client
    Reply #2: BND.ADDR/BND.PORT identifying the connected peer

then
    bidirectional TCP relay

The first BND.ADDR/BND.PORT is the listening endpoint created by the SOCKS server. The second identifies the remote peer after the inbound connection is accepted. This is materially different from CONNECT, where one success reply is enough to enter the relay state.

An implementation state machine therefore needs a distinct BIND_WAIT_PEER state rather than treating every REP=0x00 as permission to begin application relay immediately.

UDP ASSOCIATE datagram wire format

UDP ASSOCIATE uses the TCP SOCKS connection only as the control/lifetime channel. UDP payloads themselves use a separate SOCKS5 UDP header:

+----------+------+----------+----------+----------+----------+
| RSV      | FRAG | ATYP     | DST.ADDR | DST.PORT | DATA     |
+----------+------+----------+----------+----------+----------+
| 2 bytes  | 1    | 1        | variable | 2        | variable |
+----------+------+----------+----------+----------+----------+

Fields:

  • RSV is two zero bytes (0x0000).
  • FRAG=0x00 means the datagram is not fragmented.
  • ATYP, DST.ADDR, and DST.PORT use the same destination-address model as the TCP request command.
  • DATA is exactly one application UDP datagram payload.

The important boundary property is that UDP itself already preserves datagram boundaries. SOCKS5 therefore prepends routing metadata to each UDP datagram instead of turning all UDP traffic into one byte stream.

Fragmentation semantics

RFC 1928 defines a SOCKS-layer fragmentation mechanism through FRAG, but also states that an implementation may choose not to support it. An implementation that does not support fragmentation must drop any datagram whose FRAG field is not zero.

When fragmentation is implemented, the low seven bits carry the fragment sequence number and the high bit marks the final fragment. Reassembly has a short expiration timer and a fragment arriving with a lower sequence number than the highest already seen causes the reassembly queue to be discarded.

This makes SOCKS5 fragmentation very different from protocols such as Hysteria 2 or TUIC, whose fragment headers explicitly carry packet/session identifiers and fragment counts.

UDP association lifecycle and source binding

The client first sends a normal TCP UDP ASSOCIATE request. A successful reply returns BND.ADDR/BND.PORT, the UDP relay endpoint to which the client sends SOCKS5 UDP datagrams.

TCP control connection
Client ------------------------------ SOCKS server
       UDP ASSOCIATE
       <--- REP=0, BND.ADDR:BND.PORT

UDP data path
Client ===== SOCKS5 UDP datagrams ===> BND.ADDR:BND.PORT
                                      |
                                      +----> destination UDP sockets

The TCP connection is the association’s lifetime anchor: once it closes, the UDP association terminates. RFC 1928 also requires the server to restrict relay traffic to the client associated with that TCP request rather than behaving as an unrestricted public UDP forwarder.

The client may put all-zero address/port values in the request when it does not know the UDP source endpoint at request time. The server reply, not the request, is the authoritative destination for the client’s SOCKS-encapsulated UDP traffic.

Control/data state machine

The complete baseline state machine is therefore:

TCP_CONNECTED
     |
     v
METHOD_NEGOTIATION
     |
     +-- 0xff --------------------------> CLOSE
     |
     v
AUTH_SUBNEGOTIATION (if selected)
     |
     +-- auth failure ------------------> CLOSE
     |
     v
REQUEST
     |
     +-- CONNECT --> REPLY
     |                 |
     |                 +-- REP != 0 ----> CLOSE
     |                 +-- REP == 0 ----> TCP_RELAY
     |
     +-- BIND ----> REPLY_1
     |                 |
     |                 +-- failure -----> CLOSE
     |                 +-- success -----> BIND_WAIT_PEER
     |                                      |
     |                                      v
     |                                    REPLY_2
     |                                      |
     |                                      +-- success -> TCP_RELAY
     |
     +-- UDP ASSOCIATE -> REPLY
                           |
                           +-- success -> UDP_ASSOCIATED
                                           |
                                           +-- TCP control closes -> END

Packet-capture view

SOCKS5 is unencrypted unless the selected authentication method adds its own encapsulation. A normal packet capture can therefore expose the protocol phases directly:

TCP SYN/SYN-ACK/ACK
  -> 05 NMETHODS METHODS...
  <- 05 METHOD
  -> optional authentication subnegotiation
  -> 05 CMD 00 ATYP DST.ADDR DST.PORT
  <- 05 REP 00 ATYP BND.ADDR BND.PORT
  -> application bytes (CONNECT/BIND)

For UDP, the capture additionally shows independent UDP packets beginning with 00 00 FRAG ATYP .... This clear separation between a TCP control association and a UDP data plane is one of the most useful reference points when comparing SOCKS5 with QUIC-native proxy protocols.

SOCKS5 Compared With Modern Proxy Protocols

SOCKS5 is useful as a reference model because most modern proxy protocols solve the same logical problems with additional layers:

FunctionSOCKS5Modern protocols
User selectionMETHOD + authenticationUUID/password/token systems
Destination addressATYP + DST.ADDRSimilar address structures or protocol-specific metadata
TCP forwardingCONNECT then raw streamUsually stream multiplexing or framed transport
UDP forwardingUDP ASSOCIATEQUIC datagrams, custom UDP framing, multiplexed channels
EncryptionNot includedUsually TLS, QUIC TLS, REALITY, or protocol-specific security
MultiplexingNot definedCommon in QUIC/Xray transports

The conceptual mapping is:

SOCKS5 CONNECT request
        |
        +--> destination metadata
        |
        +--> authentication
        |
        +--> byte relay

Modern protocol
        |
        +--> authentication
        +--> destination metadata
        +--> transport security
        +--> multiplex/session management
        +--> framed data relay

Modern protocols generally did not replace the SOCKS5 idea; they expanded the control plane and moved more functionality into the protocol itself.

Minimal Configuration

A local chimera_client-style profile can start with:

bind_address: "127.0.0.1"
allow_lan: false
socks_port: 7891

An application can then use:

socks5://127.0.0.1:7891

When DNS behavior matters, distinguish between applications that resolve the domain locally and applications that pass the domain name to the SOCKS proxy. That difference can affect domain rules.

Strengths

  • Generic TCP proxying without HTTP-specific assumptions.
  • Domain-name, IPv4, and IPv6 destination forms.
  • Standardized UDP relay mechanism.
  • Widely supported by developer tools, browsers, SSH tooling, and networking libraries.
  • Low protocol overhead and easy local debugging.

Limitations

  • SOCKS5 itself does not provide transport encryption.
  • Application support is required unless traffic is captured by another layer.
  • UDP relay behavior can vary among clients, NATs, and proxy implementations.
  • Basic username/password authentication should not be treated as a substitute for encrypted transport.

DNS and Rule Interaction

SOCKS5 can preserve a domain name all the way to the proxy when the application uses remote resolution semantics. If the application resolves locally first, the proxy may only see the resulting IP address.

This matters for rules such as:

DOMAIN-SUFFIX,example.com,Proxy

If a domain rule unexpectedly stops matching, compare the application’s DNS behavior with the client DNS mode described in DNS Module.

Security Notes

For desktop use, bind SOCKS5 to loopback unless LAN access is intentional. Publicly exposing an unauthenticated SOCKS listener creates an open-proxy risk. If remote SOCKS access is required, place it behind a secure authenticated channel rather than relying on SOCKS5 alone for confidentiality.

Chimera Status

Chimera_Client

SOCKS5 is documented as a current client-core inbound and is the recommended starting point for validating proxy profiles. Treat TCP CONNECT as the baseline capability; validate UDP association separately when an application requires UDP.

Chimera GUI

Chimera configures the listener through the selected core. It does not itself implement the SOCKS5 protocol.

Chimera_Server

The current server capability map includes SOCKS-related inbound work. That is an implementation map rather than a guarantee of complete RFC 1928 parity, so server deployments should verify the commands and authentication modes they actually require.

Test Evidence

The current Server test index includes external-process SOCKS coverage in chimera_server_app/tests/socks_external_integration.rs for both unauthenticated TCP round trips and username/password TCP round trips. The mixed-inbound process test also exercises SOCKS5 through a real mixed listener.

This evidence is TCP-focused. It must not be used to claim complete SOCKS5 UDP ASSOCIATE support across every Chimera component; the currently audited Client local SOCKS inbound explicitly has a UDP limitation. See Test Evidence and Interoperability Matrix and Implementation Status and Source Evidence.

Troubleshooting

  1. Confirm the listener is bound to the expected address and port.
  2. Test a simple TCP destination before testing UDP.
  3. If domain rules fail, determine whether the application sends a domain name or a pre-resolved IP address.
  4. If authentication fails, test without authentication on loopback to isolate protocol behavior from credential configuration.
  5. For UDP failures, verify that the TCP control connection remains open and that local firewall/NAT rules allow the returned UDP relay endpoint.
  6. If SOCKS works but TUN does not, debug TUN routing separately rather than changing the proxy node configuration.

References

Appendices

RFC 1928 (Full Text)


### RFC 1929 (Full Text)

```text

### RFC 1961 (Full Text)

```text

### RFC 3089 (Full Text)

```text

HTTP Proxy

Positioning

An HTTP proxy is an application-level proxy used by browsers, command-line tools, package managers, and operating-system proxy settings. For ordinary HTTP requests, the client sends the request through the proxy. For HTTPS and other TCP destinations, the client normally asks the proxy to create a tunnel with the HTTP CONNECT method.

HTTP proxying should not be confused with XHTTP. An HTTP proxy is an inbound proxy protocol used by local applications; XHTTP is an Xray transport used between compatible proxy endpoints.

Protocol Flow

Plain HTTP request

  1. The client connects to the HTTP proxy.
  2. The client sends a normal HTTP request using an absolute target URI.
  3. The proxy applies authentication and routing policy.
  4. The proxy sends the request to the origin server and relays the response.

CONNECT tunnel

  1. The client connects to the HTTP proxy.
  2. The client sends a request such as CONNECT example.com:443 HTTP/1.1.
  3. The proxy validates the target and access policy.
  4. The proxy establishes a TCP connection to the requested destination.
  5. After a successful response, the proxy relays bytes in both directions.
  6. For HTTPS, the end-to-end TLS handshake happens inside that tunnel.

The CONNECT method creates a TCP-oriented tunnel. It does not by itself add UDP proxying.

CONNECT on the Wire

HTTP CONNECT is useful as the next comparison point after SOCKS5 because it solves nearly the same TCP-tunneling problem with a very different control encoding. SOCKS5 uses compact binary fields; HTTP/1.1 CONNECT uses an HTTP request and status response.

HTTP/1.1 request

A minimal request is:

CONNECT example.com:443 HTTP/1.1\r\n
Host: example.com:443\r\n
\r\n

The request target is the destination authority: host:port. RFC 9110 requires an explicit port; CONNECT has no implicit default port. Unlike a SOCKS5 request, there is no ATYP byte. The host is represented textually and the HTTP parser separates the host and port according to CONNECT’s authority-form semantics.

At the byte level the HTTP/1.1 control phase is therefore variable length:

43 4f 4e 4e 45 43 54 20 ...
 C  O  N  N  E  C  T  SP

request-line CRLF
header-field CRLF
header-field CRLF
CRLF

The empty line terminates the HTTP header section. Bytes after the successful CONNECT response are no longer ordinary HTTP/1.1 proxy-control messages; they belong to the tunneled protocol.

Successful response and protocol switch

A proxy normally replies with a response such as:

HTTP/1.1 200 Connection Established\r\n
\r\n

RFC 9110 defines any 2xx response to CONNECT as success. Immediately after the response header section, both sides switch to tunnel mode. A successful CONNECT response must not define a message body with Content-Length or Transfer-Encoding; clients ignore those fields if a non-conforming proxy sends them.

This creates a sharp state boundary:

TCP established
      |
      v
HTTP request parsing
      |
      +---- 407/auth challenge ----> retry CONNECT
      |
      +---- non-2xx ---------------> tunnel not created
      |
      `---- 2xx -------------------> opaque byte tunnel
                                        |
                                        v
                              TLS / SSH / other TCP data

For HTTPS, the first bytes after the 2xx response are normally a TLS ClientHello from the application. The proxy does not need to understand that TLS handshake when it is operating as a blind tunnel.

Proxy authentication exchange

Proxy authentication is not a fixed pre-request negotiation like SOCKS5 method selection. An HTTP proxy can challenge a request with 407 Proxy Authentication Required and at least one Proxy-Authenticate challenge. The client can then repeat CONNECT with Proxy-Authorization credentials.

Conceptually:

Client -> Proxy
CONNECT example.com:443 HTTP/1.1

Proxy -> Client
HTTP/1.1 407 Proxy Authentication Required
Proxy-Authenticate: Basic realm="proxy"

Client -> Proxy
CONNECT example.com:443 HTTP/1.1
Proxy-Authorization: Basic <credentials>

Proxy -> Client
HTTP/1.1 200 Connection Established

Client <=============================> Destination
              opaque tunnel bytes

The exact credential bytes depend on the selected HTTP authentication scheme. Basic authentication, for example, is not encryption and should not be exposed on an untrusted clear-text proxy connection.

HTTP/2 CONNECT: one tunnel per HTTP/2 stream

CONNECT is an HTTP semantic, not an HTTP/1.1 text-format feature. HTTP/2 keeps the proxy connection as an ordinary multiplexed HTTP/2 connection and converts only the request stream into a tunnel. This is a fundamental difference from HTTP/1.1 CONNECT, where the entire client-to-proxy TCP connection changes into tunnel mode.

The request header section has these required pseudo-header semantics:

:method    = CONNECT
:authority = example.com:443
:scheme    = omitted
:path      = omitted

The header block is HPACK-compressed inside a HEADERS frame, so those strings are semantic fields rather than a fixed byte prefix. A simplified HTTP/2 frame header is:

0                   1                   2                   3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                 Length (24)                   |
+---------------+---------------+---------------+
|   Type (8)    |   Flags (8)   |
+-+-------------+---------------+-------------------------------+
|R|                 Stream Identifier (31)                      |
+=+=============================================================+
|                       Frame Payload (*)                       |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

For the CONNECT request, Type=0x01 denotes HEADERS. On success, the proxy returns response HEADERS carrying a :status in the 2xx range. After the initial request and response header sections, tunnel octets are carried in HTTP/2 DATA frames (Type=0x00) on that same stream:

client                         proxy                         target
  | HEADERS stream 1            |                             |
  | :method=CONNECT              |                             |
  | :authority=host:443 -------->| TCP connect -------------->|
  |                              |<----------------------------|
  |<----- HEADERS :status=200    |                             |
  | DATA(stream 1, TLS bytes) -->|---------------------------->|
  |<---- DATA(stream 1, bytes)   |<----------------------------|
  |
  | HEADERS stream 3 CONNECT --->| ... another target ...      |

Multiple CONNECT tunnels can therefore coexist on one HTTP/2 connection. Their DATA frames can be interleaved, but the Stream Identifier keeps tunnel bytes separate. This multiplexing is an extra transport layer that standard SOCKS5 does not define.

HTTP/2 DATA is subject to both connection-level and stream-level HTTP/2 flow control. A CONNECT tunnel can therefore stop making progress even when its upstream TCP socket is writable if the peer has not supplied enough WINDOW_UPDATE credit. Conversely, one blocked stream does not require the other CONNECT streams to stop, provided connection-level credit remains.

After CONNECT succeeds, ordinary tunnel bytes are not additional HTTP messages. RFC 9113 permits DATA plus stream-management frames on the connected stream; a protocol implementation must not try to parse a TLS ClientHello inside a DATA payload as another HTTP request.

HTTP/2 half-close and reset mapping

HTTP/2 maps the lifetime of the tunneled TCP connection onto the CONNECT stream:

  • END_STREAM in the client-to-proxy direction corresponds to TCP FIN toward the destination after any accompanying DATA bytes are forwarded;
  • a destination TCP FIN causes the proxy to finish its sending direction with END_STREAM;
  • a TCP reset or other TCP connection error is represented as RST_STREAM with CONNECT_ERROR;
  • a stream error detected by the proxy requires the corresponding target TCP connection to be aborted rather than silently reused.

This is more precise than saying that a tunnel simply “closes” when one side finishes. HTTP/2, like TCP, can represent a half-closed direction, and the other direction can still contain bytes that need to drain.

HTTP/3 CONNECT: the same semantics over a QUIC request stream

HTTP/3 retains the same CONNECT pseudo-header rules but maps each request onto a client-initiated bidirectional QUIC stream. The request begins with HTTP/3 HEADERS, the proxy responds with HEADERS containing a 2xx :status, and subsequent HTTP/3 DATA frames on that request stream carry the TCP tunnel. The request stream deliberately remains open after the request header section.

At the HTTP/3 framing layer, both frame type and frame length are QUIC variable-length integers:

HTTP/3 frame
+----------------------+----------------------------------+
| varint Frame Type    | HEADERS=0x01, DATA=0x00, ...     |
| varint Frame Length  | payload byte count               |
| Frame Length bytes   | frame payload                    |
+----------------------+----------------------------------+

The HTTP/3 HEADERS payload is QPACK-encoded, so a passive capture cannot treat :method=CONNECT or :authority as literal wire strings. After the CONNECT exchange completes, ordinary tunnel octets reside in HTTP/3 DATA payloads, and those HTTP/3 frames themselves are carried as QUIC STREAM data. TCP segment boundaries at the target, HTTP/3 DATA frame boundaries, QUIC STREAM frame boundaries, and UDP packet boundaries are all independent.

HTTP/3 closes a normal tunnel direction using QUIC stream completion. If the client finishes its sending direction, the proxy maps that completion to a TCP FIN toward the target. A TCP reset or abnormal target close is represented as a stream error with H3_CONNECT_ERROR (0x010f). Resetting or aborting one request stream does not inherently close unrelated CONNECT streams, but a QUIC connection-level failure destroys every tunnel multiplexed on that connection.

HTTP/3 flow control is provided by QUIC rather than HTTP/2 WINDOW_UPDATE frames. The CONNECT request stream consumes QUIC stream and connection flow-control credit, and all CONNECT streams on the connection also share the QUIC congestion controller and path capacity. Thus “many tunnels on one connection” does not mean each tunnel has independent physical bandwidth.

Ordinary CONNECT versus Extended CONNECT

Do not confuse basic proxy CONNECT with Extended CONNECT. RFC 8441 adds the :protocol pseudo-header after explicit capability negotiation for uses such as bootstrapping WebSocket over HTTP/2. Extended CONNECT changes the request shape: it can include :protocol and, in that mode, :scheme and :path are present. A normal forward proxy tunnel to example.com:443 uses the ordinary CONNECT form described above and does not need :protocol.

This distinction is particularly useful when reading captures or XHTTP-related documentation: seeing CONNECT on an HTTP/2 or HTTP/3 stream does not by itself mean that the stream is a classic forward-proxy TCP tunnel.

Version-specific packet-capture anchors

The useful capture anchors differ by HTTP version:

HTTP/1.1 clear text
  TCP -> "CONNECT host:port HTTP/1.1\r\n" -> 2xx -> opaque tunnel bytes

HTTP/2
  TCP/TLS -> HTTP/2 stream N
             HEADERS(:method CONNECT, :authority ...)
             HEADERS(:status 2xx)
             DATA / DATA / ... / END_STREAM or RST_STREAM

HTTP/3
  UDP -> QUIC -> request stream N
                HEADERS(:method CONNECT, :authority ...)
                HEADERS(:status 2xx)
                DATA / DATA / ... / QUIC FIN or stream reset

Without the TLS/QUIC decryption material, encrypted HTTP/2 and HTTP/3 captures usually expose transport behavior rather than the target authority or tunnel contents. With decryption, a dissector should follow the request stream and its header compression context instead of searching raw packets for the ASCII word CONNECT.

Client and Proxy State Machines

A useful client-side model is:

DISCONNECTED
   |
   | TCP connect to proxy
   v
HTTP_READY
   |
   | send CONNECT
   v
WAIT_RESPONSE
   |\
   | \-- 407 --> AUTH_RETRY -- send CONNECT --> WAIT_RESPONSE
   |
   |---- 2xx --> TUNNEL
   |
   `---- other/error --> FAILED

TUNNEL -- EOF/error --> CLOSED

The proxy has a corresponding model:

ACCEPT
  |
  v
PARSE_REQUEST
  |
  +-- auth required/invalid --> send 407 --> PARSE_REQUEST or close
  |
  +-- invalid target/policy --> send failure --> HTTP_READY or close
  |
  `-- accepted CONNECT --> CONNECT_UPSTREAM
                              |
                              +-- failure --> send non-2xx
                              |
                              `-- success --> send 2xx --> RELAY
                                                        |
                                                        v
                                                      CLOSED

A production implementation also needs limits for request-header size, parsing time, authentication retries, upstream-connect timeout, idle tunnel lifetime, and half-closed TCP connections.

Capture-Level Walkthrough

For an HTTPS request through a clear-text HTTP/1.1 proxy, a packet capture can look approximately like:

Client             HTTP Proxy                TLS Origin
  | TCP SYN ---------->|                         |
  |<--------- SYN/ACK  |                         |
  | CONNECT host:443 ->|                         |
  |                    | TCP SYN -------------->|
  |                    |<------------- SYN/ACK  |
  |<------ HTTP 200 ---|                         |
  | TLS ClientHello ---------------------------->|
  |<--------------------------- TLS ServerHello  |
  |<============ encrypted TLS records =========>|

The final TLS arrows are logically end-to-end but their TCP bytes are relayed through the proxy. If the proxy performs TLS interception instead, that is a different architecture: two TLS sessions exist and the proxy is no longer a blind CONNECT tunnel for that traffic.

SOCKS5 Comparison

StageSOCKS5HTTP CONNECT
Proxy transportTCP control connectionHTTP/1.1 over TCP; HTTP/2 commonly over TCP/TLS; HTTP/3 over QUIC/UDP
Initial negotiationVER/NMETHODS/METHODS binary exchangeNo equivalent mandatory proxy-method phase; HTTP version/transport negotiation belongs to the HTTP stack
AuthenticationSelected SOCKS method, e.g. RFC 1929HTTP challenge/response such as 407 + Proxy-Authorization
TCP commandCMD=0x01 (CONNECT)HTTP method CONNECT
Destination typeExplicit ATYP for IPv4/domain/IPv6Textual authority host:port at the HTTP semantic layer
Destination port2-byte network-order integerDecimal port inside authority text; explicit port required for CONNECT
SuccessREP=0x00 plus bound address/portAny HTTP 2xx response
FailureSOCKS REP byteHTTP non-2xx before tunnel creation; H2/H3 can additionally signal stream-level CONNECT errors after creation
Post-success dataRaw TCP byte stream on the SOCKS connectionHTTP/1.1: raw bytes; H2/H3: tunnel octets inside DATA frames on one request stream
MultiplexingNot defined by RFC 1928; normally one CONNECT per TCP control connectionH2/H3 can carry many independent CONNECT streams on one HTTP connection
Reliable flow controlTCP receive window of that SOCKS connectionH1 inherits TCP; H2 adds connection/stream HTTP flow control; H3 uses QUIC connection/stream flow control
Half-closeInherited from the SOCKS TCP connection after replyH1 inherits TCP; H2 maps FIN to END_STREAM; H3 maps direction completion to QUIC stream FIN
General UDP relayUDP ASSOCIATE is standardizedBasic CONNECT does not provide SOCKS-style UDP relay
Control encodingCompact binaryHTTP semantics; HTTP/1.1 text, H2 HPACK/framing, H3 QPACK/framing over QUIC

The most important conceptual correspondence is:

SOCKS5 CONNECT request  ~=  HTTP CONNECT request
SOCKS5 REP=success      ~=  HTTP CONNECT 2xx
SOCKS5 relay state      ~=  HTTP tunnel state

The important differences are authentication timing and representation. SOCKS5 negotiates an authentication method before its proxy command. HTTP authentication is integrated into HTTP request/response semantics and can require replaying the CONNECT request after a challenge.

Edge Cases and Security Boundaries

  • A proxy must validate the CONNECT target before dialing it. RFC 9110 warns specifically about unrestricted tunneling to arbitrary services; allowing destinations such as SMTP ports can turn a web proxy into an abuse relay.
  • An empty or invalid CONNECT port is invalid. Policy should also restrict destination ports where appropriate.
  • Do not parse tunneled bytes as another HTTP request merely because they arrive on the same client connection after a successful CONNECT. The connection has changed semantic state.
  • Preserve bytes that arrive immediately after the CONNECT header boundary. Implementations that over-read while parsing must pass those bytes into the tunnel rather than discard them.
  • Handle TCP half-close deliberately. When one side closes its sending direction, already-received bytes still need a chance to drain to the peer.
  • Authentication headers are hop-specific. Proxy-Authorization authenticates to the relevant proxy, not to the final origin server.

Minimal Client-Side Configuration

A Clash-style local listener commonly looks like:

port: 7890
bind-address: 127.0.0.1
allow-lan: false

Applications can then use:

http://127.0.0.1:7890

as their HTTP/HTTPS proxy endpoint.

The exact key names depend on the selected Chimera core. See Ports and Listeners for the current chimera_client mapping.

Authentication

HTTP proxies may add an authentication layer, but authentication support varies by implementation. Common deployments use proxy-specific credentials or place the proxy behind another authenticated control plane.

Do not assume that authentication also encrypts the connection between the application and the proxy. A plain local HTTP proxy has no transport encryption unless TLS or another secure channel is explicitly added.

Strengths

  • Broad support in browsers, package managers, CLI tools, and operating systems.
  • Simple to inspect and debug during local development.
  • HTTPS traffic can be tunneled without terminating the application’s TLS session at the proxy.
  • Well suited to local or trusted-LAN ingress into a proxy core.

Limitations

  • Primarily TCP-oriented; standard HTTP proxy behavior does not provide general UDP relay.
  • A clear-text proxy listener is unsuitable for direct exposure to the public internet.
  • Applications that ignore operating-system proxy settings will bypass it.
  • Authentication and header behavior vary across implementations.

Security Notes

For a local desktop deployment, prefer binding the HTTP listener to 127.0.0.1. If LAN access is enabled, apply an explicit firewall policy and understand which clients can reach the proxy.

Exposing an unauthenticated HTTP proxy publicly can turn the host into an open proxy. Even when authentication is enabled, a plain HTTP connection can expose credentials or metadata to observers on the local network.

Chimera Status

Chimera_Client

The current Wiki documents an HTTP listener as part of the client-core inbound surface. Availability can still depend on the selected build, configuration, and runtime path. Validate HTTP CONNECT behavior with a minimal profile before combining it with TUN, DNS hijacking, or complex rules.

Chimera GUI

Chimera itself does not implement HTTP proxying. It configures and manages the selected core, so listener behavior follows that core.

Chimera_Server

HTTP proxying is mainly relevant as a local/client-side inbound. Server-side HTTP capabilities should be treated separately from remote encrypted proxy protocols such as Trojan, Hysteria 2, or VLESS.

Test Evidence

The current Server test index includes process-level HTTP and mixed-listener coverage in xray_client_proxy_e2e.rs::http_and_mixed_inbounds_proxy_tcp. That test exercises authenticated HTTP CONNECT, absolute-form HTTP forwarding, transparent-style forwarding where enabled, HTTP through the mixed inbound, and SOCKS5 through the same mixed listener.

This is stronger than parser-only evidence, but it should not be generalized to every HTTP version or every extended-CONNECT behavior described earlier in this protocol reference. See Test Evidence and Interoperability Matrix for the exact evidence classification.

Troubleshooting

If a browser or CLI tool cannot connect:

  1. Verify the listener address and port.
  2. Confirm the process is listening on the expected interface.
  3. Test a simple HTTP request before testing HTTPS.
  4. For HTTPS failures, confirm that CONNECT reaches the proxy and that the target host/port is allowed.
  5. Check authentication separately from routing rules.
  6. If only some applications fail, verify that those applications actually use the configured system proxy.

References

Shadowsocks

Shadowsocks is an encrypted proxy protocol rather than a SOCKS5 session carried over an encrypted channel. Applications may enter Chimera_Client through SOCKS/HTTP/TUN, but the remote Shadowsocks connection has its own address header, key derivation, record framing, authentication tags, and UDP packet format.

This chapter separates two protocol families that must not be conflated:

  • classic Shadowsocks AEAD, commonly using AES-GCM or ChaCha20-Poly1305;
  • Shadowsocks 2022 AEAD, which changes key material, replay protection, TCP headers, UDP session identifiers, and multi-user identity handling.

The implementation notes below were checked against the current Chimera_Client and Chimera_Server source trees. Upstream Shadowsocks specifications remain the authority for portable wire behavior; Chimera-specific limitations are called out explicitly.

Position in the Stack

Application
   │
   ▼
SOCKS / HTTP / TUN                 local ingress, optional
   │
   ▼
Shadowsocks address + data         remote proxy protocol
   │
   ▼
AEAD encryption/authentication     built into Shadowsocks
   │
   ▼
TCP or UDP
   │
   ▼
Shadowsocks server
   │
   ▼
Target

Unlike Trojan or VLESS + TLS, classic Shadowsocks AEAD does not first establish a TLS session. Encryption and integrity are part of the Shadowsocks record format itself. SIP003 plugins can add an outer transport/camouflage layer, but that layer is separate from the Shadowsocks cryptographic stream.

Address Encoding

The destination encoding uses the familiar SOCKS-style address tuple but without SOCKS5’s VER, CMD, RSV, or reply fields.

Address typeWire valueRemaining fields
IPv40x014-byte IPv4 + 2-byte big-endian port
Domain0x031-byte domain length + domain bytes + 2-byte big-endian port
IPv60x0416-byte IPv6 + 2-byte big-endian port

So a domain destination such as example.com:443 begins conceptually as:

03 0b 65 78 61 6d 70 6c 65 2e 63 6f 6d 01 bb
│  │  └──────────── "example.com" ───────────┘ │
│  domain length = 11                           port 443
└─ ATYP = domain

This address format is reused inside TCP and UDP plaintext structures before encryption.

Classic AEAD Methods

The current Chimera_Server classic AEAD path accepts these methods:

MethodKey lengthSalt lengthAEAD tag
aes-128-gcm16 bytes16 bytes16 bytes
aes-256-gcm32 bytes32 bytes16 bytes
chacha20-ietf-poly130532 bytes32 bytes16 bytes

Chimera_Client maps a wider set through the Rust shadowsocks crate, including xchacha20-ietf-poly1305, AEAD-2022 method names, and rc4-md5. Do not infer Server interoperability from the Client parser alone: the current Server explicitly rejects classic xchacha20-poly1305 and does not expose rc4-md5 in its inbound cipher parser.

Classic AEAD Key Derivation

For the current Server legacy/classic path:

  1. the textual password is converted into a master key using the traditional iterative MD5-compatible derivation;
  2. each TCP direction or UDP packet uses a random salt whose length equals the cipher key length;
  3. HKDF-SHA1 with info string ss-subkey derives the per-session subkey from master_key and salt;
  4. the AEAD nonce starts at zero and increments for each protected item in the stream direction.

The salt is therefore not merely decorative randomness: repeating it with the same master key would repeat the derived session key. The Server keeps a timed salt cache and rejects recently replayed salts.

Classic AEAD TCP Wire Format

The encrypted TCP direction starts with one salt followed by independently authenticated length and payload records:

+----------------------+  salt_len
| random salt          |
+----------------------+
| ENC(length: u16)     |  2 bytes ciphertext
| TAG                   |  16 bytes
+----------------------+
| ENC(payload)          |  length bytes ciphertext
| TAG                   |  16 bytes
+----------------------+
| ENC(next length)      |
| TAG                   |
+----------------------+
| ENC(next payload)     |
| TAG                   |
+----------------------+
             ...

The current Server caps a classic plaintext record at 0x3fff bytes. The first decrypted plaintext bytes of a client-to-server stream are the Shadowsocks destination address; application bytes follow immediately after it.

This means the target is authenticated by the same AEAD stream as the application data. There is no separate SOCKS-style request/reply exchange.

Client-to-server example shape

TCP connect to SS server
  ↓
salt
  ↓
AEAD record containing:
    ATYP | DST.ADDR | DST.PORT | early application bytes ...
  ↓
more AEAD records

Server-to-client direction

The response direction creates its own random salt and its own nonce sequence. It carries only relayed application bytes; there is no success reply containing a bound address.

Classic AEAD UDP Wire Format

Each UDP datagram is independently encrypted:

+----------------------+  salt_len
| random salt          |
+----------------------+
| encrypted plaintext  |
|   ATYP                |
|   DST.ADDR            |
|   DST.PORT            |
|   UDP payload         |
+----------------------+
| AEAD tag              | 16 bytes
+----------------------+

The server response uses the same structure, but the address identifies the remote source endpoint corresponding to the returned payload.

Because each packet contains a fresh salt and complete destination tuple, classic Shadowsocks UDP is packet-oriented. It does not use SOCKS5’s UDP RSV | FRAG | ATYP ... header and has no SOCKS5 FRAG semantics.

The current Server also rejects a recently reused classic UDP salt, providing a bounded replay check.

Shadowsocks 2022 Key Material

A Shadowsocks 2022 method name begins with 2022-blake3-. In the current Server, the configured password field for such a user is interpreted as a Base64-encoded raw pre-shared key rather than an arbitrary password phrase.

The decoded key length must exactly match the selected cipher key size.

Current Server method paths include:

  • 2022-blake3-aes-128-gcm;
  • 2022-blake3-aes-256-gcm;
  • 2022-blake3-chacha20-ietf-poly1305.

Session subkeys are derived with BLAKE3’s derive-key mode using the context string shadowsocks 2022 session subkey over PSK || salt/session-id material.

Shadowsocks 2022 TCP Request

The current Server decodes the client direction in these stages:

salt
  ↓
AEAD fixed request header
  type      : u8 = 0
  timestamp : u64 BE
  var_len   : u16 BE
  + 16-byte tag
  ↓
AEAD variable request header[var_len]
  + 16-byte tag
  ↓
AEAD length/payload records ...

The variable request header is emitted into the plaintext stream and begins with the destination address. Chimera then reads:

ATYP | DST.ADDR | DST.PORT | padding_len:u16 | padding | optional early data

The current Server allows at most 900 bytes of this post-address padding and rejects invalid or truncated values.

The variable-header ciphertext length itself is bounded to 18 KiB by the current implementation.

Timestamp and replay checks

The Server validates the 2022 timestamp against its local clock and keeps a timed salt replay cache. A valid AEAD tag is therefore insufficient on its own: stale/future timestamps or recently reused salts can still cause the request to be rejected.

Clock synchronization matters more for Shadowsocks 2022 than for classic AEAD.

Shadowsocks 2022 TCP Response

After validating the request salt, the Server creates a distinct response salt. Its first protected response header contains:

type         : u8 = 1
timestamp    : u64 BE
request_salt : original client request salt
first_len    : u16 BE

That header is AEAD-protected, followed by the separately protected first response payload. Later application bytes use the normal encrypted length + payload record sequence.

Binding the original request salt into the response header lets the client associate the response with the validated request direction.

The current 2022 stream path allows payload records up to 0xffff bytes.

AEAD-2022 Multi-user Identity / EIH

The current Server supports an identity-header path for multi-user Shadowsocks 2022 with AES methods.

Important constraints in the current implementation are:

  • the identity method must be 2022-blake3-aes-128-gcm or 2022-blake3-aes-256-gcm;
  • users behind an identity must use the same AES method;
  • multi-user AEAD-2022 without an identity is rejected;
  • the identity layer derives a BLAKE3 identity subkey and decrypts a 16-byte user hash to select the actual user PSK.

Conceptually, EIH adds a user-selection layer before the selected user’s normal 2022 session keys are used. It should not be described as a SOCKS username/password negotiation.

Shadowsocks 2022 UDP: AES Variant

For the current Server AES-2022 path, the datagram starts with a 16-byte separately encrypted header:

AES block under PSK:
    session_id : 8 bytes
    packet_id  : u64 BE

The decrypted values are then used to derive the UDP session key. The remaining AEAD body contains, for a client request:

type        : u8 = 0
timestamp   : u64 BE
padding_len : u16 BE
padding
ATYP | DST.ADDR | DST.PORT
payload
TAG : 16 bytes

A server response uses its own server session ID and packet ID and includes the client session ID in the protected body so the peer can correlate the direction.

Shadowsocks 2022 UDP: ChaCha Variant

The current Server’s 2022 ChaCha UDP path uses a 24-byte XChaCha20-Poly1305 nonce prefix. The protected client body contains:

client_session_id : 8 bytes
packet_id         : u64 BE
type              : u8 = 0
timestamp         : u64 BE
padding_len       : u16 BE
padding
ATYP | DST.ADDR | DST.PORT
payload
TAG

The response body carries the server session ID and packet ID, response type, timestamp, client session ID, padding length, source address, and payload.

This is one reason not to document “Shadowsocks UDP” as one universal packet layout: classic AEAD and AEAD-2022, and even the AES/ChaCha 2022 paths, differ materially.

UDP Replay Window in Current Chimera_Server

The Server tracks AEAD-2022 UDP packets by session ID and packet ID. The current replay state:

  • rejects an already-seen packet ID;
  • rejects packet IDs that fall more than 1024 behind the highest accepted ID;
  • expires inactive replay sessions on the same roughly one-minute time scale used by the current salt cache.

This is protocol-level anti-replay state. It is separate from operating-system UDP NAT/session timeouts.

TCP Close and Error Behavior

Shadowsocks does not define a SOCKS5-style REP status byte after the destination request. Errors therefore surface differently:

  • invalid password/key material usually manifests as AEAD authentication failure;
  • a replayed salt/session packet is rejected locally;
  • malformed address or length fields terminate the affected stream/datagram;
  • target connection failure closes the relayed stream rather than returning a SOCKS5 connection-status frame;
  • normal TCP EOF propagates through the encrypted stream shutdown.

Applications using a local SOCKS5 listener may still receive a SOCKS-layer failure from Chimera_Client, but that is generated by the local inbound and is not a Shadowsocks wire reply from the remote server.

State Machine

A simplified classic TCP state machine is:

TCP_CONNECTED
    |
    v
READ_SALT
    |
    v
DERIVE_SESSION_KEY
    |
    v
DECRYPT_RECORD_LENGTH
    |
    v
DECRYPT_FIRST_PAYLOAD
    |
    +--> parse destination
    |
    v
CONNECT_TARGET
    |
    v
RELAY_AEAD_RECORDS
    |
    v
EOF / ERROR

For Shadowsocks 2022, insert VALIDATE_TIMESTAMP, CHECK_REPLAY, and request-header parsing before destination dispatch.

Packet-capture Anchors

Without keys, an on-path capture normally exposes only outer transport metadata:

  • TCP or UDP server endpoint;
  • direction, timing, and encrypted record/datagram sizes;
  • random-looking salt/nonce prefixes;
  • plugin/TLS/WebSocket metadata if an optional outer plugin is used.

With keys and an implementation-aware decoder, useful anchors are:

  • classic TCP: salt | encrypted length+tag | encrypted payload+tag;
  • classic UDP: salt | encrypted address+payload+tag;
  • 2022 TCP: salt followed by fixed/variable authenticated headers;
  • 2022 UDP: session ID / packet ID / timestamp and address fields after successful decryption.

A capture cannot identify the target address from ciphertext alone under a working AEAD cipher.

SIP003 Plugins

Chimera_Client supports a plugin hook around the raw stream before the Shadowsocks protocol stream is created. The repository contains paths for plugin-style transports such as simple-obfs and v2ray-plugin/WebSocket when the needed build features are present.

Layering is conceptually:

TCP
  ↓
optional SIP003 plugin transport
  ↓
Shadowsocks encrypted stream
  ↓
destination + payload

The remote side must run the matching plugin layer. Pointing a plugin-wrapped client directly at a plain Shadowsocks server makes the server see plugin bytes where it expects a Shadowsocks salt/record.

Current Chimera_Client Configuration and Implementation

The Client implementation is behind the shadowsocks Cargo feature and currently has:

  • outbound TCP through ProxyClientStream;
  • outbound UDP through ProxySocket;
  • Shadowsocks inbound TCP/UDP modules;
  • configurable cipher, password, udp, plugin, and plugin-opts;
  • integration tests for TCP, UDP, multi-target UDP, and UDP session isolation.

The current outbound cipher mapper accepts:

aes-128-gcm
aes-256-gcm
chacha20-ietf-poly1305
xchacha20-ietf-poly1305
2022-blake3-aes-128-gcm
2022-blake3-aes-256-gcm
2022-blake3-chacha20-ietf-poly1305
rc4-md5

That list is a Client implementation fact, not a promise that every method is accepted by Chimera_Server.

Current Chimera_Server Implementation

The Server has inbound TCP and UDP Shadowsocks paths behind its shadowsocks feature, which is included in the current default full build.

Notable current boundaries include:

  • at least one user is required for TCP;
  • classic AES-128-GCM, AES-256-GCM, and ChaCha20-Poly1305 are implemented;
  • AEAD-2022 AES and ChaCha paths are implemented;
  • classic xchacha20-poly1305 is explicitly rejected;
  • AEAD-2022 multi-user requires the AES EIH identity path;
  • user level compatibility fields are not treated as implemented runtime policy;
  • replay caches and timestamp validation are active security behavior, not parser-only fields.

See Implementation Status and Source Evidence for the cross-project matrix.

SOCKS5 Phase-by-phase Comparison

PhaseSOCKS5ShadowsocksRelationship
Transport connectTCP to SOCKS serverTCP or UDP to SS serverConceptually same lower-layer reachability step
Method negotiationVER, NMETHODS, METHODSNoneReplaced by preconfigured cipher/key
Username/password authOptional RFC 1929 exchangeNo username/password subnegotiation; key possession authenticates/decryptsReplaced
Destination requestVER, CMD, RSV, ATYP, DSTAddress tuple embedded in decrypted plaintextSame destination concept, different framing
Success replyVER, REP, RSV, BNDNo equivalent protocol replyRemoved
TCP dataPlain bytes after SOCKS handshakeAEAD length/payload recordsExtra encryption/record layer
UDP controlUDP ASSOCIATE over TCPNo equivalent control negotiation in classic SSReplaced
UDP packetRSV, FRAG, ATYP, DST, DATAEncrypted address + payload; AEAD-2022 adds session/packet metadataSame routing purpose, different wire format
FragmentationSOCKS5 FRAG field existsNo SOCKS5-style fragmentation fieldRemoved
Replay defenseNot provided by SOCKS5Salt/session/timestamp replay checks depending on SS generationExtra security layer
Close/errorSOCKS REP during setup, then TCP/UDP semanticsAEAD/parser/target failure usually closes or drops affected trafficReplaced

Security Notes

  • Prefer modern AEAD or AEAD-2022 methods; legacy ciphers exist for compatibility and should not be treated as equivalent security choices.
  • Protect Shadowsocks passwords/PSKs as credentials. For AEAD-2022 the Base64 string represents raw key material in the current Server configuration path.
  • Reusing salts/nonces or disabling replay checks can destroy the assumptions of the AEAD construction.
  • Keep system clocks reasonably synchronized for AEAD-2022 timestamp validation.
  • A plugin can camouflage or reshape transport traffic, but it does not replace correct Shadowsocks authentication and AEAD validation.
  • Do not expose Client-only cipher support as a Server compatibility claim.

Test Evidence

Current Client-side integration coverage includes TCP, UDP, multi-target UDP, and UDP session isolation in shadowsocks_integration_tests.rs. These tests exercise real local socket paths within Chimera Client implementations.

Current Server external interoperability coverage in xray_client_proxy_e2e.rs includes classic AEAD TCP, multiple legacy users, AEAD-2022 EIH multi-user selection, and AEAD-2022 TCP plus AES UDP against an Xray client.

These tests do not prove that every cipher accepted by the Client is also accepted by the Server. In particular, keep the explicit Server cipher and configuration rejections above visible when describing compatibility. See Test Evidence and Interoperability Matrix.

Troubleshooting

When a Shadowsocks connection fails, check in this order:

  1. confirm the client and server agree on classic AEAD versus 2022-blake3-*;
  2. confirm the exact cipher name and key length;
  3. for 2022, confirm the configured value is the expected Base64 raw key and clocks are synchronized;
  4. confirm any SIP003 plugin exists on both sides with matching options;
  5. verify TCP versus UDP is enabled in the actual Client build/config;
  6. inspect logs for tag failure, replay rejection, timestamp failure, unknown EIH user, or unsupported cipher;
  7. only after the cryptographic layer succeeds, debug destination DNS/routing/target reachability.

Source Anchors

Current Chimera implementation details in this chapter are grounded in:

  • Chimera_Client/clash-lib/src/proxy/shadowsocks/;
  • Chimera_Client/clash-lib/src/config/internal/proxy.rs;
  • Chimera_Client/clash-lib/tests/shadowsocks_integration_tests.rs;
  • Chimera_Server/chimera_server_lib/src/handler/shadowsocks.rs;
  • Chimera_Server/chimera_server_lib/src/beginning/udp.rs;
  • Chimera_Server/chimera_server_lib/src/config/server_config/.

For portable protocol behavior, compare the relevant Shadowsocks specification/SIP with the version implemented by the selected peer rather than assuming all Shadowsocks generations share one wire format.

AnyTLS

AnyTLS is a TLS-carried proxy protocol with its own authentication prefix and framed stream commands. It is not “arbitrary traffic inside TLS”: after the TLS handshake, the peer still has to authenticate, negotiate protocol metadata, open a logical stream, provide a destination, and exchange framed payloads.

This chapter documents the current AnyTLS wire behavior implemented by Chimera_Client. The current Chimera_Server protocol enum does not contain an AnyTLS inbound, so Client-side AnyTLS interoperability should be evaluated against a compatible AnyTLS server implementation rather than inferred from Chimera Server support.

Position in the Stack

Application
   │
   ▼
SOCKS / HTTP / TUN                 local ingress, optional
   │
   ▼
TCP connection to AnyTLS server
   │
   ▼
TLS handshake                      mandatory in normal deployments
   │
   ▼
AnyTLS authentication + frames
   │
   ▼
TCP target or UDP-over-TCP v2

The TLS layer provides transport confidentiality and server authentication when certificate verification is enabled. The AnyTLS password hash is a separate protocol authentication layer inside the established TLS application-data stream.

Current Chimera Connection Sequence

The current outbound path performs these stages:

TCP_CONNECT
   |
   v
TLS_HANDSHAKE
   |
   v
SEND SHA256(password)        32 bytes
   |
   v
SEND padding_len             u16 BE
   |
   v
SEND SETTINGS frame
   |
   v
SEND SYN frame
   |
   v
SEND PSH(destination) frame
   |
   v
RELAY PSH / FIN / ALERT

The implementation deliberately builds the initial AnyTLS authentication bytes and first frames into one write so compatible servers that expect the first TLS application-data record as one authentication packet do not observe an incomplete password/padding structure.

Authentication Prefix

Immediately after TLS, the current Chimera client writes:

+----------------------------------+
| SHA256(password)                 | 32 bytes
+----------------------------------+
| padding_len                      | u16 BE
+----------------------------------+
| padding                          | padding_len bytes
+----------------------------------+
| AnyTLS frames ...                |
+----------------------------------+

The current outbound advertises no initial padding, so padding_len = 0.

The inbound implementation builds an O(1) lookup map from SHA256(password) to the configured user identity. In multi-user mode the hash selects the user; in single-password fallback mode the user identity is empty.

This is not RFC 1929 username/password authentication. The password itself is not sent directly; the fixed 32-byte SHA-256 digest is the lookup/authentication token inside TLS.

Authentication Failure and Fallback

The current Client inbound can be configured with a fallback backend. If the 32-byte password hash is unknown:

  1. the AnyTLS parser stops;
  2. the already consumed 32 bytes are prepended back into the decrypted TLS application stream;
  3. the remaining decrypted stream is bidirectionally proxied to the fallback backend;
  4. the inbound sends a TLS close_notify on clean shutdown where possible.

Without a fallback, the connection is rejected.

This fallback occurs after TLS termination in the current implementation. It is therefore different from a raw TCP fallback that forwards the original encrypted ClientHello/application records untouched.

Initial Padding Field

After the 32-byte hash, the server reads a 2-byte big-endian padding length and skips exactly that many bytes.

padding_len:u16 | padding[padding_len]

Malformed/truncated padding terminates the handshake. The current outbound sends zero bytes here even though later protocol metadata can advertise a padding scheme.

Frame Format

Every AnyTLS frame in the current implementation uses this header:

+---------+------------------+------------------+-------------------+
| CMD     | Stream ID        | Data Length      | Data              |
| u8      | u32 big-endian   | u16 big-endian   | DataLen bytes     |
+---------+------------------+------------------+-------------------+
   1 B          4 B                2 B              0..65535 B

The fixed frame header is therefore 7 bytes. A single frame payload cannot exceed 65535 bytes.

Command Values

The current implementation recognizes these command numbers:

CommandValueCurrent meaning
WASTE0Padding/noise frame; ignored by the current inbound handshake parser.
SYN1Opens/selects a logical stream ID.
PSH2Carries destination bytes during setup and application bytes during relay.
FIN3Ends the logical stream.
SETTINGS4Client metadata/settings.
ALERT5Error/alert text from peer.
UPDATE_PADDING_SCHEME6Padding-scheme update; current outbound reads and discards it.
SERVER_SETTINGS10Server settings; current outbound reads and discards it.

Unknown commands are ignored by the current outbound receive loop after a valid stream is established.

SETTINGS Frame

The current Chimera client sends a SETTINGS frame on stream ID 0. Its payload is UTF-8 metadata with the current shape:

v=2
client=clash-rs/<package-version>
padding-md5=47edb1f4ed8a99480bf416d178311f10

The advertised MD5 corresponds to the current fixed client padding scheme stop=0, meaning Chimera does not actively add AnyTLS protocol padding to data packets in this implementation.

The current inbound accepts SETTINGS during the handshake but does not use its metadata for routing/authentication.

Opening the Logical Stream

The current outbound uses one fixed logical stream ID:

STREAM_ID = 1

It sends:

SYN(stream=1, data="")
PSH(stream=1, data=SocksAddr(destination))

The inbound enforces ordering and identity:

  • a SYN must arrive before the destination PSH;
  • repeated SYN is tolerated only for the same stream ID;
  • the destination PSH must use the selected stream ID;
  • early FIN or ALERT aborts the handshake;
  • malformed destination bytes abort the handshake.

Although the wire header contains a 32-bit stream ID and the protocol is structurally multiplexable, the current Chimera outbound creates one logical AnyTLS stream with ID 1 per underlying connection. Do not document current Chimera as performing multi-stream multiplexing merely because the field exists.

Destination Encoding

The destination carried in the first PSH uses SocksAddr, the same address tuple used by other Clash-family protocol implementations.

Conceptually:

TypeValueEncoding
IPv40x01IPv4 bytes + port
Domain0x03length + domain bytes + port
IPv60x04IPv6 bytes + port

The address bytes are payload of an AnyTLS PSH; there is no SOCKS5 VER/CMD/RSV envelope around them.

TCP Data Relay

After the initial destination has been accepted, application bytes are transformed into PSH frames:

application write
     |
     v
CMD=PSH | stream=1 | len | payload
     |
     v
TLS application data

The current relay reads up to 16 KiB from its local in-process pipe for each generated PSH. This is an implementation buffering choice, not a protocol maximum; the frame format itself permits up to 65535 bytes.

Inbound response PSH data for the selected stream is written back to the application-facing stream.

FIN and Half-close Behavior

When the application-facing write side reaches EOF, the outbound sends:

FIN(stream=1, len=0)

and flushes the TLS stream.

When a matching inbound FIN is received, the current outbound shuts down the application-facing read side and cancels the relay tasks.

The current implementation therefore treats FIN as logical-stream termination rather than supporting a long independent multiplexed connection containing other active stream IDs.

ALERT Handling

A peer ALERT frame is interpreted as UTF-8/lossy text for logging. The current outbound then shuts down the relay and cancels the connection tasks.

There is no SOCKS-style numeric result mapping. An AnyTLS alert is an AnyTLS-layer failure; a local SOCKS inbound may translate the resulting connection failure into its own SOCKS response for the local application.

Handshake Timeout

The current AnyTLS inbound allows 10 seconds for the TLS + password + padding + SYN/PSH(destination) handshake sequence.

A timeout closes the connection without dispatching a target session.

This timeout is a current Chimera implementation policy, not a field encoded into the AnyTLS wire format.

UDP over TCP v2

The current AnyTLS UDP implementation does not send native UDP packets to the AnyTLS server. It creates a normal AnyTLS stream whose apparent destination is a reserved magic hostname:

sp.v2.udp-over-tcp.arpa:0

After that AnyTLS stream is established, it sends the UoT v2 connect header:

+------------------+-----------------------+
| isConnect        | real UDP destination  |
| u8 = 1           | SocksAddr             |
+------------------+-----------------------+

All of those bytes are still carried inside AnyTLS PSH frames.

UoT Datagram Framing

After the UoT connect header, each UDP payload is framed as:

+------------------+-----------------------+
| payload length   | UDP payload           |
| u16 big-endian   | length bytes          |
+------------------+-----------------------+

The selected destination is established once by the UoT connect header. Individual datagrams therefore do not repeat a SOCKS address header in the current connect-mode session.

The same 2-byte length-prefix form is used for responses delivered back through the stream.

UDP Session State

The current outbound creates one stream-backed datagram object tied to the requested UDP destination. The inbound recognizes the magic hostname, unwraps AnyTLS PSH frames into a byte stream, parses isConnect=1 and the real destination, and dispatches that stream as a UDP session.

This is UDP tunneling over an ordered TCP/TLS stream. Consequences include:

  • UDP datagrams inherit TCP ordering;
  • loss of one underlying TCP segment can delay later datagrams (head-of-line blocking);
  • there is no native QUIC-style independent datagram delivery;
  • MTU behavior is transformed into stream framing rather than preserved as original IP/UDP packet boundaries.

Current Inbound State Machine

TCP_ACCEPTED
    |
    v
TLS_HANDSHAKE
    |
    v
READ_PASSWORD_HASH(32)
    |
    +-- unknown --> FALLBACK or CLOSE
    |
    v
READ_PADDING_LEN + SKIP_PADDING
    |
    v
READ SETTINGS/WASTE/SYN...
    |
    v
REQUIRE SYN(stream=N)
    |
    v
REQUIRE PSH(stream=N, destination)
    |
    +-- magic UoT host --> READ UOT CONNECT --> UDP DISPATCH
    |
    +-- normal target --> TCP DISPATCH
    |
    v
RELAY PSH / FIN

The transport can therefore fail at several distinct layers: TCP reachability, TLS authentication, AnyTLS password authentication, frame ordering, destination parsing, or target connection.

Packet-capture View

Without TLS session keys, a normal capture exposes:

TCP 3-way handshake
TLS ClientHello / ServerHello / encrypted handshake
TLS Application Data
TLS Application Data
...
TCP FIN/RST or TLS close_notify

The SHA-256 password token, stream IDs, destination, UoT magic host, and frame boundaries are inside TLS application data and are not visible to a passive observer under a correctly functioning TLS session.

With TLS keys or an in-process trace, the first application bytes can be decoded as:

32B password hash
00 00                         padding_len=0
04 00 00 00 00 <len> ...     SETTINGS, stream 0
01 00 00 00 01 00 00         SYN, stream 1, len 0
02 00 00 00 01 <len> <addr>  PSH, stream 1, destination

This is a useful parser sanity check when interoperability fails immediately after a successful TLS handshake.

Current TLS Configuration Surface

The current AnyTLS outbound configuration includes:

  • password;
  • alpn;
  • sni;
  • skip-cert-verify;
  • udp;
  • optional client certificate/key for mTLS.

The client certificate and key must be provided together.

Certificate verification should remain enabled in normal deployments. Disabling it removes the normal TLS server-identity check and leaves the AnyTLS password as the main remote authentication secret.

Parsed-only Configuration Fields

Several current Chimera_Client AnyTLS fields are explicitly annotated as parsed for configuration compatibility but not applied by the runtime:

  • fingerprint;
  • client-fingerprint;
  • idle-session-check-interval;
  • idle-session-timeout;
  • min-idle-session.

These fields must be labeled Parsed-only in the Wiki. Their presence in YAML does not prove a behavior change in the current runtime.

Current Chimera_Client Evidence

AnyTLS is behind the anytls Cargo feature. The current source contains:

  • outbound TLS + AnyTLS handshake and framing;
  • outbound TCP relay;
  • outbound UDP-over-TCP v2;
  • AnyTLS inbound TLS listener;
  • multi-user SHA-256 password lookup;
  • fallback handling;
  • TCP and UDP inbound dispatch;
  • integration tests for TCP and UDP.

Recent implementation work also retains UDP sessions until cancellation rather than allowing the stream-backed datagram session to disappear prematurely.

See Implementation Status and Source Evidence for the cross-project evidence level.

Chimera_Server Status

The current Chimera_Server protocol enum and handler tree do not contain an AnyTLS inbound implementation.

Therefore:

  • Chimera_Client → third-party AnyTLS server can be a valid supported deployment;
  • Chimera_Client AnyTLS → Chimera_Server is not a currently documented compatible pair;
  • an AnyTLS page in this Wiki describes the Client implementation and protocol behavior, not an implicit Server capability.

SOCKS5 Phase-by-phase Comparison

PhaseSOCKS5AnyTLSRelationship
Initial transportTCP to SOCKS serverTCP then TLS to AnyTLS serverExtra TLS layer
Server authenticationUsually none at transport levelTLS certificate verificationExtra layer
Method negotiationClient sends supported methodsNoneRemoved/replaced by configuration
User authenticationOptional RFC 1929 username/passwordSHA256(password) token inside TLSReplaced
Request commandCONNECT/BIND/UDP ASSOCIATESYN + PSH(destination); UoT magic destination for UDPReplaced
Destination addressSOCKS request fieldsSocksAddr inside first PSHSame concept, different framing
Success replySOCKS REP replyNo equivalent fixed result structure in current pathRemoved
TCP dataRaw bytes after requestPSH frames inside TLSExtra framing + TLS
TCP closeTCP half-close/closeFIN logical command plus TLS/TCP closeExtra logical close layer
UDPNative UDP relay with SOCKS UDP headerUDP-over-TCP v2 streamReplaced transport model
UDP destinationRepeated per SOCKS UDP datagramEstablished once in UoT connect modeDifferent session semantics
FragmentationSOCKS FRAG fieldNo SOCKS5-style FRAGRemoved
MultiplexingOne SOCKS TCP control connection per request in common useFrame has stream ID, but current Chimera uses one stream ID per connectionProtocol has extra field; current implementation does not exploit full mux
Error reportingNumeric SOCKS REPTLS errors, auth rejection, ALERT, close/loggingReplaced

Security Notes

  • TLS verification and AnyTLS password authentication protect different layers; do not treat one as a substitute for the other.
  • The on-wire token is SHA256(password). Choose a high-entropy password because a captured decrypted authentication token is deterministic for a given password.
  • Keep skip-cert-verify disabled unless the trust consequences are understood.
  • Fallback targets receive decrypted TLS application bytes after an unknown password; configure them intentionally and avoid exposing sensitive internal services.
  • UDP-over-TCP can suffer head-of-line blocking and should not be described as equivalent to native UDP or QUIC datagrams.
  • Parsed-only idle/fingerprint options should not be relied upon for timeout, fingerprinting, or resource-control guarantees.

Troubleshooting

Debug AnyTLS from the outside inward:

  1. verify TCP reachability to the server;
  2. verify TLS SNI, certificate trust, ALPN, and optional mTLS material;
  3. verify both sides use the same password and that the server expects the SHA-256 token form;
  4. verify the first application packet contains the padding length and v2 SETTINGS/SYN/PSH sequence expected by the peer;
  5. for TCP, verify the destination SocksAddr is accepted;
  6. for UDP, verify sp.v2.udp-over-tcp.arpa, isConnect=1, the real destination, and 2-byte datagram lengths;
  7. inspect ALERT, timeout, fallback, or target-connect logs before changing unrelated DNS/rule settings.

A successful TLS handshake only proves the TLS layer. It does not prove AnyTLS password authentication or frame compatibility.

Source Anchors

Current Chimera implementation details in this chapter are grounded in:

  • Chimera_Client/clash-lib/src/proxy/anytls/mod.rs;
  • Chimera_Client/clash-lib/src/proxy/anytls/datagram.rs;
  • Chimera_Client/clash-lib/src/proxy/anytls/inbound/framing.rs;
  • Chimera_Client/clash-lib/src/proxy/anytls/inbound/handler.rs;
  • Chimera_Client/clash-lib/src/proxy/anytls/inbound/user.rs;
  • Chimera_Client/clash-lib/src/proxy/anytls/inbound/tls.rs;
  • Chimera_Client/clash-lib/src/config/internal/proxy.rs;
  • Chimera_Client/clash-lib/tests/anytls_integration_tests.rs.

For portable interoperability, verify the selected peer against the current AnyTLS protocol specification and implementation rather than assuming every AnyTLS implementation uses the same optional settings or multiplexing policy.

Trojan

Positioning

Trojan is a TLS-based proxy protocol designed so that the outer connection uses a normal TLS session while proxy authentication and destination metadata are carried inside encrypted application data.

The original Trojan protocol uses a pre-shared password, represented on the wire as the hexadecimal SHA-224 digest of that password. Its request address format is similar to SOCKS5 and supports both TCP CONNECT and UDP association.

The baseline protocol described here should be distinguished from additional transport combinations exposed by individual proxy cores, such as WebSocket, XHTTP, or other wrappers.

Connection Flow

  1. The client opens a TCP connection to the Trojan server.
  2. Client and server complete a normal TLS handshake.
  3. Inside TLS application data, the client sends the password digest and Trojan request header.
  4. The server validates the password and destination request.
  5. For TCP, the server connects to the target and relays the stream.
  6. For UDP, datagrams are framed inside the Trojan TLS stream.
  7. Invalid traffic can be handled by a fallback service instead of exposing a proxy-specific response.

The detailed byte layout is documented in Wire Format. Fallback behavior is discussed in Traffic Handling.

Layer-by-Layer Exchange

The easiest way to understand Trojan is to separate the ordinary network layers from the Trojan control message itself:

client                                                    server
  |                                                          |
  |---------------- TCP three-way handshake ----------------->|
  |<---------------- TCP established -------------------------|
  |                                                          |
  |==================== TLS handshake ========================|
  | ClientHello (SNI/ALPN/...)                               |
  |<---------------- ServerHello / Certificate / Finished ----|
  |---------------- Finished -------------------------------->|
  |                                                          |
  | TLS application data:                                    |
  |   56-byte hex(SHA224(password))                           |
  |   CRLF                                                    |
  |   CMD + ATYP + DST.ADDR + DST.PORT                        |
  |   CRLF                                                    |
  |   optional first payload                                  |
  |---------------------------------------------------------->|
  |                                                          |
  |          server validates password + request              |
  |          server dials requested destination               |
  |                                                          |
  |<================ encrypted relay data ===================>|

This sequence is important when reading a packet capture. Before TLS is decrypted, a passive capture shows the TCP and TLS handshakes but not the Trojan password digest, destination address, command, or proxied application data. Those fields are TLS application data.

Initial Trojan Request Wire Format

After TLS has been established, the client sends one logical request:

+-----------------------+------+----------------+------+----------+
| hex(SHA224(password)) | CRLF | Trojan Request | CRLF | Payload  |
+-----------------------+------+----------------+------+----------+
|          56           |  2   |    Variable    |  2   | Variable |
+-----------------------+------+----------------+------+----------+

The first field is 56 ASCII hexadecimal characters because SHA-224 produces 28 bytes and hexadecimal encoding uses two characters per byte. It is followed by the two bytes 0x0d 0x0a.

The Trojan request itself is:

+-----+------+----------+----------+
| CMD | ATYP | DST.ADDR | DST.PORT |
+-----+------+----------+----------+
|  1  |  1   | Variable |    2     |
+-----+------+----------+----------+

Unlike a SOCKS5 request, there is no leading VER byte and no reserved RSV byte. Authentication is also not negotiated with a method-selection exchange; it has already been supplied as the password hash immediately before the request.

CMD

The baseline Trojan protocol defines:

ValueCommandMeaning
0x01CONNECTOpen a TCP connection to the destination.
0x03UDP ASSOCIATEEnter Trojan’s framed UDP relay mode.

There is no Trojan equivalent of SOCKS5 BIND in the baseline protocol.

ATYP and Destination Encoding

Trojan deliberately reuses the SOCKS5 address-type values:

ATYPAddress formEncoding
0x01IPv4Exactly 4 address bytes.
0x03Domain nameOne length byte, followed by that many domain-name bytes.
0x04IPv6Exactly 16 address bytes.

DST.PORT is two bytes in network byte order, the same convention used by SOCKS5.

For example, a domain target conceptually becomes:

03                     ATYP = DOMAIN
0b                     domain length = 11
65 78 61 6d 70 6c 65   "example"
2e 63 6f 6d            ".com"
01 bb                  port 443

The example is shown as logical bytes only; on the wire these bytes are inside TLS application records.

Authentication: Trojan versus SOCKS5

SOCKS5 separates method negotiation, optional authentication, and proxy command selection. Trojan collapses those phases behind TLS:

SOCKS5
TCP
 -> VER/NMETHODS/METHODS
 <- VER/METHOD
 -> optional RFC 1929 username/password
 <- authentication status
 -> CONNECT/UDP ASSOCIATE request
 <- structured REP reply
 -> relay data

Trojan
TCP
 -> TLS handshake
 -> password digest + CONNECT/UDP request + optional first payload
 -> relay data, or fallback/connection handling on invalid traffic

The consequences are significant:

  • Trojan has no authentication-method negotiation byte sequence.
  • Trojan has no username/password sub-negotiation equivalent to RFC 1929.
  • Trojan authentication is protected by TLS before it is transmitted.
  • The destination request can be coalesced with initial application payload.
  • The baseline protocol does not define a SOCKS5-style REP response frame for a successful CONNECT.

The last point changes the client state machine: after sending a valid Trojan request, the client normally proceeds by observing the resulting relay behavior rather than waiting for a fixed VER/REP/ATYP/BND.ADDR/BND.PORT success frame.

TCP CONNECT State Machine

A useful client-side state machine is:

DISCONNECTED
   |
   | TCP connect
   v
TCP_CONNECTED
   |
   | TLS handshake + certificate validation
   v
TLS_ESTABLISHED
   |
   | send password digest + CONNECT request [+ first payload]
   v
REQUEST_SENT
   |
   | encrypted application bytes arrive / relay continues
   v
RELAYING
   |
   | TLS close_notify, TCP FIN/RST, timeout, or local close
   v
CLOSED

The server side can be modeled as:

ACCEPT_TCP
   |
   v
TLS_HANDSHAKE
   |
   +---- TLS failure ---------------------------> CLOSE
   |
   v
READ_AUTH_AND_REQUEST
   |
   +---- invalid / unknown ---------------------> FALLBACK_OR_CLOSE
   |
   v
DIAL_DESTINATION
   |
   +---- dial failure --------------------------> implementation handling
   |
   v
BIDIRECTIONAL_RELAY
   |
   v
CLOSE

A robust implementation must not assume that one TLS read returns the complete 56-byte digest, both CRLF delimiters, the full variable-length address, and the first payload. TLS records and the underlying TCP stream may split or coalesce those bytes arbitrarily.

First Payload and Read-Ahead

Trojan allows application payload to immediately follow the second CRLF. This reduces an avoidable application-level round trip:

TLS record payload (logical view)

[authentication][CRLF][CONNECT request][CRLF][first HTTP/TLS/etc. bytes]

A server parser therefore has an important boundary condition: bytes already read beyond the end of the Trojan header are not parser garbage. They are the first bytes destined for the requested upstream connection and must be retained and forwarded in order.

This is analogous to the boundary after a successful SOCKS5 CONNECT, except SOCKS5 normally has an explicit server reply before ordinary application data begins.

Trojan UDP Framing

For CMD = 0x03, the TLS connection becomes a stream carrying a sequence of framed UDP datagrams:

+------+----------+----------+--------+------+----------+
| ATYP | DST.ADDR | DST.PORT | Length | CRLF | Payload  |
+------+----------+----------+--------+------+----------+
|  1   | Variable |    2     |   2    |  2   | Variable |
+------+----------+----------+--------+------+----------+

Length is an unsigned two-byte payload length in network byte order. The address fields identify the destination associated with that individual UDP datagram.

The receiver must therefore parse the stream as repeated length-delimited messages:

READ_ATYP
  -> READ_ADDRESS
  -> READ_PORT
  -> READ_LENGTH
  -> EXPECT_CRLF
  -> READ_EXACTLY_LENGTH_BYTES
  -> DISPATCH_DATAGRAM
  -> READ_ATYP ...

TCP/TLS does not preserve UDP packet boundaries. The Length field is what reconstructs each datagram boundary.

UDP Fragmentation Difference from SOCKS5

SOCKS5’s UDP request header includes RSV and a FRAG byte. Trojan’s baseline UDP framing does not carry the SOCKS5 FRAG field; instead it adds a 2-byte payload length plus CRLF because multiple datagrams are serialized into one reliable TLS byte stream.

That gives a useful design comparison:

PropertySOCKS5 UDPTrojan UDP
Underlying client-to-proxy transportUDP datagramsTLS over TCP byte stream
Datagram boundaryNative UDP packetExplicit 2-byte Length
Address typeATYPSame ATYP values
Destination port2-byte network orderSame
Fragment fieldFRAG existsNo baseline FRAG field
Control lifetimeTCP UDP ASSOCIATE connectionTrojan TLS connection
Loss semantics between client/proxyUDP can lose/reorderTCP retransmits/orders bytes
Head-of-line blockingNot inherent to UDP relayPossible because all frames share TCP ordering

The final row is one of the most important architectural differences between Trojan UDP and QUIC-datagram protocols such as Hysteria 2 and TUIC.

SOCKS5 Phase-by-Phase Comparison

StageSOCKS5TrojanRelationship
Underlying connectionTCPTCP then TLSTrojan adds a security layer first.
Authentication selectionVER/NMETHODS/METHODSNoneReplaced by fixed Trojan credential model.
Authentication payloadMethod-specific, e.g. RFC 192956-byte hex SHA-224 digestReplaced and protected by TLS.
Proxy commandVER/CMD/RSV/ATYP/...CMD/ATYP/...Same core command idea, smaller header.
TCP commandCONNECT = 0x01CONNECT = 0x01Directly aligned.
UDP commandUDP ASSOCIATE = 0x03UDP ASSOCIATE = 0x03Directly aligned in command number.
BIND0x02Not in baseline TrojanSOCKS5-only feature.
IPv4/domain/IPv6ATYP 01/03/04ATYP 01/03/04Directly reused.
Destination port2-byte network orderSameDirectly reused.
Success replyStructured REP + bound addressNo equivalent fixed success frameDifferent state transition.
TCP payloadRaw after success replyTLS-protected after requestTLS is an extra layer.
UDP packet headerRSV/FRAG/ATYP/... per UDP datagramATYP/.../Length/CRLF/Payload in TLS streamReframed for stream transport.
ConfidentialityNone unless auth method adds itTLSMajor Trojan addition.
Invalid client behaviorSOCKS failure replyFallback or close behaviorTrojan adds camouflage-oriented handling.

This table is the baseline for comparing later protocols. Hysteria 2 and TUIC retain the general ideas of authentication, destination metadata, TCP-like streams, and UDP associations, but replace the SOCKS/Trojan TCP stream substrate with QUIC streams and datagrams. VLESS similarly keeps destination dispatch as a separate proxy-protocol concern while REALITY and XHTTP occupy different layers.

Packet-Capture View

Without TLS session keys, a packet capture can usually establish:

  1. DNS resolution for the Trojan server, if DNS is visible.
  2. TCP connection establishment to the Trojan server.
  3. TLS ClientHello metadata that is not encrypted by the negotiated TLS mode, such as observable handshake characteristics and commonly SNI in traditional TLS deployments.
  4. TLS handshake success or failure.
  5. Encrypted application-data records and their timing/size patterns.
  6. TLS/TCP connection shutdown.

It cannot directly reveal the Trojan CMD, ATYP, destination address, password digest, or application payload merely from the encrypted records.

With TLS key logging in a controlled development environment, the decrypted logical sequence should line up with the request format above. Such key logging must be treated as sensitive because it defeats the confidentiality being tested.

Error and Closure Semantics

The baseline Trojan specification is much less reply-oriented than SOCKS5. This means implementations need explicit local policies for conditions such as:

  • TLS authentication/certificate failure,
  • incomplete 56-byte password field,
  • missing CRLF delimiter,
  • unsupported CMD,
  • invalid ATYP,
  • truncated domain/IPv6 address,
  • incomplete two-byte port,
  • upstream dial failure,
  • declared UDP Length larger than available buffered data,
  • peer EOF in the middle of a UDP frame,
  • idle timeout,
  • TLS close_notify, TCP FIN, or TCP RST.

For malformed or unauthenticated requests, the deployment’s fallback policy is part of externally observable behavior. For already authenticated relay traffic, normal stream shutdown should preserve half-close semantics where the runtime and upstream socket APIs support them instead of converting every EOF into an immediate reset.

Configuration and Minimal Deployment Model

A practical deployment needs at least:

  • a TCP listening address and port,
  • TLS certificate/key or another implementation-specific TLS termination path,
  • one or more Trojan passwords,
  • a fallback policy if camouflage behavior is desired,
  • and routing rules for outbound traffic.

A conceptual client entry looks like:

proxies:
  - name: trojan-example
    type: trojan
    server: proxy.example.com
    port: 443
    password: "CHANGE-ME"
    sni: proxy.example.com

Exact transport keys vary by selected core. If WebSocket or another transport is enabled, both endpoints must use compatible transport settings.

Authentication

The original protocol uses a shared secret. A server can assign different passwords to different users, but credential lifecycle is still application configuration rather than a negotiated identity system.

Operationally:

  • use unique, high-entropy credentials,
  • avoid reusing a password across unrelated servers,
  • rotate credentials when a client is decommissioned,
  • and do not expose credentials in logs or example configs.

TLS Requirements

Trojan depends heavily on the quality of its TLS deployment. The certificate, SNI behavior, ALPN configuration, and fallback endpoint should be internally consistent.

For the original TLS-camouflage design, a valid and ordinary-looking HTTPS configuration is preferable to an obviously synthetic endpoint.

TCP and UDP

TCP

TCP requests are straightforward after authentication: the server opens the requested destination and relays bytes in both directions.

UDP

UDP traffic is encapsulated in per-datagram Trojan framing carried over the TLS stream. This differs from QUIC-native protocols such as Hysteria 2 and TUIC, which can use QUIC datagrams.

Strengths

  • Uses mature TLS implementations for confidentiality and server identity.
  • Small protocol-specific framing after TLS establishment.
  • Supports both TCP and UDP relay in the baseline protocol.
  • Invalid requests can be sent to a normal fallback service instead of a proxy-specific error page.
  • Familiar certificate-based operations for administrators already running HTTPS services.

Limitations

  • Certificate issuance and renewal become part of server operations unless the selected stack provides another compatible security mechanism.
  • Shared-secret authentication requires deliberate credential management.
  • TLS camouflage is only as convincing as the surrounding TLS and fallback configuration.
  • UDP is tunneled through the TLS/TCP-oriented connection model rather than using a native unreliable datagram transport.

Security Notes

Do not disable certificate verification in production merely to make a test configuration connect. A successful TCP connection with invalid TLS validation is not equivalent to a secure deployment.

Fallbacks also need care. A fallback should not unintentionally expose private services, administrative endpoints, or internal-only content.

Chimera Status

Chimera_Client

The current Wiki lists Trojan + WebSocket among the client-core capabilities. Because the original Trojan protocol and an implementation-specific WebSocket transport are separate layers, verify both the Trojan credentials and transport options when troubleshooting.

Chimera GUI

Chimera manages the selected core and profile. Trojan protocol behavior belongs to that core rather than the GUI itself.

Chimera_Server

The server capability map includes Trojan-related inbound parsing/handling. Treat this as current implementation scope, not automatic compatibility with every Trojan client or every optional transport combination.

Test Evidence

The current interoperability index records process-level Trojan fallback evidence in xray_client_proxy_e2e.rs, including TLS payload routing through Trojan fallback rules. That is important evidence for unauthenticated/fallback behavior, but it is not the same as a catalogued independent-client happy-path Trojan interoperability test.

Until a concrete external positive Trojan test is listed in the evidence index, keep happy-path compatibility claims tied to implementation/source evidence and the exact tested peer rather than describing blanket Trojan interoperability. See Test Evidence and Interoperability Matrix.

Troubleshooting

  1. Confirm DNS resolves the intended server address.
  2. Verify TCP reachability to the server port.
  3. Validate certificate trust, SNI, and system time.
  4. Check the Trojan password independently of transport-specific options.
  5. If WebSocket is used, verify path/Host/header settings on both endpoints.
  6. If authentication fails but HTTPS fallback works, inspect credential and Trojan request configuration rather than the TLS listener itself.
  7. For UDP issues, first confirm TCP Trojan traffic works and then test UDP as a separate capability.

References

Trojan Wire Format

This page describes the base Trojan request and relay framing after any configured outer transport has been established. TLS, WebSocket, and other transport wrappers are separate layers; their order and availability depend on the implementation.

TLS and Stream Boundaries

In the common TLS deployment, the client establishes TLS before sending Trojan application data. TLS records are not Trojan message boundaries: a request can span multiple TLS records, and a record can contain both the end of a request and following payload. Parsers must read the decrypted connection as an ordered byte stream rather than assume one socket read or TLS record contains one complete message.

TLS protects Trojan fields and relayed data when it is enabled. The client should validate the server certificate and hostname unless an explicitly configured trust model says otherwise.

Initial Request

After the outer transport is ready, the client sends this request:

+-----------------------+---------+----------------+---------+-----------------+
| hex(SHA224(password)) |  CRLF   | Trojan Request |  CRLF   | Payload / frame |
+-----------------------+---------+----------------+---------+-----------------+
|          56           |   2     |    Variable    |    2    |    Optional     |
+-----------------------+---------+----------------+---------+-----------------+

The authentication field is 56 ASCII hexadecimal characters representing the 28-byte SHA-224 digest of the configured password. The current Chimera client emits lowercase hexadecimal. The current Chimera server matches the encoded digest exactly, so this client/server combination requires the lowercase form it emits. This describes the accepted encoding; it does not imply constant-time authentication comparison. There is no separate authentication negotiation or success packet.

The request header is terminated by the second CRLF. After it, CONNECT carries raw bytes for the destination TCP stream; UDP ASSOCIATE begins the UDP frame stream described below. There is no additional Trojan success frame before relaying begins.

With no initial payload, request sizes are:

Destination typeTrojan RequestFull initial header
IPv48 bytes68 bytes
IPv620 bytes80 bytes
Domain of N bytesN + 5 bytesN + 65 bytes

The full header includes the 56-byte digest text and both 2-byte CRLF delimiters.

Trojan Request Fields

Trojan reuses the SOCKS5 command and address encodings, but omits the SOCKS5 version and reserved fields:

+-----+------+----------+----------+
| CMD | ATYP | DST.ADDR | DST.PORT |
+-----+------+----------+----------+
|  1  |  1   | Variable |    2     |
+-----+------+----------+----------+

CMD is one byte:

ValueMeaning
0x01CONNECT: open a TCP connection to the destination
0x03UDP ASSOCIATE: carry UDP datagrams as frames in this stream

ATYP and DST.ADDR use these encodings:

ATYPAddressEncoded DST.ADDR
0x01IPv4exactly 4 address bytes
0x03domain name1-byte length N, followed by N domain bytes
0x04IPv6exactly 16 address bytes

DST.PORT is an unsigned 16-bit integer in network byte order (big-endian). The one-byte domain length allows at most 255 bytes on the wire. The current Chimera server rejects empty domain names and domain bytes that are not valid UTF-8.

TCP Relay and Responses

Once a CONNECT request is accepted, Trojan adds no further framing to the TCP data:

client application bytes
        -> Trojan client -> outer transport -> Trojan server -> destination TCP socket
        <-                  raw bidirectional bytes                         <-

Trojan defines no method-selection response, authentication-status response, SOCKS5-style REP reply, or portable error frame. A client observes success when the tunnel becomes usable; failures before or during relay are represented by TLS/I/O failure, connection closure, fallback handling, or implementation-specific behavior.

A plain Trojan connection carries one CONNECT tunnel or one UDP association. Multiplexing or additional framing supplied by a product is outside the base Trojan request format.

UDP Associate Framing

For UDP ASSOCIATE, each datagram is encoded in the same stream as:

+------+----------+----------+--------+---------+---------+
| ATYP | DST.ADDR | DST.PORT | Length |  CRLF   | Payload |
+------+----------+----------+--------+---------+---------+
|  1   | Variable |    2     |   2    |    2    | Variable|
+------+----------+----------+--------+---------+---------+
  • Address fields use the same encoding as the initial request.
  • Length is an unsigned 16-bit payload length in network byte order.
  • Payload contains exactly Length bytes.
  • Frames are bidirectional: client-to-server frames identify the destination; server-to-client frames identify the datagram source.
  • Trojan UDP frames have no SOCKS5 RSV or FRAG field and define no native fragmentation or reassembly.

The frame header before the payload is 11 bytes for IPv4, 23 bytes for IPv6, and N + 8 bytes for a domain name of length N. Although the wire length can represent up to 65535 bytes, the current Chimera server limits Trojan UDP payloads to 8192 bytes in both directions. This is an implementation limit, not a Trojan wire-format limit.

UDP datagrams carried over a TCP/TLS stream inherit TCP head-of-line blocking: loss or retransmission on the stream can delay later datagrams.

Parsing and Failure Behavior

Implementations should read complete fields from the stream and validate the command, address type, address length, port, CRLF delimiters, and declared UDP payload length before dispatch. A malformed or truncated UDP frame loses framing synchronization; the association should fail rather than guess where the next frame begins.

The base protocol has no close command. The TLS/TCP connection lifetime bounds the relay, and an I/O or parse failure ends the affected connection. In Chimera Server, configured fallback handling can receive traffic that fails before a valid password line is accepted; after a valid digest line, malformed commands or addresses are rejected rather than sent to fallback.

Security Notes

  • hex(SHA224(password)) is a deterministic wire credential, not a password-hardening KDF. Use unique, high-entropy passwords.
  • When TLS is enabled, passive observers without session keys cannot read the digest, command, destination, UDP lengths, or payload. Endpoint addresses, timing, sizes, and some handshake metadata may remain visible.
  • Fallback destinations should be controlled carefully; routing unauthenticated traffic to sensitive internal services can expose them to probes.
  • Parsers should bound input before allocating buffers and reject malformed lengths and addresses. Authentication comparisons should avoid data-dependent early exits.

Implementation References

The current Chimera implementations used to cross-check this page are:

  • Client request construction: Chimera_Client/clash-lib/src/proxy/trojan/mod.rs.
  • Client UDP framing: Chimera_Client/clash-lib/src/proxy/trojan/datagram.rs.
  • Server authentication and request parsing: Chimera_Server/chimera_server_lib/src/handler/trojan.rs.
  • Server UDP framing: Chimera_Server/chimera_server_lib/src/handler/trojan_udp.rs.

These implementation notes describe current project behavior and are not additional protocol requirements.

References

Trojan Traffic Handling

Purpose

Trojan’s outer TLS behavior is only part of its deployment model. The server also needs a deliberate policy for traffic that reaches the TLS listener but is not a valid Trojan request.

A well-designed fallback path serves two goals:

  • ordinary HTTPS/non-Trojan traffic receives ordinary service behavior,
  • invalid proxy authentication does not produce an obvious proxy-specific banner.

Valid Trojan Traffic

After TLS completes, a valid client sends the Trojan authentication field and a well-formed request. The server validates both before opening the requested outbound connection.

For valid traffic:

Client
  │ TLS
  ▼
Trojan listener
  │ valid auth/request
  ▼
Destination

Non-Trojan Traffic

The original Trojan design allows traffic that is not recognized as a valid Trojan request to be passed to a configured fallback endpoint.

Conceptually:

Client
  │ TLS
  ▼
Trojan listener
  ├── valid Trojan request ──> proxy destination
  └── other traffic ─────────> fallback service

The fallback service might be a local web server or another deliberately configured endpoint. Its job is to return the normal application behavior that an unauthenticated visitor should see.

Why Fallback Behavior Matters

Without a fallback, malformed input may receive a connection reset or a protocol-specific response that differs from the surrounding HTTPS service. That makes the endpoint easier to distinguish operationally.

A fallback does not make a server “undetectable”. It simply avoids unnecessary behavioral differences for traffic that is not accepted as Trojan.

Security Boundaries

Fallback forwarding must be treated as a security-sensitive routing rule. Avoid forwarding unauthenticated traffic to:

  • internal dashboards,
  • metadata services,
  • databases,
  • administrative HTTP endpoints,
  • or arbitrary private-network destinations.

Prefer a dedicated low-privilege web service whose public behavior is expected and safe.

Certificate and SNI Consistency

The TLS certificate, configured SNI, fallback content, and public DNS name should tell a coherent story. For example, a certificate for one hostname with a fallback page that redirects to an unrelated private domain is operationally confusing and can make troubleshooting harder.

Reverse Proxy Deployments

If Nginx, Caddy, or another reverse proxy is part of the path, document clearly which component terminates TLS and which component sees the Trojan application payload. The original Trojan framing assumes the Trojan endpoint receives the post-TLS byte stream.

Transport wrappers such as WebSocket introduce another routing layer and should not be treated as identical to the original direct-TLS layout.

Operational Checks

When validating a deployment, test both accepted and rejected traffic:

  1. A valid Trojan client can authenticate and reach a known destination.
  2. An invalid password does not reach the proxy destination.
  3. Ordinary HTTPS/non-Trojan traffic reaches the intended fallback.
  4. The fallback cannot access sensitive private services.
  5. Logs distinguish operational failures for administrators without leaking useful authentication details to remote clients.

Chimera Notes

Chimera_Client currently documents Trojan together with WebSocket support, so its traffic path can differ from the original direct-TLS Trojan deployment. Chimera_Server should likewise be tested against the exact inbound transport configuration in use.

This page therefore describes the baseline fallback model, not a guarantee that every Chimera transport combination uses the same fallback mechanism.

References

Hysteria 2

Positioning

Hysteria 2 is a TCP and UDP proxy protocol built on QUIC. Its design combines QUIC streams for reliable TCP-style proxying, QUIC datagrams for UDP relay, TLS security from QUIC, and an HTTP/3-facing authentication path intended to make an unauthenticated endpoint behave like an ordinary HTTP/3 service.

Hysteria 2 is especially relevant on paths where packet loss or high latency makes conventional TCP-over-TCP-style designs perform poorly. It is not a universal replacement for TCP-based protocols: the network must permit stable UDP/QUIC traffic.

Protocol Layers

A useful mental model is:

Application TCP / UDP
        │
        ▼
Hysteria 2 proxy requests
        │
        ├── TCP: QUIC bidirectional streams
        └── UDP: QUIC datagrams
        │
        ▼
QUIC + TLS
        │
        ▼
UDP/IP

The protocol depends on standard QUIC and the QUIC unreliable datagram extension. Authentication is performed through an HTTP/3 request before proxy requests are accepted.

QUIC substrate before Hysteria authentication

There are two different handshakes to keep separate when reading a trace or implementing a client. First, QUIC establishes a connection over UDP and carries a TLS 1.3 handshake in QUIC CRYPTO frames. The TLS/QUIC layer establishes the server identity, traffic keys, QUIC transport parameters, and HTTP/3 (h3) application protocol. Only after that protected transport exists does Hysteria perform its own /auth exchange inside HTTP/3.

For standards-conforming QUIC DATAGRAM support, each endpoint advertises the max_datagram_frame_size QUIC transport parameter (0x20) during the QUIC/TLS handshake. The value is directional: it describes the largest DATAGRAM frame the sender of the parameter is willing to receive. A value of zero, or absence of the parameter, means DATAGRAM reception is not available under RFC 9221. An endpoint must not send a DATAGRAM frame until its peer has advertised a non-zero limit, and sending a DATAGRAM larger than the advertised limit is a QUIC protocol violation.

This produces a layered state boundary that SOCKS5 does not have:

UDP socket
  -> QUIC Initial / Handshake packets
  -> TLS authenticated + QUIC transport parameters known
  -> HTTP/3 available
  -> POST /auth
  -> :status 233
  -> Hysteria proxy streams / datagrams allowed

QUIC can support 0-RTT on resumed connections, but replay safety is an application concern. A Hysteria implementation must not assume that an earlier QUIC session ticket removes the Hysteria authentication boundary or makes a side-effecting proxy request replay-safe. RFC 9221 permits DATAGRAM use in 0-RTT only when the remembered peer limit is valid for the resumed connection.

Connection and Authentication Flow

  1. The client establishes a QUIC connection to the server.
  2. QUIC performs its TLS-based cryptographic handshake.
  3. The client sends the Hysteria authentication request through HTTP/3.
  4. The server validates the supplied authentication value and communicates capabilities such as UDP support and receive-rate information.
  5. Only after successful authentication does the connection become an active Hysteria proxy session.
  6. TCP proxy requests use new bidirectional QUIC streams.
  7. UDP packets use QUIC datagrams and Hysteria’s UDP message framing.

The official protocol uses a dedicated success status for its authentication exchange. Implementers should follow the current upstream specification rather than hard-coding behavior from older Hysteria versions.

Wire-Level State Machine

Hysteria 2 has two control transitions before proxy payload is accepted. QUIC/TLS first establishes a protected connection; an HTTP/3 authentication exchange then changes that connection from an ordinary HTTP/3 service into a Hysteria proxy session.

Client                                      Server
  | UDP + QUIC/TLS handshake                  |
  |------------------------------------------->|
  |<-------------------------------------------|
  | HTTP/3 POST /auth                          |
  | Hysteria-Auth + Hysteria-CC-RX             |
  |------------------------------------------->|
  |<---------------------- :status 233 HyOK    |
  | === authenticated proxy connection ===    |
  | open QUIC bidi stream -> TCPRequest        |
  |------------------------------------------->|
  |<----------------------------- TCPResponse  |
  |<========== stream payload ================>|
  |<========= QUIC DATAGRAM UDPMessage =======>|

A server MUST NOT interpret proxy requests before HTTP/3 authentication succeeds. A client must treat any authentication status other than 233 as failure and disconnect. This boundary matters when the endpoint also serves real HTTP/3 content or reverse-proxy masquerading.

Authentication request and response

:method: POST
:path: /auth
:host: hysteria
Hysteria-Auth: <credential>
Hysteria-CC-RX: <uint bytes/second>
Hysteria-Padding: <optional random string>

Hysteria-CC-RX is transport feedback, not authentication material. 0 means the client does not know its receive rate. Padding is ignored semantically.

Success returns:

:status: 233 HyOK
Hysteria-UDP: true | false
Hysteria-CC-RX: <uint> | auto
Hysteria-Padding: <optional random string>

Unlike SOCKS5, there is no separate one-byte method-selection exchange. Credential validation and transport capability negotiation are carried inside an HTTP/3 exchange protected by QUIC TLS. On authentication failure, the server deliberately behaves as an ordinary HTTP/3 service or forwards the request upstream instead of emitting a stable Hysteria-specific failure frame.

TCP Proxying

Each proxied TCP connection is mapped to a QUIC bidirectional stream. The client sends a Hysteria TCP request containing the destination address and optional padding. After the server accepts the request, the remainder of that QUIC stream carries the proxied TCP byte stream.

This gives independent stream-level delivery inside one QUIC connection and avoids coupling every proxied TCP session to a separate TCP connection between client and server.

TCPRequest and TCPResponse wire format

All multibyte fixed-width integers in Hysteria 2 are big-endian, while varint uses the QUIC variable-length integer encoding from RFC 9000.

Each proxied TCP connection starts on a newly opened QUIC bidirectional stream:

TCPRequest
+----------------------+----------------------------------+
| varint 0x401         | message/type identifier          |
| varint addr_len      | byte length of address string    |
| addr_len bytes       | destination as "host:port"       |
| varint padding_len   | random padding byte count        |
| padding_len bytes    | random padding                    |
+----------------------+----------------------------------+

The address is a textual host:port string rather than SOCKS5’s binary ATYP | DST.ADDR | DST.PORT tuple. A parser therefore has to honor the explicit byte length first and only then interpret the resulting string as an endpoint. Do not search the incoming stream for a colon or assume an IPv4-shaped address.

The shortest QUIC-varint encoding of the TCPRequest identifier 0x401 (1025) is the two bytes 44 01. Do not hard-code those two bytes as a magic prefix, however: RFC 9000 allows non-minimal encodings for variable-length integers other than QUIC frame-type fields. A correct Hysteria parser decodes a varint and compares its numeric value with 0x401.

The server answers on the same QUIC stream:

TCPResponse
+----------------------+----------------------------------+
| uint8 status         | 0x00 OK, 0x01 Error              |
| varint message_len   | byte length of message           |
| message_len bytes    | diagnostic message               |
| varint padding_len   | random padding byte count        |
| padding_len bytes    | random padding                    |
+----------------------+----------------------------------+

On 0x00, everything after the response belongs to the proxied byte stream. On 0x01, the server closes that QUIC stream. This transition is analogous to a successful SOCKS5 CONNECT reply followed by raw relay, but it occurs on one QUIC stream among potentially many concurrent proxy streams.

Stream parser boundary

QUIC provides an ordered byte stream, not message-sized reads. A single read can contain only part of a varint, exactly one request, or the request plus later bytes. Implementations should therefore parse incrementally and preserve any bytes already read beyond the control message. Treating one socket/stream read as one TCPRequest is incorrect for the same reason it is incorrect for a SOCKS5 request on TCP.

Multiplexing, stream limits, and TCP backpressure

Hysteria multiplexes independent proxied TCP connections as independent QUIC bidirectional streams inside one QUIC connection. Loss on one stream does not force bytes from another stream to wait for the missing stream offset, but all streams still share the connection’s congestion controller and path capacity. This is transport multiplexing, not an application-level MUX command.

Reliable stream bytes are governed by two layers of QUIC flow control:

  • connection-level credit (MAX_DATA) limits the total stream data in flight against the peer’s advertised allowance;
  • per-stream credit (MAX_STREAM_DATA) limits one individual proxy stream;
  • the peer’s bidirectional-stream limit controls how many new proxied TCP streams can be opened concurrently.

Consequently, a client that cannot immediately open a new proxy stream may be stream-limit blocked rather than rejected by the Hysteria server, and a stream whose writes stall may be flow-control or congestion blocked rather than a failed destination connection. These transport states are different from a TCPResponse status=0x01 application-level failure.

QUIC stream directions can finish independently. Closing or resetting one proxied TCP stream does not inherently close the parent QUIC connection or the other proxy streams. Implementations should preserve TCP half-close semantics where their socket abstraction supports them and should scope stream-local errors to the affected proxy stream whenever the underlying QUIC connection is still healthy.

UDP Proxying

UDP relay uses QUIC’s unreliable datagram capability. Hysteria adds metadata including a session identifier, packet identifier, destination, and fragment information.

When a UDP payload does not fit into the available QUIC datagram size, the protocol can fragment it. Reassembly requires all fragments of a packet; loss of one fragment means that datagram cannot be reconstructed.

Operationally, this makes MTU and path quality especially important for large UDP packets.

UDPMessage wire format

UDP does not open a QUIC stream. Each direction sends a complete Hysteria UDPMessage through QUIC DATAGRAM:

+----------------------+----------------------------------+
| uint32 session_id    | logical UDP association          |
| uint16 packet_id     | packet identity for fragments    |
| uint8 fragment_id    | zero-based fragment index        |
| uint8 fragment_count | total fragments                  |
| varint addr_len      | byte length of "host:port"       |
| addr_len bytes       | destination/source endpoint      |
| remaining bytes      | UDP payload fragment             |
+----------------------+----------------------------------+

The client chooses a unique Session ID for each logical UDP session. The server normally associates a distinct outbound UDP source port with that ID so that replies can be mapped back to the correct client-side flow.

There is no explicit UDP CLOSE command. The client may reuse a Session ID, and the server expires its mapping according to inactivity or implementation policy. If an expired ID later appears again, the server treats it as a new UDP session. This is a major lifecycle difference from SOCKS5, whose UDP association is explicitly anchored to the lifetime of a TCP control connection.

If the server advertised no UDP support, received UDP messages should be silently discarded rather than producing a reliable error exchange.

Fragmentation semantics

When one original UDP datagram is fragmented, all fragments carry the same Packet ID; Fragment ID runs from zero and Fragment Count states how many pieces must be reassembled. No fragment may be delivered upward until all pieces arrive. Loss of any one piece causes the entire original UDP datagram to be unrecoverable and it must be discarded.

For an unfragmented packet, Fragment Count is 1; Packet ID and Fragment ID then have no semantic significance. Implementations should bound fragment reassembly memory and lifetime even though those resource limits are local policy rather than fields in the base wire format.

QUIC DATAGRAM framing, sizing, and backpressure

A Hysteria UDPMessage is the application payload carried inside one QUIC DATAGRAM frame. RFC 9221 defines two DATAGRAM frame types, 0x30 and 0x31; the low bit only determines whether an explicit QUIC-level Length field is present. Neither QUIC frame type changes the Hysteria UDPMessage layout.

The usable Hysteria payload size is therefore smaller than a naïve max_datagram_frame_size calculation suggests. The sender has to fit all of these into one QUIC packet:

QUIC DATAGRAM frame overhead
+ Hysteria UDPMessage fixed header (8 bytes)
+ QUIC-varint address length
+ address string bytes
+ UDP payload fragment

The effective ceiling can be reduced further by QUIC’s max_udp_payload_size and by the current path MTU. QUIC DATAGRAM frames themselves are never transport-fragmented or retransmitted. If one Hysteria UDP packet is too large, Hysteria’s Packet ID / Fragment ID / Fragment Count layer performs the application-level fragmentation described above, or the packet is discarded.

DATAGRAM delivery has deliberately different backpressure semantics from TCP proxy streams. RFC 9221 DATAGRAM frames:

  • do not consume QUIC connection or per-stream flow-control credit;
  • are still subject to the QUIC connection’s congestion controller and pacing;
  • are ack-eliciting, but their application payload is not retransmitted after loss;
  • may be dropped locally if the sender cannot transmit them in time, or by the receiver if it cannot allocate resources to process them.

This explains an important diagnostic case: TCP proxy streams may remain healthy while UDP relay loses packets under pressure. SOCKS5 UDP has a similar unreliable application expectation, but it uses a separate UDP relay socket; Hysteria’s UDP traffic competes with its reliable streams inside the same QUIC connection’s congestion-control budget.

Because Packet ID is only 16 bits, long-lived high-rate sessions inevitably wrap the identifier space. Senders should avoid reusing an identifier while an older fragmented packet with the same identifier can still be reassembled, and receivers should key reassembly state with at least the logical session plus packet identity and expire incomplete entries promptly. Fragment Count=0, a fragment index outside the declared count, inconsistent counts for one in-flight packet, or lengths exceeding the received datagram are malformed inputs and should be rejected without unbounded allocation.

SOCKS5 Comparison by Stage

StageSOCKS5Hysteria 2
Underlying transportTCP control connection; separate UDP relayOne UDP-based QUIC connection
SecurityNone in RFC 1928/1929QUIC TLS before proxy authentication
Authentication negotiationVER/NMETHODS/METHODS, then selected sub-negotiationHTTP/3 POST /auth with Hysteria-Auth
Auth successAuthentication-method-specific resultHTTP status 233
TCP commandCMD=CONNECTOpen bidi stream and send varint 0x401 TCPRequest
DestinationATYP + binary/domain address + uint16 portlength-prefixed textual host:port
TCP resultSOCKS REP plus bound addressstatus + message + padding TCPResponse
TCP dataRaw bytes on the SOCKS TCP connectionRaw bytes on that QUIC stream
ConcurrencyNormally another SOCKS TCP connection per independent CONNECTMany independent QUIC streams share one QUIC connection
UDP setupUDP ASSOCIATE command and returned relay endpointNo separate command; auth response advertises UDP capability
UDP transportNative UDP to SOCKS relay with SOCKS UDP headerQUIC DATAGRAM with Hysteria UDPMessage
UDP session lifetimeBound to TCP control connectionSession ID plus server inactivity policy; no explicit close
FragmentationSOCKS UDP FRAG field; RFC recommends dropping if unsupportedExplicit Packet ID + Fragment ID + Fragment Count reassembly
Congestion controlInherited independently from TCP/UDP transportsQUIC connection congestion control shared by streams and DATAGRAMs, plus receive-rate signaling
Reliable flow controlTCP receive windows on each SOCKS TCP connectionQUIC connection + per-stream flow control (MAX_DATA, MAX_STREAM_DATA)
MultiplexingNo multiplexing in RFC 1928; normally one CONNECT per control connectionMany TCP proxy streams and UDP DATAGRAMs share one QUIC connection
Failure scopeSOCKS reply failure normally ends that requested relay; transport loss ends the TCP control connectionTCPResponse error is stream-local; QUIC connection errors affect every proxy stream/session on that connection
Optional packet obfuscationNoneSalamander, optionally wrapped by Gecko before QUIC reaches the wire

The conceptual correspondence is still recognizable: authentication precedes proxy use, a TCP request names a destination and receives success/failure, and UDP needs per-datagram destination metadata. Hysteria replaces SOCKS5’s small binary control protocol with HTTP/3 authentication plus QUIC-native streams and datagrams, and adds connection-level multiplexing, encryption, congestion control, and explicit UDP fragment identity.

Boundary Conditions and Error Scope

A robust implementation has to distinguish errors at three different layers:

  1. HTTP/3 authentication: any status other than 233 means Hysteria authentication failed and the client disconnects. The server intentionally does not need to expose a Hysteria-specific authentication error body.
  2. Proxy stream: TCPResponse status=0x01 means the requested destination failed; the server closes that QUIC stream, while unrelated streams can continue.
  3. QUIC transport: malformed QUIC frames, DATAGRAM use without negotiated support, or DATAGRAM frames beyond the advertised transport limit can be connection-level protocol errors and therefore tear down every Hysteria flow multiplexed on that QUIC connection.

Length-prefixed fields must be validated before allocation or slicing. QUIC varints can represent values up to 62 bits, which is far larger than any reasonable address, diagnostic string, or padding field. The wire type alone is not a safe allocation bound. Servers should impose practical limits on address, padding, message, fragment-reassembly, concurrent-stream, and UDP-session state.

The base Hysteria specification deliberately leaves some malformed application-message handling to implementations. Defensive parsers should fail closed on truncated varints, truncated fixed-width fields, impossible fragment metadata, and address lengths larger than the remaining message instead of trying to recover by scanning for a later boundary.

Packet-Capture View

Without QUIC decryption keys, a normal packet capture sees UDP packets carrying QUIC rather than the /auth, TCPRequest, destination, or UDPMessage fields. Useful observable phases are therefore:

UDP/IP
  -> QUIC Initial / Handshake packets
  -> protected QUIC 1-RTT packets
       -> HTTP/3 authentication (encrypted)
       -> STREAM frames for TCP proxy streams (encrypted)
       -> DATAGRAM frames for UDP relay (encrypted)

With endpoint-side QUIC/TLS secrets and suitable tooling, the investigator can separate HTTP/3 authentication, individual stream IDs, and DATAGRAM traffic. A standards-oriented trace of the QUIC handshake can also expose transport parameters such as max_datagram_frame_size before 1-RTT application data is decoded. Even then, remember that QUIC packet boundaries are not TCPRequest message boundaries: STREAM frames can split or coalesce application bytes.

For TCP, a decrypted stream begins with the varint value 0x401, then the length-prefixed destination and padding, followed by a TCPResponse, then raw proxied bytes. For UDP, the DATAGRAM Data begins with the 8-byte fixed Hysteria header (Session ID, Packet ID, Fragment ID, Fragment Count) before its address-length varint. Those are useful dissector anchors after decryption, not plaintext signatures visible to a normal on-path capture.

Congestion Control and Bandwidth Information

Hysteria 2 allows peers to communicate receive-rate information during the authentication exchange. Depending on configuration and the values exchanged, the implementation can use explicit bandwidth information or rely on a normal congestion-control algorithm.

Do not treat configured upload/download values as guaranteed throughput. They influence transport behavior; the real path is still limited by RTT, packet loss, server capacity, ISP shaping, and the congestion-control implementation.

HTTP/3 Masquerading

An unauthenticated Hysteria endpoint is expected to behave like an HTTP/3 service rather than immediately exposing a proxy-specific protocol response. Deployments can serve ordinary content or reverse-proxy to another site for non-Hysteria requests.

This is an operational behavior, not a reason to neglect normal TLS and server hardening. A Hysteria server remains a public UDP service and should be patched, rate-limited where appropriate, and protected from credential leakage.

Optional Obfuscation

Obfuscation is an outer packet transform below QUIC. It does not replace QUIC TLS, Hysteria authentication, or proxy framing.

Salamander

Salamander prepends an 8-byte random salt to every QUIC packet and XORs the QUIC packet bytes with a repeating 32-byte BLAKE2b-256-derived mask:

on-wire datagram
+----------------------+----------------------------------+
| 8-byte random salt   | sent in clear                    |
| obfuscated payload   | original QUIC packet XOR mask    |
+----------------------+----------------------------------+

mask = BLAKE2b-256(pre_shared_key || salt)
payload[i] ^= mask[i mod 32]

The receiver derives the same mask from the configured pre-shared key and the received salt, reverses the XOR, and passes the recovered packet to QUIC. This is traffic obfuscation, not an independent authenticated-encryption layer; QUIC TLS remains responsible for confidentiality and integrity of Hysteria traffic.

Gecko

The current upstream specification also defines Gecko as a wrapper around Salamander. Gecko only changes the treatment of QUIC packets with the long-header bit set. Short-header packets go directly through Salamander. A long-header packet is split into between 2 and 8 chunks, and every chunk is wrapped before Salamander processing:

Gecko frame before Salamander
+----------------------+----------------------------------+
| uint8 flags          | 0x80 fragment marker             |
| uint8 msg_id         | original-packet identifier       |
| uint8 idx_count      | high/low 4-bit chunk metadata    |
| uint16 pad_len       | big-endian random padding length |
| pad_len bytes        | random padding                   |
| remaining bytes      | original QUIC packet chunk       |
+----------------------+----------------------------------+

chunkIdx must be smaller than totalChunks, and totalChunks is in the range 2 through 8. All chunks of one original QUIC packet carry the same msgID and count. The receiver first reverses Salamander, groups Gecko fragments by source address and message ID, validates consistent metadata, concatenates chunks in index order, and only then gives the reconstructed long-header packet to QUIC. Reassembly state needs per-source and global bounds plus a TTL to avoid turning handshake camouflage into an allocation attack surface.

The practical capture consequence is significant. Without obfuscation, QUIC long-header structure is visible even though its payload is encrypted. With Salamander, the UDP payload no longer parses as ordinary QUIC. With Gecko, one QUIC handshake packet can additionally appear as several independently padded UDP datagrams. Client and server must agree on the obfuscation mode and key before QUIC itself can establish a connection.

Conceptual Client Configuration

A Clash-family profile commonly expresses a Hysteria 2 node with fields similar to:

proxies:
  - name: hy2-example
    type: hysteria2
    server: proxy.example.com
    port: 443
    password: "CHANGE-ME"
    sni: proxy.example.com
    skip-cert-verify: false

This is a compatibility-oriented example, not a promise that every field name is accepted by every Chimera core version. Use the schema of the selected core as the source of truth.

Server Deployment Checklist

A Hysteria 2 server needs:

  • UDP reachability on the selected listening port,
  • valid TLS identity/configuration expected by the client,
  • an authentication policy,
  • sufficient UDP socket buffers for the target workload,
  • appropriate firewall rules,
  • and a decision about ordinary HTTP/3 fallback/masquerade behavior.

If a cloud provider, home router, or enterprise firewall blocks UDP, changing Hysteria settings will not fix the underlying reachability problem.

Strengths

  • Native TCP and UDP proxying on top of QUIC.
  • Independent QUIC streams reduce cross-stream interference compared with one monolithic reliable stream.
  • QUIC connection behavior can perform well on lossy or high-latency paths.
  • UDP relay maps naturally to QUIC datagrams.
  • HTTP/3-facing authentication/fallback behavior provides a normal service path for unauthenticated requests.

Limitations

  • Requires usable UDP connectivity from client to server.
  • Networks may block, throttle, or degrade QUIC independently of TCP/HTTPS.
  • MTU problems can cause disproportionately confusing UDP failures.
  • Aggressive bandwidth settings can create loss rather than improve throughput.
  • Optional obfuscation adds configuration and interoperability complexity.

Security Notes

  • Keep certificate verification enabled for normal deployments.
  • Use high-entropy authentication credentials and rotate them when clients are retired.
  • Do not expose authentication values in URLs, screenshots, or debug logs.
  • Treat HTTP/3 fallback content as a real public service and patch it normally.
  • Rate limiting and abuse controls may be appropriate on publicly reachable servers.

Chimera Status

Chimera_Client

Hysteria 2 is listed as a current client-core capability. Validate the exact accepted configuration schema and optional features against the current Chimera_Client branch before assuming full parity with Hysteria’s reference implementation or Mihomo.

Chimera GUI

Chimera stores and generates profile/runtime configuration but does not itself implement Hysteria 2 transport logic.

Chimera_Server

The current server capability map includes Hysteria 2 inbound work, and the server documentation lists a Hysteria example configuration. Treat that as a stronger signal than a purely planned feature, while still validating TCP, UDP, authentication, and optional transport behavior separately.

Test Evidence

The current Server interoperability index records an ignored external E2E case, xray_client_proxy_e2e.rs::xray_client_can_proxy_tcp_and_udp_through_chimera_hysteria2_with_xray_defaults, that starts a real Xray client against Chimera Server and exercises both TCP and UDP proxying through the Hysteria 2 implementation.

Because this is an explicit process-level external test, it is strong evidence for the covered path. It does not automatically prove every congestion-control, obfuscation, masquerading, or version-specific option described on this page. See Test Evidence and Interoperability Matrix.

Troubleshooting

Cannot connect at all

  1. Confirm the hostname resolves to the intended server.
  2. Verify UDP reachability to the configured port.
  3. Check firewall/security-group rules on both ends.
  4. Verify TLS name/certificate expectations.
  5. Check the authentication value.

TCP works but UDP fails

  1. Confirm the server advertises/supports UDP relay.
  2. Test small UDP packets first.
  3. Check MTU and fragmentation behavior.
  4. Check NAT/firewall timeout behavior.
  5. Disable optional obfuscation temporarily to reduce variables.

Poor throughput

  1. Measure packet loss and RTT before changing bandwidth values.
  2. Compare with a TCP-based protocol to determine whether the path is specifically hostile to UDP/QUIC.
  3. Avoid over-reporting available bandwidth.
  4. Check server CPU, socket-buffer limits, and uplink capacity.
  5. Inspect whether a VPN, ISP, or enterprise firewall is rate-limiting QUIC.

References

TUIC

Positioning

TUIC is a standardized proxy protocol for relaying TCP and UDP traffic over a multiplexed secure transport. The current protocol specification is version 0x05 and is designed primarily around QUIC, although the protocol model itself is expressed in terms of a multiplexable TLS-encrypted stream rather than being hard-wired to one implementation.

TUIC focuses on low-latency task startup, TCP/UDP multiplexing, connection-bound authentication, and flexible UDP relay behavior.

Protocol Layers

A typical QUIC deployment looks like:

Application TCP / UDP
        │
        ▼
TUIC commands
        │
        ├── Connect       -> TCP relay
        ├── Packet        -> UDP relay
        ├── Dissociate    -> close UDP association
        └── Heartbeat     -> keep connection alive
        │
        ▼
Multiplexed QUIC connection + TLS
        │
        ▼
UDP/IP

The current upstream specification also defines an Authenticate command used to authenticate the multiplexed connection.

Authentication

TUIC v5 authentication is connection-bound. The client identifies itself with a UUID and derives an authentication token from the current TLS session using the TLS Keying Material Exporter and the configured password.

This matters operationally because authentication is tied to the secure session rather than being a reusable clear-text token sent independently of TLS.

The protocol allows authentication and relay-task setup to overlap. An implementation can receive task headers before authentication completes, but it should not process those tasks until the connection has been authenticated.

Common Command Wire Format

TUIC v5 uses one common envelope for all application commands. All fixed-width multi-byte fields are encoded in big-endian order unless the specification says otherwise:

+-----+------+----------+
| VER | TYPE |   OPT    |
+-----+------+----------+
|  1  |  1   | Variable |
+-----+------+----------+

VER is 0x05 for the current protocol version. TYPE selects the command:

TYPECommandPurpose
0x00AuthenticateAuthenticate the multiplexed connection
0x01ConnectStart one TCP relay task
0x02PacketCarry one UDP packet or fragment
0x03DissociateDestroy one UDP association
0x04HeartbeatKeep the QUIC connection active

OPT is not a TLV block with its own generic length. Its layout is determined entirely by TYPE, so a parser must know the command type before it can know how many bytes belong to the command header.

This differs from SOCKS5 in an important way. SOCKS5 has several distinct message layouts (METHOD, authentication sub-negotiation, request, reply, UDP header), while TUIC starts each application command with the same two-byte VER | TYPE discriminator and then switches to a command-specific structure.

Exact Authenticate Frame

The Authenticate command-specific data is fixed length:

+------------------+----------------------------------+
| UUID             | TOKEN                            |
+------------------+----------------------------------+
| 16 bytes         | 32 bytes                         |
+------------------+----------------------------------+

Including the common command bytes, the logical command is therefore:

0x05 | 0x00 | UUID[16] | TOKEN[32]

The client opens a QUIC unidirectional stream and sends this command. The UUID is the client’s 128-bit identity. The 256-bit token is derived from the current TLS session using the TLS exporter interface, with the client UUID as the exporter label and the raw password as exporter context.

Conceptually:

QUIC/TLS session
      |
      +-- TLS exporter(label = UUID, context = password)
                         |
                         v
                    32-byte TOKEN
                         |
Client -- uni stream --> 05 00 UUID TOKEN --> Server

The important property is session binding: knowledge of a previously observed token is not equivalent to knowledge of the raw password because a newly established TLS session produces a new exporter context. TLS 1.3 keeps the exporter interface while deriving exporter values through its HKDF-based key schedule.

There is no TUIC application-level AUTH OK frame. Successful authentication changes server-side connection state. Authentication failure is handled by the implementation, commonly by ignoring work or closing the connection.

Authentication State Machine

Client                                      Server
  |                                            |
  |--- QUIC/TLS handshake ------------------->|
  |                                            |
  |--- uni stream: Authenticate ------------->|
  |                                            | verify UUID + TOKEN
  |                                            |
  |--- Connect/Packet may already arrive ---->|
  |                                            | hold header/task if auth pending
  |                                            |
  |                          auth succeeds ----+
  |                                            | resume paused tasks
  |                                            |

TUIC explicitly permits authentication and relay setup to overlap. A server that sees Connect or Packet before Authenticate should accept enough of the task to pause it, but should not process the relay until authentication has completed.

Address Encoding

TUIC uses a SOCKS-like variable-length address structure, but its type values are different from RFC 1928:

+------+--------------------------+----------+
| TYPE | ADDR                     | PORT     |
+------+--------------------------+----------+
|  1   | Variable                 | 2        |
+------+--------------------------+----------+

The address types are:

TUIC TYPEMeaningAddress bytes
0xffNoneNo address; used by later UDP fragments
0x00Domain/FQDN1-byte length followed by domain bytes
0x01IPv44 bytes
0x02IPv616 bytes

PORT is a 16-bit big-endian integer.

For example, example.com:443 is conceptually:

00 0b 65 78 61 6d 70 6c 65 2e 63 6f 6d 01 bb
^^ ^^ -------------------------------- ^^^^^
|  |              domain bytes          port 443
|  domain length = 11
TYPE = FQDN

SOCKS5 uses almost the same structural idea but different ATYP values:

SOCKS5: ATYP 0x03 -> DOMAIN
TUIC:   TYPE 0x00 -> DOMAIN

SOCKS5: ATYP 0x01 -> IPv4
TUIC:   TYPE 0x01 -> IPv4

SOCKS5: ATYP 0x04 -> IPv6
TUIC:   TYPE 0x02 -> IPv6

The TUIC-only 0xff None value exists because a fragmented UDP packet does not need to repeat the target address in every fragment.

TCP Relay

TCP relaying uses a Connect command on a bidirectional stream:

  1. The client opens a bidirectional stream.
  2. The client sends the target address in a Connect command.
  3. The client can begin sending stream data without waiting for a separate application-level success response.
  4. The server opens the requested TCP connection.
  5. Once available, the server relays data between the destination socket and the QUIC stream.

This design contributes to TUIC’s low-startup-latency behavior.

Exact Connect Command

The command-specific part of Connect contains only the encoded target address:

+----------+
| ADDR     |
+----------+
| Variable |
+----------+

On a QUIC bidirectional stream the byte sequence is therefore logically:

05 01 | ADDR | first TCP payload ...

There is no TUIC equivalent of SOCKS5’s explicit success reply:

SOCKS5
Client -> CONNECT request
Client <- REP=0x00 success
Client -> application bytes

TUIC
Client -> Connect header | application bytes
Client <- no protocol success frame

The TUIC server opens the requested TCP connection after parsing the Connect header. The client is allowed to send application payload immediately after the header without waiting for target-dial completion. A server implementation must therefore be prepared to buffer or naturally backpressure that QUIC stream while the outbound TCP dial is pending.

If the target cannot be reached, TUIC v5 defines no universal error reply. An implementation may reset/close the QUIC bidirectional stream, close the whole QUIC connection, or otherwise apply implementation-defined behavior.

TCP Relay State Machine

Client                              Server
  |                                   |
  | open QUIC bidi stream             |
  |--- 05 01 | ADDR ----------------->| parse target
  |--- first application bytes ------>| outbound connect pending
  |                                   |
  |                                   +--- TCP connect ---> target
  |                                   |
  |<========== QUIC stream ==============================>|
  |             bidirectional byte relay                  |

Each proxied TCP flow gets its own QUIC bidirectional stream. Loss affecting one stream does not force the application data of unrelated TUIC streams into one single ordered byte sequence, although all streams still share the QUIC connection’s congestion-control and path state.

UDP Relay

TUIC uses an association identifier to keep UDP traffic for a logical session on a corresponding server-side UDP socket.

A UDP packet can be carried using:

  • a QUIC unidirectional stream for reliable delivery,
  • or a QUIC datagram for native unreliable delivery.

The first packet for an association determines the reply mode for that association in the reference protocol flow.

TUIC also defines packet identifiers and fragment fields so oversized UDP packets can be split and reassembled.

When the client no longer needs a UDP association, it can send a Dissociate command so the server releases the corresponding UDP socket.

Exact Packet Header

A TUIC UDP packet or fragment uses:

+----------+--------+------------+---------+------+----------+
| ASSOC_ID | PKT_ID | FRAG_TOTAL | FRAG_ID | SIZE | ADDR     |
+----------+--------+------------+---------+------+----------+
| 2        | 2      | 1          | 1       | 2    | Variable |
+----------+--------+------------+---------+------+----------+

Prepending the common command header gives:

05 02 | ASSOC_ID | PKT_ID | FRAG_TOTAL | FRAG_ID | SIZE | ADDR | PAYLOAD

Fields mean:

  • ASSOC_ID: 16-bit UDP association identifier generated by the client.
  • PKT_ID: 16-bit identifier shared by all fragments of one original UDP datagram.
  • FRAG_TOTAL: number of fragments in that original UDP datagram.
  • FRAG_ID: index identifying this fragment.
  • SIZE: byte length of this fragment’s UDP payload.
  • ADDR: destination address for client-to-server traffic, or source address for server-to-client traffic.
  • PAYLOAD: exactly SIZE bytes belonging to this packet fragment.

Later fragments can encode ADDR.TYPE = 0xff (None) rather than repeating the same address. This makes the first fragment important to reassembly metadata.

Association Semantics

Both peers maintain an association table scoped to one QUIC connection:

ASSOC_ID 0x0010 -> server UDP socket A
ASSOC_ID 0x0011 -> server UDP socket B
ASSOC_ID 0x0012 -> server UDP socket C

When the server receives the first Packet for a new ASSOC_ID, it allocates a UDP socket and stores the mapping. Reusing that association ID causes later client packets to leave through the same server-side UDP socket. That property is what gives the protocol its Full Cone-style UDP behavior in the reference flow.

Unlike SOCKS5, there is no separate UDP ASSOCIATE request/reply transaction before the first UDP payload. The first TUIC Packet can implicitly create the association.

Native vs Reliable UDP Modes

TUIC defines two carriage choices for Packet commands:

UDP relay mode "quic"
  Packet command -> QUIC unidirectional stream
  reliable delivery semantics

UDP relay mode "native"
  Packet command -> QUIC DATAGRAM
  unreliable delivery semantics

The server uses the same mode for return traffic that the client used for the first packet of that association.

This is a major difference from Hysteria 2. Hysteria 2’s UDP data path is specified around QUIC DATAGRAM, whereas TUIC explicitly permits either a reliable QUIC stream or an unreliable QUIC datagram for UDP packet carriage. QUIC DATAGRAM frames themselves are not retransmitted by QUIC.

Fragmentation and Reassembly

If one UDP datagram is too large for the chosen transport unit, TUIC can split it into several Packet commands. Every fragment of one original datagram uses the same PKT_ID; FRAG_TOTAL and FRAG_ID identify the reassembly set and position.

A receiver needs reassembly state conceptually keyed by at least:

QUIC connection + ASSOC_ID + PKT_ID

and should enforce bounds for:

  • maximum fragment count,
  • maximum aggregate packet size,
  • duplicate fragment handling,
  • reassembly timeout,
  • number of simultaneously incomplete packets.

Those limits are important because the base specification defines the wire fields but does not define a universal resource-management policy.

Dissociate

The close command for a UDP association is compact:

05 03 | ASSOC_ID[2]

The client sends it on a QUIC unidirectional stream. The server removes that association from its table and releases the corresponding UDP socket.

This is more explicit than Hysteria 2, whose protocol does not provide an explicit UDP-session close message, and structurally different from SOCKS5, where the UDP association lifetime is tied to the accompanying TCP control connection.

0-RTT Considerations

TUIC is designed to support very early relay-task setup and markets 0-RTT TCP and UDP proxying as a core goal.

0-RTT should be understood as a latency optimization, not a reason to ignore replay and session-security considerations. Actual behavior depends on the QUIC and TLS implementation, resumption state, server policy, and the commands being processed.

Heartbeats

When relay tasks are active, the protocol defines a heartbeat command carried through QUIC datagrams to keep the connection alive.

Long-lived mobile or NATed deployments should still account for operating-system power management, NAT timeouts, and network transitions; application heartbeats cannot guarantee that an external network preserves state indefinitely.

The logical heartbeat is simply:

05 04

with no command-specific body. In the reference QUIC flow it is periodically sent through a QUIC DATAGRAM while relay tasks are active.

Error and Close Semantics

TUIC v5 deliberately does not define a response for every command. The specification states that invalid commands, authentication failure, and target connection errors have implementation-defined handling.

That has several consequences for client implementations:

  1. Absence of a reply is normal for Authenticate, Connect, Packet, Dissociate, and Heartbeat; a client must not wait for a SOCKS-style success frame that will never arrive.
  2. A reset/close of one bidirectional stream can be used by an implementation to signal failure of one TCP relay without necessarily closing the whole QUIC connection.
  3. Authentication failure can cause connection close or silent rejection, depending on the implementation.
  4. UDP Packet commands do not have per-packet acknowledgements at the TUIC layer. Reliable-stream mode relies on QUIC stream reliability; native mode deliberately accepts datagram loss.
  5. Dissociate is advisory protocol state transition rather than a request that receives a standardized acknowledgement.

A robust implementation therefore needs to distinguish QUIC transport errors, stream reset, application timeout, UDP loss, and explicit association teardown rather than mapping every failure to one generic “proxy rejected” error.

Packet-Capture View

Without QUIC session keys, a normal packet capture sees approximately:

UDP/IP
  -> QUIC Initial / Handshake
  -> protected QUIC 1-RTT packets
       -> STREAM frames
       -> DATAGRAM frames
       -> ACK / flow-control / connection-management frames

The TUIC command bytes are encrypted inside QUIC application data. With QUIC keys available to a dissector, the mapping becomes easier to reason about:

QUIC uni stream    -> Authenticate / Packet(quic mode) / Dissociate
QUIC bidi stream   -> Connect header + proxied TCP bytes
QUIC DATAGRAM      -> Packet(native mode) / Heartbeat

A QUIC STREAM frame boundary is not a TUIC command boundary. Stream data can be split across QUIC frames or delivered from multiple frames to one application read. Parsers must accumulate exactly the fixed and variable fields required by the command before treating subsequent bytes as payload.

For Connect, parser read-ahead is especially important: bytes obtained in the same read after the variable-length ADDR are already proxied application data and must not be discarded as command padding.

Client and Server Connection State

A useful implementation-oriented connection state machine is:

QUIC_CONNECTING
      |
      v
TLS_READY
      |
      +------> AUTH_SENT / AUTH_PENDING
      |               |
      |               v
      |          AUTHENTICATED
      |               |
      |        +------+------------------+
      |        |      |                  |
      |        v      v                  v
      |      TCP    UDP associations   heartbeat
      |      tasks   + reassembly       timer
      |        |      |                  |
      +--------+------+------------------+
                       |
                       v
                 QUIC_CLOSING

The server additionally needs per-stream and per-association state, because one QUIC connection can contain many simultaneous TCP tasks and UDP associations.

SOCKS5 vs Hysteria 2 vs TUIC

The three protocols expose similar proxy concepts through very different wire models:

Stage / conceptSOCKS5Hysteria 2TUIC v5
Underlying transportTCP control; separate UDP relayQUIC over UDPUsually QUIC over UDP
SecurityNone in base protocolQUIC TLSQUIC/TLS
AuthenticationMETHOD negotiation + selected sub-protocolHTTP/3 /auth requestAuthenticate command on uni stream
Auth success replyExplicit method/auth responseHTTP status 233No TUIC success frame
User identityDepends on auth methodAuth string16-byte UUID + TLS-exporter token
TCP requestCONNECTTCPRequest on new bidi streamConnect on new bidi stream
TCP successREP=0x00TCPResponse Status=0No success response
Address modelATYP + ADDR + PORTtext host:portTYPE + ADDR + PORT
Concurrent TCP flowsUsually independent TCP control sessionsQUIC bidi streamsQUIC bidi streams
UDP setupExplicit UDP ASSOCIATEFirst datagram/session ID creates logical sessionFirst Packet/ASSOC_ID creates association
UDP transportSeparate UDP socketQUIC DATAGRAMQUIC uni stream or DATAGRAM
UDP session IDNone in UDP header; tied to TCP control session32-bit Session ID16-bit ASSOC_ID
UDP packet IDNone16-bit Packet ID16-bit PKT_ID
FragmentationFRAG field, rarely implementedFragment ID + countFRAG_TOTAL + FRAG_ID
Explicit UDP closeTCP control connection lifetimeNo explicit protocol closeDissociate command
Error modelStandard REP valuesTCPResponse error for TCP setupMostly implementation-defined
Congestion/flow controlTCP + native UDP behaviorQUICQUIC

What TUIC Reuses from the SOCKS5 Mental Model

The same basic proxy operations are still present:

identify/authenticate client
        -> name a target
        -> establish TCP relay
        -> optionally relay UDP
        -> tear state down

TUIC also retains the familiar variable-length address type + address + port idea. This makes its Connect target structurally closer to SOCKS5 than Hysteria 2’s textual host:port field.

What TUIC Replaces

TUIC replaces several SOCKS5 control transactions:

  • METHOD negotiation becomes connection-bound TLS-exporter authentication.
  • SOCKS5 CONNECT request -> REP success becomes a one-way Connect header followed immediately by payload.
  • UDP ASSOCIATE request -> relay endpoint reply becomes an implicitly created ASSOC_ID mapping.
  • one TCP control connection no longer represents one proxy task; QUIC streams multiplex many tasks inside one secure connection.

What TUIC Adds

TUIC adds concepts with no direct SOCKS5 equivalent:

  • TLS-exporter-bound authentication token,
  • QUIC stream multiplexing,
  • QUIC connection migration and shared connection-level congestion state,
  • selectable reliable/unreliable UDP carriage,
  • explicit UDP association IDs,
  • packet IDs and protocol-level UDP fragmentation,
  • Dissociate,
  • application heartbeat over QUIC DATAGRAM,
  • possible overlap between authentication and relay-task creation.

These are the main reasons TUIC should be understood as a complete secure, multiplexed proxy transport rather than simply “SOCKS5 over QUIC”.

Conceptual Configuration

A Clash-family TUIC node commonly contains information similar to:

proxies:
  - name: tuic-example
    type: tuic
    server: proxy.example.com
    port: 443
    uuid: 11111111-2222-3333-4444-555555555555
    password: "CHANGE-ME"
    sni: proxy.example.com
    skip-cert-verify: false

Additional fields may select congestion control, UDP relay mode, ALPN, and heartbeat/timeout behavior. Use the schema of the selected core rather than copying options blindly between Mihomo, ClashRS, sing-box, or another implementation.

Strengths

  • TCP and UDP relay in one multiplexed secure connection.
  • Designed for low relay-task startup latency.
  • Native QUIC advantages such as multiplexing and connection migration.
  • UDP can use unreliable QUIC datagrams or reliable stream-based delivery.
  • Connection-bound authentication using TLS exporter material.
  • Explicit UDP association lifecycle and fragmentation support.

Limitations

  • Requires a network path that handles QUIC/UDP reliably for the common deployment model.
  • Different TUIC protocol versions are not guaranteed to interoperate.
  • Configuration names and optional behavior differ between implementations.
  • QUIC fingerprinting, UDP throttling, and MTU issues can still affect real deployments.
  • Very aggressive congestion-control tuning can hurt fairness and stability.

Security Notes

  • Keep certificate verification enabled unless a controlled development setup explicitly requires otherwise.
  • Use unique UUID/password credentials per user or deployment where practical.
  • Treat 0-RTT as an optimization with security trade-offs, not as a universal fast path.
  • Protect server configuration files because the raw password participates in authentication-token derivation.
  • Keep server and client on compatible protocol versions.

Chimera Status

Chimera_Client

TUIC is currently listed in this Wiki under planned client support, not in the current client capability list. Do not present a TUIC profile as supported by chimera_client until the relevant implementation is enabled and validated in the client repository.

Chimera GUI

The GUI can only expose TUIC if the selected proxy core supports it. A profile accepted by Mihomo or another core does not automatically imply support by chimera_client.

Chimera_Server

The server capability map includes TUIC-related inbound parsing/handling work. That should be treated as implementation scope rather than a blanket guarantee of TUIC v5 interoperability, UDP modes, 0-RTT behavior, or every client option.

Test Evidence

The current Server tree contains in-repository TUIC E2E coverage in handler/tuic/e2e_tests.rs::udp_stream_and_datagram_roundtrips_record_stats. It exercises UDP stream relay, QUIC datagram relay, and traffic-stat accounting through the implemented handler.

This is strong evidence for the covered Chimera data path, but it is not external TUIC interoperability evidence with an independent client. Keep that distinction visible until such a test is added. See Test Evidence and Interoperability Matrix.

Troubleshooting

Cannot connect

  1. Verify UDP reachability to the server.
  2. Confirm server/client TUIC protocol versions are compatible.
  3. Validate SNI and certificate trust.
  4. Check UUID and password independently.
  5. Compare ALPN and other QUIC/TLS settings.

TCP works but UDP fails

  1. Verify the selected UDP relay mode is supported on both ends.
  2. Test small datagrams first.
  3. Inspect MTU and packet fragmentation.
  4. Check association timeout behavior.
  5. Confirm NAT/firewall policy allows return UDP traffic.

Intermittent mobile failures

  1. Check whether the client’s network changed between Wi-Fi and cellular.
  2. Compare with a fresh connection rather than only relying on migration.
  3. Inspect NAT and idle timeouts.
  4. Reduce optional tuning to defaults.
  5. Compare against another QUIC-based protocol to isolate path-level blocking.

References

VMess

Positioning

VMess is an encrypted proxy protocol from the V2Ray/Xray ecosystem. It carries client identity, a proxy command, a destination, and encrypted TCP- or UDP-style payloads. In current Xray-core, new VMess sessions use the VMess AEAD request header design; older pre-AEAD authentication formats should be treated as legacy protocol history rather than the wire format to implement for a current Xray-compatible peer.

VMess is a proxy-protocol layer. Xray can place its ordered byte stream inside other transport methods such as RAW/TCP, WebSocket, or HTTP-oriented transports, and can additionally wrap those transports in TLS where supported. Those outer layers do not replace the VMess authentication, command, destination, or body record format described here.

A useful layer model is:

application TCP / UDP
        |
        v
VMess AEAD
  - AuthID / user authentication
  - command + destination
  - encrypted body chunks
        |
        v
optional Mux.Cool / XUDP behavior
        |
        v
selected Xray transport
        |
        v
optional outer TLS / other transport security

Current Versus Legacy VMess

The official Project X protocol page still documents historical VMess fields, including the original timestamp-derived authentication hash and older body security choices. Current Xray-core has moved further:

  • the inbound decoder first tries the 16-byte AEAD AuthID path;
  • current VMess account security types are AES-128-GCM and ChaCha20-Poly1305, with auto resolving to one of those on the client;
  • the old alterId model is not part of current VMess AEAD sharing;
  • current Xray configuration no longer offers VMess none/zero/plain body security.

The logical command header remains recognizably derived from VMess version 1, so the legacy specification is still useful for field meanings. The important implementation rule is to distinguish that logical plaintext command layout from the current AEAD envelope that protects it on the wire.

End-to-End Connection Flow

A current VMess connection can be read as this state sequence:

Client                                                   Server
  | establish selected outer transport                      |
  |--------------------------------------------------------->|
  |                                                         |
  | AuthID (16)                                             |
  | AEAD(request-header length) (18)                        |
  | connection nonce (8)                                    |
  | AEAD(request header) (L + 16)                           |
  |--------------------------------------------------------->|
  |                                    match user + timestamp|
  |                                    reject replay         |
  |                                    decrypt/validate hdr  |
  |                                    dispatch destination  |
  |                                                         |
  | encrypted/masked VMess body chunks ====================>|
  |<========================================================>|
  |                                                         |
  |<-------------- AEAD(response-header length) (18)        |
  |<-------------- AEAD(response header) (R + 16)           |
  |<================ encrypted response body chunks ========|
  |                                                         |
  | termination record / EOF / outer transport close        |

There is no SOCKS5-style method-selection round trip. The first VMess protocol bytes already contain an authenticated user/time token and the encrypted proxy request. There is also no SOCKS5-style REP byte: destination or dispatch failure is normally observed as a failed/closed VMess exchange rather than a portable numeric VMess result code.

User Identity and Command Key

The configured VMess user ID resolves to a 16-byte UUID value. Current Xray also allows short custom strings in configuration by deterministically mapping them to UUID form; the wire authentication still operates on the resulting account identity and its derived command key.

The UUID itself is not sent as 16 plaintext bytes at the front of a current VMess AEAD request. Xray derives a 16-byte command key from the account ID. That key is used to construct and validate the AEAD AuthID and to derive the request-header AEAD keys.

This differs from VLESS, whose baseline header places its 16-byte user identity inside the VLESS request. It also differs from SOCKS5 RFC 1929, where username and password are sent in an explicit authentication sub-negotiation.

AEAD AuthID: Exact 16-Byte Plaintext Before Encryption

Current Xray creates a 16-byte AuthID plaintext:

+----------------------+----------------------------------+
| uint64 timestamp     | Unix seconds, big-endian         |
| 4 random bytes       | per-request random value         |
| uint32 CRC32         | CRC32 of the first 12 bytes      |
+----------------------+----------------------------------+
        8 + 4 + 4 = 16 bytes

Those 16 bytes are encrypted as one AES block using a key derived from the user’s command key. The resulting 16-byte ciphertext is the first VMess AEAD field visible on the protocol stream.

Server validation performs several distinct checks:

  1. try the configured users’ AuthID decoders;
  2. decrypt the candidate AuthID;
  3. verify the CRC32 over the first 12 plaintext bytes;
  4. reject negative/invalid timestamps;
  5. require the timestamp to be within 120 seconds of the server’s current Unix time;
  6. reject an AuthID already present in the anti-replay filter.

This is why VMess documentation warns that client and server UTC clocks must be synchronized. Time zone is irrelevant; Unix time freshness is what matters.

The AuthID anti-replay filter and the later request-body session-history check protect different values. Passing AuthID validation is necessary but is not the last replay-related check performed by the current server.

VMess AEAD Request Header Envelope

After creating AuthID, current Xray generates an independent random 8-byte connectionNonce and AEAD-protects both the logical request-header length and the logical request header.

On the wire:

+----------------------+--------------------------------------------+
| 16 bytes             | AuthID ciphertext                          |
| 18 bytes             | AEAD( uint16 request_header_length )       |
| 8 bytes              | connectionNonce                            |
| L + 16 bytes         | AEAD( L-byte logical request header )      |
+----------------------+--------------------------------------------+

The length plaintext is a big-endian uint16; AES-GCM adds its 16-byte tag, so that field occupies 18 bytes. The request-header ciphertext similarly adds 16 bytes to the logical header length.

Both AEAD operations use keys/nonces derived from:

  • the VMess user’s command key,
  • the 16-byte AuthID,
  • the 8-byte connection nonce,
  • and fixed VMess KDF labels.

The AuthID is also supplied as AEAD associated data. Consequently, changing the AuthID, encrypted length, connection nonce, or protected header without the correct user key causes authentication failure before the destination is parsed.

Incremental parsing boundary

The request is carried over an ordered stream. A parser must therefore read:

  1. exactly 16 bytes of AuthID;
  2. exactly 18 bytes of encrypted length;
  3. exactly 8 bytes of connection nonce;
  4. decrypt the length;
  5. then read exactly L + 16 bytes of encrypted request header.

A single TCP/QUIC/WebSocket read is not a VMess message boundary. Conversely, one transport read can contain the whole header plus the start of the encrypted body; read-ahead bytes must be preserved for the body decoder.

Logical Request Header Layout

After the AEAD envelope is opened, the current Xray logical header begins:

+----------------------+--------------------------------------------+
| uint8  version       | 0x01                                       |
| 16 bytes body_iv     | random request-body IV                     |
| 16 bytes body_key    | random request-body key                    |
| uint8 response_v     | random response authentication byte        |
| uint8 options        | body framing/options bitmask                |
| uint8 P|security     | high nibble padding length; low security    |
| uint8 reserved       | currently 0                                 |
| uint8 command        | TCP=0x01, UDP=0x02, Mux=0x03               |
| destination          | absent for Mux; otherwise port+address      |
| P bytes              | random command-header padding               |
| uint32 FNV1a         | checksum of preceding logical header        |
+----------------------+--------------------------------------------+

The first 38 bytes end with the command byte. Destination length is variable, then P can add 0–15 random bytes, followed by the four-byte FNV-1a checksum. The server validates that checksum after successfully opening the outer AEAD header. AEAD integrity and the inner FNV checksum are therefore separate validation layers.

Current Xray rejects an unresolved/unknown body security value after parsing the logical header. auto is a client configuration choice; the client resolves it to an actual on-wire security type before sending the request.

Option bits

The current common protocol definitions use these relevant bits:

BitNameMeaning
0x01chunk streampayload uses VMess chunk records; historical name is now marked deprecated in code, but current VMess outbound still sets the bit
0x04chunk maskingtwo-byte chunk lengths are XOR-masked with a SHAKE128-derived stream
0x08global paddingeach chunk may have pseudo-random padding in addition to encrypted payload
0x10authenticated lengthexperimental AEAD protection for chunk-length fields

For current AES-GCM/ChaCha20-Poly1305 VMess, Xray enables chunk masking and global padding by default. AuthenticatedLength remains an experiment that must be compatible on both peers.

Destination Encoding

VMess encodes the destination in a different order from SOCKS5. Current Xray’s VMess address parser is configured with port first:

+----------------------+----------------------------------+
| uint16 DST.PORT      | big-endian                       |
| uint8  ATYP          | 0x01 IPv4, 0x02 domain, 0x03 IPv6|
| address bytes        | depends on ATYP                  |
+----------------------+----------------------------------+

Address payloads are:

ATYPAddress layout
0x014 IPv4 bytes
0x02uint8 length + that many domain bytes
0x0316 IPv6 bytes

For comparison, SOCKS5 uses ATYP | DST.ADDR | DST.PORT; VMess uses DST.PORT | ATYP | DST.ADDR. A parser shared between the protocols must not reuse the SOCKS5 field order accidentally.

The base VMess TCP/UDP commands are:

0x01  TCP
0x02  UDP
0x03  Mux.Cool logical stream

Current common Xray definitions also have other internal request-command values, but VMess interoperability documentation should not invent wire semantics for a command unless both peers implement it.

Request Body Record Format

After the protected command header, VMess switches to independently authenticated body chunks. In the ordinary current AEAD body modes the logical record is:

+----------------------+--------------------------------------------+
| size field           | 2 bytes masked, or 18 bytes when the       |
|                      | AuthenticatedLength experiment is used     |
| ciphertext           | plaintext chunk + 16-byte AEAD tag         |
| optional padding     | 0..63 clear random bytes with global pad   |
+----------------------+--------------------------------------------+

The size value describes the encrypted payload plus any global padding. With normal chunk masking, the two-byte big-endian value is XORed with successive 16-bit values from SHAKE128 seeded by the request-body IV. The same SHAKE stream also produces the global-padding length modulo 64.

Global padding is outside the AEAD ciphertext. It changes chunk size/shape but does not become application bytes after decoding.

With the AuthenticatedLength experiment, the logical two-byte size is itself AEAD-protected and therefore occupies 18 bytes. This adds integrity to the record length rather than relying only on masking.

AES-128-GCM body mode

The request’s random 16-byte body key is used as the AES-128-GCM key. Each record uses a direction-local increasing counter in its nonce construction and adds a 16-byte authentication tag.

ChaCha20-Poly1305 body mode

Xray expands the 16-byte request body key into the 32-byte ChaCha20-Poly1305 key using the VMess-defined MD5-based expansion. Record nonces follow the same counter-plus-IV model and each record carries a 16-byte Poly1305 tag.

Current Xray outbound configuration exposes aes-128-gcm, chacha20-poly1305, and auto. As of the current implementation, none is not a valid current VMess body security mode.

TCP Data Path

For command=0x01, the destination in the request header is a TCP destination. After user/header validation the server dispatches that target, decodes VMess body records, and writes the recovered bytes to the destination TCP stream. Bytes received from the target take the reverse path through the VMess response header and response-body record encoder.

VMess body chunks are framing units, not application message boundaries. A TCP application record can span multiple VMess chunks, and one VMess chunk can contain bytes from multiple application writes. Implementations must preserve byte order, not write-call boundaries.

Flow control comes primarily from the selected outer reliable transport and the server’s destination socket. VMess chunk framing does not define a SOCKS-like window-update command or independent stream credit.

UDP Data Path

For base command=0x02, the request header names a UDP destination and body handling switches to packet transfer semantics. Current Xray’s authentication writer preserves each packet buffer as one authenticated VMess body record rather than concatenating packets into a TCP-style byte stream.

Base VMess UDP therefore differs from SOCKS5 UDP in two major ways:

  • the destination is established in the encrypted VMess request header rather than repeated in every UDP relay datagram;
  • the VMess client/server transport remains the selected reliable VMess stream, rather than switching to the separate native UDP relay socket defined by SOCKS5 UDP ASSOCIATE.

Base VMess has no SOCKS5 FRAG byte and no Hysteria/TUIC-style packet ID plus fragment count. If a deployment needs broader UDP association semantics, current Xray can add XUDP over its Mux path. That is an extra layer and should not be mistaken for the base command=0x02 wire format.

Current Xray outbound can, under its cone/XUDP policy, rewrite some UDP flows to command=0x03 with the Mux destination v1.mux.cool and then use an XUDP packet writer. A capture/dissector must therefore determine whether it is seeing base VMess UDP or VMess carrying Mux/XUDP before interpreting packet boundaries.

Response Header

Current Xray derives response body key and IV values by SHA-256 hashing the request body key and IV and taking the first 16 bytes. The response control header is then AEAD-protected separately from the body.

Wire layout:

+----------------------+--------------------------------------------+
| 18 bytes             | AEAD( uint16 response_header_length )      |
| R + 16 bytes         | AEAD( R-byte response header )             |
+----------------------+--------------------------------------------+

The decrypted response header is logically:

+----------------------+----------------------------------+
| uint8 response_v     | must equal request response_v    |
| uint8 options        | response options                 |
| uint8 command        | response command, normally 0     |
| uint8 command_len    | command-content length           |
| command_len bytes    | optional command content         |
+----------------------+----------------------------------+

The client checks response_v; a mismatch means the response is not valid for that VMess session. There is no general success/failure status byte comparable to SOCKS5 REP. A valid response header authenticates the responding VMess peer at the protocol level, while target failures are handled by stream/error behavior rather than a portable VMess result-code table.

After this header, response body chunks use the same selected body-security algorithm, but with response-direction keys, IV, length-mask stream, nonces, and padding state.

Termination, Half-Close, and Error Scope

Historically, chunked VMess sends a termination record when a direction has no more payload. With AEAD body security, an empty plaintext packet is represented by a record whose encrypted portion consists only of the AEAD authentication overhead (plus any generated padding). The decoder recognizes that shape as end-of-stream.

Current Xray also has a NoTerminationSignal experiment/behavior; the outbound checks that setting before emitting the explicit empty body record. Therefore a robust peer must also handle clean outer EOF according to the negotiated/current implementation behavior.

Keep these error scopes separate:

  • outer transport error: TCP/WebSocket/TLS/etc. fails before VMess parsing;
  • AuthID error: unknown user, timestamp outside the ±120-second window, CRC mismatch, or AuthID replay;
  • request-header AEAD error: encrypted length or payload tag fails;
  • session replay error: the tuple of VMess user + request body key + request body IV is reused within the server’s session-history window;
  • logical-header error: checksum, address, command, or security is invalid;
  • body-record error: masked/authenticated size is malformed or an AEAD tag fails;
  • destination/dispatch error: VMess parsed correctly but the requested target cannot be opened or routed;
  • response error: response AEAD or response_v validation fails.

Current Xray keeps body-session replay history for several minutes and separately keeps AuthID anti-replay state around the authentication timestamp window. Do not merge those caches into one conceptual “VMess replay token” when implementing diagnostics.

A VMess protocol error normally terminates the affected outer connection. If Mux.Cool is layered above VMess, inner logical stream failures can have a narrower scope than failure of the parent VMess/transport connection.

State Machines

Client

DISCONNECTED
    |
    v
OUTER_TRANSPORT_READY
    |
    v
BUILD AuthID + AEAD REQUEST HEADER
    |
    v
SEND HEADER
    |
    +------------------------------+
    |                              |
    v                              v
SEND BODY RECORDS              READ RESPONSE HEADER
    |                              |
    |                              +-- AEAD / response_v fail -> ERROR
    |                              |
    |                              v
    |                          READ BODY RECORDS
    |                              |
    +--------------+---------------+
                   v
              DRAIN / EOF
                   |
                   v
                 CLOSED

The two data directions can run concurrently once the request has been sent. The client does not wait for a SOCKS-style explicit success byte before it can start sending proxied body data.

Server

ACCEPT OUTER STREAM
    |
    v
READ 16-BYTE AuthID
    |
    +-- no user / stale / replay --------> DRAIN/REJECT/CLOSE
    |
    v
OPEN AEAD LENGTH + REQUEST HEADER
    |
    +-- tag/length/checksum error -------> DRAIN/REJECT/CLOSE
    |
    v
CHECK BODY KEY+IV SESSION REPLAY
    |
    +-- duplicate -----------------------> REJECT/CLOSE
    |
    v
PARSE COMMAND + DESTINATION + SECURITY
    |
    +-- invalid -------------------------> REJECT/CLOSE
    |
    v
DISPATCH DESTINATION
    |
    +-- failure -------------------------> CLOSE/ERROR
    |
    v
RELAY BODY <====> ENCODE RESPONSE HEADER/BODY
    |
    v
EOF / TIMEOUT / ERROR

Current Xray intentionally drains a behavior-derived amount of data on some invalid-request paths before closing. That is an implementation-level traffic analysis defense; clients must not interpret delayed close as protocol success.

Multiplexing and Flow Control

Base VMess does not multiplex arbitrary independent TCP proxy requests inside one VMess request. Normally each independent VMess TCP command is associated with its own outer proxy stream/connection.

Xray’s command=0x03 hands the body to Mux.Cool, which is a separate multiplexing protocol. XUDP can also ride that path. When diagnosing a trace, keep the layers distinct:

VMess AEAD authentication / encryption
        |
        `-- command 0x03
              |
              v
          Mux.Cool
              |
              +-- logical stream A
              +-- logical stream B
              `-- XUDP packets ...

VMess itself has record sizes, masking, padding, and AEAD counters but no independent per-logical-stream flow-control window. Mux flow control, HTTP/2 or QUIC stream flow control in an outer transport, and TCP congestion control are separate mechanisms.

Packet-Capture View

VMess directly on a clear outer byte stream

A current VMess AEAD request does not begin with a plaintext UUID, command, or destination. A dissector sees approximately:

16 bytes  AuthID ciphertext
18 bytes  AES-GCM-protected header length
 8 bytes  connection nonce
L+16       AES-GCM-protected logical request header
...        masked/padded AEAD body records

The first 16 bytes are deliberately not a stable user identifier. Because the AuthID contains the current timestamp plus random data before block encryption, two connections from the same user do not begin with the same 16-byte prefix.

The destination, TCP/UDP command, body IV/key, and selected body cipher are all inside the encrypted request-header payload.

VMess inside TLS/WebSocket/HTTP transports

With an outer encrypted transport, the passive capture first exposes that layer:

TCP/UDP
  -> TLS / QUIC / HTTP transport framing
       -> VMess AEAD AuthID + header
            -> VMess encrypted records
                 -> application bytes

Without outer decryption keys or endpoint instrumentation, VMess fields cannot be located simply by packet offsets. With decryption, remember that WebSocket, HTTP, or QUIC frame boundaries still do not define VMess record boundaries.

Useful endpoint-side anchors

For an instrumented implementation, useful checkpoints are:

  • first 16 bytes accepted as AuthID and mapped to a user;
  • decrypted big-endian logical header length from the next 18 bytes;
  • logical header version 0x01;
  • command and PORT | ATYP | ADDR after opening the header;
  • option/security byte and body IV/key;
  • two-byte masked lengths or 18-byte authenticated lengths in the body;
  • 16-byte AEAD tags per encrypted body record;
  • 18-byte AEAD response-header length followed by the protected response header.

SOCKS5 Comparison by Stage

Stage / conceptSOCKS5 RFC 1928/1929Current VMess AEAD
Outer connectionTCP control connectionSelected ordered Xray transport; commonly backed by TCP, possibly with additional framing/security
Method negotiationVER/NMETHODS/METHODSnone; client/server configuration already selects VMess and body security
Authenticationoptional method, e.g. RFC 1929 username/password16-byte encrypted AuthID derived from user command key, timestamp and randomness
Replay protectionnot defined by RFC 1928/1929timestamp window + AuthID replay filter + request body key/IV session history
Authentication round tripexplicit method/auth responseno separate auth reply; request header follows AuthID immediately
Proxy commandCMD after negotiationencrypted logical command byte (0x01 TCP, 0x02 UDP, 0x03 Mux)
Destination order`ATYPADDR
Domain encodingone-byte length + domainone-byte length + domain
Success replyREP=0x00 plus bound addressno SOCKS-equivalent status; authenticated response header carries response_v, options, optional command
Failure replystandardized REP valuesmostly close/error behavior; no portable destination-error code table
TCP payloadraw bytes after successful replymasked/padded AEAD body records
Payload confidentialitynone in base SOCKS5AES-128-GCM or ChaCha20-Poly1305 body encryption in current Xray
UDP setupUDP ASSOCIATE on TCP control connectionVMess command=0x02 names a fixed UDP destination in the encrypted request
UDP carrierseparate native UDP relay with SOCKS UDP headerencrypted VMess body records on the selected VMess stream; XUDP/Mux may add another model
UDP per-packet destinationpresent in every SOCKS UDP datagramnot present in base VMess UDP body; destination comes from request header
UDP fragmentation fieldSOCKS FRAGno base VMess fragment ID/count field
Multiplexingnot defined in base SOCKS5extra command=0x03 Mux.Cool layer can multiplex logical streams
Flow controlinherited from TCP / UDP behaviorinherited from outer transport plus destination; Mux/HTTP/QUIC layers may add their own flow control
End of streamTCP FIN/close anchors associationVMess termination record and/or outer EOF depending on current behavior

The most important conceptual difference is that SOCKS5 separates negotiation, authentication, command, reply, and then raw relay into visible phases. VMess compresses user authentication and proxy dispatch into a protected first-flight request and continues with authenticated record framing. Mux.Cool, XUDP, WebSocket, TLS, and other transports are additional layers rather than substitutes for that VMess request.

Boundary Conditions and Defensive Parsing

A compatible implementation should explicitly guard these cases:

  • partial reads at every fixed or variable-length AEAD field;
  • request-header length that exceeds a practical implementation bound;
  • stale or future AuthID timestamps outside the accepted 120-second window;
  • repeated AuthIDs;
  • repeated body key/IV session tuples;
  • unsupported logical header version;
  • invalid security nibble;
  • truncated IPv4/IPv6/domain addresses;
  • zero-length or overlong domain fields according to the current address parser;
  • odd behavior where a Mux command incorrectly includes ordinary destination bytes;
  • padding length larger than remaining logical header bytes;
  • FNV checksum mismatch;
  • chunk-size decode underflow/overflow after masking/padding;
  • failed AEAD tags;
  • counter/nonce exhaustion;
  • clean termination record versus abrupt outer EOF;
  • slow readers that create unbounded buffering in outer transport or Mux layers.

Do not allocate directly from an untrusted encrypted-length value until the length AEAD tag has been verified and a local upper bound has been applied. Likewise, do not dispatch the destination until the complete logical header, padding, and checksum have been validated.

Security Notes

  • Synchronize client and server UTC clocks. Current VMess AuthID validation uses a 120-second freshness window.
  • Use high-entropy VMess user IDs and rotate credentials when clients are retired.
  • Do not publish UUIDs merely because the on-wire AuthID is encrypted; the UUID is still shared authentication material.
  • Prefer current VMess AEAD. Do not build new deployments around alterId or legacy non-AEAD sharing formats.
  • Current Xray no longer offers VMess none/zero/plain body security; do not write compatibility documentation that suggests those are current choices.
  • VMess protocol encryption does not automatically make traffic look like ordinary HTTPS. If censorship resistance or normal TLS server identity is a deployment requirement, evaluate the appropriate outer transport/security layer separately.
  • Bound invalid-request drain behavior, replay caches, body buffering, and Mux state to avoid turning defensive behavior into a resource-exhaustion surface.
  • Logs may identify whether AuthID, header AEAD, checksum, body AEAD, or dispatch failed, but remote error behavior should not reveal unnecessary user/account information.

Minimal Current Xray-Style Configuration

A current outbound conceptually looks like:

{
  "protocol": "vmess",
  "settings": {
    "address": "proxy.example.com",
    "port": 443,
    "id": "5783a3e7-e373-51cd-8642-c83782b807c5",
    "security": "auto"
  }
}

security: "auto" is a client-side selection convenience. It resolves to an actual supported body cipher; the server learns the selected cipher from the protected logical VMess header. Current Project X documentation lists AES-128-GCM and ChaCha20-Poly1305 as the explicit choices.

Transport settings belong outside this VMess account object and should be tested independently from VMess AEAD correctness.

Chimera Status

Chimera_Client

The current Proxy Wiki capability page lists VMess under Planned or Targeted Support, not under the client’s currently available protocol set. Treat VMess client configuration as a target capability until the corresponding client implementation is present and verified.

Chimera GUI

Chimera can eventually expose/store VMess profile fields without implementing the VMess cryptography itself. UI/profile support and runtime protocol support should be tracked independently.

Chimera_Server

The current server capability map explicitly lists VMess inbound work. Validate that implementation against the current AEAD-only Xray behavior described here, including AuthID time/replay checks, current body-security choices, TCP, UDP, and any Mux/XUDP behavior it claims to support.

Test Evidence

The current Wiki evidence index does not catalog an independent-client VMess happy-path interoperability test for Chimera Server. The implementation-status claim is therefore grounded primarily in the audited AEAD VMess inbound source path rather than an external interop label.

Do not upgrade this page to “externally interoperable” based only on parser, handler, or unrelated Xray-client tests. Add the exact peer and test function to Test Evidence and Interoperability Matrix when external VMess coverage is introduced.

Troubleshooting

Immediate rejection

  1. Verify the user ID on both peers.
  2. Check actual UTC time and keep skew well below 120 seconds.
  3. Confirm both peers implement current VMess AEAD rather than an incompatible legacy/alterId mode.
  4. Check whether the outer transport is delivering a clean ordered byte stream.
  5. Distinguish AuthID rejection from request-header AEAD/checksum rejection in endpoint logs.

Header succeeds but data fails

  1. Confirm the body security selected by the client is AES-128-GCM or ChaCha20-Poly1305 and is decoded as that exact security nibble.
  2. Verify request body key/IV extraction and response key/IV derivation.
  3. Check chunk masking and global-padding state in both directions.
  4. If AuthenticatedLength is enabled, ensure both peers implement the same experiment behavior.
  5. Check AEAD nonce counters and packet/stream transfer mode.

TCP works but UDP fails

  1. Determine whether the flow is base VMess UDP or Mux/XUDP.
  2. For base VMess UDP, confirm command=0x02 and the fixed destination in the request header.
  3. Preserve packet boundaries through the VMess body reader/writer.
  4. Do not expect SOCKS5-style per-datagram destination headers or FRAG.
  5. Check outer transport buffering and any MTU/datagram constraints in the layers surrounding VMess.

References

VLESS

Positioning

VLESS is a lightweight, stateless proxy protocol from the Xray ecosystem. Its baseline request carries destination metadata and user identity. Historically VLESS relied almost entirely on a separate TLS or REALITY layer for confidentiality; current Xray also implements optional VLESS Encryption, a protocol-layer encrypted wrapper that can protect the VLESS request and body.

A useful way to read an Xray-style configuration is to separate three layers:

VLESS request/body           -> proxy protocol / user identity / destination
optional VLESS Encryption    -> protocol-layer encryption + key exchange
XHTTP, RAW, gRPC ...         -> transport method
optional TLS or REALITY      -> outer transport security / HTTPS appearance

Those layers can be combined only when the selected core supports the combination.

Identity and Authentication

VLESS users are identified by an id. A UUID is the common representation, and current Xray versions can also map supported custom strings to a stable UUID identity.

Unlike VMess, VLESS does not rely on synchronized system time for its basic user identity model.

The user identity is not itself encryption. Traditional deployments therefore pair VLESS with TLS or REALITY. Current Xray can instead, or additionally, use VLESS Encryption; that protects the VLESS payload but does not by itself create the ordinary HTTPS appearance supplied by TLS or REALITY.

Connection Flow

At a high level:

  1. The client establishes the configured outer transport and, if configured, TLS/REALITY.
  2. If VLESS Encryption is enabled, client and server complete its key-exchange wrapper (or resume an accepted 0-RTT session).
  3. The client sends the VLESS request containing user identity, command, and destination information through the resulting plain or encrypted body path.
  4. The server validates the VLESS user and requested mode.
  5. The server opens or dispatches the destination connection.
  6. Application traffic is relayed through the same layered path.

The byte-level framing below follows the current Xray-core main VLESS encoder/decoder. Because VLESS is an implementation-defined Xray protocol rather than an IETF standard, verify these details again when targeting a materially different core version.

VLESS Encryption: Outer Handshake and Record Layer

VLESS Encryption is negotiated by configuration rather than by adding a new method-selection field to the baseline VLESS header. The client encryption and server decryption strings must describe compatible handshake and traffic-appearance modes. Current official configuration uses mlkem768x25519plus as the handshake method and exposes three appearances: native, xorpub, and random.

A typical generated pair conceptually has this shape:

server decryption:
  mlkem768x25519plus.<appearance>.<ticket-lifetime>.<padding>.<client-auth-key>

client encryption:
  mlkem768x25519plus.<appearance>.0rtt|1rtt.<padding>.<server-auth-key>

The authentication key block can use X25519 material or ML-KEM-768 material. The ephemeral handshake itself combines ML-KEM-768 with X25519, so the configured static authentication choice and the per-connection PFS exchange are different concepts.

1-RTT client-to-server handshake layout

The current proxy/vless/encryption implementation starts with a random 16-byte IV followed by one or more NFS relays derived from the configured static authentication keys. For a relay using X25519, the public-key contribution is 32 bytes; for ML-KEM-768, the encapsulated ciphertext contribution is 1088 bytes. When more than one configured relay participates, 32-byte BLAKE3-derived linkage values bind the relay chain so an intermediate relay cannot simply be replaced.

After the IV and NFS relay area, the normal 1-RTT client handshake sends:

+----------------------+--------------------------------------------+
| 16 bytes             | random IV                                  |
| variable             | NFS relay/authentication material          |
| 18 bytes             | AEAD( uint16 length = 1232 )               |
| 1232 bytes           | AEAD( ML-KEM-768 pub 1184                  |
|                      |       + X25519 pub 32 )                     |
| 18 bytes             | AEAD( uint16 encrypted-padding length )    |
| variable             | AEAD( client padding )                     |
+----------------------+--------------------------------------------+

Why 18 bytes for a two-byte length? The length itself is a big-endian uint16, and the AEAD adds a 16-byte authentication tag. Likewise, the 1216-byte hybrid client PFS public material becomes 1232 bytes after the tag. The client can split the configured padding into multiple writes with delays; those write boundaries are camouflage behavior and are not protocol-message boundaries for a parser.

The server first derives the NFS key from the relay area and uses it to open the encrypted length. For the 1-RTT path it then decrypts the 1184-byte ML-KEM-768 encapsulation key plus the 32-byte X25519 public key, creates its own ML-KEM and X25519 contributions, and derives a 64-byte PFS secret (32 ML-KEM + 32 X25519). That PFS secret is combined with the per-connection NFS key to form the keying material used by the later record layer.

The 1-RTT server response begins with:

+----------------------+--------------------------------------------+
| 1136 bytes           | AEAD( ML-KEM-768 ciphertext 1088           |
|                      |       + X25519 pub 32 )                     |
| 32 bytes             | AEAD( 16-byte session ticket )             |
| 18 bytes             | AEAD( uint16 server-padding length )       |
| variable             | AEAD( server padding )                     |
+----------------------+--------------------------------------------+

The first field is 1120 bytes of server PFS public/ciphertext material plus a 16-byte tag. The ticket plaintext is 16 bytes and becomes 32 bytes with its tag. The first two ticket bytes encode the accepted ticket lifetime. A zero lifetime means there is no resumable 0-RTT session.

0-RTT resumption and replay boundary

When the client is configured for 0rtt, has an unexpired cached ticket, and the server allows resumption, it can avoid the full PFS exchange. It still creates a fresh IV and NFS key, then sends:

IV + NFS relays
AEAD(uint16 32)          # says the next item is a ticket
AEAD(16-byte ticket)     # 32 bytes on wire including tag
first encrypted VLESS record(s) immediately

The resumed traffic key combines the cached PFS secret with the new NFS key, so each resumed connection still has fresh connection-specific material. The server stores NFS-key use per ticket and rejects a repeated key as a replay. If the ticket has expired, current server code sends random-looking bytes so the client abandons the cached session and retries with a new handshake rather than silently accepting old 0-RTT state.

0-RTT therefore reduces startup latency; it is not a promise that arbitrary application actions become replay-safe. A caller should keep the same security caution it would apply to any early-data mechanism.

Encrypted application-record layout

After either handshake path, the VLESS header and subsequent body are carried through CommonConn. Current Xray splits writes into plaintext chunks of at most 8192 bytes and wraps each chunk as:

+--------+--------+--------+----------------+---------------------------+
| 0x17   | 0x03   | 0x03   | Length (BE16)  | AEAD ciphertext           |
+--------+--------+--------+----------------+---------------------------+
| 1 byte | 1 byte | 1 byte | 2 bytes        | plaintext + 16-byte tag   |
+--------+--------+--------+----------------+---------------------------+

The five-byte prefix intentionally has the shape of a TLS 1.3 application-data record (17 03 03), but VLESS Encryption is not TLS. The header is used as AEAD associated data. Receivers require a ciphertext length from 17 through 16640 bytes; malformed headers, truncated records, or failed AEAD tags terminate that encrypted stream.

Record keys are derived with BLAKE3 from the handshake key material and a connection-specific context. Current code chooses AES-GCM when the endpoint has appropriate AES-GCM hardware support and otherwise uses ChaCha20-Poly1305; the server can detect the peer choice while opening the first encrypted handshake length. Nonces increment independently by direction. The implementation also has a rekey path if the 96-bit nonce counter reaches its maximum rather than allowing nonce reuse.

native, xorpub, and random capture appearance

These options change observable encoding, not the inner VLESS command format:

  • native leaves the key-exchange public/ciphertext material in its native representation and retains the TLS-record-like five-byte data headers;
  • xorpub masks the public/ciphertext portions of the NFS relay using a BLAKE3-derived AES-CTR stream, reducing their native public-key appearance;
  • random additionally masks the five-byte record headers in each direction, so the post-handshake stream no longer exposes the repeated 17 03 03 record-header pattern.

If VLESS Encryption itself is carried inside real TLS or REALITY, an ordinary on-path capture sees the outer TLS/REALITY layer first. The inner appearance mode only becomes directly observable after removing that outer layer.

Encryption state machine and failure scope

OUTER_TRANSPORT_READY
        |
        v
READ IV + NFS RELAYS
        |
        +-- static auth / relay failure --------> abort/fallback policy
        |
        v
OPEN ENCRYPTED LENGTH
        |
        +-- length == 32 ------------------------> 0-RTT ticket path
        |       | expired / replay / disabled --> reject; client re-handshakes
        |       ` accepted ---------------------> ENCRYPTED_RECORDS
        |
        `-- 1-RTT PFS length
                |
                v
           ML-KEM-768 + X25519 exchange
                |
                v
           TICKET + BIDIRECTIONAL PADDING
                |
                v
           ENCRYPTED_RECORDS
                |
                v
           BASELINE VLESS HEADER -> BODY

This introduces an error layer that baseline SOCKS5 does not have. A failed ML-KEM/X25519 exchange or AEAD tag means the server has not yet reached the VLESS UUID/command parser; changing a destination address or SOCKS-style command cannot repair such a failure.

Baseline Wire Format

Request header

For a normal TCP or UDP request, current Xray-core serializes the VLESS request header in this order:

+---------+----------------+----------------+---------+----------+------------------+
| Version | User ID        | Addons         | Command | Port     | Address          |
+---------+----------------+----------------+---------+----------+------------------+
| 1 byte  | 16 bytes       | 1 + N bytes    | 1 byte  | 2 bytes  | variable         |
+---------+----------------+----------------+---------+----------+------------------+

The important point is that VLESS writes the destination port before the address, unlike SOCKS5 and Trojan, which put the address before the port.

Current Xray-core uses request version 0x00. The next 16 bytes are the binary user ID. A UUID string such as:

11111111-2222-3333-4444-555555555555

is therefore not sent as 36 ASCII characters; the corresponding 128-bit value is sent as 16 raw bytes.

Addons field

Immediately after the user ID comes one byte containing the length of the serialized VLESS addons block:

+--------------+---------------------+
| AddonsLength | Addons protobuf     |
+--------------+---------------------+
| 1 byte       | N bytes             |
+--------------+---------------------+

For the ordinary no-flow case, AddonsLength is 0x00 and no addon bytes follow. For supported flow modes such as xtls-rprx-vision, current Xray-core serializes the addons structure as protobuf and prefixes it with a single-byte length.

This is not analogous to SOCKS5 METHOD negotiation. The addons field is part of the already-selected VLESS request format and carries optional VLESS/Xray behavior for that request.

Command byte

Current Xray-core defines these request command values:

ValueCommandTransfer model
0x01TCPstream
0x02UDPpacket
0x03Muxstream
0x04Reverse (Rvs)stream

For TCP and UDP, a destination address follows the command. Mux and Rvs are special internal stream commands; the encoder does not append an ordinary network destination for those commands.

Destination address encoding

For ordinary TCP/UDP requests, the on-wire order is:

+----------+------+-------------------------+
| Port     | ATYP | Address                 |
+----------+------+-------------------------+
| 2 bytes  | 1    | variable                |
+----------+------+-------------------------+

Port is a 16-bit network-order integer. Current Xray address-family values are:

0x01  IPv4
0x02  Domain
0x03  IPv6

The address body is:

IPv4:
  ATYP=0x01 | 4 address bytes

Domain:
  ATYP=0x02 | 1-byte domain length | domain bytes

IPv6:
  ATYP=0x03 | 16 address bytes

A domain is therefore length-prefixed in the same general style as SOCKS5, but VLESS uses a different type value for domains (0x02 versus SOCKS5 0x03) and places the two-byte port before ATYP.

Example request header

Ignoring transport security and using no addons, a TCP request to example.com:443 has the logical layout:

00
<16-byte user ID>
00
01
01 bb
02 0b 65 78 61 6d 70 6c 65 2e 63 6f 6d

Read as:

00        Version 0
UUID      16-byte identity
00        zero-length addons
01        TCP command
01 bb     port 443, big endian
02        domain address type
0b        domain length 11
...       "example.com"

Application bytes can follow the header on the same underlying byte stream. A server parser must therefore stop exactly at the end of the address and retain any already-read application bytes.

Server-Side Request Parsing State Machine

A minimal inbound parser can be modeled as:

TRANSPORT_READY
      |
      v
READ_VERSION (1)
      |
      | version == 0
      v
READ_USER_ID (16)
      |
      | user exists
      v
READ_ADDONS_LENGTH (1)
      |
      v
READ_ADDONS (N)
      |
      v
READ_COMMAND (1)
      |
      +---- Mux/Rvs ------> INTERNAL_STREAM_DISPATCH
      |
      +---- TCP/UDP
      v
READ_PORT (2)
      |
      v
READ_ATYP (1)
      |
      v
READ_ADDRESS
      |
      v
DISPATCH_DESTINATION
      |
      v
SEND_RESPONSE_HEADER
      |
      v
RELAY

An invalid request version, unknown user ID, malformed addons block, unsupported command, invalid address type, truncated port, or truncated address must abort normal VLESS request processing. Whether the outer connection is simply closed, reset, or handled by another transport/fallback path depends on the surrounding Xray transport and security configuration.

The parser must use exact-length reads for fixed-size fields. TCP, TLS, XHTTP, and other stream transports do not preserve VLESS header boundaries.

Response Header

VLESS has a small server-to-client response header before downlink application data. Current Xray-core writes:

+---------+--------------+------------------+
| Version | AddonsLength | Addons protobuf  |
+---------+--------------+------------------+
| 1 byte  | 1 byte       | N bytes          |
+---------+--------------+------------------+

The response version must equal the request version. In the common no-addon case, the response begins:

00 00

This is an important difference from SOCKS5. SOCKS5 returns a REP status plus BND.ADDR/BND.PORT; baseline VLESS does not return an equivalent fixed per-destination status code or bound-address tuple in this response header.

Consequently, a VLESS implementation normally learns about many destination or transport failures through stream termination/reset and implementation error handling rather than by parsing a SOCKS5-style REP byte.

TCP Data Path

For Command=0x01, once the server has accepted the request and dispatched the destination, the remaining body is a byte stream:

Client                                Server                         Target
  |                                     |                              |
  | VLESS request header + early data   |                              |
  |------------------------------------>|                              |
  |                                     | TCP connect / dispatch       |
  |                                     |----------------------------->|
  |                                     |                              |
  |<------- VLESS response header ------|                              |
  |                                     |                              |
  |============ application bytes ================================>   |
  |<=========== application bytes =================================   |

There is no per-record VLESS framing for ordinary TCP payload in the no-flow case. The outer transport may of course add its own framing: TLS records, XHTTP requests, WebSocket frames, HTTP/2 frames, and so on are separate layers.

This separation is useful when debugging. A packet boundary from the outer transport is not a VLESS application-message boundary.

UDP Body Framing

Current Xray-core handles Command=0x02 differently from TCP. Each UDP packet is serialized onto the VLESS body stream as:

+----------+------------------------+
| Length   | UDP payload            |
+----------+------------------------+
| 2 bytes  | Length bytes           |
+----------+------------------------+

The two-byte length is big endian. The destination is supplied by the VLESS request header; ordinary packets in that VLESS request therefore do not repeat ATYP + address + port for every datagram.

Conceptually:

VLESS UDP request header
    |
    +-- uint16 length -- UDP datagram #1
    +-- uint16 length -- UDP datagram #2
    +-- uint16 length -- UDP datagram #3

This design is markedly different from SOCKS5 UDP relay:

  • SOCKS5 sends each datagram over a real UDP socket and repeats the destination in every SOCKS UDP header.
  • VLESS can carry UDP packet semantics over a stream transport by restoring packet boundaries with a two-byte length.
  • Baseline VLESS body framing has no SOCKS5 FRAG byte. Fragmentation, MTU, or packetization behavior introduced by the outer transport is a separate concern.

A receiver must first read exactly two bytes, decode the length, and then read exactly that many payload bytes. Treating a single socket read as one UDP packet will fail as soon as the underlying stream splits or combines writes.

Multiplexing Boundaries

A normal VLESS TCP request represents one logical destination stream. VLESS itself does not magically make every Command=TCP request multiplexed just because the outer connection is HTTP/2, XHTTP, or another multiplex-capable transport.

There are two distinct places where multiplexing may appear:

  1. the VLESS Mux command / Xray multiplexing layer; and
  2. the outer transport, which may itself provide multiple logical streams or request flows.

Do not collapse these into one concept in implementation documentation. The SOCKS5 baseline has neither feature: one SOCKS5 TCP control connection becomes one CONNECT relay stream.

Connection Close and Error Semantics

For baseline TCP relay, end-of-stream propagates through the selected outer transport. With VLESS Encryption enabled, EOF/reset first crosses the encrypted record wrapper and only then the baseline VLESS body. Implementations need to distinguish:

  • clean EOF after valid response/data,
  • VLESS Encryption handshake failure,
  • expired or replayed 0-RTT ticket,
  • malformed encrypted record header or failed AEAD tag,
  • transport reset,
  • invalid VLESS request before dispatch,
  • destination connection failure,
  • timeout / idle expiration,
  • and outer TLS/REALITY/XHTTP failure before VLESS can even be parsed.

Unlike SOCKS5, VLESS does not provide a fixed reply-code taxonomy equivalent to REP=connection refused, network unreachable, or address type unsupported. Logs and the transport’s close/reset semantics therefore carry more diagnostic weight.

For UDP-over-stream, a truncated two-byte length or EOF before the declared payload length is a malformed/incomplete packet, not a shorter valid datagram.

Packet-Capture View

VLESS over TLS/RAW

Without decryption, a capture typically exposes only the outer layers:

TCP
  -> TLS handshake
  -> TLS application data
       -> [optional VLESS Encryption handshake + records]
       -> VLESS request/body

With TLS keys or instrumentation below TLS, the next layer is either the baseline VLESS request header or, when enabled, the VLESS Encryption handshake. After a VLESS Encryption 1-RTT handshake, native/xorpub mode commonly exposes five-byte inner record headers shaped as 17 03 03 <BE16 length>; random masks those headers as well. These are inner VLESS Encryption records, not a second real TLS session.

VLESS over REALITY

The capture first looks like the REALITY/TLS-facing handshake. VLESS fields are inside the accepted secure session and are not visible as clear-text UUID, command, or address fields on the network.

VLESS over XHTTP

The packet capture sees HTTP-layer requests/responses or HTTP/2/HTTP/3 transport frames first. VLESS is payload carried inside those XHTTP flows. Therefore:

IP/TCP(or QUIC)
  -> TLS/REALITY
      -> HTTP/XHTTP
          -> VLESS
              -> destination application protocol

This layer ordering is essential when deciding where a failure occurred.

VLESS Compared with SOCKS5

Stage / conceptSOCKS5VLESS / current Xray
Initial transportTCP to SOCKS serverSelected Xray transport
Built-in confidentialityNoneBaseline none; optional VLESS Encryption; TLS/REALITY can be an additional outer layer
Encryption negotiationnone in RFC 1928/1929preconfigured encryption / decryption; no on-wire method list
Encryption handshakenoneoptional NFS authentication + ML-KEM-768/X25519 hybrid PFS, or ticket resumption
Early dataSOCKS request follows method/auth completionVLESS Encryption can resume with ticket-backed 0-RTT
Encrypted record framingnone beyond TCPoptional 17 03 03 + uint16 length + AEAD(ciphertext) style records; random masks header appearance
Protocol versionVER=0x05request Version=0x00
Identity negotiationMETHOD list + selected METHODno method negotiation
User identityRFC 1929 username/password or other methodfixed 16-byte user ID in request header
Optional protocol metadataauthentication subprotocolone-byte addons length + optional protobuf
TCP commandCMD=0x01 CONNECTCommand=0x01 TCP
UDP commandCMD=0x03 UDP ASSOCIATECommand=0x02 UDP
Other commandsBINDMux, Rvs are Xray-specific
Address orderATYP, ADDR, PORTPORT, ATYP, ADDR
IPv4 type0x010x01
Domain type0x030x02
IPv6 type0x040x03
Domain length1 byte1 byte
Port2-byte network order2-byte network order
TCP success replyexplicit REP responseversion + addons response; no SOCKS-style REP
Bound address in responseyesno baseline equivalent
TCP bodyraw byte streamraw body in ordinary no-flow mode
UDP transportseparate UDP relay endpointlength-framed packets over selected VLESS body transport
Destination repeated per UDP packetyesno, destination is in request header
SOCKS UDP FRAG equivalentFRAG byteno baseline equivalent in VLESS body framing
Multiplexingnot part of SOCKS5optional Xray/VLESS and/or transport layers
Failure before proxy commandmethod/auth failureouter transport or VLESS Encryption handshake/AEAD failure can happen before UUID/command parsing

The conceptual inheritance is still recognizable: authenticate/identify the client, express a command, encode a destination, then relay traffic. Baseline VLESS compresses those control phases into one request header. Current VLESS Encryption adds a separate configured cryptographic wrapper before that header, while TLS/REALITY, XHTTP, and multiplexing can still add further outer layers. None of those encryption stages replaces the VLESS destination command.

Implementation Checklist

A low-level VLESS implementation should verify at least these points:

  1. Read exactly one version byte and reject unsupported versions.
  2. Read exactly 16 user-ID bytes before looking up the user.
  3. Bound and completely read the one-byte-length addons block.
  4. Validate the command before interpreting destination fields.
  5. For TCP/UDP, read the two-byte port before the address type.
  6. For domains, enforce the one-byte length and read the complete domain.
  7. Preserve bytes read beyond the end of the header as application payload.
  8. Emit and consume the VLESS response header before treating downlink bytes as target payload.
  9. For UDP, reconstruct packet boundaries from the two-byte length prefix.
  10. Apply strict limits/timeouts so partial headers and declared UDP lengths cannot retain resources indefinitely.
  11. Keep outer transport errors distinct from VLESS request-validation errors.
  12. If VLESS Encryption is enabled, bound/read the IV, relay area, encrypted lengths, PFS material, ticket, and padding exactly; reject failed AEAD tags.
  13. Keep 0-RTT ticket expiry and replay rejection distinct from UUID or destination rejection.
  14. Parse encrypted application records incrementally: exactly 5 header bytes, then exactly the declared ciphertext length; never use transport read boundaries as record boundaries.
  15. Test native, xorpub, and random independently if the selected core exposes them; they change outer encoding, not the baseline VLESS header.
  16. Test each transport/security combination independently; a correct VLESS parser does not imply XHTTP or REALITY interoperability.

Transport Security

VLESS Encryption

Current Xray treats VLESS Encryption as optional protocol-layer security. It can make streamSettings.security: "none" acceptable on a public-address connection from the confidentiality/integrity perspective, but the official transport guidance explicitly distinguishes that from censorship camouflage: VLESS Encryption does not make the connection look like ordinary HTTPS in the way TLS or REALITY can.

Use xray vlessenc to generate matching client encryption and server decryption values unless there is a specific reason to construct the detailed blocks manually. A mismatch in handshake method, appearance, or authentication material fails before the baseline VLESS request can be decoded.

TLS

TLS gives VLESS ordinary certificate-based transport security. The server name, certificate chain, and client verification settings must be configured correctly.

REALITY

REALITY modifies the TLS-facing security layer and is commonly combined with VLESS. See REALITY for its key, short-ID, target, and fallback model.

No transport security

Current Xray documentation warns against using VLESS with no outer transport security for ordinary public-internet proxying unless the peer is on a trusted private path or VLESS Encryption is explicitly enabled and appropriate for the deployment.

For this Wiki, the conservative rule is simple: do not deploy bare VLESS over an untrusted public path unless you understand and intentionally configure the security model of the selected implementation.

Flow Control / XTLS Vision

Xray exposes flow options such as xtls-rprx-vision for compatible VLESS combinations. Flow control is not merely a cosmetic config flag: client, server, transport security, and underlying transport need to agree on the supported combination.

Current Xray also allows Vision with VLESS Encryption without the older transport restrictions. If the underlying path cannot use direct raw copying, Vision can still penetrate the VLESS Encryption layer to avoid redundant crypto-copy overhead; on compatible raw TCP paths it can additionally attempt the normal direct/splice optimization. This is an optimization layer above the wire-format correctness described earlier, not a new VLESS command.

When documenting Chimera compatibility, treat Vision and VLESS Encryption support separately from basic VLESS request parsing.

Configuration Surface and Minimal Xray-Style Server Example

{
  "inbounds": [
    {
      "listen": "0.0.0.0",
      "port": 443,
      "protocol": "vless",
      "settings": {
        "clients": [
          {
            "id": "11111111-2222-3333-4444-555555555555"
          }
        ],
        "decryption": "none"
      },
      "streamSettings": {
        "network": "xhttp",
        "security": "reality",
        "xhttpSettings": {
          "path": "/api/sync",
          "mode": "auto"
        },
        "realitySettings": {
          "target": "example.com:443",
          "serverNames": ["example.com"],
          "privateKey": "SERVER-PRIVATE-KEY",
          "shortIds": ["0123456789abcdef"]
        }
      }
    }
  ]
}

This example demonstrates layer composition. It is not intended to be copied unchanged: the target, keys, identifiers, path, and supported option names must match the actual core version.

Conceptual Client Example

proxies:
  - name: vless-example
    type: vless
    server: proxy.example.com
    port: 443
    uuid: 11111111-2222-3333-4444-555555555555
    network: xhttp
    tls: true
    servername: example.com

Clash-family field names are implementation-specific. A profile valid in Mihomo is not automatically valid in chimera_client.

Strengths

  • Small and relatively simple proxy-protocol layer.
  • User identities scale beyond one shared global password.
  • Can be combined with multiple Xray transport methods.
  • Works with TLS and REALITY security layers in supported combinations.
  • XTLS/Vision modes can optimize compatible traffic paths.

Limitations

  • VLESS alone should not be treated as complete public-internet transport security.
  • Many useful deployments depend on Xray-specific transport/security behavior.
  • Flow and transport compatibility can be confusing across different clients.
  • Configuration schemas differ between Xray, Mihomo, Clash-family clients, and other implementations.
  • A successful parser import does not prove transport interoperability.

Security Notes

  • Prefer TLS or REALITY for public deployments unless using a deliberately configured alternative security mechanism.
  • Keep certificate verification enabled for TLS.
  • Protect VLESS user IDs and server configuration even though an ID should not be treated like a human-memorable password.
  • Rotate or disable identities for retired clients.
  • Do not copy flow settings between unrelated transports without confirming support.

Chimera Status

Chimera_Client

Upstream alignment: Needs assessment (target: Xray-core; scope: outbound VLESS wire behavior and supported transport, security, and flow combinations)

Local maturity: Experimental

The current Chimera_Client source defines a VLESS outbound and registers its runtime handler. This confirms that VLESS outbound support exists; it does not establish parity for every Xray transport, security mode, flow, or option. Use the implementation matrix and test evidence to determine the combinations verified by this Wiki, and do not infer full Xray compatibility from the protocol’s presence in the outbound enum.

Chimera GUI

The GUI can store or generate VLESS-style profiles only to the extent that the selected core understands them. Selecting Mihomo, clash-rs, or chimera_client can therefore change the effective feature set.

Chimera_Server

VLESS is explicitly included in the current server capability map, with example server configurations documented in the server repository. This still does not mean every transport, flow, fallback, encryption option, or Xray version is fully compatible.

Test Evidence

The strongest currently indexed VLESS evidence covers several distinct layer combinations rather than “VLESS in general”:

  • Chimera Client → Chimera Server REALITY/Vision cross-project positive and negative E2E suites;
  • Xray client → Chimera Server VLESS + REALITY + Vision;
  • Xray client → Chimera Server VLESS + TLS + Vision;
  • Xray client → Chimera Server VLESS over gRPC;
  • Xray client → Chimera Server VLESS over HTTPUpgrade.

Use the exact test function when making an interoperability claim because a successful VLESS/REALITY/Vision path does not prove XHTTP, gRPC, HTTPUpgrade, UDP, encryption, or every flow combination. See Test Evidence and Interoperability Matrix.

Troubleshooting

Authentication / immediate disconnect

  1. Verify the user id on both ends.
  2. Confirm the client and server are using compatible VLESS configuration shapes.
  3. Check flow independently; remove optional flow tuning while isolating the base connection.

TLS/REALITY succeeds but VLESS fails

  1. Confirm the server inbound protocol is actually VLESS.
  2. Check the user identity and decryption/encryption settings.
  3. Verify the transport method (raw, XHTTP, gRPC, etc.) matches both ends.
  4. Inspect server logs for request-version or user-validation errors.

Works in one core but not another

  1. Compare accepted field names rather than only values.
  2. Compare transport/security combinations.
  3. Check whether one core silently ignores unsupported fields.
  4. Reduce the profile to one user, one transport, and no optional flow settings.

References

Dokodemo-door

Dokodemo-door is a destination-forwarding inbound rather than an authenticated proxy wire protocol. A client connects or sends a UDP datagram to the inbound listener, and the server forwards the payload to either a configured target or the operating system’s recovered original destination.

There is no Dokodemo-specific request header, authentication negotiation, success reply, record framing, or encryption format. That absence is the most important fact for packet-level analysis: after any configured outer transport/security wrapper is removed, the bytes are the application’s own bytes.

This page documents the current Chimera_Server implementation and its Xray-shaped configuration surface.

Position in the Stack

Fixed-target TCP mode is conceptually:

client TCP
   ↓
optional transport/security wrapper
   ↓
Dokodemo-door inbound
   ↓
configured address:port
   ↓
target TCP service

Transparent redirect mode is instead:

intercepted TCP/UDP traffic
   ↓
Linux redirect/TProxy-style socket metadata
   ↓
recover original destination
   ↓
Dokodemo-door forwarding/routing
   ↓
original target

Dokodemo-door therefore answers where to forward. It does not define a new application protocol between the client and server.

Configuration Fields

The current Server parses the following settings fields:

FieldCurrent meaning
addressFixed forwarding target address when followRedirect is false.
portFixed forwarding target port when followRedirect is false.
followRedirectUse the socket’s original destination instead of the configured target.

When address is omitted, the current builder uses the inbound bind address as the target address. When port is omitted, it uses the inbound listen port as the target port.

For ordinary fixed forwarding, configure both fields explicitly unless that fallback behavior is genuinely desired.

Example: Fixed TCP Target

{
  "inbounds": [
    {
      "tag": "dokodemo-door-tcp",
      "listen": "127.0.0.1",
      "port": 11003,
      "protocol": "dokodemo-door",
      "settings": {
        "address": "example.com",
        "port": 80,
        "followRedirect": false
      },
      "streamSettings": {
        "network": "tcp"
      }
    }
  ]
}

A TCP client connecting to 127.0.0.1:11003 does not send a proxy destination header. The Server already knows the target example.com:80 from configuration and forwards the client’s first byte as target application data.

TCP Data Path

The current TCP handler returns a direct forwarding result containing:

  • the selected remote location;
  • the same accepted byte stream;
  • no protocol-specific success response;
  • a dokodemo-door traffic context carrying the inbound tag.

Conceptually:

ACCEPT TCP
   |
   +-- followRedirect=false --> target = configured address:port
   |
   +-- followRedirect=true  --> target = connection.original_destination
   |
   v
SELECT ROUTING / OUTBOUND
   |
   v
CONNECT TARGET
   |
   v
COPY RAW BYTES BOTH DIRECTIONS

No bytes are consumed by a Dokodemo request parser because no such parser exists.

followRedirect on TCP

When followRedirect is enabled, the handler declares that it requires an original destination in the TCP connection context.

On Linux, the listener obtains this using the socket original-destination mechanism:

  • IPv4 uses the original-destination socket information exposed through the Linux socket API;
  • IPv6 uses the corresponding IPv6 original-destination path;
  • the recovered IP and port become the Dokodemo forwarding target.

If the operating system does not provide an original destination, the TCP handler rejects the flow with an address-not-available error instead of falling back silently to the configured target.

On non-Linux platforms, the current Server rejects TCP followRedirect as unsupported.

Transparent Interception Is an OS Feature

followRedirect does not itself create firewall/NAT interception rules. The operating system must first redirect traffic to the Dokodemo listener while preserving enough original-destination metadata for the Server to recover it.

A working transparent deployment therefore has at least two independent pieces:

firewall / policy routing / redirect setup
                    ↓
              listener socket
                    ↓
          original-destination lookup
                    ↓
            Dokodemo forwarding

A correct Dokodemo configuration cannot compensate for missing or incorrect OS interception rules.

TCP Transport Wrappers

For TCP mode, the current Server builder accepts these streamSettings.network values:

  • empty / tcp;
  • httpupgrade;
  • grpc.

The normal security-layer builder can also wrap the TCP path where the selected combination is valid.

This means Dokodemo-door can be the inner forwarding handler behind another transport. In that case, the wrapper consumes its own handshake bytes first, and only the resulting inner raw stream is forwarded to the configured/original target.

See gRPC Transport and HTTPUpgrade Transport for the transport-layer behavior.

UDP Mode

UDP mode is selected with:

"streamSettings": {
  "network": "udp"
}

The current Server’s generic UDP entry path supports Dokodemo-door and Shadowsocks at this stage.

For Dokodemo UDP, streamSettings.security must be none. Applying a stream security layer to the UDP Dokodemo path is rejected during configuration building.

Example: Fixed UDP Target

{
  "inbounds": [
    {
      "tag": "dokodemo-door-udp",
      "listen": "127.0.0.1",
      "port": 11020,
      "protocol": "dokodemo-door",
      "settings": {
        "address": "127.0.0.1",
        "port": 5353,
        "followRedirect": false
      },
      "streamSettings": {
        "network": "udp"
      }
    }
  ]
}

Each client datagram is ordinary application UDP payload. There is no Dokodemo UDP header around it.

Fixed-target UDP Resolution

When followRedirect is false, the Server resolves the configured target once while starting the UDP inbound and stores the resulting socket address for the relay path.

The receive loop then treats every incoming datagram as payload for that fixed target, subject to routing/outbound selection.

This is different from SOCKS5 UDP, where each client datagram can carry its own destination address.

UDP Session Key

For direct/freedom forwarding, the current relay reuses an outbound UDP session using a key composed of:

client_addr
target_addr
outbound_tag

Datagrams with the same tuple can therefore reuse the same outbound socket/session.

The current session channel capacity is 64 queued payloads and the idle timeout is 60 seconds. Successful sends and accepted responses reset the idle timer.

These values are current Chimera runtime policies, not fields in a Dokodemo wire format.

UDP Response Validation

A direct UDP session accepts a response only when the source socket address exactly matches the expected target address for that session.

A response from an unexpected source is ignored rather than forwarded to the original client.

Valid response bytes are written directly back to the client’s socket address without adding a Dokodemo or SOCKS header.

UDP Routing and Blackhole

Before creating/reusing a direct UDP session, the Server applies its UDP outbound selection using information including:

  • inbound tag;
  • client address;
  • target socket address;
  • target logical location.

A rule can therefore route Dokodemo UDP traffic to a blackhole outbound. In that case the payload is accounted for and dropped without creating the target relay session.

The repository contains an Xray-compatible example specifically for Dokodemo UDP routing to blackhole.

UDP followRedirect

On Linux, the current UDP implementation can enable original-destination reception on the listener socket. For each datagram it obtains:

client address
original destination address
payload

The original destination becomes both the routing target and the forwarding destination for that datagram/session.

On non-Linux platforms, current UDP followRedirect is rejected as unsupported.

As with TCP, the OS must have redirected the datagram in a way that preserves recoverable original-destination metadata.

TCP vs UDP followRedirect

PropertyTCPUDP
Current platformLinux onlyLinux only
Destination sourceAccepted socket’s original destinationPer-datagram original destination metadata
Missing metadataFlow rejectedReceive/relay path fails rather than using fixed target
Application framingRaw TCP bytesRaw UDP payload
Dokodemo headerNoneNone

UDP original destination is per datagram because one listener can receive datagrams originally addressed to different targets. TCP gets one original destination from the accepted connection socket.

No Authentication Handshake

Dokodemo-door does not authenticate a remote proxy user. If the listener is reachable by an untrusted network and forwards to a fixed sensitive service, it can effectively expose that service through the listener.

Security must come from deployment controls such as:

  • bind/listen scope;
  • firewall rules;
  • outer TLS/REALITY/transport layers where appropriate for TCP;
  • routing policy;
  • target-service authentication.

Do not confuse a configured Host, gRPC service name, or transport path with Dokodemo user authentication.

No Success Reply

There is no Dokodemo equivalent of the SOCKS5 REP response.

For fixed TCP forwarding, a client sees only normal target/application behavior after the Server succeeds in opening the outbound path. If target connection establishment fails, the observable effect is stream failure/close rather than a Dokodemo status packet.

For UDP, there is likewise no control channel announcing success; datagrams are forwarded or dropped according to routing and runtime errors.

State Machine: Fixed TCP

TCP_ACCEPT
    |
    v
SELECT_CONFIGURED_TARGET
    |
    v
SELECT_OUTBOUND / ROUTE
    |
    v
CONNECT_TARGET
    |
    v
RAW_BIDIRECTIONAL_RELAY
    |
    v
EOF / ERROR

State Machine: Redirected TCP

TCP_ACCEPT
    |
    v
READ_SO_ORIGINAL_DST
    |
    +-- unavailable --> ERROR
    |
    v
SELECT_ORIGINAL_TARGET
    |
    v
ROUTE / CONNECT / RELAY

State Machine: UDP

RECEIVE_DATAGRAM
    |
    +-- fixed mode ------> configured target
    |
    +-- redirect mode ---> original destination
    |
    v
SELECT_OUTBOUND
    |
    +-- blackhole --> DROP
    |
    v
GET_OR_CREATE_SESSION(client,target,outbound)
    |
    v
SEND RAW PAYLOAD
    |
    v
ACCEPT EXPECTED-TARGET RESPONSES
    |
    v
SEND RAW RESPONSE TO CLIENT

Packet-capture View

In plain fixed TCP mode, a capture at the Dokodemo listener looks like the underlying application protocol itself. For example, forwarding HTTP means the first client bytes may literally be:

GET / HTTP/1.1\r\n

There is no preceding Dokodemo signature.

In fixed UDP mode, each captured UDP payload is likewise the application’s datagram without a Dokodemo address envelope.

With HTTPUpgrade, gRPC, TLS, or another wrapper, capture interpretation must first remove that outer layer before reaching the raw target application bytes.

Comparison with SOCKS5

PhaseSOCKS5Dokodemo-doorRelationship
Client transportClient connects to SOCKS listenerClient connects/sends to Dokodemo listenerSame ingress concept
Method negotiationVER/NMETHODS/METHODSNoneRemoved
AuthenticationOptional subnegotiationNoneRemoved/delegated to deployment
Destination requestClient sends CMD + ATYP + DSTTarget is configured or recovered from OS original destinationReplaced
Success responseREP + BNDNoneRemoved
TCP payloadRaw after SOCKS handshakeRaw from first byteDokodemo has no protocol preface
UDP destinationAddress in every SOCKS UDP headerFixed target or OS original destinationReplaced
UDP framingRSV/FRAG/ATYP/DST/DATARaw application payloadRemoved
Fragmentation fieldSOCKS FRAGNoneRemoved
Transparent interceptionNot inherent to normal SOCKS operationCore use case for followRedirectExtra OS-integration mode
Error reportingProtocol REP during requestSocket/handler/log failureReplaced

Dokodemo-door is therefore closer to a programmable port forward / transparent redirect target than to a client-negotiated SOCKS proxy.

Current Test Evidence

The current Server source contains tests for:

  • TCP followRedirect selecting the original destination;
  • TCP rejection when original destination context is missing;
  • Linux TCP original-destination extraction path;
  • fixed-target UDP relay;
  • UDP session reuse for the same flow;
  • forwarding multiple UDP responses;
  • Linux UDP followRedirect routing by original destination;
  • UDP routing/blackhole behavior;
  • Xray-compatible Dokodemo TCP and UDP example parsing/building.

The Xray-compatible examples include:

  • dokodemo-door-tcp.json5;
  • dokodemo-door-udp.json5;
  • dokodemo-door-udp-routing-blackhole.json5.

This is stronger evidence than a protocol enum entry alone, although transparent interception still depends on real Linux firewall/socket behavior in deployment.

Current Implementation Status and Compatibility Boundaries

The current implementation should be documented with these boundaries visible:

  • followRedirect is Linux-only for both TCP and UDP;
  • UDP Dokodemo does not support streamSettings.security;
  • supported network choices are UDP, TCP/default, HTTPUpgrade, and gRPC as allowed by the builder;
  • there is no Dokodemo authentication/header/reply protocol;
  • fixed UDP target DNS resolution happens during inbound startup;
  • UDP sessions expire after 60 seconds of inactivity;
  • response packets from an unexpected target socket are ignored.

Troubleshooting

For fixed forwarding:

  1. verify the listener bind address/port;
  2. verify configured address and port rather than relying on defaults unintentionally;
  3. verify target DNS resolution and reachability;
  4. verify routing has not selected blackhole or an unintended outbound;
  5. for TCP wrappers, debug HTTPUpgrade/gRPC/TLS before Dokodemo forwarding;
  6. inspect the target application protocol directly because Dokodemo adds no inner framing.

For followRedirect:

  1. confirm the host is Linux;
  2. confirm firewall/policy-routing rules actually intercept traffic into the listener;
  3. confirm original-destination metadata survives the interception mode;
  4. distinguish TCP socket original destination from UDP per-datagram destination metadata;
  5. only then debug Server routing/target reachability.

A followRedirect failure is often an OS interception problem rather than a proxy wire-format problem.

Source Anchors

Current Chimera behavior in this chapter is grounded in:

  • Chimera_Server/chimera_server_lib/src/config/server_config/builder/mod.rs;
  • Chimera_Server/chimera_server_lib/src/config/server_config/types.rs;
  • Chimera_Server/chimera_server_lib/src/handler/dokodemo.rs;
  • Chimera_Server/chimera_server_lib/src/beginning/mod.rs;
  • Chimera_Server/chimera_server_lib/src/beginning/udp.rs;
  • Chimera_Server/examples/xray-compatible/dokodemo-door-tcp.json5;
  • Chimera_Server/examples/xray-compatible/dokodemo-door-udp.json5;
  • Chimera_Server/examples/xray-compatible/dokodemo-door-udp-routing-blackhole.json5;
  • Chimera_Server/chimera_server_lib/tests/xray_compatible_examples.rs.

For portable transparent-proxy behavior, also verify the Linux interception mechanism used by the deployment; Dokodemo-door can consume original-destination metadata but does not create the operating-system redirect rules that produce it.

Transport Reference

A transport carries the byte stream of a supported inner proxy protocol between peers. It defines connection setup, HTTP or stream framing, session lifetime, ordering, and backpressure. It does not authenticate proxy users, choose the proxied destination, or interpret the inner protocol’s command.

For those responsibilities see Proxy Protocol Reference. For TLS/REALITY and other channel-protection questions, see Transport Security Reference.

Transport Methods

TransportTransport-owned behaviorWhat it passes to the inner protocol
XHTTPHTTP request/response modes, split sessions, ordering, and paddingReassembled ordered bytes
gRPCHTTP/2 gRPC stream and Hunk message envelopeDecapsulated stream bytes
HTTPUpgradeHTTP/1.1 upgrade preface and 101 responseRaw stream bytes after the upgrade

Other transport paths such as RAW/TCP and WebSocket also exist in the broader Chimera/Xray ecosystem. The implementation matrix distinguishes the specific Client and Server paths currently documented. This page does not claim that every protocol or direction supports every transport.

QUIC is different: protocols such as Hysteria 2 and TUIC define protocol-specific semantics over QUIC. Their QUIC framing and session rules belong to those protocol chapters rather than a hypothetical interchangeable Xray transport wrapper.

Ownership Boundary

Inner proxy bytes (e.g. a VLESS request)
    ↓
Transport encoder (e.g. XHTTP, gRPC, HTTPUpgrade)
    ↓
Optional transport security (e.g. TLS or REALITY)
    ↓
TCP / underlying network

The receiving peer reverses that path. An HTTP 200, gRPC status, or HTTP 101 can confirm transport-layer progress; it never, by itself, confirms that the inner proxy authentication or requested destination succeeded.

For a transport document, put path, host, serviceName, stream envelopes, timeout handling, and HTTP behavior here. Put UUIDs, passwords, proxy commands, and destination address encoding in the protocol reference. Keep certificate validation and REALITY authentication in the security reference.

Compatibility and Failure Isolation

Before deploying a composition, verify the actual client direction, server direction, inner proxy protocol, transport method, security layer, and feature gates together. See Implementation Status and Test Evidence; a working transport listener alone is not an end-to-end proxy compatibility test.

Diagnose transport problems after network/security connectivity and before inner proxy parsing: inspect HTTP route and headers, ALPN or HTTP version where relevant, transport-specific session/framing errors, and then the handoff of decoded bytes to the proxy handler. See End-to-End Troubleshooting.

XHTTP Transport

Positioning

XHTTP is an Xray transport method used to carry proxy traffic through HTTP-shaped request/response flows. It belongs to the transport layer, not the proxy-protocol layer. This page owns HTTP framing, session handling, and transport settings; proxy identity/destination rules belong to the Proxy Protocol Reference, and TLS/REALITY settings belong to Transport Security.

A typical deployment combines:

VLESS                 -> proxy protocol
XHTTP                 -> transport method
TLS or REALITY        -> transport security

Current Xray transport documentation allows XHTTP to be combined with ordinary TLS or REALITY. The exact HTTP behavior and tuning options have evolved over time, so the selected core version should be treated as the source of truth.

Why XHTTP Exists

Long-lived raw TCP, WebSocket, and gRPC connections have different network signatures and operational constraints. XHTTP provides another way to express uplink and downlink traffic using HTTP-like exchanges and connection reuse.

Typical reasons to evaluate XHTTP include:

  • deployment behind HTTP-aware infrastructure,
  • environments where WebSocket/gRPC behavior is unreliable,
  • separate control over upload/download request patterns,
  • and compatibility with Xray’s TLS/REALITY transport-security layer.

It should not be described simply as “HTTP proxying”. A local HTTP proxy and an XHTTP transport solve different problems.

Layer Model

Local application
      │
      ▼
Client proxy protocol (for example VLESS)
      │
      ▼
XHTTP transport
      │
      ▼
TLS or REALITY
      │
      ▼
HTTP-capable path / reverse proxy / direct server
      │
      ▼
XHTTP server transport
      │
      ▼
Server proxy protocol

Both endpoints must agree on the XHTTP transport settings that affect request routing and stream interpretation.

Core Fields

The current Xray implementation exposes a broad XHTTP configuration surface. For documentation and initial deployment, focus on the small set of fields that are essential to establish a connection:

FieldPurpose
pathHTTP request path used by the XHTTP endpoint
hostOptional HTTP Host value / virtual-host selection
modeXHTTP upload/download behavior; auto is a common starting point
headers / extra headersOptional HTTP metadata depending on implementation/version
xmuxConnection/request reuse and concurrency tuning
downloadSettingsAdvanced split upload/download routing in newer Xray versions

Current Xray also exposes fields that can materially change the wire-visible HTTP request shape, including sessionIDPlacement, seqPlacement, uplinkDataPlacement, uplinkHTTPMethod, xPaddingObfsMode, xPaddingPlacement, xPaddingMethod, sessionIDTable, sessionIDLength, uplinkChunkSize, and serverMaxHeaderBytes. These are not cosmetic knobs: a client and server that disagree on where metadata lives will parse different sessions or payloads.

Avoid copying large tuning blocks from random examples before the minimal path works. The advanced placement controls are especially version-sensitive and should be validated against the exact Xray-core/Mihomo/other-core implementation in use.

Minimal Xray-Style Server Example

{
  "inbounds": [
    {
      "listen": "0.0.0.0",
      "port": 443,
      "protocol": "vless",
      "settings": {
        "clients": [
          { "id": "11111111-2222-3333-4444-555555555555" }
        ],
        "decryption": "none"
      },
      "streamSettings": {
        "network": "xhttp",
        "security": "tls",
        "tlsSettings": {
          "serverName": "proxy.example.com",
          "certificates": [
            {
              "certificateFile": "/etc/ssl/fullchain.pem",
              "keyFile": "/etc/ssl/privkey.pem"
            }
          ]
        },
        "xhttpSettings": {
          "path": "/api/sync",
          "mode": "auto"
        }
      }
    }
  ]
}

For REALITY, replace the TLS security block with a compatible REALITY block and ensure the selected Xray/core version supports that transport/security combination.

Conceptual Clash-Family Client Example

proxies:
  - name: vless-xhttp
    type: vless
    server: proxy.example.com
    port: 443
    uuid: 11111111-2222-3333-4444-555555555555
    network: xhttp
    tls: true
    servername: proxy.example.com
    xhttp-opts:
      path: /api/sync
      mode: auto

Field names such as xhttp-opts are frontend/core specific. Native Xray JSON, Mihomo, ClashRS, and chimera_client may expose different schemas.

path

The path is one of the most important interoperability fields.

Client and server need compatible path handling. If a reverse proxy is present, it must route that path to the XHTTP backend without accidentally serving a normal website response instead.

Use a deliberate path and document it. Do not reuse a sensitive application endpoint merely to make the traffic appear more realistic.

host

host can participate in virtual-host routing through Nginx, Caddy, a CDN, or another HTTP-aware frontend.

When a reverse proxy chooses an upstream based on Host, a missing or mismatched value can produce a perfectly valid HTTP response from the wrong virtual host, which may look like a proxy protocol failure.

mode

XHTTP has multiple transport modes in current Xray implementations. auto is a reasonable baseline because it allows the core to choose compatible behavior without forcing a specialized upload strategy.

Only force a specific mode when:

  • both client and server versions support it,
  • the HTTP version/path is understood,
  • and you have a concrete reason such as CDN behavior or upstream limitations.

Mode tuning should come after basic connectivity.

For current Xray-core, auto has concrete selection behavior rather than being a fourth wire mode. The client starts from packet-up; when REALITY is used it selects stream-one, or stream-up when REALITY is combined with downloadSettings. Treat this as an implementation policy that can evolve, not as a protocol constant that every XHTTP implementation must copy.

Wire-Level Session Model

XHTTP is unusual compared with SOCKS5 because the transport itself does not carry a single fixed binary CONNECT request. The proxy protocol (for example VLESS) produces an ordered byte stream, and XHTTP maps that byte stream onto one or more HTTP requests and responses.

At the server, current Xray-core reconstructs a connection roughly as follows:

HTTP request metadata
        │
        ├── path / Host validation
        ├── optional Session ID
        └── optional upload sequence number
                │
                ▼
        per-session upload queue
                │
                ▼
        reconstructed byte stream
                │
                ▼
        VLESS / Trojan / other proxy parser

This distinction is fundamental: a VLESS request header can be split across multiple XHTTP upload requests. Conversely, one HTTP upload request can contain the VLESS header plus application payload. The proxy parser therefore must not use HTTP request boundaries as proxy-message boundaries.

Session creation and lifetime

For split modes, current Xray-core indexes server-side state by a Session ID. The first request that references an unknown Session ID creates an httpSession containing an upload queue. A newly created session has a 30-second provisional lifetime while the downlink side has not connected. Once the downlink GET is established, that provisional reap is cancelled; the session then lives with the downlink request and is deleted when that request finishes.

Conceptually:

unknown Session ID
       │
       ▼
create upload queue
       │
       ├── no downlink within provisional TTL -> delete session
       │
       └── downlink attached
                 │
                 ▼
          full duplex logical stream
                 │
                 ▼
          downlink ends -> delete session

The Session ID is therefore an XHTTP transport identifier. It is not the VLESS UUID, not a SOCKS5 authentication identity, and not the destination address.

Session ID and sequence placement

Older XHTTP examples make the split-session URL look structurally fixed, for example /path/<session>/<seq>. Current Xray-core no longer requires that layout. sessionIDPlacement and seqPlacement independently accept:

path | query | header | cookie

The defaults remain path. For non-path placement, the implementation uses configurable keys; current defaults are:

session query/cookie key : x_session
session header key       : X-Session
sequence query/cookie key: x_seq
sequence header key      : X-Seq

The same packet-up logical request can therefore appear in several equivalent HTTP shapes:

path:   POST /api/S/12
query:  POST /api?x_session=S&x_seq=12
header: X-Session: S
        X-Seq: 12
cookie: Cookie: x_session=S; x_seq=12

The server reverses exactly the configured placement before looking up the session and parsing the sequence number. Packet-capture tooling should therefore extract semantics from configuration, not hard-code a path regular expression.

Current Xray can also generate Session IDs from a configurable ASCII character table and length range (sessionIDTable / sessionIDLength). If that mechanism is not configured, the implementation falls back to a UUID string. The config builder rejects a custom table/length combination whose total identifier space is too small, rejects non-ASCII tables, and requires a positive lower length bound. This is an anti-collision/resource-isolation property, not proxy-user authentication.

Current Transport Modes

Current Xray-core distinguishes three important data-shaping models.

stream-one

stream-one keeps uplink and downlink on one HTTP exchange. There is no split Session ID in the normal path: the request body is the reconstructed upstream reader and the response body is the downstream writer.

client                           server
  |                                |
  | HTTP request body -----------> | upstream bytes
  | <----------- HTTP response body| downstream bytes
  |                                |

This is the closest XHTTP mode to a conventional full-duplex stream, although actual duplex behavior still depends on the HTTP version and intermediaries.

stream-up

stream-up separates a long-lived upload request from the downlink request. The upload request body is pushed into the session’s upload queue as a reader, while a GET-like downlink response carries server-to-client bytes.

                 Session ID = S
client                                 server
  |                                      |
  | upload request(S), streaming body -> |--+
  |                                      |  | upload queue
  | GET/downlink(S) -------------------> |<-+
  | <=========== response body ==========|

The server currently rejects a split streaming upload when an explicitly configured mode does not permit stream-up.

packet-up

packet-up slices upstream bytes into independently delivered HTTP requests. Each upload carries the Session ID plus a sequence number. The server parses the sequence number as an unsigned integer and inserts the payload into the session’s upload queue, which is responsible for restoring byte-stream order.

logical upstream bytes:

AAAA BBBB CCCC DDDD

HTTP transport:

request(S, seq=0, AAAA)
request(S, seq=1, BBBB)
request(S, seq=2, CCCC)
request(S, seq=3, DDDD)

server upload queue:

seq 0 -> seq 1 -> seq 2 -> seq 3 -> reconstructed stream

The important implementation consequence is that HTTP request completion order need not be the proxy-stream order. Sequence metadata, not arrival order, is the ordering authority.

Upload Data Placement

In current Xray-core, packet-style uplink data can be transported in the HTTP body, encoded into numbered HTTP headers, or encoded into numbered cookies. uplinkDataPlacement accepts auto, body, header, and cookie; header and cookie placement are valid only for packet-up. The default normalized data path is the request body.

Header and cookie forms use unpadded URL-safe Base64 before the server restores the original bytes. One logical packet can be split across multiple metadata fields. With a configured key such as X-Data, headers are numbered:

X-Data-0: <base64url chunk 0>
X-Data-1: <base64url chunk 1>
...

Cookie placement similarly uses names such as:

x_data_0=<base64url chunk 0>; x_data_1=<base64url chunk 1>; ...

uplinkChunkSize controls the encoded chunk sizes. Current defaults are sized differently for cookies and headers (roughly 2–3 KiB for cookies and 3–4 KB for headers), while body placement follows the normal packet-upload size. The server’s normalized maximum aggregate HTTP-header budget is 8192 bytes unless serverMaxHeaderBytes overrides it. These limits are important when a CDN or reverse proxy imposes a smaller header/cookie ceiling than Xray itself.

The HTTP method is configurable through uplinkHTTPMethod and defaults to POST. Current Xray permits GET only for packet-up, because the other modes need streaming request-body semantics.

This means a packet capture may show an apparently empty POST or GET while the actual proxy bytes are carried in headers or cookies. Troubleshooting should inspect uplinkDataPlacement, its key, chunk size, and the HTTP method rather than assuming that all upstream data is in the HTTP body.

The server also enforces configured upload and metadata limits. Oversized request bodies can be rejected with HTTP 413 Request Entity Too Large; malformed encoded header/cookie data is rejected as a bad request.

XPadding Placement and Obfuscation

XHTTP adds padding to vary request/response shape independently of the inner proxy bytes. In current Xray, default normalized xPaddingBytes is 100–1000. Without obfuscation mode, the implementation uses a predictable compatibility form: an x_padding query parameter embedded in the Referer URL.

With xPaddingObfsMode enabled, the placement becomes configurable:

cookie | header | query | queryInHeader

queryInHeader means the padding is a query parameter inside a URL-valued HTTP header; xPaddingHeader selects that header and xPaddingKey selects the query key. The implementation can generate padding using:

  • repeat-x: repeated X bytes, or
  • tokenish: randomized Base62-looking text whose HPACK/QPACK Huffman-encoded length is adjusted toward the configured target.

This matters at the wire level because HTTP/2 HPACK and HTTP/3 QPACK compress header values. Counting source string characters is not necessarily the same as counting compressed bytes. Current tokenish validation explicitly measures HPACK Huffman length (with a small tolerance), while repeat-x is chosen so its characters have a stable 8-bit Huffman code in the shared HPACK/QPACK table.

Padding is camouflage/traffic-shaping metadata, not authentication and not cryptographic padding for VLESS payload security. A server that requires the configured padding shape validates it before accepting the request. A mismatch can therefore fail at XHTTP with HTTP-level errors before VLESS sees a UUID.

Server Request State Machine

A useful implementation-oriented server state machine is:

HTTP request arrives
       │
       ▼
validate Host / path
       │ failure -> HTTP 404
       ▼
validate padding / transport metadata
       │ failure -> HTTP 400
       ▼
extract Session ID + sequence
       │
       ├── split streaming upload
       │      -> attach request body to upload queue
       │
       ├── packet upload
       │      -> decode placement
       │      -> validate size
       │      -> parse sequence
       │      -> enqueue payload
       │      -> HTTP 200
       │
       └── downlink or stream-one
              -> HTTP 200 + flush
              -> expose reconstructed connection
              -> proxy-protocol parser consumes bytes

A 404, 400, 409, 413, or 405 seen at this layer is therefore an XHTTP transport/routing failure and should be diagnosed before changing the VLESS UUID or destination command.

For the downlink response, current Xray-core writes 200 OK, flushes the response, and then writes proxy bytes to the HTTP response body. It also sets Cache-Control: no-store and X-Accel-Buffering: no; unless disabled, it uses an SSE-like Content-Type to discourage HTTP middleboxes from buffering the stream.

This is operationally important. A reverse proxy can accept every request and still break XHTTP if it buffers the response body instead of forwarding chunks promptly. In that case authentication and routing may be correct while latency or apparent stalls occur at the HTTP transport layer.

Current Xray can construct the downlink side from a second StreamConfig via downloadSettings. The client creates the normal XHTTP logical Session ID, but the downlink request can then dial a different destination, Host, security configuration, XHTTP path, HTTP version, and HTTP connection pool from the uplink. The code explicitly logs this as a stream-down path and creates a second HTTP/XMUX client when necessary.

Conceptually:

                         logical XHTTP Session S
                     /-------------------------------\
client -- uplink --->| origin/CDN A -> XHTTP server  |
client <-- downlink -| origin/CDN B <- XHTTP server  |
                     \-------------------------------/

The Session ID is the correlation point at the XHTTP server; it does not imply that both directions use the same TCP connection, QUIC connection, IP family, CDN edge, TLS/REALITY settings, or even HTTP version. A capture taken on only one network path may therefore contain only half of a logically healthy XHTTP session.

This is an extra transport layer compared with SOCKS5. SOCKS5 CONNECT turns one established TCP control connection into the relay; it has no standard mechanism for routing the two byte-stream directions through independently configured HTTP transports.

HTTP/1.1, HTTP/2, and HTTP/3 Boundaries

XHTTP’s logical session is above the HTTP transport version:

HTTP/1.1 -> TCP connection(s) -> HTTP requests
HTTP/2   -> TCP connection -> multiplexed HTTP streams
HTTP/3   -> QUIC connection -> multiplexed HTTP streams

The current server supports HTTP/1.1 and unencrypted HTTP/2 on its TCP-side HTTP server; when configured for HTTP/3 it listens on UDP/QUIC and serves HTTP/3. TLS or REALITY can wrap the TCP-side listener according to stream settings.

Do not confuse HTTP multiplexing with XHTTP/XMUX logical multiplexing. HTTP/2 and HTTP/3 can multiplex HTTP requests on one underlying connection; XHTTP still has to correlate those requests into the correct reconstructed proxy stream.

Packet-Capture View

With TLS, a normal capture primarily exposes:

TCP/IP
  -> TLS records
       -> encrypted HTTP/1.1 or HTTP/2
            -> XHTTP metadata/data
                 -> VLESS bytes

For HTTP/3:

UDP/IP
  -> QUIC Initial / Handshake
  -> protected QUIC 1-RTT
       -> HTTP/3 request streams
            -> XHTTP session/sequence metadata
                 -> proxy bytes

After TLS/QUIC decryption, debugging proceeds from the outside inward:

  1. identify the HTTP request, method, Host, and base path,
  2. identify where Session ID and sequence metadata are configured to live (path, query, header, or cookie),
  3. identify and validate XPadding placement separately from session metadata,
  4. determine whether packet-up data is in body/header/cookie and Base64-decode metadata placement when required,
  5. reconstruct XHTTP upload ordering,
  6. correlate a separately configured downloadSettings path if present,
  7. only then parse the inner VLESS/Trojan bytes.

A single HTTP request is not necessarily a single proxy request, and a single proxy request is not necessarily contained in one HTTP request.

Proxy-Protocol Boundary

XHTTP is not a replacement for a SOCKS5 or VLESS proxy handshake. It reconstructs and delivers a byte stream to an inner proxy handler; that handler owns client identity, destination address, and TCP/UDP semantics. See SOCKS5 and VLESS for those protocol-level messages.

An XHTTP HTTP 200 confirms only that the transport request was accepted. It does not confirm inner proxy authentication or destination acceptance. Likewise, XHTTP session IDs, ordering metadata, and XPadding are transport fields rather than proxy users, commands, or encryption keys.

Ordering, Flow Control, and Backpressure

There are several independent flow-control domains:

  1. the application/proxy byte stream,
  2. the XHTTP per-session upload queue,
  3. HTTP request/stream flow control,
  4. TCP flow control for HTTP/1.1 or HTTP/2,
  5. QUIC stream/connection flow control for HTTP/3,
  6. reverse-proxy/CDN buffering and request limits.

A stall can occur in any one of these domains. Increasing XMUX concurrency does not fix a full server upload queue, and increasing HTTP/2 stream concurrency does not fix a reverse proxy that buffers the downlink.

For packet uploads, bound the number and total size of buffered out-of-order requests. Otherwise a peer that sends high sequence numbers while withholding earlier chunks can consume memory without allowing the reconstructed stream to advance.

Close and Error Semantics

XHTTP does not have one universal binary close command comparable to an imaginary SOCKS CLOSE command (base SOCKS5 has none either). Lifetime is expressed through the participating HTTP requests and underlying transport:

  • ending the downlink request tears down the associated split session,
  • cancelling a streaming upload ends that upload reader,
  • HTTP error responses reject malformed or incompatible transport requests,
  • TCP FIN/RST, HTTP/2 stream reset, or QUIC/HTTP/3 stream/connection errors can terminate individual transport paths,
  • the inner proxy protocol may independently observe EOF/reset after XHTTP reconstruction.

When diagnosing closure, record which layer closed first. An HTTP 413 is not a VLESS destination error; a QUIC connection close is not an XHTTP sequence error; and a VLESS parser rejection is not necessarily an HTTP routing error.

Implementation Checklist

A robust XHTTP implementation should explicitly test:

  1. Host and path mismatch handling,
  2. split Session ID creation and cleanup,
  3. provisional sessions that never obtain a downlink,
  4. duplicate, missing, delayed, and out-of-order packet sequence values,
  5. every supported Session ID / sequence placement and custom key,
  6. custom Session ID table/length entropy and collision handling,
  7. body/header/cookie upload placement, chunk ordering, and Base64 decode failures,
  8. configured body/header/chunk-size ceilings,
  9. XPadding placement, method, compressed-length validation, and obfuscation mode,
  10. allowed HTTP methods, especially GET restricted to packet-up,
  11. partial inner-protocol headers spanning multiple HTTP uploads,
  12. one upload containing multiple inner-protocol reads worth of data,
  13. downlink flushing through direct and reverse-proxied paths,
  14. downloadSettings where uplink and downlink use different physical paths,
  15. HTTP/1.1, HTTP/2, and HTTP/3 connection-loss behavior,
  16. queue/backpressure limits under a slow inner proxy consumer,
  17. TLS and REALITY combinations independently from XHTTP session logic.

XMUX and Connection Reuse

XHTTP can maintain pools of HTTP connections and reuse them for multiple proxy requests. Current Xray code exposes settings such as maximum concurrency, connection counts, request reuse limits, and connection lifetime controls.

Tuning these values changes server load and traffic shape. More concurrency is not always faster: it can increase connection churn, memory usage, and pressure on reverse proxies or CDNs.

Start with implementation defaults, collect latency/throughput data, and tune one dimension at a time.

Reverse Proxy and CDN Considerations

When placing XHTTP behind Nginx, Caddy, or a CDN, check:

  • TLS termination location,
  • HTTP/2 or HTTP/3 support,
  • request and response buffering,
  • maximum request body sizes,
  • idle and upstream timeouts,
  • path rewriting,
  • Host/SNI routing,
  • and whether the provider permits the connection pattern.

A connection that works directly against Xray but fails behind a reverse proxy usually indicates an HTTP routing or timeout mismatch rather than a VLESS user problem.

XHTTP + REALITY

Current Xray transport documentation supports XHTTP with REALITY.

Keep the layers separate during diagnosis:

  1. Is the TCP/QUIC path reachable?
  2. Does REALITY authenticate correctly?
  3. Does the XHTTP path/mode match?
  4. Does the proxy protocol user identity match?
  5. Does the reverse proxy/CDN route the request correctly?

Changing all of these at once makes failures difficult to localize.

Strengths

  • HTTP-oriented transport behavior suitable for HTTP-aware infrastructure.
  • Can be combined with TLS or REALITY in current Xray versions.
  • Supports connection reuse and multiplex-oriented tuning.
  • Can be deployed directly or behind reverse-proxy/CDN layers when configured correctly.
  • Gives operators more control over upload/download transport behavior than a single raw stream.

Limitations

  • More configuration surface than raw TCP.
  • Path, Host, mode, reverse-proxy, and security settings must align.
  • Advanced tuning changes between Xray versions and implementations.
  • CDN/reverse-proxy policies can break otherwise valid direct connections.
  • Incorrect multiplex tuning can reduce rather than improve performance.

Security Notes

  • Use TLS or REALITY on untrusted networks unless the selected architecture has another deliberate security layer.
  • Keep TLS certificate verification enabled.
  • Do not place authentication secrets in custom HTTP headers unless the protocol explicitly requires it and the operational implications are understood.
  • Treat reverse-proxy access logs as potentially sensitive because paths, headers, and connection metadata may be recorded.
  • Keep Xray/core versions patched; XHTTP evolves actively and old examples can become misleading.

Chimera Status

Chimera_Client

XHTTP is listed as a current client-core capability. The important compatibility question is not only “does XHTTP exist?” but which proxy protocol, mode, security layer, and option names are currently implemented. Validate the exact combination before copying a Mihomo/Xray profile unchanged.

Chimera GUI

Chimera can manage an XHTTP profile only through the schema accepted by the selected core. A GUI field being present does not prove that every XHTTP mode or XMUX option is supported by that core.

Chimera_Server

The server capability map includes XHTTP-related parsing/transport work. Treat basic XHTTP connectivity, TLS, REALITY, reverse-proxy behavior, and advanced XMUX/download settings as separate compatibility dimensions.

Test Evidence

The Server has dedicated ignored Xray/Chimera XHTTP matrices rather than one single happy-path test:

  • xhttp_matrix_e2e.rs covers transport modes, uplink methods, session/sequence placement, data placement, padding, and selected header variants;
  • xhttp_security_matrix_e2e.rs covers none/TLS/REALITY security wrappers;
  • xhttp_protocol_matrix_e2e.rs covers process-level behavior and negative cases such as host/path rejection, padding validation, sequencing, body-size limits, duplicate stream-up, and mode conflicts.

These tests are the basis for the interoperability claims on this page. They do not make rejected Xray-shaped fields implemented; keep the explicit field boundaries in the implementation-status table and this page. See Test Evidence and Interoperability Matrix.

Troubleshooting

Immediate EOF / disconnect

  1. Verify proxy user identity first.
  2. Check transport security (TLS/REALITY).
  3. Verify path on both ends.
  4. Check mode compatibility.
  5. Remove custom headers and XMUX tuning.

Works directly but not through Nginx/CDN

  1. Check path rewriting.
  2. Verify Host and SNI routing.
  3. Increase/inspect upstream and idle timeouts.
  4. Check request buffering/body-size limits.
  5. Confirm HTTP/2 or HTTP/3 support on every hop.

Handshake works but throughput is poor

  1. Return XMUX/tuning to defaults.
  2. Compare direct and reverse-proxied paths.
  3. Measure RTT/loss to the actual CDN edge or server.
  4. Check connection churn and upstream limits.
  5. Tune only after identifying whether the bottleneck is transport, server, or provider policy.

References

gRPC Transport

The gRPC transport documented here is an Xray-style transport wrapper implemented by Chimera_Server. It is not the server’s management gRPC API and it is not itself a proxy protocol. It turns a bidirectional byte stream for an inner protocol into gRPC messages over HTTP/2-compatible HTTP serving. This page covers the gRPC wrapper only: inner identity and destination semantics belong to the Proxy Protocol Reference, while TLS/REALITY handshakes belong to Transport Security.

The current Chimera_Client outbound tree does not contain a matching gRPC transport module, so this page primarily documents Server behavior and the Xray interoperability surface exercised by Server E2E tests.

Position in the Stack

TCP
  ↓
optional TLS or REALITY
  ↓
HTTP/2-compatible connection
  ↓
POST /<serviceName>/Tun
  ↓
gRPC message framing
  ↓
protobuf Hunk { bytes data = 1 }
  ↓
inner proxy byte stream
  ↓
VLESS / VMess / Trojan / other supported inner handler

A successful HTTP/gRPC exchange only proves the transport wrapper. The inner proxy protocol can still reject authentication, destination fields, flow mode, or other protocol state afterward.

Server Configuration Boundary

The current Server activates this transport when streamSettings.network is grpc and the grpc_transport Cargo feature is compiled.

grpcSettings is required. The current builder normalizes serviceName by trimming surrounding / characters and whitespace. If the resulting name is empty, configuration is rejected.

The default service name is:

GunService

The effective request path is then:

/GunService/Tun

or generally:

/<serviceName>/Tun

Current Configuration Support

The parsed configuration structure contains fields such as:

  • serviceName;
  • multiMode;
  • authority;
  • idleTimeout;
  • healthCheckTimeout;
  • permitWithoutStream;
  • initialWindowsSize.

Current runtime behavior is more limited than the parsed shape:

  • multiMode = true is explicitly rejected;
  • authority, idleTimeout, healthCheckTimeout, permitWithoutStream, and initialWindowsSize are currently parsed but not applied by the transport builder;
  • serviceName is active runtime behavior.

These fields should therefore not all be labeled equally as implemented.

Security Wrappers

The gRPC transport can currently sit behind three Server security modes:

SecurityCurrent behavior
PlainHTTP connection directly on accepted TCP.
TLSServer terminates TLS before HTTP/gRPC; h2 is added to ALPN if absent.
REALITYServer accepts a REALITY stream before handing it to the HTTP/gRPC server.

For TLS, certificate and private key material are required. The transport builder ensures h2 is present in the ALPN list because normal gRPC transport relies on HTTP/2 semantics.

HTTP Request Requirements

The current request handler accepts a request only when all three conditions hold:

  1. method is POST;
  2. URI path is exactly /<serviceName>/Tun;
  3. Content-Type begins with application/grpc.

A request that fails these checks receives an HTTP 200 response carrying:

grpc-status: 12
grpc-message: unimplemented gRPC method

This is gRPC’s error model: the HTTP status can remain 200 while the gRPC status reports the application/transport error.

gRPC Message Envelope

Each gRPC message starts with the standard 5-byte message prefix used by this implementation:

+----------------------+---------------------------+
| compressed flag      | message length            |
| u8                   | u32 big-endian            |
+----------------------+---------------------------+
        1 B                       4 B

The current Server requires:

compressed flag = 0

Any non-zero compressed flag is rejected. Compressed gRPC Hunk messages are therefore not currently supported.

The current maximum encoded gRPC message size is 4 MiB.

Hunk Protobuf Payload

Inside the 5-byte gRPC envelope, Chimera expects one small protobuf message whose field 1 carries the raw tunnel bytes.

Conceptually:

message Hunk {
  bytes data = 1;
}

For field 1 with wire type length-delimited, the first protobuf byte is:

0x0a

followed by a protobuf varint length and then the raw data bytes:

0a | VARINT(data_len) | data[data_len]

The current decoder rejects messages that do not begin with field 1 tag 0x0a, contain an invalid varint, or truncate the declared payload.

Full Upload Wire Shape

Putting the layers together, one client-to-server Hunk looks like:

HTTP/2 DATA payload
    |
    +-- 00                         gRPC compressed flag = 0
    +-- 00 00 00 NN               gRPC message length, u32 BE
    +-- 0a                         protobuf field 1 tag
    +-- <varint raw length>
    +-- <inner proxy bytes>

HTTP/2 can split these bytes across DATA frames. The current decoder buffers body fragments until a complete gRPC message is available, so an HTTP/2 frame boundary is not a gRPC Hunk boundary.

Upload Stream to Inner Protocol

The request body decoder performs this transformation:

HTTP body fragments
   ↓
buffer
   ↓
decode 5-byte gRPC prefix
   ↓
decode protobuf Hunk field 1
   ↓
write raw bytes to 64 KiB duplex pipe
   ↓
inner TcpServerHandler

When the HTTP request body ends, the write side of the logical byte stream is shut down. If unconsumed partial gRPC bytes remain, the decoder reports a truncated gRPC message.

Download / Response Stream

The inner protocol writes raw response bytes into the other side of the duplex pipe. The transport wraps every non-empty read chunk as:

gRPC 5-byte prefix
  ↓
protobuf Hunk field 1
  ↓
HTTP response body DATA

After the logical response stream ends, the Server emits response trailers with:

grpc-status: 0

The normal response headers include:

HTTP status: 200
Content-Type: application/grpc
grpc-encoding: identity
grpc-accept-encoding: identity

Single-stream Model

The current Server rejects grpcSettings.multiMode = true. The implemented path maps one accepted gRPC request to one logical duplex byte stream and one inner proxy handler invocation.

Do not infer Xray gRPC multi-mode parity from HTTP/2’s own multiplexing capability. HTTP/2 can multiplex requests at the transport layer, but the currently implemented Chimera configuration/runtime model deliberately supports the single-stream gRPC mode documented here.

Flow Control

There are multiple independent buffering/flow-control layers:

  1. TCP flow control;
  2. HTTP/2 connection and stream flow control;
  3. HTTP body backpressure;
  4. the current 64 KiB in-process duplex pipe;
  5. inner protocol buffering and target TCP flow control.

The parsed initialWindowsSize field is not currently applied by Chimera Server, so users should not assume that setting changes the active HTTP/2 window in the current implementation.

Close and Error Behavior

Important failure points include:

  • TLS/REALITY handshake failure before HTTP;
  • wrong HTTP method/path/content type;
  • compressed gRPC message flag;
  • message larger than 4 MiB;
  • malformed/truncated Hunk protobuf;
  • truncated request body;
  • inner proxy protocol failure;
  • target forwarding failure.

Transport validation errors can appear as gRPC status responses or as connection/log errors depending on where failure occurs. Inner protocol errors happen after the gRPC byte stream has already been established and should be debugged separately.

Packet-capture Anchors

With plain gRPC transport, a capture can show HTTP/2/gRPC metadata and traffic sizes. With TLS or REALITY, those details are encrypted after the outer security handshake.

After decrypting HTTP/2 DATA, useful anchors are:

00 xx xx xx xx    gRPC prefix
0a ...            protobuf field 1

The raw bytes after the Hunk protobuf belong to the inner protocol. For example, VLESS parsing begins only after gRPC transport decoding has removed both the gRPC and protobuf envelopes.

HTTP/2 vs gRPC vs Inner Protocol

Keep these boundaries explicit:

LayerResponsibility
HTTP/2multiplexed HTTP transport, DATA frames, flow control
gRPC envelopecompressed flag + 32-bit message length
Hunk protobuflength-delimited field containing tunnel bytes
inner proxy protocolauthentication, destination, TCP/UDP semantics

An HTTP/2 DATA frame is not equivalent to one proxy packet, and one Hunk message is not necessarily one application request.

Current Test Evidence

The strongest current transport-level interoperability evidence is:

  • chimera_server_app/tests/xray_client_proxy_e2e.rs → xray_client_can_proxy_tcp_through_chimera_grpc, which starts Xray as the VLESS/gRPC client and Chimera as the server;
  • chimera_server_lib/src/beginning/grpc_transport.rs unit tests for Hunk round-trip encoding and incomplete-frame buffering.

Do not use grpc_all_interfaces_e2e.rs, grpc_external_integration.rs, or grpc_xray_compat_e2e.rs as evidence for this proxy transport. Those files test the Server’s Xray-compatible management gRPC API, which is a different control-plane subsystem despite sharing the word “gRPC”.

Chimera_Client Status

The current Chimera_Client outbound transport tree does not contain a gRPC transport implementation. Therefore a Server gRPC feature must not be presented as a current Chimera Client → Chimera Server end-to-end combination unless a different compatible client is used.

Proxy-Protocol Boundary

Unlike SOCKS5, gRPC transport does not negotiate a proxy user, encode a target address, or send a proxy success reply. It maps inner protocol bytes to HTTP/2, gRPC, and Hunk envelopes and back. A successful HTTP/gRPC response verifies transport setup only; the selected inner protocol can still reject authentication, flow mode, or destination handling.

Security Notes

  • Prefer TLS or REALITY for Internet-facing gRPC transport; plain gRPC exposes HTTP metadata and inner ciphertext/plaintext according to the inner protocol.
  • Keep TLS certificate validation and key material correct; h2 ALPN is part of the active Server TLS setup.
  • A valid gRPC path is not authentication by itself. Security still depends on the configured outer security and inner proxy protocol.
  • Do not rely on parsed-but-unused timeout/window fields for resource-control guarantees.
  • Bound message sizes and reject compression unless the implementation explicitly supports it; decompression support would add a separate resource-abuse surface.

Troubleshooting

Check layers in this order:

  1. TCP reachability;
  2. TLS or REALITY handshake if configured;
  3. HTTP/2 negotiation, especially h2 ALPN for TLS;
  4. exact POST /<serviceName>/Tun path;
  5. Content-Type: application/grpc;
  6. compressed flag 0 and gRPC message length;
  7. protobuf field 1 (0x0a) and varint length;
  8. inner proxy authentication/destination;
  9. target connection.

A grpc-status: 12 response usually points to method/path/content-type mismatch, while successful gRPC transport followed by no proxy traffic points lower in the inner protocol stack.

Source Anchors

Current Chimera behavior in this chapter is grounded in:

  • Chimera_Server/chimera_server_lib/src/beginning/grpc_transport.rs;
  • Chimera_Server/chimera_server_lib/src/config/mod.rs;
  • Chimera_Server/chimera_server_lib/src/config/server_config/builder/mod.rs;
  • Chimera_Server/chimera_server_app/tests/xray_client_proxy_e2e.rs;
  • Chimera_Server/chimera_server_lib/src/beginning/grpc_transport.rs test module.

For portable behavior, compare against the current Xray gRPC transport definition and the peer implementation used in deployment; the Server’s parsed configuration surface is broader than its currently active runtime settings.

HTTPUpgrade Transport

HTTPUpgrade is an HTTP/1.1 transport wrapper implemented by Chimera_Server. It uses an HTTP Upgrade-looking handshake to switch from an HTTP request/response exchange into a raw bidirectional byte stream for an inner proxy protocol. This chapter owns the upgrade preface and resulting stream, not inner proxy authentication/destination semantics (see Proxy Protocols) or outer TLS/REALITY settings (see Transport Security).

Despite the current header value Upgrade: websocket, this implementation is not a WebSocket transport: it does not perform the WebSocket key/accept handshake and it does not add WebSocket data frames after the 101 Switching Protocols response.

The current Chimera_Client outbound transport tree does not contain a matching HTTPUpgrade module, so this page primarily documents Server-side behavior and compatibility boundaries.

Position in the Stack

TCP
  ↓
optional outer security configured by the server stack
  ↓
HTTP/1.1 GET upgrade request
  ↓
HTTP/1.1 101 Switching Protocols
  ↓
raw bidirectional byte stream
  ↓
inner proxy protocol
  ↓
target forwarding

The HTTP exchange is therefore a transport preface. Once the upgrade succeeds, subsequent bytes belong directly to the inner handler.

Configuration Activation

The current Server activates this wrapper when:

streamSettings.network = "httpupgrade"

and the binary was built with the httpupgrade Cargo feature.

httpupgradeSettings is required. The current parsed fields include:

  • host;
  • path;
  • header;
  • acceptProxyProtocol;
  • ed.

Runtime support is intentionally narrower than the parsed structure.

Current Configuration Semantics

path

The Server normalizes the configured path:

  • empty path becomes /;
  • a path already beginning with / is kept;
  • otherwise / is prepended.

For request matching, query and fragment text are stripped before comparison. For example, a configured path /upgrade accepts a request target such as:

/upgrade?token=abc

because only /upgrade is compared.

host

host is optional. When configured, it is trimmed and lowercased. The inbound validates the HTTP Host header against that value.

A normal host:port request header can match a configured bare hostname. Host validation is therefore about the host identity, not strict textual equality with a client-side port suffix.

Custom header configuration is parsed but is not used by the current Server inbound matcher. The builder explicitly treats custom headers as a client-side request-construction concern rather than an inbound routing field.

Do not document arbitrary header entries as Server-side validation rules.

Explicitly Rejected Fields

The current builder rejects:

acceptProxyProtocol = true
ed != 0

with explicit configuration errors.

Therefore these fields are neither silently ignored nor partially implemented in the current Server path.

Handshake Request

The current handler reads one HTTP header block terminated by:

\r\n\r\n

and requires all of the following:

  • request method GET;
  • version exactly HTTP/1.1;
  • request path matching the configured normalized path;
  • optional Host matching when configured;
  • Connection: Upgrade;
  • Upgrade: websocket.

Conceptually:

GET /upgrade HTTP/1.1
Host: example.com
Connection: Upgrade
Upgrade: websocket


Header names are normalized to lowercase during parsing; the relevant header values are compared case-insensitively after trimming.

Response

A valid request receives:

HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: websocket


Immediately after this response, the same underlying stream is handed to the inner proxy handler.

There is no WebSocket Sec-WebSocket-Accept computation in this HTTPUpgrade path.

Why This Is Not WebSocket

A real WebSocket opening handshake normally has additional fields such as:

Sec-WebSocket-Key
Sec-WebSocket-Version
Sec-WebSocket-Accept

and after the 101 response, application data is carried in WebSocket frames with FIN/opcode/mask/length fields.

Current Chimera HTTPUpgrade does neither of those things. Its post-upgrade layout is simply:

HTTP request headers
HTTP 101 response headers
<raw inner-protocol bytes>
<raw inner-protocol bytes>
...

This distinction is essential in packet captures. Seeing Upgrade: websocket does not mean a WebSocket decoder should be applied to subsequent bytes.

Preserving Early Inner-protocol Bytes

The current unit test deliberately sends bytes immediately after the HTTP header terminator:

...\r\n\r\nprotocol

After the upgrade completes, the inner handler reads exactly those bytes as the beginning of its protocol stream.

That proves the wrapper must not discard or reinterpret bytes that arrive in the same TCP receive sequence after the HTTP headers.

For layered protocols, those first preserved bytes may be an authentication header, UUID/request header, or another transport/protocol preface.

Header Size Limit

The current Server reads the HTTP header one byte at a time until either:

  • \r\n\r\n is found; or
  • the accumulated header reaches 12 KiB.

The hard limit is:

12288 bytes

A larger header is rejected with an invalid-data error.

This is a runtime resource bound and should be considered when migrating configurations that add very large custom request headers on a compatible client.

Handshake Timeout

The current HTTPUpgrade handshake must complete within:

4 seconds

The timeout covers reading and validating the HTTP header preface. Once the 101 response is sent and the inner stream is handed off, normal inner-protocol and TCP timeouts apply instead.

The 4-second value is a current Chimera implementation policy, not an HTTPUpgrade wire field.

Request Parsing Details

The request line must contain exactly three whitespace-separated components:

METHOD TARGET VERSION

Missing components or extra request-line components are rejected.

Header lines without a colon are ignored by the current parser rather than causing the entire request to fail. Recognized headers are stored by lowercased name; later duplicate names overwrite earlier values in the current map-based representation.

The header block itself must be valid UTF-8 for the current parser.

Host Matching

The current matcher accepts a bare configured hostname against an actual HTTP Host value containing a port:

configured: example.com
actual:     example.com:443

Case is normalized before comparison.

IPv6 bracket handling has a dedicated path. Operators should still prefer using the same host form generated by the compatible client instead of relying on unusual textual variants.

Inner Protocol Handoff

The wrapper implements TcpServerHandler and performs:

HTTPUpgrade validation
     |
     v
send 101 response
     |
     v
inner.setup_server_stream_with_context(same_stream, same_context)

The forwarding context is preserved across the wrapper. HTTPUpgrade itself does not authenticate proxy users, parse target addresses, or decide TCP/UDP proxy semantics; those are responsibilities of the nested inner handler.

Layering with Proxy Protocols

Conceptually, a VLESS deployment might look like:

TCP
  ↓
HTTPUpgrade handshake
  ↓
raw VLESS request header
  ↓
VLESS application stream

A Trojan or other supported TCP inner handler can use the same transport wrapper when the Server configuration builder permits that combination.

Do not treat HTTPUpgrade as a standalone remote proxy protocol: it has no user identity field or destination request of its own.

Vision Compatibility Boundary

The current Chimera_Server builder explicitly rejects configurations where xtls-rprx-vision is combined with httpupgrade or grpc transport in the relevant VLESS flow path.

That is an implementation-level compatibility restriction, not a statement that HTTP Upgrade can never coexist with similar flow designs in another implementation.

When documenting a VLESS transport combination, verify both the transport wrapper and the configured VLESS flow.

Error and Close Behavior

The current handler can reject before upgrade for reasons including:

  • timeout;
  • header size limit;
  • invalid UTF-8/header parsing;
  • non-GET method;
  • non-HTTP/1.1 version;
  • path mismatch;
  • host mismatch;
  • missing/incorrect Connection: Upgrade;
  • missing/incorrect Upgrade: websocket.

For these validation failures, the current handler returns an internal error to the server stack; it does not construct an HTTP error page or WebSocket close frame.

After a successful 101, close/error semantics belong to the inner byte stream and underlying TCP connection. There is no HTTPUpgrade-specific record-level close message.

Packet-capture View

Without an outer encryption layer, a capture can identify the HTTP preface directly:

C → S: GET /path HTTP/1.1
       Host: ...
       Connection: Upgrade
       Upgrade: websocket

S → C: HTTP/1.1 101 Switching Protocols
       Connection: Upgrade
       Upgrade: websocket

C ↔ S: raw inner-protocol bytes

A WebSocket dissector may misinterpret the post-101 bytes because the handshake superficially advertises websocket. The correct interpretation for this transport is raw inner-protocol data.

If TLS or another outer security wrapper protects the connection, the HTTP preface is visible only after decrypting that outer layer.

HTTPUpgrade vs WebSocket

PropertyHTTPUpgrade in current Chimera ServerWebSocket transport
HTTP methodGETGET
Upgrade: websocketRequiredRequired
Connection: UpgradeRequiredRequired
Sec-WebSocket-KeyNot requiredRequired by WebSocket handshake
Sec-WebSocket-AcceptNot generatedGenerated by server
Post-101 framingRaw bytesWebSocket frames
Client maskingNone at this layerClient→server WebSocket frames are masked
Ping/pongNo HTTPUpgrade-specific control framesWebSocket control frames
Close frameNoneWebSocket close frame

The shared HTTP headers provide camouflage/upgrade semantics, but the resulting data plane is different.

HTTPUpgrade vs HTTP CONNECT

HTTP CONNECT also transitions into a tunnel, but the setup semantics differ:

PropertyHTTP CONNECT proxyHTTPUpgrade transport
RequestCONNECT host:port HTTP/1.1GET /path HTTP/1.1
DestinationExpressed in CONNECT authorityNot in the HTTPUpgrade HTTP header; inner proxy protocol carries it
SuccessUsually 2xx101 Switching Protocols
Proxy authenticationHTTP proxy mechanisms may applyNone in this wrapper
Post-handshake bytesTunnel/application bytesInner proxy-protocol bytes

HTTPUpgrade is therefore an extra transport layer for another proxy protocol, whereas an HTTP CONNECT proxy itself performs destination proxying.

Proxy-Protocol Boundary

An HTTP 101 Switching Protocols response confirms the HTTPUpgrade preface but not proxy authentication, destination acceptance, or relay success. Those remain the responsibility of the selected inner proxy protocol, such as SOCKS5 in its own application-proxy role. HTTPUpgrade contributes no additional record framing after the upgrade.

Current Chimera_Client Status

The current Chimera_Client outbound transport tree does not contain an HTTPUpgrade transport module.

Therefore a Chimera_Server HTTPUpgrade listener currently needs another compatible client implementation. Do not list Chimera_Client → Chimera_Server HTTPUpgrade as a verified combination until a Client runtime path and interoperability test exist.

Current Test Evidence

The current evidence has two layers:

  • handler/httpupgrade.rs unit coverage verifies that a valid upgrade succeeds, first inner-protocol bytes immediately following the HTTP headers are preserved, and an incorrect path is rejected;
  • chimera_server_app/tests/xray_client_proxy_e2e.rs → xray_client_can_proxy_tcp_through_chimera_httpupgrade starts Xray as a VLESS/HTTPUpgrade client and Chimera as the server, providing external interoperability evidence.

The external test is marked ignored because it launches both binaries and is intended for the explicit E2E suite rather than the default fast unit-test path.

Security Notes

  • Host and path are routing/camouflage checks, not cryptographic authentication.
  • Internet-facing deployments should use an appropriate outer security layer where confidentiality and peer authentication are required.
  • Do not expose acceptProxyProtocol or ed as supported merely because they are present in the parsed Xray-compatible configuration structure; current Server rejects them.
  • The 12 KiB header limit and 4-second timeout are useful resource bounds and should not be weakened casually.
  • Because bytes after 101 are raw, security tools that assume WebSocket framing can produce misleading results.

Troubleshooting

Check in this order:

  1. TCP reachability and any outer TLS/security layer;
  2. request is exactly HTTP/1.1 GET;
  3. normalized path matches;
  4. optional Host matches;
  5. Connection: Upgrade and Upgrade: websocket are present;
  6. header block stays within 12 KiB and arrives within 4 seconds;
  7. server sends 101 Switching Protocols;
  8. stop using WebSocket framing after 101 and inspect the raw inner protocol;
  9. debug inner protocol authentication/destination/target connection separately.

If the HTTP upgrade succeeds but the proxy handshake fails, the problem is below this transport layer.

Source Anchors

Current Chimera behavior in this chapter is grounded in:

  • Chimera_Server/chimera_server_lib/src/handler/httpupgrade.rs;
  • Chimera_Server/chimera_server_lib/src/config/mod.rs;
  • Chimera_Server/chimera_server_lib/src/config/server_config/builder/mod.rs;
  • Chimera_Server/chimera_server_lib/src/config/server_config/types.rs;
  • Chimera_Server/chimera_server_lib/src/handler/tcp/tcp_handler_util.rs.

For portable Xray compatibility, compare these current implementation boundaries with the peer implementation rather than assuming every parsed httpupgradeSettings field is active at runtime.

Transport Security Reference

Transport security protects and/or authenticates the outer connection. It does not contain the inner proxy protocol’s destination request, UUID, or password, and it must not be treated as a substitute for that protocol.

The distinct responsibilities are documented under Proxy Protocol Reference (inner proxy semantics) and Transport Reference (carrying proxy bytes).

Security Mechanisms

MechanismSecurity-layer responsibilityDocumentation
TLSEncrypted channel and certificate-based peer authenticationDeployment Security and Threat Model
REALITYTLS-like outer handshake, key/short-ID validation, and target/fallback behaviorREALITY
QUIC TLSHandshake and channel security integrated with QUICHysteria 2, TUIC

Protocol-owned cryptography is separate: Shadowsocks and VMess define encrypted proxy records, and VLESS can use VLESS Encryption. Consult their protocol chapters for those semantics. Security mechanisms and transport wrappers are not freely interchangeable; the actual peer/core determines allowed combinations.

Layer Boundaries

In an independently layered TCP-based configuration, the security handshake occurs before the protected transport can deliver the inner proxy stream:

TCP connection
    → TLS / REALITY authentication (if configured)
    → transport session / framing (RAW, XHTTP, gRPC, ...)
    → proxy-protocol authentication and target request

This sequence is conceptual: individual transports and QUIC-based protocols have different negotiation requirements. Success at the security layer does not mean the HTTP transport route or the proxy user was accepted.

Security-page configuration owns certificates, SNI and verification, REALITY key material, short IDs, fingerprints and fallback behavior. Transport-page configuration owns HTTP/stream framing, while protocol-page configuration owns proxy identity and destination handling.

Verification and Diagnostics

Verify the selected core and both endpoint directions in Implementation Status and the interoperability tests. For failed connections, distinguish TCP/UDP reachability, security-handshake rejection, transport setup failure, and inner protocol authentication or dispatch errors. See End-to-End Troubleshooting.

REALITY

Positioning

REALITY is an Xray transport-security mechanism. It is not a standalone proxy protocol: it protects and camouflages a supported transport while the actual proxy protocol can be VLESS, Trojan, or another compatible Xray inbound/outbound combination. This page owns REALITY authentication, key material, and fallback behavior; inner proxy semantics belong to Proxy Protocols, and HTTP/stream framing belongs to Transports.

Current Xray documentation describes REALITY as a modified TLS design that borrows the appearance and handshake characteristics of a target site. In the current Xray transport matrix, REALITY is used with RAW, XHTTP, or gRPC.

A useful mental model is:

VLESS / Trojan / ...   -> proxy protocol
RAW / XHTTP / gRPC     -> transport method
REALITY                 -> transport security

Main Configuration Concepts

A REALITY deployment commonly includes:

  • a server-side X25519 private key,
  • the corresponding client-side X25519 public value, called password in current Xray configuration (publicKey is the older field name),
  • one or more short IDs,
  • one or more permitted server names,
  • a target site/address used for handshake appearance and fallback behavior,
  • and a client TLS fingerprint setting in implementations that expose uTLS-like fingerprint controls.

Current Xray can additionally configure an ML-DSA-65 signing key on the server and verification key on the client. This is an optional extra certificate verification layer; it does not replace the base REALITY X25519 key relation or the ClientHello authentication described below.

These pieces belong to the same security configuration and must be kept consistent.

Connection Flow

At a high level:

  1. The client connects to the REALITY-enabled endpoint.
  2. The client begins a TLS-like handshake using the configured server name and client fingerprint behavior.
  3. The REALITY endpoint validates the handshake using its key material and the supplied short ID/security parameters.
  4. If validation succeeds, the underlying proxy transport proceeds.
  5. If traffic is not accepted as a valid REALITY session, Xray can forward it toward the configured target instead of returning a proxy-specific response.

The target therefore participates in both camouflage and fallback behavior and must be chosen deliberately.

Handshake Internals and On-Wire Authentication

REALITY deliberately keeps its authentication inside a TLS-looking ClientHello instead of adding a SOCKS-like method negotiation or a VLESS-like plaintext identity header before TLS. This means the first bytes visible to a passive observer are ordinary TLS record/handshake bytes; the REALITY-specific credentials are embedded into fields of the generated ClientHello and protected with keys derived for that handshake.

A useful client-side state machine is:

TCP connection
    |
    v
Build uTLS ClientHello from selected fingerprint
    |
    +-- choose SNI/serverName
    +-- create TLS 1.3 ephemeral key share
    +-- allocate 32-byte legacy Session ID
    |
    v
Derive REALITY authentication key
    |
    v
Encode + protect REALITY metadata in ClientHello Session ID
    |
    v
Send TLS ClientHello
    |
    v
Receive TLS-looking ServerHello / certificate flight
    |
    +-- REALITY temporary certificate verifies -> proxy transport continues
    +-- genuine target certificate -> not an authenticated REALITY session
    +-- invalid certificate/authentication -> abort

The current Xray-core client constructs a 32-byte ClientHello legacy Session ID. Before protection, the first 16 bytes carry REALITY metadata with this logical layout:

byte 0       client major version
byte 1       client minor version
byte 2       client patch version
byte 3       reserved (0)
bytes 4..7   Unix timestamp, uint32 big-endian
bytes 8..15  short ID, padded to 8 bytes when shorter

The remaining 16 bytes of the 32-byte Session ID are used by the AEAD result. This is an implementation-level wire detail, not a new TLS extension: REALITY reuses the TLS ClientHello Session ID field so that the outer message still has the shape of a normal TLS handshake.

Key derivation

The client already has the server REALITY public key. During construction of the TLS 1.3 ClientHello it also owns the private side of its ephemeral key share. Current Xray-core computes an X25519 ECDH result between that ephemeral key and the configured REALITY public key, then expands it with HKDF-SHA256 using:

IKM  = ECDH(client ephemeral private key, REALITY server public key)
salt = ClientHello.random[0..20]
info = "REALITY"

The resulting authentication key is used with an AEAD cipher. Current code uses the last 12 bytes of the ClientHello random (random[20..32]) as the nonce and the serialized ClientHello as associated data while sealing the first 16 bytes of REALITY Session-ID metadata. The protected 32-byte value is then written back into the fixed Session ID location of the ClientHello.

This explains why REALITY authentication is bound to the concrete TLS handshake: a copied Session ID is not an independently reusable password token. The ClientHello random, ephemeral key share, serialized hello, server key, timestamp, and short ID all participate directly or indirectly in validation.

Server-side decision path

Conceptually the REALITY listener has to make a decision before handing the connection to the proxy protocol:

read TLS ClientHello
      |
      v
obtain client key share + ClientHello random
      |
      v
ECDH with REALITY server private key
      |
      v
HKDF -> authentication key
      |
      v
open protected Session-ID metadata
      |
      +-- version/time/short-ID/serverName accepted?
      |       |
      |       +-- yes -> complete authenticated REALITY TLS path
      |       |          -> expose decrypted transport to VLESS/Trojan/...
      |       |
      |       +-- no ----+
      |
      v
forward/fallback toward configured target according to implementation policy

serverNames and short IDs are therefore authentication/selection inputs at the REALITY layer. A VLESS UUID is checked later, by VLESS, after REALITY has successfully produced the protected transport. Keeping these checks separate is important when diagnosing failures.

Certificate result and client verification state machine

The protected Session ID authenticates the ClientHello to the REALITY server, but the client also has to authenticate the server-side REALITY result. Current Xray does that through the certificate flight rather than by expecting an ordinary CA-issued certificate for the REALITY endpoint.

The client can conceptually reach three certificate outcomes:

receive certificate flight
        |
        +-- REALITY temporary certificate
        |      |
        |      +-- HMAC/auth-key check succeeds
        |      +-- optional ML-DSA-65 verification succeeds
        |      `--> Verified=true -> continue proxy transport
        |
        +-- genuine target certificate
        |      |
        |      +-- normal X.509 verification for serverName succeeds
        |      `--> not REALITY-authenticated -> crawler/spider path
        |
        `-- neither verification path succeeds
               `--> TLS verification error / alert / disconnect

In the current Xray client implementation, a REALITY temporary certificate is recognized through an Ed25519 public key and an HMAC-SHA512 value derived from the connection’s REALITY AuthKey. When configured, mldsa65Verify adds an ML-DSA-65 verification step tied to the handshake transcript before the client sets its internal Verified flag. This certificate is therefore bound to the same handshake-derived authentication material as the protected ClientHello; it is not a reusable conventional server certificate.

If the certificate instead validates as the genuine target site’s normal X.509 certificate, the TLS certificate itself can be valid while REALITY Verified=false. That state means the client reached the target/fallback path (or was redirected there) rather than the authenticated proxy path. Current REALITY documentation describes this as entering the crawler/spider behavior. An invalid certificate that satisfies neither path terminates the handshake.

This three-way distinction is useful during packet-level debugging: “valid TLS certificate” and “valid REALITY connection” are not equivalent states.

Packet-Capture View

Without TLS key material, a normal capture should look approximately like:

TCP SYN / SYN-ACK / ACK
TLS record: ClientHello
  SNI = configured serverName
  fingerprint-dependent cipher/extensions/key_share
  legacy_session_id = 32 bytes (contains protected REALITY metadata)
TLS-looking server handshake records
TLS application-data records

A packet capture cannot identify the VLESS UUID or VLESS destination merely by seeing the REALITY ClientHello. Those values are inside the protected transport and belong to the next protocol layer.

Do not assume one TCP segment contains one ClientHello. TLS handshake bytes may span TCP segments, and newer fingerprints can produce larger ClientHello messages. A server implementation must parse a byte stream and TLS lengths, not depend on packet boundaries or a single read() call.

Security and Proxy Authentication Are Different

REALITY validates a TLS-like security-layer handshake: key relation, short ID, server name, and other configured constraints. It does not carry a proxy destination request or authenticate a VLESS UUID. A valid REALITY session may still fail when the inner proxy protocol checks its own identity or target rules.

For example, SOCKS5 negotiates a method and then a destination request, whereas REALITY has no SOCKS-style reply or UDP ASSOCIATE command. Proxy request framing remains in the inner protocol after the secure transport is established.

Parser, Timing, and Boundary Conditions

  • Treat ClientHello as a length-delimited TLS handshake carried over a TCP byte stream; never assume TCP packet boundaries are message boundaries.
  • Validate timestamp freshness with the implementation’s accepted clock window. maxTimeDiff is expressed in milliseconds; large client/server clock skew can make otherwise correct key material fail when a non-zero limit is enforced.
  • The 8-byte short-ID slot is configured as hexadecimal text. Current Xray accepts at most 16 hex characters, requires an even number of characters, and pads shorter values with trailing zero bytes. An empty client short ID is only valid when the server explicitly accepts an empty entry.
  • minClientVer and maxClientVer, when configured, add version checks to the REALITY authentication decision. They are separate from the inner VLESS protocol version byte.
  • A fingerprint must provide a TLS 1.3-capable key share. Current Xray-core rejects fingerprints that cannot supply the required ephemeral ECDH material.
  • Authentication failure and target fallback are not equivalent to successful proxy authentication. Seeing the target site’s genuine certificate is a strong clue that the connection did not enter the authenticated REALITY path.
  • A server can accept a no-SNI ClientHello by including an empty string in serverNames. Current Xray’s client-side configuration uses a valid IP string as the serverName placeholder to request this mode; packet analysis should therefore not assume an SNI extension is always present.
  • The TLS/uTLS implementation, REALITY implementation, target behavior, and peer version form one interoperability surface. Changes to ClientHello construction or the target site’s TLS behavior can affect REALITY even when VLESS configuration is unchanged.

Post-quantum additions in current Xray

Current Xray can use the hybrid X25519MLKEM768 TLS key-exchange group when the selected target supports it. This belongs to the TLS key-exchange portion of the REALITY handshake and is negotiated based on current client/target capability; it does not add a SOCKS-like command or a new proxy destination field.

Separately, mldsa65Seed on the server and mldsa65Verify on the client add an ML-DSA-65 signature check to the temporary REALITY certificate. Because the post-quantum signature enlarges that certificate, the official configuration guidance warns that the selected target should itself return a sufficiently large certificate so the REALITY certificate flight does not become an obvious size fingerprint.

These are optional hardening/interoperability features. A parser or diagnostic tool should report whether hybrid key exchange and ML-DSA verification were actually negotiated rather than assuming their presence from the word “REALITY” alone.

Key Material

REALITY uses an X25519 server private key and the corresponding public value on the client. Current Xray names that client field password; publicKey is the older alias. The rename is operationally important: although the value is an X25519 public key mathematically, REALITY treats it as client-held connection credential material rather than as something to publish indiscriminately.

Do not place a server private key in client profiles, screenshots, issue reports, or public documentation examples. Treat the client password value as sensitive deployment material as well, even though it is derived from the server’s public key.

For Chimera_Server, the current Wiki documents an x25519 helper in chimera_cli for generating compatible key material.

Short IDs

Short IDs add another server-validated value to REALITY sessions. A server can accept one or more values, while a client selects a matching value.

At the current Xray configuration boundary a short ID is 0 to 8 bytes, encoded as 0 to 16 hexadecimal characters. Its textual length must be even; shorter values are padded with zero bytes to fill the 8-byte Session-ID metadata slot. This is why a value such as aa1234 is valid while an odd-length hexadecimal string is rejected.

Treat short IDs as configuration/security material rather than decorative labels. Client and server must use compatible values and formatting.

Target and Server Names

The server-side target identifies the service whose TLS-facing behavior is used as part of the REALITY design and also receives traffic that does not pass REALITY authentication in the current Xray model.

serverNames restrict which client server-name values are accepted.

A practical target should:

  • be reachable reliably from the server,
  • provide a TLS behavior compatible with the intended setup,
  • not expose sensitive internal infrastructure,
  • and not create an undesirable open-forwarding path.

Current Xray documentation explicitly warns that a poorly chosen target can turn the REALITY server into an unintended forwarder for traffic that fails authentication. Current releases provide optional limitFallbackUpload and limitFallbackDownload token-bucket controls for unauthenticated fallback traffic, but the official guidance also notes that deterministic fallback rate limits can themselves become a fingerprint. They are an abuse-control tradeoff, not part of REALITY authentication.

Minimal Xray-Style Server Example

{
  "inbounds": [
    {
      "listen": "0.0.0.0",
      "port": 443,
      "protocol": "vless",
      "settings": {
        "clients": [
          { "id": "11111111-2222-3333-4444-555555555555" }
        ],
        "decryption": "none"
      },
      "streamSettings": {
        "network": "raw",
        "security": "reality",
        "realitySettings": {
          "target": "example.com:443",
          "serverNames": ["example.com"],
          "privateKey": "SERVER-PRIVATE-KEY",
          "shortIds": ["0123456789abcdef"]
        }
      }
    }
  ]
}

The example is intentionally minimal. Use real generated key material and a server/target combination appropriate for the deployment.

Conceptual Client Example

proxies:
  - name: reality-example
    type: vless
    server: proxy.example.com
    port: 443
    uuid: 11111111-2222-3333-4444-555555555555
    network: tcp
    tls: true
    servername: example.com
    reality-opts:
      public-key: CLIENT-PUBLIC-KEY
      short-id: 0123456789abcdef

Clash-family names are not the same as native Xray JSON field names. The selected core’s schema is authoritative.

REALITY vs TLS

Both REALITY and ordinary TLS occupy the transport-security layer, but their operational models differ.

Ordinary TLS

  • Uses a certificate chain presented by the server.
  • Normally requires certificate issuance/renewal.
  • Client trust follows normal TLS certificate verification.

REALITY

  • Uses REALITY key material and target-site handshake behavior.
  • Does not use the deployment’s own conventional public certificate in the same way as a normal TLS server.
  • Relies on client/server REALITY compatibility and correct fingerprint/target behavior.

Do not describe REALITY simply as “TLS without a certificate”; that hides the key validation, target forwarding, and implementation-specific handshake logic that actually define the deployment.

Strengths

  • Avoids operating a conventional certificate for the REALITY endpoint itself.
  • Integrates with Xray’s supported proxy and transport combinations.
  • Unauthenticated traffic can follow a normal target-service path instead of a bespoke proxy response.
  • Commonly paired with VLESS and XTLS Vision in modern Xray deployments.

Limitations

  • Primarily an Xray-ecosystem mechanism rather than a general Internet standard.
  • Client fingerprint and server target behavior must be compatible.
  • A bad target choice can create reliability or abuse problems.
  • Configuration has more moving parts than normal certificate-based TLS.
  • Transport support is constrained by the selected Xray/core version.

Security Notes

  • Never expose the REALITY server private key.
  • Keep public/private key pairs synchronized during rotation.
  • Use controlled short IDs and remove values no longer needed.
  • Do not set a sensitive private endpoint as the fallback target.
  • Treat allowInsecure/certificate-style bypass options in surrounding transports as debugging tools, not production defaults.
  • Keep client fingerprint selection realistic and supported by the actual core.

Chimera Status

Chimera_Client

The current client overview lists Reality + TCP as a supported combination. In current upstream Xray terminology, the corresponding base transport is often called RAW; Clash-family configurations may still expose it as tcp. This is a naming difference that should be accounted for when translating profiles.

The exact supported proxy protocol underneath REALITY should be verified in the current Chimera_Client implementation instead of assuming complete Xray compatibility from the transport alone.

Chimera GUI

Chimera manages the profile and selected core. REALITY key/fingerprint fields must be emitted in the schema expected by that core.

Chimera_Server

The server documentation includes a VLESS + REALITY example and an X25519 key helper. This makes REALITY an important server target, but transport combinations and Xray-version compatibility should still be tested explicitly.

Troubleshooting

Immediate handshake failure

  1. Verify server public/private key pairing.
  2. Check the short ID.
  3. Verify the client server name is permitted by serverNames.
  4. Confirm the target is reachable from the server.
  5. Check client fingerprint support.

Target site works but proxy does not

This often means the public listener and fallback path are reachable while the REALITY authentication path is failing. Re-check keys, short ID, server name, proxy user identity, and transport method.

Works in Xray but not another core

  1. Compare accepted field names.
  2. Confirm the core supports the same proxy + transport + REALITY combination.
  3. Check whether tcp and raw are translated correctly.
  4. Remove optional Vision/XMUX/XHTTP tuning until the base handshake works.

References

Open Questions

This page tracks unresolved, source-verified documentation or implementation gaps. Remove an item when the source or tests answer it; do not keep historical TODOs merely because they once appeared in an older Wiki revision.

Cross-Project Compatibility

  • Add and maintain a generated or semi-generated compatibility matrix that can be checked against Chimera_Client and Chimera_Server source changes.
  • Record the exact build artifact/features used for interoperability tests, not only the repository commit.
  • Expand interoperability evidence beyond the current REALITY/Vision, XHTTP, gRPC, SOCKS, and selected Xray/client test paths.
  • Define a stable policy for how long an audited source snapshot remains “current” before the Wiki requires a re-audit.

Chimera Desktop

  • Classify each runtime setting as hot-reloadable, restart-required, or application/OS-owned by following its actual update path.
  • Document the profile/enhance pipeline in enough detail to show where generated runtime YAML can differ between Mihomo, clash-rs, and Chimera Client.
  • Document failure handling for core download/update, generated-config validation, foreground process startup, and service-mode startup.
  • Review patch_clash_config and adjacent IPC paths and document the concrete controller/restart behavior they use today.

Chimera_Service

  • Document the local IPC transport/ACL model per operating system with exact source-backed permission behavior.
  • Document which privileged network operations are implemented on each platform; /network/set_dns must not be assumed portable merely because it exists in the shared IPC API.
  • Add a compatibility note for desktop/service/shared-type version skew and the expected failure behavior.

AChimera

  • Document the exact Android route, DNS-server, MTU, IPv4/IPv6, and application include/exclude behavior configured by TunService.
  • Record which Chimera_Client Cargo features are built into the Android native artifact so Android protocol availability can be stated precisely.
  • Add an end-to-end Android test plan covering VPN permission, TUN setup, protect(fd), DNS, profile validation, and one remote proxy path.
  • Document controller polling intervals/backoff and behavior when the embedded core exits while the Android service remains alive.

Chimera_Client

  • Keep the AnyTLS Parsed-only field list synchronized with the Client config struct when compatibility fields are added or become active runtime behavior.
  • Add a feature/build matrix to release documentation so users can determine whether anytls, shadowsocks, trojan, hysteria, and ws are compiled into a distributed binary.
  • Clarify the intended future status of VMess, TUIC, WireGuard, SSH, and gRPC outbound support; these are not current variants of the inspected outbound enum.
  • Document the unimplemented HTTP proxy-provider path if it remains exposed in configuration or migration guidance.

Chimera_Server

  • Add per-protocol implementation pages that map configuration fields to ServerConfig validation, listener/transport selection, and handler code.
  • Convert explicit not supported yet builder/runtime errors into a maintained compatibility table and tests so documentation cannot silently drift.
  • Document current outbound/routing limitations separately from inbound protocol support; for example, an inbound VMess implementation does not imply a VMess outbound proxy path.
  • Expand XHTTP documentation with the exact list of accepted and rejected Xray fields, including the current downloadSettings limitation.
  • Document VLESS Vision direct-mode limitations and the conditions exercised by the existing REALITY/Vision E2E matrix.

Protocol and Transport Reference

  • Pin the upstream AnyTLS and Shadowsocks specification/version references used for interoperability claims when the corresponding upstream protocols change.
  • Add cross-links from each protocol page to its Client/Server implementation status and interoperability tests.