Skip to content

Shadowsocks 2022

Source files: 42 · checked against Etemenanki 46c12e4 · katana v6.1.0
  • Etemenanki/protocols/src/ss_aead.rs
  • Etemenanki/protocols/src/ss_2022/mod.rs
  • Etemenanki/protocols/src/ss_2022/crypto.rs
  • Etemenanki/protocols/src/ss_2022/protocol.rs
  • Etemenanki/protocols/src/ss_2022/users.rs
  • Etemenanki/protocols/src/ss_2022/core.rs
  • Etemenanki/protocols/src/ss_2022/codec.rs
  • Etemenanki/protocols/src/ss_2022/replay.rs
  • Etemenanki/protocols/src/core/mod.rs
  • Etemenanki/protocols/src/core/harness.rs
  • Etemenanki/protocols/src/helpers/crypto.rs
  • Etemenanki/protocols/src/helpers/address.rs
  • Etemenanki/protocols/src/sniff/mod.rs
  • Etemenanki/concepts/src/runtime.rs
  • Etemenanki/concepts/src/client.rs
  • Etemenanki/concepts/src/buffer.rs
  • Etemenanki/app/src/config.rs
  • Etemenanki/app/src/lower.rs
  • Etemenanki/supervisor/src/build/inbound.rs
  • Etemenanki/supervisor/src/build/outbound.rs
  • Etemenanki/supervisor/src/build/users.rs
  • Etemenanki/supervisor/src/build/validate.rs
  • Etemenanki/supervisor/src/serve.rs
  • Etemenanki/supervisor/src/topology/inbound/mod.rs
  • Etemenanki/supervisor/src/topology/outbound/mod.rs
  • Etemenanki/protocols/tests/unit/ss_aead.rs
  • Etemenanki/protocols/tests/unit/ss_2022/protocol.rs
  • Etemenanki/protocols/tests/unit/ss_2022/core.rs
  • Etemenanki/protocols/tests/unit/ss_2022/codec.rs
  • Etemenanki/protocols/tests/unit/ss_2022/replay.rs
  • Etemenanki/protocols/tests/unit/ss_2022/users.rs
  • Etemenanki/protocols/tests/pipeline/shadowsocks.rs
  • Etemenanki/supervisor/src/topology/spec_plan/inbound.rs
  • Etemenanki/supervisor/tests/unit/validate.rs
  • Etemenanki/app/tests/integration/e2e_xray_wrapped.rs
  • katana/src/lower/inbound.rs
  • katana/src/lower/mod.rs
  • katana/src/lower/outbound.rs
  • katana/src/api/newv2board.rs
  • katana/tests/unit/lower/inbound.rs
  • katana/tests/unit/lower/outbound.rs
  • katana/tests/unit/api/newv2board.rs

The etemenanki_protocols::ss_2022 module implements Shadowsocks 2022 (SIP022) for TCP. It is a port of sing-shadowsocks/shadowaead_2022, reshaped into the workspace’s sans-I/O model. A server core, Ss2022Core, is driven by the per-connection runtime, and a client codec, Ss2022Stream, by the client runtime. Both sit on the AEAD record stream in protocols/src/ss_aead.rs, which legacy Shadowsocks shares. On top of that stream they add BLAKE3 subkeys, a salt-bound response, a timestamp window, a salt replay filter, and the AES block cipher that wraps the Extended Identity Header (EIH) for multi-user servers.

This page is for contributors who change that module or the code that builds it. It goes down to the byte layout of each header, the state machines on both sides, and the tests that pin each rule. The user-facing configuration is in the Shadowsocks guide page. The legacy AEAD family (SIP004) and the shared record stream are described on Shadowsocks AEAD.

TCP only The module has no datagram path. The supervisor’s Outbound::Ss2022 answers every UDP flow with shadowsocks-2022 carries no datagrams (io::ErrorKind::Unsupported).

Concern Where What it does
Methods and key sizes crypto.rs → Method Parses the three 2022-blake3-* names, reports the key (and salt) length and the ss_aead::Cipher each runs on.
Key derivation crypto.rs → session_key, session, identity_subkey, eih_hash, fold_key BLAKE3 session and identity subkeys, a keyed Aead per direction, the 16-byte identity hash, SHA-256 folding of over-long PSKs.
Record stream ss_aead.rs → Aead, ChunkEncoder, ChunkDecoder Seals and opens the header chunks and the records after them under one little-endian nonce counter. Shared with legacy Shadowsocks.
EIH block cipher crypto.rs → BlockCipher One raw AES block (ECB), AES-128 or AES-256 by key length.
Timestamp window crypto.rs → now_unix, check_timestamp, check_timestamp_at Rejects a header timestamp more than 30 seconds from the clock it is checked against.
Header framing protocol.rs Stages the request and response headers into a Staging area; parses them from opened chunks; unwraps EIH blocks.
Users users.rs → Ss2022User, Ss2022ServerConfig, Validator, decode_psk, normalise_psk PSK decoding and normalisation, and the identity-hash table for multi-user servers.
Replay filter replay.rs → SaltFilter Remembers the salts of accepted requests and refuses a repeat. The module is private to the crate.
Server core.rs → Ss2022Core The sans-I/O server: authenticates and parses the request, opens the flow, relays records, writes the salt-bound response.
Client codec.rs → Ss2022Stream The sans-I/O client codec: writes the request (with an optional identity chain), seals records, checks the response’s echoed salt.

mod.rs re-exports Ss2022Stream, Ss2022Core, Method, Ss2022ServerConfig, Ss2022User and Validator.

What the module leaves to others:

  • I/O, buffers and back-pressure belong to the runtimes in etemenanki-concepts (ProxyServerRuntime, ProxyClientRuntime). The core and the codec only see byte slices and a Staging area.
  • Dialing and routing belong to the supervisor’s connector. The core emits Effect::Open with a Flow, and the codec is told its destination when it is built.
  • Configuration belongs to the front ends, which lower it into a spec (app/src/lower.rs in etemenanki-app, src/lower/ in katana). The supervisor builds the server types from the spec; see Wiring.
pub enum Method {
Blake3Aes128Gcm,
Blake3Aes256Gcm,
Blake3ChaCha20Poly1305,
}
impl Method {
pub fn from_name(name: &str) -> Option<Self>;
pub fn name(self) -> &'static str;
pub const fn key_len(self) -> usize;
pub const fn cipher(self) -> Cipher;
}
method Method variant key_len() (PSK and salt) cipher() EIH block cipher Multi-user server
2022-blake3-aes-128-gcm Blake3Aes128Gcm 16 Cipher::Aes128Gcm AES-128 Yes
2022-blake3-aes-256-gcm Blake3Aes256Gcm 32 Cipher::Aes256Gcm AES-256 Yes
2022-blake3-chacha20-poly1305 Blake3ChaCha20Poly1305 32 Cipher::ChaCha20Poly1305 none No

Method::from_name matches the canonical names exactly, so 2022-BLAKE3-AES-128-GCM is refused. etemenanki-app dispatches on the 2022- prefix first, so a misspelt 2022 name fails with inbound <tag>: unknown shadowsocks-2022 method "<name>" (or outbound <tag>: …) instead of falling through to the legacy family. katana’s newV2board client does not look at the prefix: it tries the exact 2022 names it serves (2022-blake3-aes-128-gcm, 2022-blake3-aes-256-gcm), then the legacy names, and refuses anything else; a helium panel names the cipher in its node config, which holds only those. Method derives Clone, Copy, PartialEq, Eq and Debug; key_len is self.cipher().key_len().

