Shadowsocks 2022
Source files: 42 · checked against Etemenanki 46c12e4 · katana v6.1.0
Etemenanki/protocols/src/ss_aead.rsEtemenanki/protocols/src/ss_2022/mod.rsEtemenanki/protocols/src/ss_2022/crypto.rsEtemenanki/protocols/src/ss_2022/protocol.rsEtemenanki/protocols/src/ss_2022/users.rsEtemenanki/protocols/src/ss_2022/core.rsEtemenanki/protocols/src/ss_2022/codec.rsEtemenanki/protocols/src/ss_2022/replay.rsEtemenanki/protocols/src/core/mod.rsEtemenanki/protocols/src/core/harness.rsEtemenanki/protocols/src/helpers/crypto.rsEtemenanki/protocols/src/helpers/address.rsEtemenanki/protocols/src/sniff/mod.rsEtemenanki/concepts/src/runtime.rsEtemenanki/concepts/src/client.rsEtemenanki/concepts/src/buffer.rsEtemenanki/app/src/config.rsEtemenanki/app/src/lower.rsEtemenanki/supervisor/src/build/inbound.rsEtemenanki/supervisor/src/build/outbound.rsEtemenanki/supervisor/src/build/users.rsEtemenanki/supervisor/src/build/validate.rsEtemenanki/supervisor/src/serve.rsEtemenanki/supervisor/src/topology/inbound/mod.rsEtemenanki/supervisor/src/topology/outbound/mod.rsEtemenanki/protocols/tests/unit/ss_aead.rsEtemenanki/protocols/tests/unit/ss_2022/protocol.rsEtemenanki/protocols/tests/unit/ss_2022/core.rsEtemenanki/protocols/tests/unit/ss_2022/codec.rsEtemenanki/protocols/tests/unit/ss_2022/replay.rsEtemenanki/protocols/tests/unit/ss_2022/users.rsEtemenanki/protocols/tests/pipeline/shadowsocks.rsEtemenanki/supervisor/src/topology/spec_plan/inbound.rsEtemenanki/supervisor/tests/unit/validate.rsEtemenanki/app/tests/integration/e2e_xray_wrapped.rskatana/src/lower/inbound.rskatana/src/lower/mod.rskatana/src/lower/outbound.rskatana/src/api/newv2board.rskatana/tests/unit/lower/inbound.rskatana/tests/unit/lower/outbound.rskatana/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).
Responsibilities
Section titled “Responsibilities”| 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 aStagingarea. - Dialing and routing belong to the supervisor’s connector. The core emits
Effect::Openwith aFlow, 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.rsin etemenanki-app,src/lower/in katana). The supervisor builds the server types from the spec; see Wiring.
Methods and key sizes
Section titled “Methods and key sizes”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.
PSK decoding, normalisation and folding
Section titled “PSK decoding, normalisation and folding”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_psktrims surrounding whitespace and decodes with the standard base64 alphabet. A decoding failure becomesdecode PSK: <base64 error>(InvalidInput).users.rs→normalise_pskkeeps a PSK of exactlykey_len()bytes, folds a longer one withfold_key, and refuses a shorter one withshadowsocks-2022: PSK too short (<len> < <key_len>)(InvalidInput).crypto.rs→fold_keyis sing’sKey(key, keyLength): SHA-256 of the whole key, truncated tokey_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.
Session subkeys
Section titled “Session subkeys”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).
Identity subkeys and the identity hash
Section titled “Identity subkeys and the identity hash”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"]
The record stream
Section titled “The record stream”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_counterpins the interleaving. - A larger payload. Both halves build their encoders and decoders with
max_payload=MAX_PACKET_SIZE, so any length au16can 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.
Wire format
Section titled “Wire format”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.
Request (client to server)
Section titled “Request (client to server)”| 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:
- draws a random salt and keys the encoder with
session(method, psk, salt)andMAX_PACKET_SIZE; - encodes the address into a stack buffer of
AddressCodec::MAX_LENbytes, or fails withInvalidInput,shadowsocks-2022: address; - pads with a random length in
1..=MAX_PADDING_LENGTH(900) when the initial payload is shorter than 900 bytes, and with nothing otherwise; - refuses a variable header longer than a
u16withInvalidInput,shadowsocks-2022: request header longer than a chunk may carry; - checks that
outhas room for the salt, the EIH blocks, both headers and their two tags, or fails withshadowsocks: staging room below the framehaving staged nothing; - 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.
Response (server to client)
Section titled “Response (server to client)”| 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.
The timestamp window
Section titled “The timestamp window”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_clockpassesnow_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.
Multi-user: the Extended Identity Header
Section titled “Multi-user: the Extended Identity Header”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:
- For each hop in its chain, the client derives
identity_subkey(current_psk, request_salt), takeseih_hash(next_psk), and encrypts that 16-byte hash as one AES block. The chain isidentity_keys ++ [psk], so with a single iPSK there is one block: the uPSK’s hash under the iPSK’s subkey. - The client derives the session subkey from the uPSK, not from the iPSK.
- 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 itsValidator. - 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, aPermissionDeniederror (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.
BlockCipher
Section titled “BlockCipher”#[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.
Validator
Section titled “Validator”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 matchedusers_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).
Identity chains on the client
Section titled “Identity chains on the client”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>).
Server configuration types
Section titled “Server configuration types”#[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::newnormalises raw PSK bytes and leavesemailempty;from_passworddecodes a base64 PSK, normalises it and takes a label.Ss2022ServerConfig::newnormalises the PSK and starts with no users;from_passworddecodes first.Ss2022Userhas a hand-writtenDebugthat shows the label and never the PSK (debug_shows_the_label_but_never_the_psk).Ss2022ServerConfigimplementsClonefor anyT, and itsDebugshows 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.
The server core: Ss2022Core
Section titled “The server core: Ss2022Core”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.
States
Section titled “States”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.
Refusing a request
Section titled “Refusing a request”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::DeadlinewithExpired::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.
The replay filter
Section titled “The replay filter”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_fixedinserts 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.insertreturnsfalsefor a salt already recorded, andopen_fixedturns that intoshadowsocks-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 forREMEMBERor more, the current generation becomes the previous one and the old previous one is dropped. If it has run for twiceREMEMBERor 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 leastREMEMBERand 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 (
insertreturnsfalse) 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.
Opening the flow and sniffing
Section titled “Opening the flow and sniffing”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 entersState::SniffandTiming::enter(Phase::Sniff)armsSNIFF_TIMEOUT(300 ms). - In
State::Sniffeach record’s plaintext goes into the prefix. The prefix takes at mostSNIFF_LIMIT(4 KiB) in total. - Once the verdict is not
More,open_sniffedcopies the result intoflow.sniffedand opens the flow: it entersPhase::Relay, which pushesSetDeadline(RELAY_IDLE_TIMEOUT), then pushesEffect::OpenandEffect::ForwardHeldover everything collected. It then pushesEffect::Forwardfor any bytes of the last chunk or record that the prefix did not take. Event::DeadlinewithExpired::Sniff, orEvent::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 response
Section titled “The response”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.
End of stream and errors
Section titled “End of stream and errors”| 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.
The client codec: Ss2022Stream
Section titled “The client codec: Ss2022Stream”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>;}startcallsbuild_requestwith an empty initial payload, keeps the encoder and the request salt, and returnsHandshake::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.replyis never called for aDonehandshake and returnsshadowsocks-2022: no handshake replyif it is.finishstages nothing: SIP022 has no close frame, so the client runtime half-closes the transport.sealtakes at mostMAX_PACKET_SIZEbytes and writes one record withseal_record. The client runtime offers at mostroom - STAGING_RESERVEbytes, so the record always fits; a short room would be a runtime bug and returnsshadowsocks: staging room below the frame. Sealing beforestartreturnsshadowsocks-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.
Downstream states
Section titled “Downstream states”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.
Wiring
Section titled “Wiring”-
supervisor/src/build/users.rs→credential_kindmaps a Shadowsocks 2022 inbound toCredentialKind::Ss2022Psk. -
supervisor/src/build/validate.rs→validate_admissionrefuses 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_tablebuilds the table:Ss2022ServerConfig::new(method, psk, Principal::anonymous())for the server key;- for each admitted user whose credential is a 2022 PSK, an
Ss2022Userwhosepskisnormalise_psk(method, user_psk)and whoseemailisprincipal.label(), paired with that user’sArc<Principal>; Validator::from_config, wrapped in anArc.
The result is an
Ss2022Users { config, validator }, kept inStreamProtocol::Ss2022(ArcSwap<Ss2022Users>)(supervisor/src/topology/inbound/mod.rs). The label is the front end’s name for the user: the configemailin etemenanki-app, and the panel user id in decimal in katana. The users are added in the order of the supervisor’s admissions map, aBTreeMapsorted 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 itsInboundTransportSpecdescribes, so a server offers Shadowsocks 2022 over plain TCP, TLS, WebSocket or gRPC, with or without TLS (REALITY is VLESS’s alone), andvalidate_inboundholds 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_connectionloads the table (users.load_full()) and runsdrive::<{ Ss2022Core::<Principal>::BUF_SIZE }, _, _>with the closure|| Ss2022Core::with_system_clock(users.config.clone(), users.validator.clone(), sniff, source)and the connection’sReport.drivecalls the closure once to build the runtime; a core handed in would stay indrive’s future beside the runtime’s copy. Each connection therefore starts with the table that is current when it is accepted.sourceis 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_outboundbuilds anSs2022Streamper flow from the spec’smethod,pskandidentity_psks, overtransport_connector, so the client can run over TLS, WebSocket or gRPC. The client runtime buffer isSS2022_BUF=Ss2022Stream::BUF_SIZE(supervisor/src/topology/outbound/mod.rs), andOutbound::connect_datagramrefuses UDP withshadowsocks-2022 carries no datagrams.
app/src/config.rs→ShadowsocksInboundSettingshasmethod,passwordandusers(aliasclients), each user aShadowsocksUserCfg { password, email }.ShadowsocksOutboundSettingshasmethodandpassword. Both refuse unknown fields.app/src/lower.rs→lower_inbound, the"shadowsocks"arm, takes the 2022 path whenmethodstarts with2022-:Ss2022Method::from_name, orinbound <tag>: unknown shadowsocks-2022 method "<name>";- the server key is
normalise_psk(method, decode_psk(password)), with errors prefixed byinbound <tag>:; - each user is keyed by its
email, andInlineUsers::ss2022_pskdecodes itspasswordinto the user’s 2022 PSK credential, with errors prefixed byinbound <tag>: users[<i>]:; - the inbound gets a user set only when
usersis non-empty; without users it is single-PSK; - the spec’s
transportis whatinbound_transportlowers from[inbound.stream], as for legacy Shadowsocks.
app/src/lower.rs→lower_shadowsocks_outboundsplits the password on:and runs every segment throughdecode_pskandnormalise_psk, with errors prefixed byoutbound <tag>:. The last segment becomespsk, the restidentity_psks.
- A 2022 node’s cipher is the node config’s
SsCipher::Ss2022, withAes128GcmorAes256Gcmand a server key that helium-node-api holds to the cipher’s key length.src/lower/inbound.rs→lower_shadowsocks(cipher, transport)maps it toBlake3Aes128GcmorBlake3Aes256Gcmwith the key’s bytes as the server key, and the spec carries the transport the panel names for the node (shadowsocks_rides_the_panels_transport). A helium panel writes the key as padded standard base64 of 16 or 32 bytes. A UniProxy panel’sserver_keyis read insrc/api/newv2board.rs→shadowsocksas the kernel reads a key,normalise_psk(method, decode_psk(server_key)), so a longer key is folded to the cipher’s length; a key that is not base64 fails withshadowsocks server_key is not base64, which does not quote it (shadowsocks_ciphers_and_keys). credentialstakes each user’s uPSK from the firstkey_len()bytes of the user’s panel UUID string, cut rather than folded. A UUID string shorter than that is not a usable credential:src/lower/mod.rsskips the user with the warningskipping user <uid>: shadowsocks-2022 key too short (< <key_len>)(ss2022_builds).src/lower/outbound.rs→lower_shadowsockssplits an outbound passwordiPSK:...:uPSKthe same way as the app, and fails withshadowsocks outbound <tag> needs a passwordwhen there is none (shadowsocks_builds_both_generations).
Invariants
Section titled “Invariants”| 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) |
Limits
Section titled “Limits”| 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.
Configuration errors
Section titled “Configuration errors”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.
Changing this code
Section titled “Changing this code”-
Changing the headers.
build_requestandbuild_responseare the only writers, andparse_request_fixed,parse_request_variableandparse_response_fixedthe only readers; the core and the codec call them. Keep the room check ahead of the firstput, so that a refused header stages nothing, and keeprequest_and_response_round_trip_under_every_methodanda_header_that_does_not_fit_is_refused_and_nothing_is_stagedpassing. -
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_firstmust keep passing for both modes. -
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. -
Changing buffer sizes. Both
BUF_SIZEvalues must hold a full record,MAX_RECORD_LEN, or a peer that seals a whole0xFFFF-byte read fails the connection. The two full-size pipeline tests pin that. -
Changing the users API. The supervisor builds
Ss2022ServerConfig,Ss2022UserandValidatorinuser_table; a change to these public types is a SemVer change foretemenanki-protocolsand 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.
cargo test -p etemenanki-protocols --lib ss_2022cargo test -p etemenanki-protocols --lib ss_aeadcargo 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.