Skip to content

REALITY server

Source files: 13 · checked against Etemenanki 2f00a88
  • Etemenanki/reality/src/server/mod.rs
  • Etemenanki/reality/src/server/handshake.rs
  • Etemenanki/reality/src/server/accept.rs
  • Etemenanki/reality/src/camouflage.rs
  • Etemenanki/reality/src/stream.rs
  • Etemenanki/reality/tests/server.rs
  • Etemenanki/reality/tests/support/dest.rs
  • Etemenanki/reality/tests/unit/server/config.rs
  • Etemenanki/reality/tests/unit/server/handshake.rs
  • Etemenanki/reality/tests/unit/server/accept.rs
  • Etemenanki/reality/tests/unit/camouflage.rs
  • Etemenanki/reality/tests/unit/stream.rs
  • Etemenanki/reality/tests/unit/support/mod.rs

A REALITY server takes a TCP connection and a second, already connected socket to dest, the site it passes itself off as. Every byte of the client’s ClientHello goes to dest as it arrives. A client that authenticates gets a TLS 1.3 handshake shaped like dest’s and becomes a RealityStream; everyone else, and any connection whose handshake goes wrong before the server’s flight is sent, becomes a Camouflage relay that carries on between the client and dest as if the server were not there.

This page covers reality/src/server/, the relay in reality/src/camouflage.rs and the established stream in reality/src/stream.rs. The authentication primitives are on the overview, the records and messages on TLS 1.3 subset. How the protocols crate dials dest and the supervisor runs the relay is on Transports: REALITY.

The server does It leaves to others
Decode its settings once, and make the throwaway certificate key, when a ServerConfig is built. Reading a config file or a spec: the front ends and the supervisor.
Mirror the ClientHello to dest, decide, capture dest’s answer, send a flight in dest’s shape, check the client’s Finished. Connecting to dest: the caller passes in a connected socket.
Hand a refused connection back as a relay with everything each side already said, and a reason safe to log. Running the relay, its idle limit, and whether a refusal counts against anyone: the caller.
Carry application data one record at a time, follow KeyUpdate, end at close_notify. The proxy protocol on top: VLESS, and Vision, which takes the socket back through into_raw_parts.
reality/src/server/mod.rs
#[derive(Clone, Debug)]
pub struct ServerConfig { /* private key, server names, shortIds, optional bounds, hybrid rule, timeout, Arc<TempCert> */ }
impl ServerConfig {
pub fn new<N, I>(private_key: &str, server_names: N, short_ids: I) -> Result<Self, ConfigError>;
pub fn from_bytes<N, I>(private_key: &[u8; 32], server_names: N, short_ids: I)
-> Result<Self, ConfigError>; // short_ids: IntoIterator<Item = [u8; 8]>
pub fn with_max_time_diff(self, max: Duration) -> Self;
pub fn with_client_versions(self, min: Option<&str>, max: Option<&str>) -> Result<Self, ConfigError>;
pub fn with_client_version_bounds(self, min: Option<[u8; 3]>, max: Option<[u8; 3]>) -> Self;
pub fn with_hybrid_required(self, required: bool) -> Self;
pub fn with_handshake_timeout(self, timeout: Duration) -> Self;
}
Setting Xray’s name Default Notes
private_key privateKey required new parses unpadded base64url; from_bytes takes the 32 bytes
server_names serverNames required Matched exactly against the SNI; no wildcards
short_ids shortIds required Hex strings for new, 8-byte values for from_bytes; "" is the all-zero one
with_max_time_diff maxTimeDiff (milliseconds there) no check Zero turns the check off, as in Xray
with_client_versions minClientVer, maxClientVer no bounds Inclusive, each optional; reversed bounds fail with ClientVersionRange
with_client_version_bounds no bounds The decoded form; the caller checks the order
with_hybrid_required false Require XTLS’s 2026-10 key-share rule
with_handshake_timeout 10 s Covers the whole handshake; see Timeout

Both constructors generate the throwaway Ed25519 key (TempCert) up front, so a bad value or an OpenSSL failure (ConfigError::Crypto) shows before any connection. The certificate key sits behind an Arc, so cloning a config per listener is cheap.