The key length doubles as the salt length: every salt this module writes or reads is key_len() bytes.

The constants next to the method:

Constant Value Meaning
MAX_PACKET_SIZE 0xFFFF Largest plaintext one chunk or record carries (the length prefix is a u16).
MAX_RECORD_LEN MAX_PACKET_SIZE + RECORD_OVERHEAD = 65 569 The largest frame a peer may send: a record carrying MAX_PACKET_SIZE bytes.
SESSION_SUBKEY_CONTEXT "shadowsocks 2022 session subkey" BLAKE3 derive_key context for session subkeys.
IDENTITY_SUBKEY_CONTEXT "shadowsocks 2022 identity subkey" BLAKE3 derive_key context for EIH subkeys.

TAG_LEN (16) and RECORD_OVERHEAD (2 + 16 + 16 = 34) come from ss_aead.

A PSK enters the module as base64 text from the configuration and leaves it as exactly key_len() bytes.

pub fn decode_psk(password: &str) -> io::Result<Vec<u8>>;
pub fn normalise_psk(method: Method, psk: Vec<u8>) -> io::Result<Vec<u8>>;
pub fn fold_key(key: &[u8], key_len: usize) -> Vec<u8>;
  • users.rs → decode_psk trims surrounding whitespace and decodes with the standard base64 alphabet. A decoding failure becomes decode PSK: <base64 error> (InvalidInput).
  • users.rs → normalise_psk keeps a PSK of exactly key_len() bytes, folds a longer one with fold_key, and refuses a shorter one with shadowsocks-2022: PSK too short (<len> < <key_len>) (InvalidInput).
  • crypto.rs → fold_key is sing’s Key(key, keyLength): SHA-256 of the whole key, truncated to key_len. A 32-byte key given to an aes-128 method is therefore accepted and becomes the first 16 bytes of its SHA-256 digest.

Which layer runs these functions is on Wiring.

pub fn session_key(psk: &[u8], salt: &[u8], key_len: usize) -> Vec<u8>;
pub fn session(method: Method, psk: &[u8], salt: &[u8]) -> io::Result<Aead>;

session_key computes blake3::derive_key(SESSION_SUBKEY_CONTEXT, psk || salt) and keeps the first key_len bytes. BLAKE3 is an extendable-output function, so the first 16 bytes of the 32-byte output equal a 16-byte XOF read, which is what sing computes for aes-128. session keys one direction: it hands that subkey to ss_aead::Aead::new with method.cipher(), and the Aead starts at nonce 0.

Each direction of a connection has its own salt and therefore its own subkey. The client’s request salt keys the upstream stream, and the server’s fresh response salt keys the downstream one. Both derive from the same PSK: the single PSK, or in multi-user mode the user’s own PSK (uPSK).

pub fn identity_subkey(psk: &[u8], salt: &[u8], key_len: usize) -> Vec<u8>;
pub fn eih_hash(psk: &[u8]) -> [u8; 16];

identity_subkey is session_key with IDENTITY_SUBKEY_CONTEXT. eih_hash is the first 16 bytes of blake3::hash(psk), which equal sing’s blake3.Sum512(psk)[:16].

flowchart LR
  pw["password (base64)"] --> dec["decode_psk"]
  dec --> norm["normalise_psk"]
  norm --> psk["PSK, key_len bytes"]
  salt["request or response salt"] --> sk["session_key"]
  psk --> sk
  sk --> aead["Aead (session)"]
  aead --> cw["ChunkEncoder / ChunkDecoder"]
  ipsk["identity PSK"] --> ik["identity_subkey"]
  salt --> ik
  ik --> bc["BlockCipher"]
  upsk["user PSK"] --> hash["eih_hash"]
  hash --> bc
  bc --> eih["16-byte EIH block"]

SIP022 runs on the same AEAD stream as legacy Shadowsocks, implemented once in protocols/src/ss_aead.rs. The types, the error texts and the rule that no byte is decrypted twice are described on Shadowsocks AEAD. What is particular to SIP022:

  • Bare chunks for the headers. A header is sealed as one chunk, ciphertext || tag, with no length in front (ChunkEncoder::seal_chunk, ChunkDecoder::open_chunk). The reader knows each header’s length in advance: the request’s fixed header is 11 bytes, and it carries the length of the variable header.
  • Records after them. Data travels in records, AEAD(len_u16_be) || AEAD(data) (seal_record, open_record).
  • One counter. The nonce starts at zero and advances once per AEAD operation, across the header chunks and the records, with no reset between them. On the request, the fixed header uses nonce 0, the variable header nonce 1, and the first record nonces 2 and 3. bare_chunks_and_records_share_one_counter pins the interleaving.
  • A larger payload. Both halves build their encoders and decoders with max_payload = MAX_PACKET_SIZE, so any length a u16 can hold is legal and the decoder’s length cap never refuses one.

An empty record is legal and opens with an empty plain; the core skips it instead of forwarding it. This module never writes one: the core seals its downlink in chunks(MAX_PACKET_SIZE), and the client runtime returns early on an empty write before it reaches Ss2022Stream::seal. The response’s first payload chunk may be empty, but that is a bare chunk, not a record.

Addresses use AddressCodec::SOCKS (protocol.rs → ADDR): a type byte (0x01 IPv4, 0x03 domain, 0x04 IPv6), the address (a domain carries a one-byte length), then the big-endian port. The longest encoding is AddressCodec::MAX_LEN = 259 bytes.

Field Size Meaning
Salt key_len Random. Keys the upstream stream through session(method, psk, salt).
EIH blocks 16 × hops Multi-user only. One AES block per identity key in the client’s chain.
Fixed header chunk 11 + 16 Nonce 0: type, timestamp and variable-header length.
Variable header chunk var_len + 16 Nonce 1: address, padding and initial payload.
Records repeated AEAD(len) followed by AEAD(data), nonces 2, 3, …

The fixed header (REQUEST_FIXED_LEN = 11 bytes of plaintext):

Field Size Meaning
Type 1 HEADER_TYPE_CLIENT = 0. Anything else fails with shadowsocks-2022: bad header type (expected client).
Timestamp 8 Unix seconds, big-endian u64. Checked against the 30-second window.
Variable length 2 Big-endian u16: the plaintext length of the variable header chunk.

The variable header:

Field Size Meaning
Address 7, 19, or 4 + domain length SOCKS-style destination address and port.
Padding length 2 Big-endian u16.
Padding padding length Zero bytes, ignored.
Initial payload the rest First payload bytes for the target; may be empty.
pub fn build_request(
method: Method,
psk: &[u8],
identity_keys: &[Vec<u8>],
dest: &Destination,
initial_payload: &[u8],
out: &mut Staging<'_>,
) -> io::Result<(ChunkEncoder, Vec<u8>)>;
pub fn parse_request_fixed(fixed: &[u8]) -> io::Result<(u64, usize)>;
pub fn parse_request_variable(variable: &[u8]) -> io::Result<(Destination, Range<usize>)>;

