Shadowsocks AEAD
Source files: 41 · checked against Etemenanki 46c12e4 · katana v6.1.0
Etemenanki/protocols/src/ss_aead.rsEtemenanki/protocols/src/ss_legacy/mod.rsEtemenanki/protocols/src/ss_legacy/aead.rsEtemenanki/protocols/src/ss_legacy/users.rsEtemenanki/protocols/src/ss_legacy/core.rsEtemenanki/protocols/src/ss_legacy/codec.rsEtemenanki/protocols/src/ss_legacy/protocol.rsEtemenanki/protocols/src/helpers/crypto.rsEtemenanki/protocols/src/helpers/address.rsEtemenanki/protocols/src/helpers/parse.rsEtemenanki/protocols/src/core/mod.rsEtemenanki/concepts/src/runtime.rsEtemenanki/concepts/src/client.rsEtemenanki/concepts/src/buffer.rsEtemenanki/app/src/lower.rsEtemenanki/app/src/transport.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/flow.rsEtemenanki/supervisor/src/topology/inbound/mod.rsEtemenanki/supervisor/src/topology/outbound/mod.rsEtemenanki/protocols/tests/unit/ss_aead.rsEtemenanki/protocols/tests/unit/ss_legacy/aead.rsEtemenanki/protocols/tests/unit/ss_legacy/codec.rsEtemenanki/protocols/tests/unit/ss_legacy/core.rsEtemenanki/protocols/tests/unit/ss_legacy/users.rsEtemenanki/protocols/tests/pipeline/shadowsocks.rsEtemenanki/app/tests/unit/transport.rsEtemenanki/app/tests/unit/lower.rsEtemenanki/app/tests/integration/e2e_xray_wrapped.rsEtemenanki/supervisor/src/topology/spec_plan/inbound.rsEtemenanki/supervisor/tests/unit/validate.rskatana/src/lower/inbound.rskatana/src/lower/outbound.rskatana/src/api/newv2board.rskatana/tests/unit/lower/inbound.rskatana/tests/unit/lower/outbound.rskatana/tests/unit/api/newv2board.rs
This page describes the legacy Shadowsocks implementation in etemenanki-protocols. It covers:
- the SIP004 AEAD record stream, which now lives in
protocols/src/ss_aead.rsand is shared with Shadowsocks 2022; - how keys and nonces are derived;
- how one port serves several users;
- the two sans-I/O halves built on the stream: the server core
ShadowsocksCoreand the client codecSsStream.
It is written for contributors who change protocols/src/ss_legacy/ or protocols/src/ss_aead.rs. Shadowsocks 2022 lives in a separate module and has its own page. The crate-level summary of the shared record stream is in protocol foundations.
TCP only Neither half carries UDP.
Responsibilities
Section titled “Responsibilities”The ss_legacy module owns:
- the four SIP004 methods and their key and salt sizes (
Method); - keying one direction of a session from a master key and a salt (
session); - turning a password list into a key table once per user-set change (
Resolved); - the server side as a
ProxyCoreDecode(ShadowsocksCore) and the client side as aProxyCoreEncode(SsStream).
The shared module ss_aead owns what both Shadowsocks flavours use:
- the four AEAD ciphers and one direction’s keyed cipher with its nonce counter (
Cipher,Aead); - sealing and opening records in place, without decrypting any byte twice (
ChunkEncoder,ChunkDecoder,RecordStep).
It leaves out, on purpose:
| Not here | Where it is instead |
|---|---|
Stream ciphers, none, plain |
Not supported anywhere. Method::from_name returns None, and both etemenanki-app and katana refuse the configuration. |
| Shadowsocks 2022 (SIP022) | protocols/src/ss_2022/, see Shadowsocks 2022. It reuses ss_aead with its own key schedule and a larger payload limit. |
| UDP relay | Not implemented; see No UDP. |
| Sockets, timers, buffers | The per-connection runtimes; see server runtime and client runtime. |
| The SOCKS-style address codec | protocols/src/helpers/address.rs → AddressCodec, shared with other protocols; see foundations. |
| Sniffing | protocols/src/sniff/, see sniffing. |
| Users, credentials and sessions | The supervisor; see Users, principals and sessions. |
| File | Contents |
|---|---|
protocols/src/ss_aead.rs |
TAG_LEN, RECORD_HEADER_LEN, RECORD_OVERHEAD, Cipher, Aead, ChunkEncoder, ChunkDecoder, RecordStep, and the crate-private no_room. |
protocols/src/ss_legacy/mod.rs |
Re-exports Method, SsStream, ShadowsocksCore, Resolved, ShadowsocksServerConfig, ShadowsocksUser. |
protocols/src/ss_legacy/aead.rs |
Method, session, random_salt, MAX_PAYLOAD, FIRST_CHUNK_LEN. |
protocols/src/ss_legacy/users.rs |
ShadowsocksUser, ShadowsocksServerConfig<T>, UserEntry<T>, Resolved<T>. |
protocols/src/ss_legacy/core.rs |
ShadowsocksCore<T>, the server state machine. |
protocols/src/ss_legacy/codec.rs |
SsStream, the client codec. |
protocols/src/ss_legacy/protocol.rs |
ADDR, the address codec (AddressCodec::SOCKS). |
Wire format
Section titled “Wire format”A Shadowsocks TCP connection carries two independent encrypted streams, one per direction. Each stream starts with a random salt and continues with AEAD records sealed under a subkey derived from that salt. SIP004 calls the records chunks. There is no handshake and no reply header. The client starts sending the moment it connects, and the server’s first bytes are its own salt.
| Field | Size (bytes) | Meaning |
|---|---|---|
| Salt | key_len: 16 or 32 |
Random; the HKDF salt for the uplink subkey. |
| Record 0 | RECORD_OVERHEAD + address length |
Its plaintext is the target address. SsStream seals the address alone in this record. |
| Record 1 … n | RECORD_OVERHEAD + payload length |
Payload, at most MAX_PAYLOAD bytes each. |
| (end) | none | Transport EOF. Nothing marks the end of a direction. |
| Field | Size (bytes) | Meaning |
|---|---|---|
| Salt | key_len: 16 or 32 |
A fresh random salt chosen by the server; the HKDF salt for the downlink subkey. Sent ahead of the first downlink byte, or at the target’s EOF if the target sent nothing. |
| Record 0 … n | RECORD_OVERHEAD + payload length |
Payload from the target, at most MAX_PAYLOAD bytes each. |
| (end) | none | Transport EOF. |
One record
Section titled “One record”| Field | Size (bytes) | Meaning |
|---|---|---|
| Sealed length | 2 | The payload length as a big-endian u16, encrypted. |
| Length tag | 16 (TAG_LEN) |
AEAD tag of the length. |
| Sealed payload | length | The payload, encrypted. |
| Payload tag | 16 (TAG_LEN) |
AEAD tag of the payload. |
A record therefore costs RECORD_OVERHEAD = 2 + 16 + 16 = 34 bytes beyond its payload. Its first 18 bytes (RECORD_HEADER_LEN, the sealed length and its tag) are what the server trial-decrypts to identify the user; ss_legacy/aead.rs names them FIRST_CHUNK_LEN. Neither seal uses associated data.
The length is at most MAX_PAYLOAD = 0x3FFF. SIP004 caps it there and reserves the top two bits, and shadowsocks-libev and ss-rust send no more. The decoder enforces the cap: a larger declared length ends the connection (see ChunkDecoder).
A zero length is an ordinary record with an empty payload. It is still sealed, so it still carries both tags, and it ends nothing. A direction ends only with the transport’s EOF. Neither half writes an empty record: the core seals its reply in chunks(MAX_PAYLOAD), which yields no empty piece, and the client runtime returns early on an empty write before it reaches SsStream::seal. Both halves skip an empty record they read (an_empty_chunk_is_skipped). ss-rust and Xray treat a zero length the same way.
The address
Section titled “The address”The plaintext of the uplink starts with the target address in SOCKS form (protocols/src/ss_legacy/protocol.rs → ADDR is AddressCodec::SOCKS); everything after it is payload.
| Field | Size (bytes) | Meaning |
|---|---|---|
| Address type | 1 | 0x01 IPv4, 0x03 domain, 0x04 IPv6. Any other value is an error. |
| Address | 4, 1 + n, or 16 | For a domain, one length byte and then n bytes of name. |
| Port | 2 | Big-endian. |
The longest encoded address is AddressCodec::MAX_LEN = 1 + 1 + 255 + 2 = 259 bytes. The server does not assume the address arrives in one record: it accumulates plaintext until the address parses.
Keys, salts and nonces
Section titled “Keys, salts and nonces”flowchart LR pw["password"] --> evp["EVP_BytesToKey (MD5)"] evp --> master["master key, key_len bytes"] salt["salt, key_len bytes"] --> hkdf["HKDF-SHA1, info ss-subkey"] master --> hkdf hkdf --> sub["subkey, key_len bytes"] sub --> aead["Aead: cipher + nonce counter"] aead --> enc["ChunkEncoder"] aead --> dec["ChunkDecoder"]
Master key
Section titled “Master key”protocols/src/helpers/crypto.rs → evp_bytes_to_key is OpenSSL’s EVP_BytesToKey with MD5, one iteration and no salt: D1 = MD5(password), Di = MD5(Di-1 ‖ password), concatenated and truncated to key_len. For a 16-byte key the result is MD5(password), which evp_key_known_answer pins with the known answer for "test".
pub fn evp_bytes_to_key(password: &[u8], key_len: usize) -> Vec<u8>The master key is derived once per table or outbound, never per connection: by Resolved::new for every server user, and by the supervisor’s outbound builder for a client.
Session subkey
Section titled “Session subkey”pub fn session(method: Method, master_key: &[u8], salt: &[u8]) -> io::Result<Aead>ss_legacy/aead.rs → session keys one direction. It runs hkdf_sha1_ss_subkey (HKDF-SHA1 with the salt as HKDF salt, the master key as input keying material and the fixed info string ss-subkey) into the first key_len bytes of a 32-byte stack buffer, then hands that subkey to Aead::new with method.cipher(). Every direction of every connection therefore has its own key. The two error paths cannot be reached with the four methods, whose keys are 16 or 32 bytes: a key longer than 32 bytes would be Truncated("shadowsocks subkey"), and a subkey of the wrong length would be refused by Aead::new.
pub fn hkdf_sha1_ss_subkey(master_key: &[u8], salt: &[u8], out: &mut [u8])pub fn random_salt(n: usize) -> Vec<u8>Salts come from random_salt, which fills n bytes from rand::rng(). The client draws the uplink salt in SsStream::start; the server draws the downlink salt when it first responds.
Nonces
Section titled “Nonces”Each Aead carries its own nonce counter. It starts at all zeroes and is incremented as a little-endian integer (protocols/src/helpers/crypto.rs → increment_le) after every successful AEAD operation. Sealing or opening a record takes two operations, so record i of a direction uses nonce 2i for its length and 2i + 1 for its payload. The two directions never share a counter or a subkey, because each has its own salt and its own Aead.
Methods
Section titled “Methods”Method |
Names from_name accepts |
Key and salt (key_len) |
Cipher |
Nonce | Tag |
|---|---|---|---|---|---|
Aes128Gcm |
aes-128-gcm, aead_aes_128_gcm |
16 | Aes128Gcm |
12 | 16 |
Aes256Gcm |
aes-256-gcm, aead_aes_256_gcm |
32 | Aes256Gcm |
12 | 16 |
ChaCha20Poly1305 |
chacha20-poly1305, chacha20-ietf-poly1305, aead_chacha20_poly1305 |
32 | ChaCha20Poly1305 |
12 | 16 |
XChaCha20Poly1305 |
xchacha20-poly1305, xchacha20-ietf-poly1305 |
32 | XChaCha20Poly1305 |
24 | 16 |
from_name lower-cases its argument before matching, so AEAD_CHACHA20_POLY1305 is accepted; it does not trim whitespace. The salt is always as long as the key: key_len serves as both. Method::key_len is self.cipher().key_len(), and the nonce length now belongs to Cipher alone. method_lengths pins the AES key lengths and the ChaCha20 and XChaCha20 nonce lengths.
Key types
Section titled “Key types”Method and the SIP004 constants
Section titled “Method and the SIP004 constants”pub const MAX_PAYLOAD: usize = 0x3FFF;pub const FIRST_CHUNK_LEN: usize = RECORD_HEADER_LEN; // 18
pub enum Method { Aes128Gcm, Aes256Gcm, ChaCha20Poly1305, XChaCha20Poly1305,}
impl Method { pub const fn key_len(self) -> usize; pub const fn cipher(self) -> Cipher; pub fn from_name(name: &str) -> Option<Self>;}Method is the SIP004 name for a cipher. It derives Debug, Clone, Copy, PartialEq and Eq. cipher maps each variant one to one onto ss_aead::Cipher.
The shared record stream (ss_aead.rs)
Section titled “The shared record stream (ss_aead.rs)”pub const TAG_LEN: usize = 16;pub const RECORD_HEADER_LEN: usize = 2 + TAG_LEN; // 18pub const RECORD_OVERHEAD: usize = RECORD_HEADER_LEN + TAG_LEN; // 34
pub enum Cipher { Aes128Gcm, Aes256Gcm, ChaCha20Poly1305, XChaCha20Poly1305,}
impl Cipher { pub const fn key_len(self) -> usize; // 16 for AES-128-GCM, 32 otherwise pub const fn nonce_len(self) -> usize; // 24 for XChaCha20-Poly1305, 12 otherwise}
pub struct Aead(Keyed);
impl Aead { pub fn new(cipher: Cipher, key: &[u8]) -> io::Result<Self>; pub fn opens_length(&self, header: &[u8]) -> bool;}Aead is one direction of a session: a cipher keyed with its subkey, and the nonce counter it seals or opens under next. The private Keyed enum holds one boxed aes-gcm or chacha20poly1305 instance per variant, next to a [u8; 12] counter (a [u8; 24] counter for XChaCha20-Poly1305). The private each_cipher! macro runs the same code for all four variants, since only the concrete types differ.
Aead::newrefuses a key of any length other thanCipher::key_lenwithInvalidInput,shadowsocks: AEAD key of the wrong length(a_key_of_the_wrong_length_is_refused). The counter starts at zero.- The private
sealencrypts a buffer in place under the current nonce, advances the nonce and returns the detached tag. An encryption failure isshadowsocks: AEAD seal failed. - The private
opendecrypts in place against a tag, then advances the nonce. A tag that does not verify, or a tag slice of the wrong length, isInvalidData,shadowsocks: invalid AEAD tag. The nonce does not advance on failure, and the failure ends the connection anyway. opens_lengthis the trial-decryption primitive. It copies the two sealed length bytes, opens the copy under the current nonce, and reports whether the tag verified. It takes&self, so neither the bytes nor the nonce change. A header shorter thanRECORD_HEADER_LENreportsfalse.a_trial_key_neither_changes_the_bytes_nor_advanceschecks all four ciphers: the right key opens, a wrong one does not, the wire is unchanged, and the matching key then opens the record from nonce 0.
no_room() builds the error for a staging area without room for the frame being sealed, shadowsocks: staging room below the frame, with kind Other. The runtimes’ reserve contracts rule that case out, so it signals a caller bug rather than a peer error.
ChunkEncoder
Section titled “ChunkEncoder”pub struct ChunkEncoder { aead: Aead, max_payload: usize,}
impl ChunkEncoder { pub fn new(aead: Aead, max_payload: usize) -> Self; pub fn seal_chunk(&mut self, plain: &[u8], out: &mut Staging<'_>) -> io::Result<()>; pub fn seal_record(&mut self, plain: &[u8], out: &mut Staging<'_>) -> io::Result<()>;}max_payload is the longest record the flavour allows. Legacy Shadowsocks passes MAX_PAYLOAD.
seal_record seals one record straight into a runtime’s Staging area. Before it touches the nonce, it checks the two things that can refuse the record:
- The payload must fit a
u16andmax_payload; otherwise it returnsInvalidInput,shadowsocks: record payload over the limit. out.reserve(RECORD_OVERHEAD + plain.len())must succeed; otherwise it returnsshadowsocks: staging room below the frame.
Only then does it write the big-endian length, seal it, copy the payload and seal that. A refused record therefore stages nothing and leaves the nonce where it was. a_refused_seal_stages_nothing_and_keeps_the_counter refuses one record for its size and one for want of room, checks that nothing was staged, and then seals a record that the peer’s decoder opens at nonce 0.
seal_chunk seals a bare chunk, plain ‖ tag, with no length in front. Shadowsocks 2022 carries its headers that way on the same counter (bare_chunks_and_records_share_one_counter). Legacy Shadowsocks never calls it in production; its tests use it to forge a sealed length.
Callers split their input; the encoder never does.
ChunkDecoder and RecordStep
Section titled “ChunkDecoder and RecordStep”pub enum RecordStep { NeedMore, Data { consumed: usize, plain: Range<usize> },}
pub struct ChunkDecoder { aead: Aead, max_payload: usize, pending_len: Option<usize>,}
impl ChunkDecoder { pub fn new(aead: Aead, max_payload: usize) -> Self; pub fn open_chunk(&mut self, chunk: &mut [u8]) -> io::Result<usize>; pub fn open_record(&mut self, wire: &mut [u8]) -> io::Result<RecordStep>;}open_record looks at the record at the front of wire:
NeedMore: no whole record yet. Present the same bytes again with more appended.Data: the payload has been decrypted in place,plainis its range insidewire, andconsumedcovers the whole record. For a zero-length recordplainis empty. The caller forwardsplainby range and advances byconsumed.
After opening the length, open_record compares it with max_payload. A larger declared length fails with InvalidData, shadowsocks: record length 0x4000 exceeds 0x3fff (the declared length and the limit, in lower-case hex). The check comes before any payload is awaited. a_length_over_0x3fff_is_refused forges both lengths with seal_chunk: 0x3FFF waits for its payload, 0x4000 is refused.
open_chunk opens a bare chunk in place and returns its plaintext length. A chunk shorter than its tag is Truncated("AEAD chunk shorter than its tag"), which becomes UnexpectedEof. Only Shadowsocks 2022 calls it.
Nothing is decrypted twice
Section titled “Nothing is decrypted twice”A server runtime hands a core the whole unparsed region on every call, and on the next call it presents the unconsumed bytes again with more appended (see server cores). Suppose a decoder decrypted the length header in place and then returned NeedMore because the payload had not arrived. The next call would see already-decrypted bytes and decrypt them again under the wrong nonce.
ChunkDecoder avoids that in two ways:
- It opens the length from a copy of the 18 header bytes, never in the wire buffer, so the header in
wirestays ciphertext. - It remembers the opened length in
pending_len, having advanced the nonce once. On the next call it skips straight to the payload check.
The payload is opened in place only once RECORD_HEADER_LEN + len + TAG_LEN bytes are present, and pending_len is cleared in the same step. However many times a partial record is presented, its length is opened once.
sequenceDiagram participant R as Runtime participant D as ChunkDecoder R->>D: open_record(header and two payload bytes) D->>D: open length from a copy, nonce += 1, pending_len = Some(len) D-->>R: NeedMore R->>D: open_record(same bytes and more of the payload) D->>D: pending_len is set, header skipped D-->>R: NeedMore R->>D: open_record(whole record) D->>D: open payload in place, nonce += 1, pending_len = None D-->>R: Data with consumed and plain range
a_record_presented_again_is_never_decrypted_twice pins this sequence. It presents the first 20 bytes of a 39-byte record (the header and two payload bytes), then the first 30 bytes, then the whole wire, and then opens a second record behind it. The same decoder serves Shadowsocks 2022, so a change here changes both flavours.
Users: ShadowsocksServerConfig, Resolved, UserEntry
Section titled “Users: ShadowsocksServerConfig, Resolved, UserEntry”#[derive(Clone)]pub struct ShadowsocksUser { pub password: String, pub email: String,}
pub struct ShadowsocksServerConfig<T> { pub method: Method, pub password: String, pub password_data: Arc<T>, pub users: Vec<(ShadowsocksUser, Arc<T>)>,}
pub struct UserEntry<T> { pub key: Vec<u8>, pub email: CompactString, pub data: Arc<T>,}
pub struct Resolved<T> { pub method: Method, pub users: Vec<UserEntry<T>>,}
impl<T> Resolved<T> { pub fn new(config: &ShadowsocksServerConfig<T>) -> Self;}ShadowsocksUser has a hand-written Debug that shows the email label and never the password (debug_shows_the_label_but_never_the_password). ShadowsocksServerConfig implements Clone for any T, and its Debug shows the method and the users’ labels.
Resolved::new derives every master key once, when the table is built:
config.users |
Resolved::users |
|---|---|
| Empty (single-password mode) | One entry: the key of config.password, an empty email, and password_data. |
| Not empty | One entry per user, in list order: the key of that user’s password, its email, and its payload. config.password is not used. |
Users that share a password derive the same key, and trial decryption could only ever pick the first of them. Resolved::new therefore keeps only the first user of each key and logs a warning for each one it leaves out:
shadowsocks: users "alice" and "carol" share a password; only "alice" is matchedusers_sharing_a_password_keep_only_the_first builds alice, bob and carol, with alice and carol sharing a password, and expects the table alice, bob. A front end does not reach this path: the supervisor refuses two users of one inbound who present the same password before it builds a table (see Wiring).
T is the per-user payload carried into routing. Every front end serves Shadowsocks through etemenanki-supervisor, which uses T = Principal (supervisor/src/topology/flow.rs). The unit and pipeline tests use (). The core hands the payload on in the flow’s NetworkUser::user_data. One Arc<Resolved<T>> serves every connection that starts while it is the inbound’s current table; each connection only reads it.
ShadowsocksCore
Section titled “ShadowsocksCore”pub struct ShadowsocksCore<T> { inner: Arc<Resolved<T>>, sniff: bool, source: Option<IpAddr>, timing: Timing, state: State, matched: Option<Matched<T>>, decoder: Option<ChunkDecoder>, encoder: Option<ChunkEncoder>, held: Vec<u8>, prefix: SniffPrefix, flow: Option<Flow<T>>,}
impl<T> ShadowsocksCore<T> { pub const BUF_SIZE: usize = 20 * 1024; pub fn new(inner: Arc<Resolved<T>>, sniff: bool, source: Option<IpAddr>) -> Self; pub fn is_established(&self) -> bool;}
impl<T: Send + Sync + 'static> ProxyCoreDecode for ShadowsocksCore<T> { type Key = Single; type Target = Flow<T>; type Error = io::Error; type TransportAddr = (); const STAGING_RESERVE: usize = 32 + 2 * RECORD_OVERHEAD + 28; fn handle( &mut self, event: Event<'_, Self>, fx: &mut Effects<'_, Self>, ) -> Result<usize, io::Error>; fn held(&self) -> &[u8];}| Field | Role |
|---|---|
inner |
The key table this connection was started with. |
sniff, source |
Whether to sniff IP targets; the client address copied into the Flow. |
timing |
The one deadline, armed per phase (protocols/src/core/mod.rs → Timing). |
state |
The private State enum: Salt, Address, Sniff, Relay(Passthrough<Single>), Rejected(io::Error), Done. |
matched |
The chosen user’s master key, kept to derive the response subkey, and its NetworkUser. |
decoder |
The uplink ChunkDecoder, created when the user is matched. |
encoder |
The downlink ChunkEncoder, created with the response salt. |
held |
Plaintext accumulated until the address parses, then the payload that followed it. |
prefix |
The SniffPrefix collecting the first payload bytes of an IP target. |
flow |
The Flow built from the address, waiting for Effect::Open. |
The key is Single: one connection carries one flow to one outbound. is_established is true once Timing has reached the relay phase (Phase::Relay or Phase::Closing). The supervisor’s serve loop reads it through the Established trait to stop its handshake watchdog and release the handshake permit.
SsStream
Section titled “SsStream”pub struct SsStream { method: Method, key: Vec<u8>, dest: Destination, encoder: Option<ChunkEncoder>, down: Down,}
impl SsStream { pub const BUF_SIZE: usize = 20 * 1024; pub fn new(method: Method, key: Vec<u8>, dest: &Destination) -> Self;}
impl ProxyCoreEncodeHandshake for SsStream { type Target = Destination; type Error = io::Error; const STAGING_RESERVE: usize = 32 + RECORD_OVERHEAD + AddressCodec::MAX_LEN + 61; 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 SsStream { fn seal(&mut self, plain: &[u8], out: &mut Staging<'_>) -> io::Result<usize>; fn open(&mut self, wire: &mut [u8]) -> io::Result<Opened>;}key is the master key (evp_bytes_to_key of the password), computed by the caller. new clones the destination. Down is private: Salt while waiting for the response salt, then Records(ChunkDecoder). BUF_SIZE is the cap a client runtime over this codec puts on its buffers: room for the salt and one record of MAX_PAYLOAD plus its overhead, with some to spare. The buffers start small and grow toward the cap as bytes pass through them (concepts/src/client.rs).
Data flow
Section titled “Data flow”sequenceDiagram participant C as SsStream (client) participant S as ShadowsocksCore (server) participant O as Outbound C->>S: salt_c, then record 0 = sealed address Note over S: try each user's key on the first 18 bytes, build the ChunkDecoder Note over S: open records until the address parses S->>O: Effect::Open (Flow with user and destination) C->>S: records 1..n (payload) S->>O: Effect::Forward (plaintext range, in place) O-->>S: Event::Outbound (reply bytes) S-->>C: salt_s, then sealed records O-->>S: Event::OutboundEof S-->>C: ShutdownTransport (no terminator)
Multi-user resolution
Section titled “Multi-user resolution”In the Salt state the core waits, consuming nothing, until it holds key_len + FIRST_CHUNK_LEN bytes. It then walks Resolved::users in order. For each entry it keys an Aead with session(method, &entry.key, salt) and calls opens_length on the 18 bytes after the salt. An entry whose session call fails is skipped. The first entry whose key opens the length wins:
- That same
Aead, still at nonce 0 becauseopens_lengthdoes not advance it, becomes the uplinkChunkDecoderwithMAX_PAYLOAD. The decoder opens the first record again, this time for real. matchedrecords the key, for the response subkey later, and aNetworkUser. ItsauthorizationisUserAuthorization::UsernamePassword { username: email, password: "" }, and itsuser_datais the entry’s payload. The password itself never leaves the key table.- The core consumes only the salt and moves to
Address. The 18 bytes it tested are opened again in the next step.
the_matching_user_is_picked_by_trial_decryption_and_the_address_parsed feeds the salt and 10 bytes first and expects nothing consumed, then the whole request of the second user, bob, and expects an Open labelled bob and a Forward of the payload.
A stream no key opens
Section titled “A stream no key opens”If no key opens the length, the core does not close the connection. It moves to State::Rejected holding the error PermissionDenied, shadowsocks: no matching user, and returns data.len(): it consumes every byte it was given. From then on it swallows whatever the client sends, stages nothing and opens nothing. The connection fails with the stored error 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.
PermissionDenied 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 relies on that: it reports such an error to the supervisor’s guard with Report::failed, as a refused credential from the connection’s client (supervisor/src/serve.rs, supervisor/src/guard.rs).
The module docs give the reason: the moment of the close does not tell a prober how many bytes the server needed to decide. A client that sends fewer bytes than a salt and a length header waits in Salt 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.
Three tests pin this. an_unknown_password_is_drained_then_refused_when_the_client_leaves feeds a request under an unknown password and 4096 more bytes. It expects every byte consumed, no effects and nothing staged, then PermissionDenied at TransportEof. a_rejected_client_is_cut_off_at_the_handshake_deadline expects PermissionDenied, not TimedOut, at the deadline. no_byte_count_makes_the_server_close_first feeds 1, 49, 50, 51 and 4096 bytes of junk to an AES-256-GCM server, whose threshold is 32 + 18 = 50, and expects neither effects nor staged bytes for any of them.
Address accumulation
Section titled “Address accumulation”In the Address state the core opens records one after another from the front of the slice and appends each record’s plaintext to held. After every record it tries ADDR.read_slice(&self.held), wrapped in protocols/src/helpers/parse.rs → need_more. A truncated address, which the parser reports as UnexpectedEof, means “keep going”; any other parse error fails the connection. Once the address parses, the core takes the bytes after it as the leading payload, calls on_address, and returns how far it got. The rest of the slice comes back on the next call.
The parse is retried after every record, and an address is at most AddressCodec::MAX_LEN bytes. So held never grows beyond one record’s plaintext plus 258 bytes. an_address_split_across_chunks_is_reassembled seals the first four address bytes, the rest of the address and GET as three separate records. It expects one Open for example.com followed by a Forward of GET.
Sniffing or opening
Section titled “Sniffing or opening”on_address builds the Flow (Flow::new(dest, user, source)) and decides:
- No sniffing:
sniffis false, or the destination is a domain (worth_sniffing). The leading payload becomesheld, andopenentersPhase::Relay, which pushesSetDeadline(RELAY_IDLE_TIMEOUT). Only then does it pushEffect::Open, thenEffect::ForwardHeldover the held bytes if there are any. - Sniffing an IP target: the leading payload goes into
prefix.- If the sniffer wants more, the core enters
State::SniffandPhase::Sniff, which armsSNIFF_TIMEOUT. - If the sniff budget ran out with payload left over, the collected prefix and the rest are joined into
held, so oneForwardHeldcarries both. - Otherwise the flow opens with
flow.sniffedset and the prefix held.
- If the sniffer wants more, the core enters
In State::Sniff, every further record’s plaintext is pushed into prefix; an empty record adds nothing. When the verdict is no longer More, the core opens the flow (the relay deadline, Open, then ForwardHeld of the prefix). It then forwards the part of that record the sniffer did not take with a plain Effect::Forward. sniffing_an_ip_target_waits_for_a_recognisable_prefix sends an HTTP request split across two records. It expects SNIFF_TIMEOUT armed after the first, then, in this order, the relay idle deadline, an Open with the sniffed domain example.com and a ForwardHeld of 41 bytes. The sniffer itself is described on sniffing.
The deadline comes before the Open for a reason given 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 sniff phase’s 300 ms deadline would then still be armed during the connect and could end the flow as idle.
held() returns held when it is non-empty and the sniff prefix otherwise, so a ForwardHeld resolves against whichever buffer the open used. Both are cleared at the start of the next Transport or Outbound event in Relay. The runtime’s held-buffer pin rule makes that safe.
In State::Relay every call opens as many whole records as the slice holds. It pushes one Effect::Forward per non-empty payload, with ranges pointing into the slice where the plaintext now lies. An empty record is consumed and skipped (an_empty_chunk_is_skipped: records data, empty, more forward datamore and push no Shutdown). There is no copy between the wire buffer and the outbound.
On the way back, Event::Outbound reaches on_outbound. start_response stages a fresh salt once and creates the downlink ChunkEncoder from the matched key and that salt. Then the data is split with chunks(MAX_PAYLOAD) and each piece sealed with seal_record. STAGING_RESERVE covers the salt plus two record overheads plus 28 bytes, 128 in all. The runtime delivers an outbound read of n bytes only with STAGING_RESERVE + n bytes of staging free, and one read of at most BUF_SIZE (20 480) bytes splits into at most two records.
State machine
Section titled “State machine”stateDiagram-v2 [*] --> Salt Salt --> Address: a user key opens the first length Salt --> Rejected: no user key opens it Salt --> Done: transport EOF Rejected --> [*]: client EOF or handshake deadline, no matching user Address --> Relay: address parsed, open Address --> Sniff: sniffing on, IP address, sniffer wants more Address --> Done: transport EOF Address --> [*]: bad record, bad address or handshake deadline Sniff --> Relay: verdict, budget spent, deadline or EOF Relay --> [*]: both halves closed, outbound gone or idle timeout Done --> [*]
How each event is handled:
| Event | Salt / Address |
Rejected |
Sniff |
Relay |
|---|---|---|---|---|
Transport |
Timing::touch, which arms HANDSHAKE_TIMEOUT on the first byte, then parse as above. |
Every byte consumed, nothing staged. | Push plaintext into the prefix; open on a verdict. | Clear prefix and held, then forward non-empty payloads. |
Outbound |
Consumed and discarded (no outbound exists yet). | Consumed and discarded. | Consumed and discarded. | Clear prefix and held, then seal toward the client. |
TransportEof |
Move to Done and push Effect::Finish; nothing was opened. |
Fail with PermissionDenied, shadowsocks: no matching user. |
Open with what was sniffed, then Passthrough::on_transport_eof. |
on_transport_eof: Effect::Shutdown of the outbound; Finish once the outbound has ended too. |
OutboundEof |
Ignored. | Ignored. | Ignored. | Stage the response salt if none was sent, then on_outbound_eof: Effect::ShutdownTransport, and Finish if the client’s side has already ended. |
ConnectFailed, OutboundError |
Logged at debug. |
Logged at debug. |
Logged at debug. |
Logged, then on_outbound_gone: ShutdownTransport and Finish. |
Deadline |
Expired::Handshake: fail with TimedOut. |
Expired::Handshake: fail with the stored rejection. |
Expired::Sniff: open with what was collected. |
Expired::Idle: Timing has already pushed Finish. |
Connected, datagram events |
Ignored. | Ignored. | Ignored. | Ignored. |
The log line for a lost outbound is shadowsocks: outbound gone: <error>.
The handshake deadline is armed once, by the first Transport or Outbound event, and not refreshed while records arrive. It bounds the time from the first byte until the address parses, and in Rejected the time until the connection fails. After the address, the sniff window or the relay idle deadline replaces it, and the idle deadline is re-armed on every byte event.
A client that connects and never sends a byte produces no runtime event at all. The supervisor covers that case. supervisor/src/serve.rs → drive bounds every wait for the runtime’s next step by the same HANDSHAKE_TIMEOUT until is_established() is true, and fails with inbound handshake timed out after 10s. See Listeners and the serve loop.
The client codec
Section titled “The client codec”SsStream runs inside the client runtime, one codec per flow:
startdraws the uplink salt and keys theChunkEncoderfrom it. It writes the destination withADDR.write_sliceinto a stack buffer ofAddressCodec::MAX_LENbytes, failing withInvalidInput,shadowsocks: address, if it cannot be encoded. Only then does it stage the salt and seal the address as the first record. The error when the salt does not fit isshadowsocks: staging room below the declared reserve.startreturnsHandshake::Done, so plaintext may follow at once, with no round trip.STAGING_RESERVEis 32 + 34 + 259 + 61 = 386 bytes, which covers the largest salt, one record overhead and the longest address.replyis never called for aDonehandshake; if it were, it would fail withshadowsocks: no handshake reply.sealsealsmin(plain.len(), MAX_PAYLOAD)bytes as one record and returns how many it took; the runtime calls again for the rest. Beforestartit fails withshadowsocks: sealed before start.openfirst waits forkey_lenbytes of response salt. It keys the downlinkChunkDecoderfrom them and reports the salt asOpened::Frame { consumed: salt_len, plain: 0..0 }, a frame with no plaintext. After that it mapsRecordStepone to one ontoOpened:NeedMoretoNeedMore,DatatoFrame. An empty record is an empty frame, never an end; the client runtime advances past an empty frame without handing anything to the reader.finishstages nothing: the uplink ends with the transport’s EOF.
request_is_a_salt_and_a_sealed_address_then_records decodes the codec’s output with a ChunkDecoder. It checks that the address and the payload are separate records and that seal takes MAX_PAYLOAD of a larger input. response_salt_is_an_empty_frame_and_records_open_in_place feeds a server-shaped response: a partial salt gives NeedMore, the salt is an empty frame, then a data record, then a zero-length record that opens as an empty frame of 34 bytes.
No UDP
Section titled “No UDP”The ss_legacy/aead.rs module docs describe SIP004’s UDP packet format, salt | AEAD(addr ‖ payload) under an all-zero nonce, but nothing implements it:
ShadowsocksCorehastype TransportAddr = ()and ignores every datagram event.- The inbound carries no UDP over any transport.
InboundProtocolSpec::Shadowsockscarries anInboundTransportSpec, so a server offers Shadowsocks over plain TCP, TLS, WebSocket or gRPC, with or without TLS, but only the TCP side rides it. The doc comment on the variant gives the reason: Xray sends a Shadowsocks datagram as a UDP packet of its own, never inside its transport, so a transport carries the TCP side alone. - The supervisor’s outbound is
ProxyClient<SS_BUF, SsStream, NoUdp>.Outbound::connect_datagramrefuses a UDP flow routed to it withUnsupported,shadowsocks carries no datagrams(supervisor/src/topology/outbound/mod.rs→no_udp).
Wiring
Section titled “Wiring”-
supervisor/src/build/users.rs→credential_kindmaps a Shadowsocks inbound toCredentialKind::Password. -
supervisor/src/build/validate.rs→validate_admissionrefuses two users of one inbound who present the same password:inbound <tag>: users <a> and <b> present the same credential.validate_inboundholds the inbound’s transport to the rules every protocol’s transport meets (TLS material exactly with a TLS shape, plain TCP on a Unix listener, no REALITY, which is VLESS’s alone) and has no further rule for Shadowsocks; unlike Trojan, VLESS and VMess it has a mode without a user set. -
supervisor/src/build/inbound.rs→user_tablebuilds aShadowsocksServerConfig<Principal>:methodandpasswordcome from the spec, andpassword_dataisPrincipal::anonymous();usersholds each admitted user whose credential is a password, asShadowsocksUser { password, email: principal.label() }paired with that user’sArc<Principal>.
It resolves the config once with
Resolved::new. The label is the front end’s name for the user (UserId::name()): the configemailin etemenanki-app, and the panel user id in decimal in katana. The table’s order is the order of the supervisor’s admissions map, aBTreeMapsorted by the front end’s user id, so trial decryption tries users in that order rather than in config order. -
The handler keeps the table in
StreamProtocol::Shadowsocks(ArcSwap<Resolved<Principal>>)(supervisor/src/topology/inbound/mod.rs). A user change builds a new table and stores it into that cell (UserTable::store_into). -
supervisor/src/serve.rs→serve_connectionrunsdrive::<{ ShadowsocksCore::<Principal>::BUF_SIZE }, _, _>with the closure|| ShadowsocksCore::new(resolved.load_full(), sniff, source)and the connection’sReport.drivecalls the closure once, when it builds the runtime, so each connection starts with the table that is current then. The doc comment gives the reason for a closure: a core handed todrivewould stay in its future while the runtime holds a second copy.sourceis the connection’s client: 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. A connection that ends with an error is logged atdebugasshadowsocks connection from <source> ended: <error>, with the client’sOption<IpAddr>inDebugform. The runtime’s error text carries the prefixproxy core:. How a user change reaches sessions that are already open is on Users, principals and sessions. -
supervisor/src/build/outbound.rs→build_outboundderives the master key once withevp_bytes_to_keyand builds anSsStreamper flow. The outbound goes throughtransport_connector, so it can run over TLS, WebSocket or gRPC, as the inbound can. The client runtime buffer isSS_BUF=SsStream::BUF_SIZE= 20 KiB (supervisor/src/topology/outbound/mod.rs). See Outbounds, UDP fan-out and balancers.
app/src/lower.rs→lower_inbound, the"shadowsocks"arm:- It reads
[inbound.stream]withinbound_transport, as for Trojan; on a Unix socket a stream block that asks for a transport is refused and the shape is plain TCP. - A
methodstarting with2022-goes to Shadowsocks 2022. - Anything else must pass
Method::from_name, or lowering fails withinbound <tag>: unknown shadowsocks method "<name>". - Each entry of
usersis keyed by itsemail. A user without one fails withinbound <tag>: users[<i>] has no email; a user of this inbound is named by its email. Two entries with the same email fail withinbound <tag>: users[<i>] and users[<j>] are both named "<email>". Each entry’spasswordbecomes its credential. - The inbound gets a user set only when
usersis non-empty. Without users, the serverpasswordalone is the shared mode.
- It reads
- The lowered spec is
InboundProtocolSpec::Shadowsocks { method, password, transport }on a TCP bind. app/src/lower.rs→lower_shadowsocks_outbounddoes the same2022-dispatch for an outbound. An unknown legacy method fails withoutbound <tag>: unknown shadowsocks method "<name>".
How the app’s configuration becomes a spec is on etemenanki-app: from TOML to a spec.
src/lower/inbound.rs→lower_stream_protocollowers a Shadowsocks node over the transport the panel names for it, as Xray serves one: plain TCP, TLS, WebSocket or gRPC, with or without TLS. A wrapped node relays TCP alone (shadowsocks_rides_the_panels_transport).- The node’s cipher is the node config’s
SsCipher, helium-node-api’s: a legacy node isSsCipher::Legacy, one ofaes-128-gcm,aes-256-gcm,chacha20-ietf-poly1305andxchacha20-ietf-poly1305, with no server key.lower_shadowsocks(cipher, transport)maps each to the kernel’s method of the same name (every_legacy_cipher_lowers_to_the_kernels). A helium panel writes those four names. A UniProxy panel’scipheris read insrc/api/newv2board.rs→shadowsocks, as a Shadowsocks 2022 method first and then withss_legacy::Method::from_name, so every alias the kernel knows a legacy method by is taken. Anything else fails withnode requests kernel-unsupported feature: shadowsocks cipher "<name>"(shadowsocks_ciphers_and_keys). credentialsgives each panel user the user’s UUID string as the password, the XrayR convention. The users’ passwords make up the table.src/lower/outbound.rs→lower_shadowsocksserves theshadowsocksandssoutbound protocols. A missingpasswordfails withshadowsocks outbound <tag> needs a password. A cipher that is neither a 2022 nor a legacy method fails withunsupported shadowsocks cipher "<name>"(shadowsocks_builds_both_generations).
See Lowering inbounds and outbounds and Lowering a node into a spec.
Invariants
Section titled “Invariants”| Invariant | Enforced by | Pinned by |
|---|---|---|
| No wire byte is decrypted twice. | ChunkDecoder opens the length from a copy, stores it in pending_len, and opens the payload only when the whole record is present. |
a_record_presented_again_is_never_decrypted_twice (protocols/tests/unit/ss_aead.rs) |
| Trying a user changes nothing. | Aead::opens_length takes &self and works on a copy; the core consumes nothing until a user matched. |
a_trial_key_neither_changes_the_bytes_nor_advances (ss_aead.rs); only_the_sealing_key_opens_the_first_length (protocols/tests/unit/ss_legacy/aead.rs); the_matching_user_is_picked_by_trial_decryption_and_the_address_parsed (protocols/tests/unit/ss_legacy/core.rs) |
| An unknown key never opens a flow, and the server does not close first. | Salt moves to Rejected, which consumes every byte, stages nothing and fails only at the client’s EOF or the handshake deadline. |
an_unknown_password_is_drained_then_refused_when_the_client_leaves, a_rejected_client_is_cut_off_at_the_handshake_deadline, no_byte_count_makes_the_server_close_first (core.rs) |
No record carries more than MAX_PAYLOAD, either way. |
seal_record refuses larger input; the core splits with chunks(MAX_PAYLOAD); SsStream::seal takes at most MAX_PAYLOAD; open_record refuses a larger declared length. |
a_declared_length_over_the_limit_is_refused (ss_aead.rs), a_length_over_0x3fff_is_refused (aead.rs), request_is_a_salt_and_a_sealed_address_then_records (codec.rs), the_response_is_a_salt_then_sealed_chunks_until_the_target_closes (core.rs) |
| A refused seal stages nothing and costs no nonce. | seal_record checks the size and reserves the room before sealing. |
a_refused_seal_stages_nothing_and_keeps_the_counter (ss_aead.rs) |
| The address may span records. | Plaintext accumulates in held and the parse is retried after every record. |
an_address_split_across_chunks_is_reassembled (core.rs) |
| Each direction has its own subkey and nonce sequence. | Separate salts, a separate Aead each, counters starting at zero. |
both_ends_of_a_session_agree_under_every_method (aead.rs); end to end by ss_new_server_vs_new_client_tcp (protocols/tests/pipeline/shadowsocks.rs), for all four methods |
| The response salt comes first, exactly once, even for a silent target. | start_response runs on the first Outbound and on OutboundEof, guarded by encoder.is_some(). |
a_silent_target_still_gets_a_salt_before_eof, the_response_is_a_salt_then_sealed_chunks_until_the_target_closes (core.rs) |
| Only EOF ends a direction; an empty record is data. | open_record returns an empty plain; the core forwards only non-empty payloads; SsStream::finish stages nothing. |
an_empty_chunk_is_skipped (core.rs), response_salt_is_an_empty_frame_and_records_open_in_place (codec.rs), records_round_trip_under_every_cipher (ss_aead.rs) |
| Sniffed bytes reach the outbound in one piece, ahead of the rest. | SniffPrefix plus Effect::ForwardHeld; leftovers are joined into held. |
sniffing_an_ip_target_waits_for_a_recognisable_prefix (core.rs) |
| The relay idle deadline is armed before the flow opens. | open calls Timing::enter(Phase::Relay) before it pushes Effect::Open. |
sniffing_an_ip_target_waits_for_a_recognisable_prefix (core.rs) |
The flow’s user is the matched entry, labelled by email. |
matched.user built from the UserEntry. |
the_matching_user_is_picked_by_trial_decryption_and_the_address_parsed (core.rs) |
| One key, one user. | validate_admission refuses a shared password on one inbound; Resolved::new keeps only the first user of each key. |
two_users_may_not_present_the_same_credential (supervisor/tests/unit/validate.rs), users_sharing_a_password_keep_only_the_first (protocols/tests/unit/ss_legacy/users.rs) |
A user’s password never appears in Debug output of these types. |
Hand-written Debug for ShadowsocksUser and ShadowsocksServerConfig. |
debug_shows_the_label_but_never_the_password (users.rs) |
Failure paths and cancellation
Section titled “Failure paths and cancellation”Every error the core returns ends the connection. The runtime stops with RuntimeError::Core, whose text is the core’s message behind the prefix proxy core: . Before the core is established, drive reports a PermissionDenied error to the guard as a refused credential. It turns every error into an io::Error of kind Other, and serve_connection logs it at debug together with the protocol name and the client address. The error kinds below are therefore visible only at the core boundary.
| Where | Condition | Result |
|---|---|---|
Salt |
No user’s key opens the first length. | State Rejected: bytes are swallowed. At the client’s EOF or the handshake deadline: PermissionDenied, shadowsocks: no matching user. |
| Any record | A tag does not verify. | InvalidData: shadowsocks: invalid AEAD tag |
| Any record | The declared length is above 0x3FFF. |
InvalidData: shadowsocks: record length 0x<len> exceeds 0x3fff |
Address |
Unknown address type, or an unreadable domain. | InvalidData from the address codec, for example unknown address type: 5, empty domain name or non-utf8 domain |
Salt, Address |
The client closes. | Effect::Finish; no outbound was opened. |
Salt, Address |
HANDSHAKE_TIMEOUT passes after the first byte. |
TimedOut: client did not complete its request in time |
Before Relay (supervisor drive) |
No runtime step within HANDSHAKE_TIMEOUT, for example a client that never sends a byte. |
TimedOut: inbound handshake timed out after 10s |
Relay |
The outbound fails to connect or errors. | debug log shadowsocks: outbound gone: …, then ShutdownTransport and Finish. |
| Core | Staging room below STAGING_RESERVE for the response salt. |
staging room below the core's declared reserve; a caller bug, not a peer error. |
| Core | Staging room below a record. | shadowsocks: staging room below the frame; a caller bug. |
| Core | A missing decoder, encoder or match, or a rejection read outside Rejected. |
InvalidData: shadowsocks: no session or shadowsocks: the connection was not rejected. Guards that the state machine does not reach. |
SsStream::start |
The destination cannot be encoded. | InvalidInput: shadowsocks: address |
SsStream::start |
No room for the salt. | shadowsocks: staging room below the declared reserve |
SsStream |
seal before start. |
shadowsocks: sealed before start |
SsStream |
No room for a record. | shadowsocks: staging room below the frame |
SsStream |
A downlink tag or length fails. | shadowsocks: invalid AEAD tag, or the record-length error above |
The client runtime wraps every SsStream error as InvalidData (concepts/src/client.rs → codec_err), so the InvalidInput kind of shadowsocks: address does not reach the caller.
Cancellation needs nothing from the core. It holds no tasks, locks or channels; dropping the runtime drops the core, its Aeads and its buffers. The client codec is the same.
Limits
Section titled “Limits”| Constant | Value | Where |
|---|---|---|
TAG_LEN |
16 bytes | ss_aead.rs, every cipher |
RECORD_HEADER_LEN |
18 bytes | ss_aead.rs, the sealed length and its tag |
RECORD_OVERHEAD |
34 bytes | ss_aead.rs |
FIRST_CHUNK_LEN |
18 bytes | ss_legacy/aead.rs, the trial-decrypted header |
MAX_PAYLOAD |
0x3FFF = 16 383 bytes |
ss_legacy/aead.rs, the most one record carries, sealed or opened |
ShadowsocksCore::BUF_SIZE |
20 * 1024 = 20 480 bytes |
core.rs, the cap on the server runtime’s buffers |
ShadowsocksCore STAGING_RESERVE |
32 + 2 × 34 + 28 = 128 bytes | core.rs |
SsStream::BUF_SIZE |
20 * 1024 = 20 480 bytes |
codec.rs, the cap on the client runtime’s buffers |
SsStream STAGING_RESERVE |
32 + 34 + 259 + 61 = 386 bytes | codec.rs |
SS_BUF |
SsStream::BUF_SIZE |
supervisor/src/topology/outbound/mod.rs |
AddressCodec::MAX_LEN |
259 bytes | helpers/address.rs |
HANDSHAKE_TIMEOUT |
10 s | protocols/src/core/mod.rs |
SNIFF_TIMEOUT |
300 ms | protocols/src/sniff/mod.rs |
SNIFF_LIMIT |
4 KiB | protocols/src/sniff/mod.rs |
RELAY_IDLE_TIMEOUT |
300 s | protocols/src/core/mod.rs |
A full record is 34 + 16 383 = 16 417 bytes. With a 32-byte salt ahead of it, it still fits within the 20 480-byte cap with room to spare. The read buffer starts at 2 KiB and doubles up to the cap while a record is still arriving (concepts/src/buffer.rs). Because both decoders refuse a longer declared length, every record they accept fits the read buffer at its cap.
Changing this code
Section titled “Changing this code”-
Adding a cipher. Add a
Ciphervariant with itskey_lenandnonce_len, aKeyedvariant, its arm inAead::newand ineach_cipher!. Then add theMethodvariant with itscipherarm andfrom_namenames.Cipheris shared, so Shadowsocks 2022 compiles against the new variant too. ExtendCIPHERSinprotocols/tests/unit/ss_aead.rs,METHODSinprotocols/tests/unit/ss_legacy/aead.rsand the method list inss_new_server_vs_new_client_tcp.sessionkeys into a 32-byte buffer, and bothSTAGING_RESERVEvalues assume a salt of at most 32 bytes, so a longer key needs all three raised. -
Touching the decoder.
ChunkDecoderserves both flavours. Keep the rule that the header is opened from a copy and its length remembered, and that the length is checked againstmax_payloadbefore any payload is awaited. Any extra state that advances with a record belongs next topending_len.a_record_presented_again_is_never_decrypted_twicemust keep passing with partial presentations. -
Changing record sizes.
MAX_PAYLOAD, bothBUF_SIZEvalues,SS_BUFand the core’sSTAGING_RESERVEare tied together; the reserve allows two records per outbound read. RaisingBUF_SIZEpast twoMAX_PAYLOADrecords means raising the reserve too.MAX_PAYLOADitself is fixed by SIP004. -
Changing the users API. The supervisor constructs
ShadowsocksServerConfigandShadowsocksUserfield by field inuser_tableand callsResolved::new. A change to these public types is a SemVer change foretemenanki-protocolsand needs the supervisor updated with it. -
Adding a refusal before the user is known. Keep it silent: go 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.
| Test | File | What it pins |
|---|---|---|
records_round_trip_under_every_cipher |
protocols/tests/unit/ss_aead.rs |
hello, an empty record and a 0x3FFF-byte record round-trip under all four ciphers; the wire is exactly three overheads plus the payloads. |
bare_chunks_and_records_share_one_counter |
same | seal_chunk and seal_record interleave on one counter; open_chunk refuses a chunk shorter than a tag. |
a_record_presented_again_is_never_decrypted_twice |
same | Partial presentations of 20 and 30 bytes give NeedMore; the whole record gives Data with the right ranges; the next record still opens. |
a_declared_length_over_the_limit_is_refused |
same | 0x3FFF waits for its payload; 0x4000 is InvalidData. |
a_refused_seal_stages_nothing_and_keeps_the_counter |
same | An oversized payload and a short staging area are both refused, nothing is staged, and the next record opens at nonce 0. |
a_trial_key_neither_changes_the_bytes_nor_advances |
same | opens_length accepts the right key, rejects a wrong key and a short header, leaves the wire unchanged, and the key then opens the record. |
a_key_of_the_wrong_length_is_refused |
same | Aead::new with a 20-byte key is InvalidInput for every cipher; nonce lengths 24 and 12. |
evp_key_known_answer |
protocols/tests/unit/ss_legacy/aead.rs |
EVP_BytesToKey("test") equals MD5("test"); the 32-byte key extends it. |
method_lengths |
same | Key and nonce lengths through Method and Method::cipher. |
both_ends_of_a_session_agree_under_every_method |
same | Two session calls with the same key and salt seal and open the same records, for all four methods. |
only_the_sealing_key_opens_the_first_length |
same | Only the sealing user’s key opens the first 18 bytes. |
a_length_over_0x3fff_is_refused |
same | The SIP004 cap through session and MAX_PAYLOAD. |
debug_shows_the_label_but_never_the_password |
protocols/tests/unit/ss_legacy/users.rs |
ShadowsocksUser’s Debug shows alice, never the password. |
users_sharing_a_password_keep_only_the_first |
same | alice, bob, carol with alice and carol sharing a password resolve to alice, bob. |
request_is_a_salt_and_a_sealed_address_then_records |
protocols/tests/unit/ss_legacy/codec.rs |
Client request layout; seal caps at MAX_PAYLOAD. |
response_salt_is_an_empty_frame_and_records_open_in_place |
same | Partial salt, salt as an empty frame, a data record, a zero-length record as an empty frame. |
the_matching_user_is_picked_by_trial_decryption_and_the_address_parsed |
protocols/tests/unit/ss_legacy/core.rs |
Nothing consumed with only 10 bytes after the salt; the second user, bob, chosen; Open then Forward; established. |
an_unknown_password_is_drained_then_refused_when_the_client_leaves |
same | Every byte swallowed, nothing opened or staged; PermissionDenied at TransportEof. |
a_rejected_client_is_cut_off_at_the_handshake_deadline |
same | PermissionDenied, not TimedOut, at the deadline. |
no_byte_count_makes_the_server_close_first |
same | 1, 49, 50, 51 and 4096 bytes of junk all give no effects and nothing staged. |
an_address_split_across_chunks_is_reassembled |
same | Address across two records, then the payload. |
sniffing_an_ip_target_waits_for_a_recognisable_prefix |
same | SNIFF_TIMEOUT armed; then the relay idle deadline, an Open with the sniffed domain and one ForwardHeld of 41 bytes, in that order. |
the_response_is_a_salt_then_sealed_chunks_until_the_target_closes |
same | A reply of MAX_PAYLOAD + 10 bytes decodes back after the salt; ShutdownTransport and nothing staged at OutboundEof. |
a_silent_target_still_gets_a_salt_before_eof |
same | Exactly key_len bytes staged. |
an_empty_chunk_is_skipped |
same | data, an empty record and more forward datamore, with no Shutdown. |
ss_new_server_vs_new_client_tcp |
protocols/tests/pipeline/shadowsocks.rs |
70 000 bytes echoed through real runtimes with a two-user, sniffing server, for every method, then a clean close. |
two_users_may_not_present_the_same_credential |
supervisor/tests/unit/validate.rs |
A shared password on one inbound is refused (shown there with Trojan; the rule is per credential kind). |
shadowsocks_runs_over_a_transport |
supervisor/tests/unit/validate.rs |
A Shadowsocks and a Shadowsocks 2022 inbound validate over TLS, WebSocket and gRPC, with and without TLS. |
socks_and_shadowsocks_lower_their_stream, socks_and_shadowsocks_on_a_unix_socket_refuse_a_stream |
app/tests/unit/lower.rs |
A Shadowsocks inbound lowers its [inbound.stream] into the spec’s transport, and one on a Unix socket refuses a stream block. |
app_server_shadowsocks_over_grpc, app_client_shadowsocks_over_grpc, app_server_shadowsocks_over_ws_tls, app_client_shadowsocks_over_ws_tls |
app/tests/integration/e2e_xray_wrapped.rs |
Shadowsocks over gRPC, and over WebSocket and TLS, against the pinned Xray in both directions. |
shadowsocks_rides_the_panels_transport, every_legacy_cipher_lowers_to_the_kernels |
katana tests/unit/lower/inbound.rs |
A WebSocket Shadowsocks node lowers to a Ws shape and a gRPC-over-TLS Shadowsocks 2022 node to a Grpc shape with TLS; each legacy cipher of the node config lowers to the kernel’s method of the same name. |
shadowsocks_ciphers_and_keys |
katana tests/unit/api/newv2board.rs |
A UniProxy node’s legacy cipher is read by its name or an alias (aead_aes_256_gcm, chacha20-poly1305); an rc4-md5 node is refused. |
shadowsocks_builds_both_generations |
katana tests/unit/lower/outbound.rs |
The cipher name picks legacy or 2022; rc4-md5 is refused. |
Run the protocol tests with:
cargo test -p etemenanki-protocols --lib ss_aeadcargo test -p etemenanki-protocols --lib ss_legacycargo test -p etemenanki-protocols --test pipeline shadowsocksThe last command also runs the Shadowsocks 2022 pipeline tests, which live in the same file. How the harnesses work (CoreHarness::feed, serve_runtime, client) is covered on testing.