reality/src/server/accept.rs
pub enum Outcome<S, D> {
Authenticated(RealityStream<S>), // dest was closed
Camouflage(Camouflage<S, D>), // run the relay
}
pub async fn accept<S, D>(client: S, dest: D, config: &ServerConfig) -> io::Result<Outcome<S, D>>
where
S: AsyncRead + AsyncWrite + Unpin,
D: AsyncRead + AsyncWrite + Unpin;

accept runs in one task over both sockets. An Err means the connection is unusable: a socket failed, or an authenticated client’s handshake went wrong or timed out after the flight was sent. Both sockets are dropped then.

Every way to dest carries a reason. It is a category, safe to log: never a key, a shortId or a session_id. The enum is #[non_exhaustive].

Variant Display When
NotClientHello not a TLS ClientHello The first bytes are not a ClientHello this server reads, or more than 128 KiB arrived without one
ClientClosed client closed before its ClientHello The client’s end of file came before its hello was complete
NotTls13 ClientHello without TLS 1.3 supported_versions does not offer 0x0304
ServerName server name not accepted No SNI, or not one of the configured names
KeyShare no usable key share No share to authenticate with, or not the one the hybrid rule requires
NotAuthenticated not authenticated The session_id is not 32 bytes or does not open under the server’s key
ClientVersion client version out of bounds The sealed version is outside the configured bounds
TimeSkew client time too far off The sealed time is further from the server’s clock than max_time_diff
ShortId shortId not accepted The sealed shortId is not configured
DestSpokeFirst dest sent data before the ClientHello dest sent bytes before the hello was complete
DestHandshake dest's handshake cannot be mirrored dest’s answer is not a TLS 1.3 handshake this server can copy, dest closed, or the flight does not fit dest’s records
Timeout handshake timed out The deadline passed before a decision or while waiting for dest
reality/src/camouflage.rs
pub struct Camouflage<S, D> { /* client, dest, to_client, to_dest, closed flags, reason */ }
impl<S, D> Camouflage<S, D> {
pub fn reason(&self) -> CamouflageReason;
}
impl<S, D> Camouflage<S, D> where S: AsyncRead + AsyncWrite + Unpin, D: AsyncRead + AsyncWrite + Unpin {
pub async fn run(self, idle: Duration) -> io::Result<()>;
}

Debug shows the reason only. The relay is described under The camouflage relay.

reality/src/stream.rs
pub struct RealityStream<S> { /* io, Session, role, read side, write side */ }
impl<S> RealityStream<S> {
pub fn get_ref(&self) -> &S;
pub fn into_raw_parts(self) -> io::Result<RawParts<S>>;
}
impl<S: AsyncRead + AsyncWrite + Unpin> AsyncRead for RealityStream<S> {}
impl<S: AsyncRead + AsyncWrite + Unpin> AsyncBufRead for RealityStream<S> {}
impl<S: AsyncRead + AsyncWrite + Unpin> AsyncWrite for RealityStream<S> {}
#[non_exhaustive]
pub struct RawParts<S> {
pub io: S,
pub plaintext: Vec<u8>, // decrypted content not yet read
pub buffered: Vec<u8>, // bytes received after the current record, not decrypted
}

The same type serves the client; its role decides what a post-handshake message may be. Debug shows the role, the suite and whether each side is closed.

sequenceDiagram
  participant C as client
  participant S as accept
  participant D as dest
  C->>S: ClientHello records
  S->>D: every byte, as it arrives
  Note over S: decide (SNI, key share, session_id, version, time, shortId)
  alt not ours, or anything fails before the flight
    S-->>C: Camouflage relay from here on
    D-->>C: dest's own answer, through the relay
  else authenticated
    D->>S: ServerHello, ChangeCipherSpec, encrypted records
    Note over S: note the record lengths, build the flight
    S->>C: dest's ServerHello with our key share, CCS, padded records
    C->>S: optional CCS, Finished
    Note over S: check Finished, close dest
    S-->>C: RealityStream
  end

reality/src/server/handshake.rs holds the four steps as pure code; accept.rs does the I/O around them.

accept reads the client in 16 KiB chunks, keeps every byte and writes each one to dest as soon as it can. ClientHelloReader (on TLS 1.3 subset) assembles the hello from the records. The hello counts as complete only once every byte received so far is also at dest, so dest has seen exactly what the client sent, including any bytes after the hello in the same read; those are also kept for the next step.