build_request stages the whole request header into out and returns the uplink encoder, positioned for the records that follow, and the request salt the response must echo. In order, it:

  1. draws a random salt and keys the encoder with session(method, psk, salt) and MAX_PACKET_SIZE;
  2. encodes the address into a stack buffer of AddressCodec::MAX_LEN bytes, or fails with InvalidInput, shadowsocks-2022: address;
  3. pads with a random length in 1..=MAX_PADDING_LENGTH (900) when the initial payload is shorter than 900 bytes, and with nothing otherwise;
  4. refuses a variable header longer than a u16 with InvalidInput, shadowsocks-2022: request header longer than a chunk may carry;
  5. checks that out has room for the salt, the EIH blocks, both headers and their two tags, or fails with shadowsocks: staging room below the frame having staged nothing;
  6. stages the salt and the EIH blocks, then seals the fixed and the variable header as bare chunks.

a_header_that_does_not_fit_is_refused_and_nothing_is_staged pins steps 4 and 5: a 0xFFFF-byte payload is InvalidInput, a 64-byte staging area refuses both headers, and nothing is staged in either case.

parse_request_fixed reads an opened fixed header: the type byte, then the timestamp and the variable length. It does not check the timestamp. An empty chunk would be truncated input: request header. parse_request_variable reads the address with ADDR.read_slice and returns the destination (DialNetwork::Tcp) and the range of the initial payload inside the chunk. It does not bound the padding length; it only requires the padding to fit inside the chunk, or fails with shadowsocks-2022: padding exceeds request header. A chunk too short to hold the padding-length field fails with shadowsocks-2022: truncated request header.

Field Size Meaning
Salt key_len Fresh random salt. Keys the downstream stream.
Fixed header chunk key_len + 11 + 16 Nonce 0: type, timestamp, the request salt and the first payload length.
First payload chunk len + 16 Nonce 1. Always present, possibly empty.
Records repeated AEAD(len) followed by AEAD(data), nonces 2, 3, …

The fixed response header (response_fixed_len(key_len) = key_len + 11 bytes of plaintext):

Field Size Meaning
Type 1 HEADER_TYPE_SERVER = 1. Anything else fails with shadowsocks-2022: bad header type (expected server).
Timestamp 8 Unix seconds, big-endian u64. Checked against the 30-second window.
Request salt key_len The salt of the request this response answers.
Length 2 Big-endian u16: the plaintext length of the first payload chunk.
pub fn build_response(
method: Method,
psk: &[u8],
request_salt: &[u8],
first_payload: &[u8],
out: &mut Staging<'_>,
) -> io::Result<ChunkEncoder>;
pub fn parse_response_fixed(fixed: &[u8], key_len: usize) -> io::Result<(u64, &[u8], usize)>;

build_response draws the response salt and keys the downlink encoder the same way. It refuses a first payload longer than a u16 with shadowsocks-2022: first payload longer than a chunk may carry. It checks the room for the salt, the fixed header, the first payload and two tags before it stages anything (shadowsocks: staging room below the frame). Then it stages the salt, seals the fixed header and the first payload, and returns the encoder positioned for the records. parse_response_fixed returns the timestamp (unchecked), the echoed salt and the first payload’s length.

The echoed request salt binds the response to the request. The client compares it with helpers::crypto::ct_eq, a constant-time comparison, and fails with shadowsocks-2022: response salt does not match request salt on any difference.

pub fn now_unix() -> u64;
pub fn check_timestamp(epoch: u64) -> io::Result<()>;
pub fn check_timestamp_at(epoch: u64, now: u64) -> io::Result<()>;

check_timestamp_at fails with shadowsocks-2022: bad timestamp (InvalidData) when |now - epoch| exceeds 30 seconds; a difference of exactly 30 seconds passes. check_timestamp checks against now_unix. Both directions check the window:

  • The server core checks the request’s fixed header against the clock it was constructed with, a fn() -> u64. Ss2022Core::with_system_clock passes now_unix; the tests pass a fixed time.
  • The client codec checks the response’s fixed header against now_unix.

now_unix returns 0 if the system clock reads before the Unix epoch, which then fails the check. Both header builders stamp their header with now_unix.

A multi-user server listens with one identity PSK (iPSK) and knows a list of user PSKs (uPSKs). The client proves which user it is before any AEAD chunk:

  1. For each hop in its chain, the client derives identity_subkey(current_psk, request_salt), takes eih_hash(next_psk), and encrypts that 16-byte hash as one AES block. The chain is identity_keys ++ [psk], so with a single iPSK there is one block: the uPSK’s hash under the iPSK’s subkey.
  2. The client derives the session subkey from the uPSK, not from the iPSK.
  3. The server reads the salt and one 16-byte block, decrypts it with decrypt_eih(identity_psk, salt, key_len, &mut block), and looks the hash up in its Validator.
  4. A known hash yields the user’s uPSK, label and payload. The server keys the uplink from that uPSK and continues with the fixed header. An unknown hash rejects the request with shadowsocks-2022: unknown identity, a PermissionDenied error (see Refusing a request).
pub fn decrypt_eih(
identity_psk: &[u8],
salt: &[u8],
key_len: usize,
eih: &mut [u8; 16],
) -> io::Result<()>;

each_identity_header_names_the_next_key_down_the_chain builds a request with a two-key chain for both AES methods. It checks that each block decrypts, under its key, to the identity hash of the next key down the chain, and that past the blocks the uPSK opens an ordinary request.

#[derive(Clone)]
pub enum BlockCipher {
Aes128(Box<aes::Aes128>),
Aes256(Box<aes::Aes256>),
}
impl BlockCipher {
pub fn try_new(key: &[u8]) -> io::Result<Self>;
pub fn encrypt_block(&self, block: &mut [u8]);
pub fn decrypt_block(&self, block: &mut [u8]);
}

The EIH is a single raw AES block, so the identity subkey must be an AES key. BlockCipher::try_new picks AES-128 or AES-256 from the key length (16 or 32 bytes) and refuses any other with invalid AES key length (InvalidData). encrypt_block and decrypt_block transform the first 16 bytes of the slice and do nothing to a shorter slice. SIP022 defines the EIH for the AES-GCM methods only, so a multi-user server needs one of them.

pub struct Validator<T> {
pub identity_psk: Vec<u8>,
pub hash_to_user: HashMap<[u8; 16], usize>,
pub users: Vec<(Vec<u8>, CompactString, Arc<T>)>,
}
impl<T> Validator<T> {
pub fn from_config(config: &Ss2022ServerConfig<T>) -> io::Result<Option<Self>>;
pub fn resolve(&self, hash: &[u8; 16]) -> Option<(Vec<u8>, CompactString, Arc<T>)>;
}

from_config returns Ok(None) for a configuration without users (single-PSK mode). Otherwise it takes the config’s psk as identity_psk and builds hash_to_user from eih_hash(uPSK) to an index into users, whose entries are (uPSK, email, payload). resolve is one hash-map lookup and clones the entry.

Users that share a PSK share an identity hash, and the lookup could only ever find one of them. from_config keeps the first user of each hash and logs a warning for each one it leaves out:

shadowsocks-2022: users "alice" and "carol" share a key; only "alice" is matched

users_sharing_a_psk_resolve_to_the_first builds alice, bob and carol, with alice and carol sharing a key: the table holds two users, and alice’s key resolves to alice. The supervisor also refuses two users of one inbound who present the same PSK (validate_admission, see Wiring).

The outbound password is iPSK:...:uPSK. The front ends split it on :, decode and normalise every segment, pop the last segment as the session PSK, and pass the rest as identity_keys:

impl Ss2022Stream {
pub const BUF_SIZE: usize = MAX_RECORD_LEN;
pub fn new(
method: Method,
psk: Vec<u8>,
identity_keys: Vec<Vec<u8>>,
dest: &Destination,
) -> Self;
}
Password psk identity_keys EIH blocks on the wire
uPSK uPSK empty none
iPSK:uPSK uPSK [iPSK] 1
iPSK1:iPSK2:uPSK uPSK [iPSK1, iPSK2] 2

An empty segment (a::b, or an empty password) decodes to zero bytes and fails with shadowsocks-2022: PSK too short (0 < <key_len>).

#[derive(Clone)]
pub struct Ss2022User {
pub psk: Vec<u8>,
pub email: String,
}
impl Ss2022User {
pub fn new(method: Method, psk: Vec<u8>) -> io::Result<Self>;
pub fn from_password(method: Method, password: &str, email: String) -> io::Result<Self>;
}
pub struct Ss2022ServerConfig<T> {
pub method: Method,
pub psk: Vec<u8>,
pub psk_data: Arc<T>,
pub users: Vec<(Ss2022User, Arc<T>)>,
}
impl<T> Ss2022ServerConfig<T> {
pub fn new(method: Method, psk: Vec<u8>, data: Arc<T>) -> io::Result<Self>;
pub fn from_password(method: Method, password: &str, data: Arc<T>) -> io::Result<Self>;
}

psk has two meanings, chosen by whether users is empty:

Mode users psk is Session PSK Flow user
Single-PSK empty the session PSK psk empty username, psk_data
Multi-user non-empty the identity PSK (iPSK) the matched user’s psk the user’s email as username, that user’s payload
  • Ss2022User::new normalises raw PSK bytes and leaves email empty; from_password decodes a base64 PSK, normalises it and takes a label.
  • Ss2022ServerConfig::new normalises the PSK and starts with no users; from_password decodes first.
  • Ss2022User has a hand-written Debug that shows the label and never the PSK (debug_shows_the_label_but_never_the_psk). Ss2022ServerConfig implements Clone for any T, and its Debug shows the method and the users’ labels.

T is the per-user payload carried into the Flow. Every front end serves Shadowsocks 2022 through etemenanki-supervisor, which uses T = Principal; the tests use (). The struct fields are public. The tests and supervisor/src/build/inbound.rs build Ss2022User values directly, so code that fills the fields itself must supply keys of exactly key_len() bytes to stay compatible with other SIP022 implementations.

pub struct Ss2022Core<T> {
config: Arc<Ss2022ServerConfig<T>>,
validator: Option<Arc<Validator<T>>>,
sniff: bool,
source: Option<IpAddr>,
now: fn() -> u64,
timing: Timing,
state: State,
session: Option<(Vec<u8>, NetworkUser<T>)>,
request_salt: Vec<u8>,
decoder: Option<ChunkDecoder>,
encoder: Option<ChunkEncoder>,
prefix: SniffPrefix,
flow: Option<Flow<T>>,
}
impl<T> Ss2022Core<T> {
pub const BUF_SIZE: usize = MAX_RECORD_LEN;
pub fn new(
config: Arc<Ss2022ServerConfig<T>>,
validator: Option<Arc<Validator<T>>>,
sniff: bool,
source: Option<IpAddr>,
now: fn() -> u64,
) -> Self;
pub fn with_system_clock(
config: Arc<Ss2022ServerConfig<T>>,
validator: Option<Arc<Validator<T>>>,
sniff: bool,
source: Option<IpAddr>,
) -> Self;
pub fn is_established(&self) -> bool;
}
impl<T: Send + Sync + 'static> ProxyCoreDecode for Ss2022Core<T> {
type Key = Single;
type Target = Flow<T>;
type Error = io::Error;
type TransportAddr = ();
const STAGING_RESERVE: usize = 32 + 1 + 8 + 32 + 2 + 2 * TAG_LEN + RECORD_OVERHEAD + 115;
// ...
}
Field Role
config, validator The server key and, in multi-user mode, the identity lookup this connection was started with.
sniff, source Whether to sniff IP targets; the client address copied into the Flow.
now The clock the request timestamp is checked against.
timing The one deadline, armed per phase (protocols/src/core/mod.rs → Timing).
session The session PSK and the user it belongs to, once the salt (and EIH) are in.
request_salt The request salt, recorded in the replay filter and echoed in the response.
decoder The uplink: the header chunks, then records.
encoder The downlink, once the response header is out.
prefix, flow The sniff prefix and the Flow waiting for Effect::Open.

The core is generic over the user payload T, has one outbound (Single), and runs over a byte stream (TransportAddr = ()). is_established is true once Timing reaches the relay phase; the supervisor’s serve loop reads it through its Established trait.

enum State {
Salt,
Fixed,
Variable(usize),
Sniff,
Relay(Passthrough<Single>),
Rejected(io::Error),
Done,
}
stateDiagram-v2
  [*] --> Salt
  Salt --> Fixed: salt and EIH resolved, uplink keyed
  Salt --> Rejected: unknown identity
  Fixed --> Variable: fixed chunk opened, timestamp in window, salt new
  Fixed --> Rejected: tag, type, timestamp or replay fails
  Variable --> Relay: flow opened
  Variable --> Sniff: sniffing an IP target, verdict More
  Sniff --> Relay: host found, budget spent, deadline or EOF
  Rejected --> [*]: client EOF or handshake deadline
  Salt --> Done: TransportEof
  Fixed --> Done: TransportEof
  Variable --> Done: TransportEof
  Relay --> [*]: both halves closed, idle or outbound gone
  Done --> [*]

Every Event::Transport and Event::Outbound first calls Timing::touch, which arms HANDSHAKE_TIMEOUT on the first byte event and refreshes RELAY_IDLE_TIMEOUT while relaying. Each handshake state consumes only a whole unit and returns Ok(0) until it has one:

State Waits for Does
Salt key_len bytes, plus 16 with a validator Resolves the session PSK and user: the single PSK, or decrypt_eih and Validator::resolve. Keys the uplink ChunkDecoder with session(method, psk, salt) and remembers the request salt. An unknown identity moves to Rejected.
Fixed REQUEST_FIXED_LEN + TAG_LEN = 27 bytes open_fixed: opens the chunk in place, parses it, checks the timestamp against (self.now)(), records the salt in the replay filter, and stores var_len. Any failure moves to Rejected.
Variable(var_len) var_len + TAG_LEN bytes Opens the chunk, parses the destination and payload range, builds the Flow, then opens the flow or starts sniffing.
Sniff whole records Feeds each record’s plaintext to SniffPrefix::push until the verdict is not More, then opens the flow with the sniffed result.
Relay whole records Clears the sniff prefix, then pushes one Effect::Forward per non-empty record, with ranges into the transport slice.
Rejected nothing Consumes every byte and stages nothing.
Done nothing Consumes nothing.

A server that never received a whole unit has decrypted nothing, so the runtime can hand the same bytes back safely. The Fixed and Variable states open their chunks only once data.get_mut(..len) returns the whole chunk; the record states rely on ChunkDecoder’s remembered length. single_psk_request_opens_with_its_first_payload feeds the first 40 bytes of an AES-256 request and expects only the 32-byte salt consumed, then the rest and expects Open and a Forward of hello.

