A Shadowsocks client and server: AEAD and Shadowsocks 2022 ciphers, ss:// links, simple-obfs, a UDP relay, and a stream that runs over any tunnel.Stream.
import net.shadowsocks
Shadowsocks is a small encrypted proxy protocol. A client connects to a Shadowsocks server and says which host and port it wants to reach; the server connects there and carries bytes both ways. Everything after the first byte looks like random data, so there is no handshake to recognise. net.shadowsocks is a client and a server for it written in Salam, with no native library. It is one of the proxy packages built on net.tunnel and can be plugged into the same routers and chains as the others.
The main calls are few. Dial opens a Conn through a server to a target such as example.com:443; Read, Write and Close then work like on any socket. Listen starts a server and Serve or ServeRelay answers clients. Config holds the server address, the cipher method, the password and the optional obfs disguise. Everything else (Buf, Encoder, Decoder, the BLAKE3 and key functions) is the lower level the protocol is built from, public so you can test it or build your own framing.
Quick start
This program starts a server on a free port, connects a client through it to example.com:443 and sends one message. The handler never connects to example.com; it only reads the target the client asked for with TargetOf and echoes the bytes back, so the whole run stays on the loopback interface. Stop wakes the accept loop so that Serve returns, and Destroy frees the server.
net-shadowsocks-guide-loopback.salam
import mem
import net.shadowsocks
const PASSWORD := "correct horse"mut srv := shadowsocks.Server {}
mut seen := ""funcanswer(c: shadowsocks.Conn):
t := shadowsocks.TargetOf(c)
seen = t.host + ":" + t.port
buf := mem.Allocate(4096asu64)
n := shadowsocks.Read(c, buf, 4096)
shadowsocks.Write(c, buf, n)
mem.Free(buf)
shadowsocks.Close(c)
endfuncserve():
shadowsocks.Serve(srv, (c: shadowsocks.Conn): answer(c) end)
endfuncmain:
srv = shadowsocks.Listen(0, "chacha20-ietf-poly1305", PASSWORD)
println shadowsocks.ServerOk(srv)
t := spawn(serve)
cfg := shadowsocks.Config {
host = "127.0.0.1",
port = shadowsocks.ServerPort(srv),
method = "chacha20-ietf-poly1305",
password = PASSWORD
}
c := shadowsocks.Dial(cfg, "example.com", 443)
println shadowsocks.Ok(c)
shadowsocks.WriteStr(c, "hello through shadowsocks")
println shadowsocks.ReadStr(c, 4096)
shadowsocks.Close(c)
shadowsocks.Stop(srv)
join(t)
shadowsocks.Destroy(srv)
println"server saw", seen
end
Output
true
true
hello through shadowsocks
server saw example.com:443
A real server uses ServeRelay, which does the forwarding for you: for each client it connects to the requested target and copies bytes in both directions until either side closes. The next example runs a relay in front of a small TCP echo server and sends a message through it.
The client side is just Dial with a Config. Dial returns at once without waiting for the server: the target address travels in the first encrypted packet together with your first Write. So a wrong password is not reported by Dial; the server drops the connection and your first Read returns 0 or a negative number. Check Ok for a connection that could not even start (an unknown method, or the server not reachable).
Ciphers
The method is a name from this table. LookupMethod turns a name into a Method and returns one with ok false for a name it does not know. The name chacha20-poly1305 is accepted too, as an alias of chacha20-ietf-poly1305. Old stream ciphers such as rc4-md5 and aes-256-cfb are not supported and never will be: they are broken.
Method
Key
Salt
Password form
Notes
aes-128-gcm
16 bytes
16 bytes
any text
Classic AEAD. Slow here, see below.
aes-256-gcm
32 bytes
32 bytes
any text
Classic AEAD. The default of Config. Slow here, see below.
For the first three, the password is any text and the key is derived from it the classic way (BytesToKey, MD5 based), so use a long random password. For the 2022 ciphers the password is the key: it must be the base64 of exactly the key length, for example the output of openssl rand -base64 32. A password of the wrong length makes MakeKey return a Buf with bad set, and Listen or Dial then fail. The 2022 ciphers add replay protection with a timestamp (a request more than 30 seconds off is refused) and a salt cache, and the connection header is authenticated.
What is not there
•
Shadowsocks 2022 UDP has its own functions. PackUdp and UnpackUdp are for the classic methods and refuse the three 2022 methods; use PackUdp2022 and UnpackUdp2022, or UdpListen and UdpDial, which pick the right one.
•
Several users on one port (the 2022 extensible identity headers) work only with the two AES 2022 methods. The ChaCha 2022 method takes a single key.
•
No real server was used to test the interoperability of simple-obfs and of the 2022 TCP stream. They are tested against this package itself and against separate Python reimplementations written from the specifications, not against ssserver, shadowsocks-rust or the real obfs-server. The classic AEAD ciphers are checked against published test vectors. Treat the 2022 methods and the obfuscation as young and test against your own server before relying on them.
•
AES is done in software (bitsliced, to avoid timing leaks) and is slow: in the tests here about four to five times slower than ChaCha20. Prefer chacha20-ietf-poly1305.
•
The relay has no half close: when one side closes, the whole connection is shut down. A protocol that depends on a client finishing its request with a close and still reading the answer will break.
•
No anti probing behaviour: a server that receives a bad first packet closes the connection at once instead of draining it as a real web server would, so a prober can tell it is not one.
•
UDP works over IPv4 and IPv6 (client and relay sockets accept both; UdpListenOn("::", port) serves both), and the UDP relay has no replay filter (TCP has one, a salt cache of 100000 entries).
•
Only the HTTP and TLS shapes of simple-obfs exist, not the plugin v2ray-plugin or other plugins.
ss:// links and plugin options
Shadowsocks servers are shared as ss:// links. ParseUri reads the SIP002 form ss://base64(method:password)@host:port/?plugin=...#tag, the form with the user info in plain percent encoded text (used by the 2022 ciphers), and the old form where the whole method:password@host:port is base64. It returns a Uri whose ok is true only when the link is well formed and the method is known. FormatUri writes the link back (a 2022 link is written with the method and password in text, the others as base64). ToConfig turns a Uri into a Config that Dial accepts, including the obfuscation options of the plugin.
The plugin text is a plugin name followed by key=value options separated by semicolons, with a backslash to escape a semicolon or equals sign. ParsePlugin splits it into a Plugin and PluginGet and PluginHas read the options. Free it with PluginFree. ToConfig understands the plugin names obfs-local and simple-obfs with the options obfs (http or tls) and obfs-host; any other plugin is ignored, so check u.plugin yourself if you need to refuse it.
true chacha20-ietf-poly1305 secret 203.0.113.5 8388 my server
obfs-local;obfs=tls;obfs-host=cdn.example.com
obfs-local tls true false
203.0.113.5 8388 chacha20-ietf-poly1305 tls cdn.example.com
ss://Y2hhY2hhMjAtaWV0Zi1wb2x5MTMwNTpzZWNyZXQ@203.0.113.5:8388/?plugin=obfs-local%3Bobfs%3Dtls%3Bobfs-host%3Dcdn.example.com#my%20server
false
simple-obfs
simple-obfs hides the first bytes of a Shadowsocks connection inside something that looks like ordinary web traffic, which helps against filters that classify connections by their first packet. Set obfs in the client Config to "http" or "tls", set obfs_host to the host name to show (the Host header or the TLS server name, default www.bing.com), and start the server with ListenObfs and the same mode. Both sides must agree: a server without obfs does not understand an obfs client and the other way round.
•
http: the first client packet is sent as an HTTP request with a WebSocket upgrade header, the server answers with a 101 Switching Protocols, and after that the data flows as is.
•
tls: the first client packet is a fake TLS ClientHello carrying the data in a session ticket extension and the server name you chose, the server answers with a fake ServerHello, and the rest is wrapped in TLS application data records.
This is camouflage, not encryption: the Shadowsocks cipher underneath still protects the data. The fake handshake is simple and a determined censor can fingerprint it; it also does not make the connection look like a real site to an active prober. ObfsMode turns the names into the constants OBFS_NONE, OBFS_HTTP and OBFS_TLS, and ObfsInit, ObfsWrap, ObfsUnwrap and ObfsFree expose the framing for your own use.
Shadowsocks carries UDP too, for DNS and for games, one encrypted datagram at a time: the packet holds a random salt, the target address and the payload, sealed as a whole. UdpListen starts a relay on a UDP port; UdpServe loops until UdpStop is called, and UdpStep handles one packet and returns 1 when it did, so you can drive it yourself. The relay keeps one outgoing socket per client and forgets a client after 60 seconds of silence. On the client, UdpDial makes a UdpClient, UdpSend sends a payload to a target through the relay and UdpRecv returns the next reply and who it came from; UdpSetTimeout bounds the wait. UDP also works with the three 2022 ciphers (SIP022): the client picks a random session ID, numbers its packets, and the first 16 bytes of each datagram are that header encrypted on its own (AES-ECB for the AES methods, an XChaCha20-Poly1305 nonce for the ChaCha one). Packets carry a timestamp that must be within 30 seconds, and the relay drops any packet ID it has already seen in a 64 packet window. The classic methods get a salt filter on the relay, so a recorded datagram is answered once. UDP targets must be IPv4 or domain names.
An AES 2022 server can serve many users, each with their own key. Give the server its own key as the password, then call AddUser (UdpAddUser for UDP) once per user key. A client connects with the password serverkey:userkey: it sends an identity header that names its user without revealing the key, and the server picks that user's key for the session. ChainOf, EihSeal and EihOpen are the pieces underneath. The ChaCha 2022 method has no identity headers, so it takes a single key. ListenOn and UdpListenOn bind to one address instead of every interface, for example 127.0.0.1. When a handshake fails the server keeps the socket open for a random 1.5 to 4.5 seconds and reads what is sent before closing, so a probe cannot tell a refusal from a slow server. Relay passes a half close in both directions: when one side stops sending, the other side is told and can still answer.
Running over a tunnel.Stream
The client normally dials its server with TCP, but DialOver takes any tunnel.Stream instead: a WebSocket, a TLS connection, the output of another proxy hop, or a stream you made. The server side has AcceptOver. In both cases the Shadowsocks layer treats the stream as the wire, so you can put Shadowsocks inside a transport from net.transport, or behind a proxy chain from net.tunnel. AsStream does the opposite: it wraps a Conn as a tunnel.Stream, so a Shadowsocks connection can be handed to anything that takes a stream, such as a router outbound or another protocol layer.
net-shadowsocks-guide-over-stream.salam
import mem
import sync
import net.tcp
import net.tunnel
import net.shadowsocks
mut port := 0mut ready := sync.NewWaitGroup()
funcserver():
carrier := tcp.Bind(0)
port = tcp.Port(carrier)
srv := shadowsocks.Listen(0, "aes-128-gcm", "inner")
sync.Done(ready)
raw := tcp.Accept(carrier)
c := shadowsocks.AcceptOver(srv, tunnel.TcpStream { conn = raw })
if shadowsocks.Ok(c):
buf := mem.Allocate(4096asu64)
n := shadowsocks.Read(c, buf, 4096)
shadowsocks.Write(c, buf, n)
mem.Free(buf)
shadowsocks.Close(c)
end
shadowsocks.Destroy(srv)
tcp.CloseServer(carrier)
endfuncmain:
sync.Add(ready, 1asi64)
t := spawn(server)
sync.Wait(ready)
link := tunnel.TcpStream { conn = tcp.Dial("127.0.0.1", port) }
cfg := shadowsocks.Config { method = "aes-128-gcm", password = "inner" }
c := shadowsocks.DialOver(link, cfg, "example.com", 443)
shadowsocks.WriteStr(c, "any stream will do")
println shadowsocks.ReadStr(c, 4096)
s := shadowsocks.AsStream(c)
println s.Ok()
shadowsocks.Close(c)
join(t)
end
Output
any stream will do
true
The framing layer
The bottom of the package is public. An Encoder seals a byte stream into length prefixed AEAD chunks (EmitSalt first, then EncodeStream); a Decoder takes in the bytes as they arrive with Feed and returns the plaintext with NextChunk, or all at once with DecodeAll. EncodeTarget and ParseTarget write and read the address header (ATYP_IPV4, ATYP_DOMAIN, ATYP_IPV6), and PackUdp and UnpackUdp do the same for one datagram. Buf is the growable byte buffer all of them use: you own it, free it with BufFree and wipe key material with BufWipe first. This is how the protocol is tested against known vectors, and how you can write a custom front end.
The example under Buf below runs a whole round trip: it seals a stream and opens it again, writes and reads an address header, and packs and unpacks one UDP datagram.
Practical notes for Iran
These are tips for people building tools for networks with heavy filtering. They come from how the protocol works, not from tests against any particular ISP, and what works changes from month to month.
•
Pick ChaCha20. Use chacha20-ietf-poly1305 unless the other end only offers something else. It is the fastest cipher here by a wide margin, and the security is the same as AES-GCM. Choose a 2022 method only when your server also speaks it and you can test it end to end; it has the best design (replay protection, authenticated header) but the least interoperability testing.
•
Use a long random password for the classic methods, at least 20 characters from a password generator. Short passwords can be guessed offline from a captured connection.
•
Do not rely on plain Shadowsocks alone. Pure random looking traffic on an unusual port is itself a signal, and the lack of an anti probing reply makes it easier to confirm. Put it on port 443, behind a transport that looks like a web site (a WebSocket over TLS, with DialOver and AcceptOver), or use simple-obfs with tls and a host name that is allowed and common on that network.
•
Use the tunnel router.net.tunnel has routing rules with an Iran preset: domestic sites go direct and the rest goes through the proxy, so the local network is not slowed down and domestic sites do not see a foreign address. Make a Shadowsocks outbound from a Config, wrap it as a stream with AsStream where a dialer wants a stream, and let the router choose. For a local SOCKS or HTTP entry point see net.socks and net.httpproxy.
•
Resolve names remotely. Pass the host name to Dial and let the server resolve it; do not resolve it locally first, or the lookup leaks. When a local lookup is unavoidable, net.doh sends it over HTTPS.
•
Keep sharing safe. A link carries the password in clear text apart from base64: send it over a private channel, and do not publish servers you want to keep alive.
A replay filter: it remembers the salts of recent connections in two generations so memory stays bounded. It is thread safe.
Name
Type
Description
cur
HashMap<str, bool>
The current generation of seen salts.
old
HashMap<str, bool>
The previous generation, dropped when the current one fills.
cap
int = 0
How many salts one generation holds.
lock
sync.Mutex
The mutex that guards both generations.
net-shadowsocks-SaltFilter.salam
import net.shadowsocks
funcmain:
mut f := shadowsocks.NewSaltFilter(1000)
a := "salt number one, 32 bytes long.."
b := "salt number two, 32 bytes long.."println f.cap, shadowsocks.FilterSeen(f, a asvoid*, 32)
println shadowsocks.FilterCheck(f, a asvoid*, 32), shadowsocks.FilterSeen(f, a asvoid*, 32)
println shadowsocks.FilterCheck(f, a asvoid*, 32), shadowsocks.FilterCheck(f, b asvoid*, 32)
println f.cur.Size(), f.old.Size()
shadowsocks.FilterFree(f)
end
Everything one connection needs: the socket or underlying stream, both ciphers, the buffers and the handshake progress. You only hold a pointer to it inside a Conn.
Name
Type
Description
sock
tcp.Conn
The TCP socket, when the connection does not run over a stream.
method
Method
The cipher method.
key
Buf
The master key.
enc
Encoder
The encoder for the data that is sent.
dec
Decoder
The decoder for the data that is received.
plain
Buf
Decrypted bytes that were not read yet.
plain_pos
int = 0
How much of plain was read.
out
Buf
A scratch buffer for the bytes about to be sent.
rd
void*
The receive buffer.
pending
Buf
The address header held back until the first write.
target
Target
The destination of the connection: asked for by the client, or read by the server.
obfs
Obfs
The disguise layer.
up
dyn tunnel.Stream
The underlying stream, when use_up is true.
use_up
bool = false
True when the connection runs over a stream and not a socket.
obuf
Buf
A scratch buffer for disguised output.
oin
Buf
Raw bytes received before the disguise was removed.
rd2
void*
The raw receive buffer.
v2022
bool = false
True for a 2022 method.
is_server
bool = false
True on the server side.
wphase
int = 0
The write side handshake step.
rphase
int = 0
The read side handshake step.
first_len
int = 0
The length announced by the first 2022 header.
target_ok
bool = false
True once the target was received.
vtmp
Buf
A scratch buffer for the 2022 header.
live
bool = false
True while the connection is open.
eih
Buf
The identity keys of a serverkey:userkey password, all keys except the last one, one after another.
eih_n
int = 0
How many identity keys eih holds.
eih_done
bool = false
On a server, true once the identity header of the client was opened and its user key is in use.
user
str = ""
On a server, the name of the user the identity header named; empty otherwise.
The state of a running server: the listening socket, the cipher and key, the replay filter and the worker pool. You get one inside a Server and only pass it around.
Name
Type
Description
ls
tcp.Server
The listening TCP socket.
host
str = ""
The address the server listens on; empty means every IPv4 interface. Stop uses it to wake the accept loop.
method
Method
The cipher the server uses.
key
Buf
The master key, from the password.
filter
SaltFilter
The salt cache that rejects a replayed connection.
workers
pool.Pool
The pool of threads that run client handlers.
stop
i64*
A flag that tells Serve to stop; Stop sets it.
jobs
chan.Chan<i64>
The queue of accepted connections waiting for a worker.
obfs_mode
str = ""
The obfuscation mode, http, tls or empty for none.
users
HashMap<str, Buf>
The keys of the users added with AddUser, by the hex of the hash that names them in an identity header.
user_names
HashMap<str, str>
The names of those users, by the same hex.
user_n
int = 0
How many users were added.
net-shadowsocks-IPv6.salam
import net.shadowsocks
funcmain:
server := shadowsocks.ListenOn("::1", 0, "aes-256-gcm", "secret", "")
println shadowsocks.ServerOk(server), server.st.host
shadowsocks.Stop(server)
shadowsocks.Destroy(server)
end
Returns true when a salt is already in the filter, without recording it. A server that must authenticate the first chunk before it trusts a connection asks this first and calls FilterCheck only once the chunk is good, so a forged packet cannot fill the filter.
Turns a password into the master key for a method: for a classic method the derived key, for a 2022 method the base64 decoded password. The returned Buf has bad set when a 2022 password has the wrong length.
funcEncodeTarget(host: str, port: int, out &: Buf): bool
Appends the address header for a host and port to the buffer. A host that looks like an IPv4 or IPv6 address is sent as such, anything else as a name of at most 255 bytes. Returns false for a bad port or name.
funcObfsUnwrap(o &: Obfs, p: void*, n: int, out &: Buf): int
Removes the disguise from incoming bytes and appends the payload to the buffer. Returns the number of bytes consumed, 0 when more bytes are needed, or a negative number when the data is not a valid disguise.
Builds one UDP datagram: a random salt, then the target and the payload sealed together. Appends it to the buffer. Returns false for a 2022 method or a bad target.
funcUnpackUdp(m: Method, key: void*, p: void*, n: int, t &: Target, out &: Buf): bool
Opens a datagram, fills the target and appends the payload to the buffer. Returns false when authentication fails, the packet is short or the method is a 2022 method.
Makes a UDP client for the server and the method in the Config. For a 2022 method the password may be serverkey:userkey. ok is false for an unknown method or a bad password.
funcUdpRecv(c: UdpClient, buf: void*, max: int, from &: Target): int
Waits for one reply, opens it and copies the payload to the buffer (up to max bytes), filling from with the sender. Returns the length, or a negative number on timeout or on a packet that does not authenticate.
Starts a UDP relay on a port with a method and a password. For a 2022 method the password is the base64 key. ok is false for an unknown method, a bad password or a port that is taken.
Handles at most one waiting datagram, forwards it, hands pending replies back to their clients and drops idle clients. Returns 1 when a datagram was handled, else 0. It waits about 20 ms for a packet.
Waits for data and copies up to max bytes to the buffer. Returns the length, 0 when the other side closed, or a negative number on error or a failed authentication.
Connects to a Shadowsocks server and asks it to reach a target host and port. The host may be a name; the server resolves it. Returns at once, with the target sent along with the first write.
Splits a 2022 password written as serverkey:userkey (up to 8 base64 keys) into a KeyChain. ok is false for a classic method, more than 8 parts or a part that is not a key of the right length.
Derives the key that seals an identity header: a BLAKE3 key derivation with IDENTITY_CONTEXT over the identity key followed by the salt. Writes klen bytes.
Builds one identity header block: the hash of the next key down the chain, encrypted with AES under the key from IdentityKey. Writes 16 bytes. Returns false for a bad key length.
Checks the packet number of a received datagram against the replay window of the session. Returns true and records the number when it is new and not more than 63 behind the highest; false for a repeat or a number that is too old.
Builds one Shadowsocks 2022 datagram and appends it to the buffer: the encrypted header with the session ID and the packet number, the identity header blocks for a multi user password, then the sealed body with the time, the target and the payload. ukey is the user key and hdr_key the key of the header block; for one key both are that key, and with identity keys it is the first of them. client says which side is sending. Returns false for a classic method or a bad target.
Reads the session ID out of the header of a datagram without opening the body, so that a relay can find the session first. Works for the AES 2022 methods only; false for ChaCha or a packet that is too short.
funcUnpackUdp2022(m: Method, ukey: void*, hdr_key: void*, skip: int, client: bool, p: void*, n: int, s &: UdpSession, t &: Target, out &: Buf): bool
Opens a 2022 datagram: checks the header and the tag, the time (within 30 seconds) and the side, fills the target and appends the payload to the buffer. skip is the number of identity header bytes between the header and the body. On the client side it also rejects replayed packets with the session. Returns false when anything is wrong.
Opens the identity header block of a datagram with the identity key of the server and writes the 16 byte hash of the user key it names. Works for the AES 2022 methods only; false for ChaCha or a packet that is too short.
funcListen(port: int, method: str, password: str): Server
Starts a server on a TCP port (0 picks a free one) with a method and a password. For a 2022 method the password is base64 of the key. Returns a Server that is not ServerOk when the method, the password or the port is bad.
Like ListenObfs, but listens only on the given address, such as 127.0.0.1, instead of every interface. The last argument is the obfuscation, http, tls or empty for none.
Adds a user to a 2022 AES server: a name that shows up in logs and the base64 user key. Clients then connect with the password serverkey:userkey. Returns false for a classic method, for ChaCha 2022 or for a bad key.
Waits for the next client whose handshake succeeds and returns its Conn. A connection that fails the handshake (a wrong password, a replay, a bad timestamp) is closed without a reply and the wait continues. TargetOf tells where the client wants to go.
Like Accept but for one client that arrives over a stream you already have, such as a WebSocket. Returns a Conn that is not Ok when the handshake fails.
Serves one accepted connection as a proxy: connects to the target the client asked for and copies bytes in both directions until one side ends, then closes everything. There is no half close.