Meanwhile dest is read too: dest has nothing to say before the hello is complete, so any byte from it hands the connection to dest (DestSpokeFirst, with those bytes queued for the client), and dest closing does too (DestHandshake). The client closing gives ClientClosed; a reader result of Invalid, or more than 128 KiB without a complete hello, gives NotClientHello; the deadline gives Timeout. Any client bytes not yet mirrored are queued for dest in the relay.

pub(crate) fn decide(config: &ServerConfig, hello: &ClientHello, now: SystemTime)
-> Result<AuthKey, CamouflageReason>;

decide checks, in this order, and stops at the first failure:

  1. supported_versions offers TLS 1.3 (NotTls13).
  2. The SNI is one of the server names, byte for byte (ServerName).
  3. A key share to authenticate with exists under the key-share rule (KeyShare).
  4. The session_id is 32 bytes, the X25519 agreement with the server’s private key is not refused or all zeros, the auth key derives and the session_id opens under it (NotAuthenticated).
  5. The sealed version is within the bounds (ClientVersion).
  6. With max_time_diff set, the sealed time is within it of now, in either direction (TimeSkew).
  7. The sealed shortId is configured (ShortId).

The key-share rule picks the X25519 public key REALITY authenticates against. Shares of other groups, and shares of the wrong length (32 bytes for X25519, 1216 for X25519MLKEM768), are passed over either way.

Rule When Picks
Lenient Default The first X25519 share; else the X25519 half (the last 32 bytes) of the first X25519MLKEM768 share
Strict with_hybrid_required(true) Exactly one X25519MLKEM768 share, before any X25519 share; then the first X25519 share after it, or else the hybrid’s X25519 half. A second hybrid share before the first X25519 share, or an X25519 share before any hybrid one, fails

The lenient rule is the default because sing-box and mihomo clients send no hybrid share. The strict rule is XTLS/REALITY’s since 2026-10, which the Xray-core release the crate is tested against enforces (see the overview).

A failed decision is a Camouflage with nothing queued: every client byte is already at dest, and dest’s answer reaches the client through the relay.

DestCapture reads dest’s answer to the same ClientHello as XTLS reads it, keeping every byte in case the connection goes to dest after all. The client is not read during this step.

Record Must be
1 A handshake record whose first body byte is ServerHello; ServerHello::parse must accept it
2 A ChangeCipherSpec record of exactly one byte, 1
3 to 6 Application data records: EncryptedExtensions, Certificate, CertificateVerify, Finished
7 Optional: a session ticket

Every record needs version 0x0303 and at most 17 KiB, and a header is looked at only once a sixth byte is in, as XTLS does. If the first application data record is longer than 512 bytes, it is taken to hold the whole flight from EncryptedExtensions to Finished in one record (DestRecords::Combined), and capture ends at its header. Otherwise four records are noted one per message (DestRecords::Separate). A ticket counts only if its record had begun arriving in the same read that completed the Finished record; its header gives its length. More than 17 KiB in all, or anything else, makes the answer Invalid.

Capture ends in DestHandshake when the answer cannot be mirrored or dest closes, and in Timeout at the deadline. The relay then starts with dest’s bytes queued for the client, so the client receives dest’s handshake as dest sent it.

pub(crate) fn build_flight(config: &ServerConfig, hello: &ClientHello, auth: &AuthKey,
dest: &DestCapture) -> Result<Flight, Fatal>;

build_flight uses dest’s suite and group. The client must have offered both (IllegalParameter otherwise). The server answers the client’s share for that group with a fresh key pair and writes its share into a copy of dest’s ServerHello, which is otherwise byte for byte dest’s. Then:

  1. The transcript takes the ClientHello and the new ServerHello; the handshake secret comes from the exchange; c hs traffic and s hs traffic follow.
  2. EncryptedExtensions acknowledges the SNI with an empty server_name and carries no ALPN.
  3. Certificate carries the per-connection certificate with the HMAC under the auth key.
  4. CertificateVerify signs the transcript with the certificate’s Ed25519 key (scheme 0x0807).
  5. Finished is the server’s MAC over the transcript; the application secrets are derived over the transcript through it.