A request that fails before it authenticates is not closed at once. The core moves to State::Rejected holding the error, consumes all the bytes it was given, and from then on swallows whatever the client sends, stages nothing and opens nothing. The connection fails with the stored error only at one of two points:

  • Event::TransportEof, when the client closes;
  • Event::Deadline with Expired::Handshake, when the handshake deadline armed by the client’s first byte passes. The core returns the rejection here, not the generic handshake timeout.

The module docs give the reason: the moment of the close does not tell a prober how many bytes the server needed to decide. These failures reject:

Where Failure Stored error
Salt (multi-user) The EIH names no user. PermissionDenied: shadowsocks-2022: unknown identity
Fixed The fixed chunk does not open under the session key. InvalidData: shadowsocks: invalid AEAD tag
Fixed The header type is not 0. InvalidData: shadowsocks-2022: bad header type (expected client)
Fixed The timestamp is outside the window. InvalidData: shadowsocks-2022: bad timestamp
Fixed The salt is already in the replay filter. InvalidData: shadowsocks-2022: replayed request salt

core.rs → denied builds the unknown identity with kind PermissionDenied. That is the kind every core uses for a refused credential, and for nothing else before it is established (protocols/src/core/mod.rs). The supervisor’s drive reports such an error to its guard with Report::failed, as a refused credential from the connection’s client (supervisor/src/serve.rs, supervisor/src/guard.rs).

The single-key server therefore decides after the fixed chunk, at key_len + 27 bytes, and the multi-user server after the EIH, at key_len + 16. A client that sends fewer bytes waits in Salt or Fixed and meets the same two ends: its close is a plain Finish, and the deadline is client did not complete its request in time. Either way the server sends nothing back and does not close first.

Failures after the request has authenticated still end the connection at once: a variable chunk or record that does not open, a malformed address or padding, a staging error.

a_wrong_key_is_drained_until_the_handshake_deadline sends a request under the wrong key and 4096 more bytes, expects every byte consumed and no effects, and at the deadline expects InvalidData rather than TimedOut. no_byte_count_makes_the_server_close_first feeds junk of 1, threshold − 1, threshold, threshold + 1 and 4096 bytes to a single-key server (threshold 59) and a multi-user server (threshold 48), and expects neither effects nor staged bytes for any of them. eih_selects_the_user_and_a_stale_timestamp_is_refused expects an unknown identity and a clock of 1_000 to be swallowed and then refused at TransportEof with the matching error, and the unknown identity to be PermissionDenied.

A request is accepted while its timestamp is within 30 seconds of the server’s clock, so a recorded request could otherwise be replayed for up to a minute. SIP022 has a server remember the salt of every request it accepted for that long and refuse a repeat. replay.rs → SaltFilter does that:

pub(crate) const REMEMBER: Duration = Duration::from_secs(60);
pub(crate) struct SaltFilter { /* two generations of salts */ }
impl SaltFilter {
pub(crate) fn insert(&self, salt: &[u8]) -> bool;
}
  • When a salt is recorded. open_fixed inserts the request salt only after the fixed chunk has opened, parsed and passed the timestamp check. A client without the key therefore cannot fill the filter; this is the order ss-rust settled on in its issue #442. insert returns false for a salt already recorded, and open_fixed turns that into shadowsocks-2022: replayed request salt, which rejects the request as above.
  • How long it is kept. The filter holds two generations of salts, each REMEMBER (60 s) long. A salt goes into the current generation. When an insert finds that the current generation has run for REMEMBER or more, the current generation becomes the previous one and the old previous one is dropped. If it has run for twice REMEMBER or more, both are dropped. A new current generation starts at that insert. A salt found in either generation is a repeat. A salt is therefore kept at least REMEMBER and at most twice that.
  • Keys. Each salt is stored zero-padded to 32 bytes, the longest SIP022 salt, so a 16-byte salt is a key of its own. A salt longer than 32 bytes is refused (insert returns false) rather than let through, since the filter cannot hold it.

a_replayed_request_is_refused feeds one request to a core, which opens the flow, and the same bytes to a second core, which rejects them with replayed request salt.

Sniffing runs only if the inbound enables it and sniff::worth_sniffing accepts the destination, that is, when the destination is an IP address. Then:

  • The initial payload from the variable header goes into SniffPrefix. If the collector wants more, the core enters State::Sniff and Timing::enter(Phase::Sniff) arms SNIFF_TIMEOUT (300 ms).
  • In State::Sniff each record’s plaintext goes into the prefix. The prefix takes at most SNIFF_LIMIT (4 KiB) in total.
  • Once the verdict is not More, open_sniffed copies the result into flow.sniffed and opens the flow: it enters Phase::Relay, which pushes SetDeadline(RELAY_IDLE_TIMEOUT), then pushes Effect::Open and Effect::ForwardHeld over everything collected. It then pushes Effect::Forward for any bytes of the last chunk or record that the prefix did not take.
  • Event::Deadline with Expired::Sniff, or Event::TransportEof, opens the flow with whatever the prefix holds.

Without sniffing, open enters Phase::Relay, then pushes Effect::Open and, if the initial payload is non-empty, an Effect::Forward over its range in the variable chunk, with no copy. Opening moves the core to State::Relay(Passthrough::new(Single)), and is_established() becomes true. The next Transport or Outbound event in relay calls SniffPrefix::clear, after the runtime has applied the ForwardHeld that referenced the held bytes. sniffing_reads_records_until_a_host_appears splits an HTTP Host header across the request and one record. It expects SNIFF_TIMEOUT armed after the request, then, in this order, the relay idle deadline, an Open with the sniffed domain example.com and a ForwardHeld of all 41 collected bytes.

Either way the deadline is pushed before the Open. The reason is at protocols/src/core/mod.rs → Timing::enter: a forward queued after an open waits until the outbound has connected, and so would a deadline queued after that forward. The previous phase’s deadline would then stay armed during the connect; after sniffing, that is the 300 ms window, which could end the flow as idle.

The core writes nothing until the target answers. The first Event::Outbound in relay calls start_response with the first min(len, MAX_PACKET_SIZE) bytes as the first payload. start_response calls build_response(method, session_psk, request_salt, first, staging) and keeps the returned ChunkEncoder. The rest of that event, and every later event, goes out as records through seal_record in MAX_PACKET_SIZE slices. Event::Outbound before relay is acknowledged and dropped: no outbound exists yet to produce it.

STAGING_RESERVE is 256 bytes. It adds the largest response header without its payload (a 32-byte salt, 1 + 8 + 32 + 2 bytes of fixed header and two tags: 107 bytes), one record’s overhead (34) and 115 bytes of slack. The runtime delivers an outbound read of n bytes only with STAGING_RESERVE + n bytes of staging free, so the first downlink event can stage the header and a following record.

If the target closes without sending anything, Event::OutboundEof stages a response with an empty first payload before the half-close, so the client can complete its response read before the end of stream. (Ss2022Stream itself would also accept a bare end of stream before any response byte: the client runtime treats an end of file with no unparsed bytes as clean, and one inside a frame as upstream closed inside a frame.) a_target_that_never_answers_still_gets_an_empty_response_header expects a 107-byte response for aes-256 (salt, fixed chunk, empty payload chunk) and ShutdownTransport.

sequenceDiagram
  participant C as Ss2022Stream
  participant S as Ss2022Core
  participant T as Target
  C->>S: salt, EIH, fixed chunk, variable chunk
  Note over S: resolve user, check timestamp, record salt, parse address
  S->>T: Effect::Open, then Forward of initial payload
  C->>S: records
  S->>T: Effect::Forward per record
  T-->>S: first downlink bytes
  S-->>C: response salt, fixed chunk with request salt, first payload
  T-->>S: more bytes
  S-->>C: records

the_response_opens_with_the_codec_and_binds_the_request_salt sends a request from a real Ss2022Stream, feeds the core two outbound reads, and decodes everything the core staged back through the codec.

Event In Salt, Fixed, Variable In Rejected In Sniff In Relay
TransportEof State::Done, Effect::Finish Fails with the stored error Opens the flow, then Passthrough::on_transport_eof Passthrough::on_transport_eof: shuts the outbound’s write half down
OutboundEof ignored ignored ignored Empty response header if none was sent, then Passthrough::on_outbound_eof
ConnectFailed, OutboundError logged at debug, nothing else logged at debug, nothing else logged at debug, nothing else Logged at debug, then Passthrough::on_outbound_gone: shut the transport down and finish
Deadline Expired::Handshake returns handshake_timed_out() (client did not complete its request in time, TimedOut) Expired::Handshake returns the stored error Expired::Sniff opens the flow Expired::Idle: Timing has already pushed Effect::Finish
Connected, Datagram, SendFailed, TransportDatagram, TransportSendFailed ignored ignored ignored ignored

The debug line for a lost outbound is shadowsocks-2022: outbound gone: <error>. The outbound events can only arrive after Effect::Open, which moves the core to Relay, so in practice the other columns never see them.

An Err from handle ends the connection. The runtime wraps a core error as proxy core: <error>, and supervisor/src/serve.rs → serve_connection logs it at debug as shadowsocks-2022 connection from <source> ended: proxy core: <error>, where <source> is the client IP formatted as an Option (Some(…)). Until the core is established, the supervisor’s drive also waits at most HANDSHAKE_TIMEOUT for each runtime step, and otherwise fails with inbound handshake timed out after 10s. A client that never sends a byte produces no runtime event and so never reaches the core’s own deadline. See Listeners and the serve loop.

shadowsocks-2022: no session and shadowsocks-2022: the connection was not rejected guard states the state machine does not reach.