The bytes on the wire are a plaintext ServerHello record, a ChangeCipherSpec record, then the four messages under the server’s handshake key: in one record padded to dest’s combined length, or one record each padded to dest’s length for that message. When dest sent a ticket, an empty application data record of the ticket’s length follows, already under the server’s application key, as Go switches to it right after its Finished. Each of our messages must fit its record with room for the type byte, and no record may exceed what TLS 1.3 allows; otherwise build_flight fails and the connection goes to dest with DestHandshake.

Once the flight is written, a failure closes instead of camouflaging: the client has seen our certificate. AwaitFinished::advance reads the client’s records, starting with any bytes that came after its hello:

  • a ChangeCipherSpec record of one byte 1 is skipped, at most 32 of them (UnexpectedMessage beyond);
  • an application data record is opened under the client’s handshake key and must carry non-empty handshake content;
  • the first complete message must be a Finished that ends its record, and its MAC must check out (DecryptError otherwise); the message reader is bounded to the hash length, so a longer message fails at once;
  • any other record type, a version other than 0x0303 or a record over 16640 bytes fails.

While waiting, accept keeps reading dest only to notice it closing: dest closing first ends the handshake with ConnectionAborted (REALITY: dest closed during the handshake), as XTLS does, and dest’s other bytes are dropped. The client closing gives UnexpectedEof; more than 2 × 16645 + 16384 bytes without a Finished gives UnexpectedMessage. On success dest is dropped, and the bytes after the Finished become the start of the RealityStream’s input.

One deadline, handshake_timeout from the start of accept, covers every step. Before the flight is sent, its expiry hands the connection to dest (Timeout) instead of closing it, so a probe sees dest’s own timeout. After the flight, it closes the connection with TimedOut (REALITY: handshake timed out).

Camouflage::run(idle) relays both ways through two pipes, each with a fixed 16 KiB buffer. The bytes each side already sent during the handshake go first: the client’s unmirrored bytes to dest, dest’s captured bytes to the client. A buffer that started larger for those leftovers shrinks back to 16 KiB once they are out.

  • Each side’s end of file is passed on as a half-close (shutdown) of the other side, as XTLS does. A side that had already closed during the handshake is passed on at once. An error on that shutdown is ignored: the peer may already be gone.
  • run returns Ok(()) when both directions have read end of file, written everything and passed the end on.
  • It returns the error of any failed read or write, and TimedOut (REALITY: camouflage relay idle) after idle without a byte moving either way. Any traffic resets the idle timer.
  • Both sockets are dropped when run returns.

The stream never buffers more than a record each way, and at any moment it can give the socket back with exactly the bytes it read and did not return.

Reading. A record is decrypted only once the previous record’s content has been read. The read buffer grows to at least 4096 bytes or the whole next record, up to one maximum record, and moves the live bytes to the front when it needs room. After the handshake:

Record or content Result
Application data with content Returned to the reader; resets the empty-record count
Application data without content Counted as empty
Handshake content Counted like an empty record; must be non-empty; messages of at most 16 KiB
KeyUpdate Must end its record; the read side moves to the next key generation; a request for an update is remembered
NewSessionTicket Read and dropped on a client (no resumption); UnexpectedMessage on a server
Any other handshake message UnexpectedMessage
Alert close_notify (description 0, any level) End of stream
Any other alert ConnectionAborted, REALITY: peer sent alert <n>
ChangeCipherSpec, a version other than 0x0303, an unknown content type UnexpectedMessage
A record over 16640 bytes RecordOverflow
A record that does not authenticate BadRecordMac
More than 32 records in a row without application data UnexpectedMessage

The peer closing the socket at a record boundary without close_notify is an end all the same, as Go treats it; closing inside a record is UnexpectedEof (REALITY: connection closed inside a record).

Writing. poll_write first writes out what is already sealed, so the socket’s backpressure reaches the writer. It then seals one record of at most 16384 bytes, tries to write it, and reports those bytes as taken. A KeyUpdate the peer asked for is sealed before the next data or at the next flush, with update_requested off, and the write side then moves to the next key generation. poll_shutdown seals close_notify once, writes it and shuts the socket down; a write after that fails with BrokenPipe.

AsyncBufRead. poll_fill_buf hands out the current record’s unread content and decrypts the next record only after consume has used it up. The Vision adapter reads this way, one record at a time.