pub struct Ss2022Stream {
method: Method,
psk: Vec<u8>,
identity_keys: Vec<Vec<u8>>,
dest: Destination,
request_salt: Vec<u8>,
encoder: Option<ChunkEncoder>,
down: Down,
}
impl ProxyCoreEncodeHandshake for Ss2022Stream {
type Target = Destination;
type Error = io::Error;
const STAGING_RESERVE: usize = 2048;
fn start(&mut self, out: &mut Staging<'_>) -> io::Result<Handshake>;
fn reply(&mut self, _: &mut [u8], _: &mut Staging<'_>) -> io::Result<Reply>;
fn finish(&mut self, _: &mut Staging<'_>) -> io::Result<()>;
}
impl ProxyCoreEncode for Ss2022Stream {
fn seal(&mut self, plain: &[u8], out: &mut Staging<'_>) -> io::Result<usize>;
fn open(&mut self, wire: &mut [u8]) -> io::Result<Opened>;
}
  • start calls build_request with an empty initial payload, keeps the encoder and the request salt, and returns Handshake::Done: plaintext may follow at once, with no round trip. Because the payload is empty, the request always carries 1 to 900 bytes of padding. STAGING_RESERVE (2048) covers the request header with full padding and an identity chain, or one record’s overhead.
  • reply is never called for a Done handshake and returns shadowsocks-2022: no handshake reply if it is. finish stages nothing: SIP022 has no close frame, so the client runtime half-closes the transport.
  • seal takes at most MAX_PACKET_SIZE bytes and writes one record with seal_record. The client runtime offers at most room - STAGING_RESERVE bytes, so the record always fits; a short room would be a runtime bug and returns shadowsocks: staging room below the frame. Sealing before start returns shadowsocks-2022: sealed before start.

request_header_then_records_and_a_bound_response decodes the codec’s request with the header parsers and a ChunkDecoder, and checks that the header carries no payload and a sealed record follows. It then feeds a response in pieces (NeedMore on 10 bytes), expects firstsecond from the first payload and a record, and expects a response bound to another salt to fail.

enum Down {
Salt,
Fixed(ChunkDecoder),
FirstPayload(ChunkDecoder, usize),
Records(ChunkDecoder),
}
stateDiagram-v2
  [*] --> Salt
  Salt --> Fixed: key_len bytes, decoder keyed from the response salt
  Fixed --> FirstPayload: type, timestamp and echoed salt checked
  FirstPayload --> Records: first payload opened
  Records --> Records: one record per call

open takes the state out with std::mem::replace and puts it back on every NeedMore, so a partial read leaves the codec where it was. Each step returns Opened::Frame:

State Consumes plain
Salt key_len empty
Fixed response_fixed_len(key_len) + TAG_LEN empty
FirstPayload first_len + TAG_LEN the first payload, possibly empty
Records one record the record’s data, possibly empty

The codec never returns Opened::End: the stream ends at the transport’s end of file. After an error the codec is left in Down::Salt; the runtime tears the connection down and does not call it again. The client runtime wraps every codec error as InvalidData.

  • supervisor/src/build/users.rs → credential_kind maps a Shadowsocks 2022 inbound to CredentialKind::Ss2022Psk.

  • supervisor/src/build/validate.rs → validate_admission refuses two users of one inbound who present the same PSK, inbound <tag>: users <a> and <b> present the same credential, and a user PSK that is too short, inbound <tag>: user <name>: shadowsocks-2022: PSK too short (<len> < <key_len>).

  • supervisor/src/build/inbound.rs → user_table builds the table:

    1. Ss2022ServerConfig::new(method, psk, Principal::anonymous()) for the server key;
    2. for each admitted user whose credential is a 2022 PSK, an Ss2022User whose psk is normalise_psk(method, user_psk) and whose email is principal.label(), paired with that user’s Arc<Principal>;
    3. Validator::from_config, wrapped in an Arc.

    The result is an Ss2022Users { config, validator }, kept in StreamProtocol::Ss2022(ArcSwap<Ss2022Users>) (supervisor/src/topology/inbound/mod.rs). The label is the front end’s name for the user: the config email in etemenanki-app, and the panel user id in decimal in katana. The users are added in the order of the supervisor’s admissions map, a BTreeMap sorted by the front end’s user id.

  • The spec is InboundProtocolSpec::Ss2022 { method, psk, transport }. Like every protocol that takes a transport, the inbound is built with the transport its InboundTransportSpec describes, so a server offers Shadowsocks 2022 over plain TCP, TLS, WebSocket or gRPC, with or without TLS (REALITY is VLESS’s alone), and validate_inbound holds that transport to the shared rules. Only the TCP side rides the transport: the module has no datagram path. shadowsocks_runs_over_a_transport (supervisor/tests/unit/validate.rs) pins the shapes.

  • supervisor/src/serve.rs → serve_connection loads the table (users.load_full()) and runs drive::<{ Ss2022Core::<Principal>::BUF_SIZE }, _, _> with the closure || Ss2022Core::with_system_clock(users.config.clone(), users.validator.clone(), sniff, source) and the connection’s Report. drive calls the closure once to build the runtime; a core handed in would stay in drive’s future beside the runtime’s copy. Each connection therefore starts with the table that is current when it is accepted. source is the socket’s peer, or the client a PROXY protocol v2 header names when the inbound reads one, or, for a socket a relay on the same host handed over, the client the header sent with it names. How a user change reaches sessions that are already open is on Users, principals and sessions.

  • supervisor/src/build/outbound.rs → build_outbound builds an Ss2022Stream per flow from the spec’s method, psk and identity_psks, over transport_connector, so the client can run over TLS, WebSocket or gRPC. The client runtime buffer is SS2022_BUF = Ss2022Stream::BUF_SIZE (supervisor/src/topology/outbound/mod.rs), and Outbound::connect_datagram refuses UDP with shadowsocks-2022 carries no datagrams.

Invariant Enforced by Pinned by
Each direction has its own salt, subkey and nonce counter; the counter starts at zero and spans header chunks and records. session keys a fresh Aead per salt; one ChunkEncoder or ChunkDecoder per direction request_and_response_round_trip_under_every_method (protocols/tests/unit/ss_2022/protocol.rs), bare_chunks_and_records_share_one_counter (protocols/tests/unit/ss_aead.rs)
A response is accepted only if it echoes the request’s salt. parse_response_fixed plus ct_eq in Ss2022Stream::open request_header_then_records_and_a_bound_response (protocols/tests/unit/ss_2022/codec.rs)
A header more than 30 seconds from the clock is refused. check_timestamp_at in open_fixed and in Down::Fixed eih_selects_the_user_and_a_stale_timestamp_is_refused (protocols/tests/unit/ss_2022/core.rs), request_and_response_round_trip_under_every_method
A request salt is accepted once while it is remembered, and only authenticated requests are recorded. SaltFilter::insert after the fixed chunk and the timestamp check a_replayed_request_is_refused (core.rs); a_salt_is_accepted_once, a_salt_outlives_one_generation_and_goes_with_the_next, a_long_quiet_spell_clears_both_generations, an_overlong_salt_is_refused (protocols/tests/unit/ss_2022/replay.rs)
A request that fails before it authenticates opens nothing, and the server does not close first. State::Rejected swallows every byte and fails only at the client’s EOF or the handshake deadline a_wrong_key_is_drained_until_the_handshake_deadline, no_byte_count_makes_the_server_close_first, eih_selects_the_user_and_a_stale_timestamp_is_refused (core.rs)
No bytes are decrypted twice when the runtime re-presents an unconsumed slice. Whole-chunk checks in the Fixed and Variable states and in Down; ChunkDecoder::pending_len for records a_record_presented_again_is_never_decrypted_twice (ss_aead.rs), single_psk_request_opens_with_its_first_payload (a 40-byte slice yields only the salt), request_header_then_records_and_a_bound_response (NeedMore on a partial response)
A multi-user server selects the user by the EIH. decrypt_eih and Validator::resolve in on_salt eih_selects_the_user_and_a_stale_timestamp_is_refused, each_identity_header_names_the_next_key_down_the_chain (protocol.rs), ss2022_multi_user_new_server_vs_new_client
One identity hash, one user. Validator::from_config keeps the first user of each hash users_sharing_a_psk_resolve_to_the_first (protocols/tests/unit/ss_2022/users.rs)
A header that does not fit stages nothing. Room and length checks at the top of build_request and build_response; seal_record checks before sealing a_header_that_does_not_fit_is_refused_and_nothing_is_staged (protocol.rs), a_refused_seal_stages_nothing_and_keeps_the_counter (ss_aead.rs)
Every frame a peer may send fits the runtime buffer whole. BUF_SIZE = MAX_RECORD_LEN on both sides, the cap the buffers grow to ss2022_server_takes_full_size_chunks_from_a_raw_client, ss2022_client_takes_full_size_chunks_from_a_raw_server (protocols/tests/pipeline/shadowsocks.rs)
The client always sees a response header, even from a silent target. start_response(&[]) on OutboundEof a_target_that_never_answers_still_gets_an_empty_response_header (core.rs)
Sniffed bytes are forwarded once, ahead of the rest. SniffPrefix plus Effect::ForwardHeld, with took offsetting the next Forward sniffing_reads_records_until_a_host_appears (core.rs)
The relay idle deadline is armed before the flow opens. open calls Timing::enter(Phase::Relay) before it pushes Effect::Open sniffing_reads_records_until_a_host_appears (core.rs)
A user’s PSK never appears in Debug output of these types. Hand-written Debug for Ss2022User and Ss2022ServerConfig debug_shows_the_label_but_never_the_psk (users.rs)
Name Value Where Meaning
Ss2022Core::BUF_SIZE MAX_RECORD_LEN = 65 569 bytes core.rs Cap on the server runtime’s buffers: the largest frame a client may send.
SS2022_BUF Ss2022Stream::BUF_SIZE = MAX_RECORD_LEN supervisor/src/topology/outbound/mod.rs Cap on the client runtime’s buffers for Ss2022Stream: the largest frame a server may send.
Ss2022Core::STAGING_RESERVE 256 bytes core.rs Room guaranteed per event beyond the payload: the response header without its payload, one record’s overhead and slack.
Ss2022Stream::STAGING_RESERVE 2048 bytes codec.rs Room for the request header with full padding and an identity chain, or one record’s overhead.
MAX_PACKET_SIZE 65 535 bytes crypto.rs Largest plaintext per chunk or record.
MAX_RECORD_LEN 65 569 bytes crypto.rs A full record: MAX_PACKET_SIZE plus 34 bytes of overhead.
MAX_PADDING_LENGTH 900 bytes protocol.rs Upper bound of the padding build_request writes.
Timestamp window ±30 s check_timestamp_at Inclusive.
REMEMBER 60 s replay.rs Length of one replay-filter generation; a salt is kept between one and two of them.
HANDSHAKE_TIMEOUT 10 s protocols/src/core/mod.rs The core’s deadline from the first byte event until the request is parsed, and until a rejected connection fails; the supervisor’s drive also uses it as the per-step wait until the core is established.
SNIFF_TIMEOUT 300 ms protocols/src/sniff/mod.rs Sniffing window after the request.
SNIFF_LIMIT 4 KiB protocols/src/sniff/mod.rs Bytes the sniffer inspects across records.
RELAY_IDLE_TIMEOUT 300 s protocols/src/core/mod.rs Relay with no bytes in either direction.

The buffers are capped at MAX_RECORD_LEN because ss-rust and sing seal a whole read of up to 0xFFFF bytes into one record, and every other frame is smaller: the request’s variable header chunk carries at most 0xFFFF bytes plus its tag, and the response’s first payload chunk likewise. A buffer starts small and doubles while a frame is still arriving, up to the cap (concepts/src/buffer.rs), so it always holds the next frame whole. ss2022_server_takes_full_size_chunks_from_a_raw_client sends a variable header of exactly 0xFFFF bytes and a full record to the server core; ss2022_client_takes_full_size_chunks_from_a_raw_server answers the client codec with a full first payload and a full record.

etemenanki-app lowers and validates the configuration at load time, so etemenanki-app --test -c <file> shows these errors without starting a listener. The texts below are what the pinned binary prints after configuration invalid: :

Condition Error
Unknown 2022- method, or wrong case inbound <tag>: unknown shadowsocks-2022 method "<name>" (outbound <tag>: … for an outbound)
Server password not valid base64 inbound <tag>: decode PSK: <base64 error>, for example Invalid symbol 32, offset 3.
Server PSK shorter than the key length inbound <tag>: shadowsocks-2022: PSK too short (16 < 32)
User password not valid base64 inbound <tag>: users[<i>]: decode PSK: <base64 error>
User PSK shorter than the key length inbound <tag>: user <name>: shadowsocks-2022: PSK too short (16 < 32)
Two users with the same PSK inbound <tag>: users <a> and <b> present the same credential
A user without email inbound <tag>: users[<i>] has no email; a user of this inbound is named by its email
Two users with the same email inbound <tag>: users[<i>] and users[<j>] are both named "<email>"
Outbound segment not valid base64 outbound <tag>: decode PSK: <base64 error>
Outbound segment too short, or empty outbound <tag>: shadowsocks-2022: PSK too short (0 < 32)

A PSK longer than the key length is accepted and folded, as described under PSK decoding.

  1. Changing the headers. build_request and build_response are the only writers, and parse_request_fixed, parse_request_variable and parse_response_fixed the only readers; the core and the codec call them. Keep the room check ahead of the first put, so that a refused header stages nothing, and keep request_and_response_round_trip_under_every_method and a_header_that_does_not_fit_is_refused_and_nothing_is_staged passing.

  2. Adding a refusal before authentication. Route it through reject, so that the connection still ends only at the client’s EOF or the handshake deadline. no_byte_count_makes_the_server_close_first must keep passing for both modes.

  3. Touching the replay filter. Keep the insert after the fixed chunk and the timestamp check, so that only authenticated requests are recorded, and keep a salt remembered for at least REMEMBER, the span of timestamps the window accepts.

  4. Changing buffer sizes. Both BUF_SIZE values must hold a full record, MAX_RECORD_LEN, or a peer that seals a whole 0xFFFF-byte read fails the connection. The two full-size pipeline tests pin that.

  5. Changing the users API. The supervisor builds Ss2022ServerConfig, Ss2022User and Validator in user_table; a change to these public types is a SemVer change for etemenanki-protocols and needs the supervisor updated with it.

Unit tests are compiled into the library through #[path] modules. The pipeline tests run the server core and the client codec over real sockets.

Terminal window
cargo test -p etemenanki-protocols --lib ss_2022
cargo test -p etemenanki-protocols --lib ss_aead
cargo test -p etemenanki-protocols --test pipeline ss2022
Test File What it pins
request_and_response_round_trip_under_every_method protocols/tests/unit/ss_2022/protocol.rs For all three methods, a request and a server’s read of it agree on destination and payload, a record follows on the same counter, the timestamp passes now and fails 60 s later, and the response echoes the request salt and carries its first payload (after sing’s service_test.go).
each_identity_header_names_the_next_key_down_the_chain same With a two-key chain, each EIH block decrypts to the identity hash of the next key; past the blocks, the uPSK opens an ordinary request.
a_header_that_does_not_fit_is_refused_and_nothing_is_staged same A variable header over 0xFFFF bytes is InvalidInput; a 64-byte staging area refuses a request and a response; nothing is staged.
single_psk_request_opens_with_its_first_payload protocols/tests/unit/ss_2022/core.rs The core takes only the salt from a 40-byte slice, then opens and forwards the initial payload in place.
eih_selects_the_user_and_a_stale_timestamp_is_refused same The username comes from the matched user (bob); an unknown identity and a clock of 1_000 are swallowed, then refused at TransportEof; the unknown identity is PermissionDenied, a refused credential.
a_wrong_key_is_drained_until_the_handshake_deadline same A wrong key and 4096 more bytes are swallowed; the deadline returns InvalidData, not TimedOut.
no_byte_count_makes_the_server_close_first same Junk around the single-key (59) and multi-user (48) thresholds gives no effects and nothing staged.
a_replayed_request_is_refused same The same request opens once and is refused by a second core with replayed request salt.
sniffing_reads_records_until_a_host_appears same An HTTP Host split across the header and a record is sniffed; the relay deadline comes before the Open, and ForwardHeld covers all 41 collected bytes.
the_response_opens_with_the_codec_and_binds_the_request_salt same The core’s response and records decode through Ss2022Stream.
a_target_that_never_answers_still_gets_an_empty_response_header same OutboundEof without downlink bytes stages a 107-byte response (aes-256) and ShutdownTransport.
request_header_then_records_and_a_bound_response protocols/tests/unit/ss_2022/codec.rs The codec’s request parses with no payload in the header; NeedMore on a partial response; the first payload and a record concatenate; a response bound to another salt fails.
a_salt_is_accepted_once protocols/tests/unit/ss_2022/replay.rs A repeat is refused; a 16-byte salt is a key of its own.
a_salt_outlives_one_generation_and_goes_with_the_next same Salts inserted at 0 s and 59 s are still refused at 60 s and 119 s, and accepted again at 120 s.
a_long_quiet_spell_clears_both_generations same Salts inserted at 0 s and 61 s are accepted again at 181 s.
an_overlong_salt_is_refused same A 33-byte salt is refused.
debug_shows_the_label_but_never_the_psk protocols/tests/unit/ss_2022/users.rs Ss2022User’s Debug shows alice, never the key.
users_sharing_a_psk_resolve_to_the_first same alice, bob, carol with alice and carol sharing a key: two entries, and the shared key resolves to alice.
records_round_trip_under_every_cipher and the other ss_aead tests protocols/tests/unit/ss_aead.rs The shared record stream; see Shadowsocks AEAD.
ss2022_new_server_vs_new_client_tcp protocols/tests/pipeline/shadowsocks.rs For all three methods, 70 000 bytes echo through the server runtime and the client runtime, then a clean end of stream.
ss2022_multi_user_new_server_vs_new_client same The same echo through a multi-user server with an iPSK:uPSK client.
ss2022_server_takes_full_size_chunks_from_a_raw_client same A raw client’s 0xFFFF-byte variable header and full-size record reach the target through the server core.
ss2022_client_takes_full_size_chunks_from_a_raw_server same A raw server’s full-size first payload and record reach the reader through the client codec.
shadowsocks_runs_over_a_transport supervisor/tests/unit/validate.rs A Shadowsocks 2022 inbound validates over TLS, WebSocket and gRPC, with and without TLS.
app_server_shadowsocks_2022_over_grpc_tls, app_client_shadowsocks_2022_over_grpc_tls app/tests/integration/e2e_xray_wrapped.rs Shadowsocks 2022 with a user behind the server key, over gRPC and TLS, against the pinned Xray in both directions.
ss2022_builds katana tests/unit/lower/inbound.rs A 2022 node lowers, and a user’s key is the leading bytes of their UUID’s text.
shadowsocks_rides_the_panels_transport same A 2022 node over gRPC with TLS lowers to a Grpc shape with its TLS material.
shadowsocks_builds_both_generations katana tests/unit/lower/outbound.rs A 2022 outbound takes a base64 PSK or an iPSK:uPSK chain.

When you add a test, keep the negative cases next to the positive ones: a changed header field, a wrong key, a shifted clock, a repeated salt. The core tests use CoreHarness (protocols/src/core/harness.rs), whose feed keeps handing the core the unconsumed tail of one slice until the core consumes nothing more, and returns the total consumed. To test a partial read, feed a prefix and then the rest, as single_psk_request_opens_with_its_first_payload does. Timestamp cases use Ss2022Core::new with a fixed clock.