into_raw_parts. Takes the stream apart into the socket, the unread content of the current record (plaintext) and the bytes received after that record, not decrypted (buffered). It fails with WouldBlock (REALITY: flush the stream before taking it apart) while sealed bytes wait to be written. The Vision flow uses it to switch to the raw socket; see VLESS Vision.

  • Before the flight is sent, no client is told anything by the server: every outcome is a relay to dest, carrying what each side already said.
  • dest sees every byte of the ClientHello, whatever the decision.
  • The flight’s ServerHello is dest’s with only the key share replaced, and each flight record has the length of dest’s record.
  • A CamouflageReason and a Camouflage’s Debug name a category, never a secret.
  • No parse error on the client’s or dest’s bytes panics or leaves half a state; before the flight it becomes a relay.
  • RealityStream holds at most one record’s content to read and does not seal more data while earlier output is unwritten.
Where Outcome
Socket error at any step Err, both sockets dropped
Any refusal or dest failure before the flight Ok(Outcome::Camouflage) with its reason
Deadline before the flight Ok(Outcome::Camouflage) with Timeout
Deadline after the flight Err(TimedOut)
dest closes after the flight Err(ConnectionAborted)
Bad record or Finished after the flight Err(InvalidData), the Fatal inside

accept and run hold no task of their own: dropping either future drops both sockets, which is how the caller cancels them.

Limit Value Constant
Handshake deadline 10 s unless set DEFAULT_HANDSHAKE_TIMEOUT
Read chunk during the handshake 16 KiB READ_CHUNK
Raw ClientHello bytes kept 128 KiB MAX_HELLO_BYTES
dest’s answer kept 17 KiB DEST_CAPTURE_LIMIT
First record treated as a combined flight over 512 bytes COMBINED_THRESHOLD
Records without content before the Finished, and in a row afterwards 32 MAX_USELESS_RECORDS
Client bytes kept while waiting for the Finished 2 × 16645 + 16384 MAX_FINISHED_BYTES
Relay buffer per direction 16 KiB RELAY_BUFFER
Post-handshake message 16 KiB MAX_POST_HANDSHAKE_MESSAGE
Record written 16384 bytes of content MAX_PLAINTEXT
File Covers
reality/tests/unit/server/config.rs Xray’s three settings, every bad value refused up front, the optional settings, Debug without keys or shortIds, the reasons’ texts.
reality/tests/unit/server/handshake.rs A REALITY client let in, one case per decision check and its reason, hellos that are not REALITY, the lenient and strict key-share rules case by case, a low-order share; dest captures with one record per message, a ticket counted only if it had begun arriving, a combined flight, byte-by-byte capture, answers that cannot be mirrored; the flight for every suite and group, dest’s ServerHello compared byte for byte, the Finished whole, byte by byte and without a ChangeCipherSpec, a wrong Finished, the limit of 32 empty records, flights that cannot take dest’s shape, 300 fuzzed Finished records.
reality/tests/unit/server/accept.rs Over TCP against a local OpenSSL dest: an authenticated client with data both ways, the flight having dest’s record lengths, a client of another server, a required hybrid share, the timeout after the flight, dest closing during the handshake, an unknown shortId.
reality/tests/unit/camouflage.rs Handshake bytes first then both ways, more saved bytes than a buffer, a side already closed passed on at once, silence ending the relay and traffic keeping it, Debug.
reality/tests/unit/stream.rs Data both ways, writes split into 16 KiB records, reading one record at a time, raw parts and their flush rule, one pending record, KeyUpdate followed and answered and one not ending its record refused, close_notify and shutdown, ends at and inside a record, the empty-record limit, records that do not belong after the handshake, tickets dropped by a client, bytes read during the handshake coming first, Debug.
reality/tests/unit/support/mod.rs Shared builders: ClientHellos with chosen fields, a minimal sans-I/O REALITY test client, the local dest.
reality/tests/server.rs The server from outside against a local OpenSSL dest on 127.0.0.2: a TLS client gets dest’s certificate and answer, another server name gets dest, HTTP and garbage probes get byte for byte what dest sends them, a stalled hello ends on dest’s timing, a client closing early, an idle relay dropped.
reality/tests/support/dest.rs The dest stand-in: OpenSSL TLS 1.3 with an RSA certificate whose Certificate record is larger than REALITY’s, so an authenticated flight pads to it.