Documentation
¶
Overview ¶
Package shadowaead2022 implements the Shadowsocks 2022 AEAD ciphers.
The Shadowsocks 2022 protocol enhances security over the original shadowaead implementation through:
1. BLAKE3-based key derivation instead of HKDF-SHA1 2. Pre-shared key (PSK) authentication 3. Salt size equals key size for better security 4. Enhanced replay protection
Supported ciphers:
- 2022-blake3-aes-128-gcm
- 2022-blake3-aes-256-gcm
- 2022-blake3-chacha20-poly1305
The package provides both stream (TCP) and packet (UDP) connection wrappers that automatically handle encryption/decryption with salt generation and replay attack mitigation.
Index ¶
- Constants
- Variables
- func AESGCM(meta core.MetaCipher, password string) (core.ShadowCipher, error)
- func AdditionalHeaders(c core.ShadowCipher, seperateHeaderEncoding []byte) ([]byte, error)
- func Chacha20Poly1305(meta core.MetaCipher, password string) (core.ShadowCipher, error)
- func CheckSalt(salt []byte) bool
- func EncodeFixedLengthHeader(header *RequestFixedLengthHeader) []byte
- func EncodeResponseFixedLengthHeader(header *ResponseFixedLengthHeader) []byte
- func EncodeSeparateHeader(header *SeparateHeader) []byte
- func EncodeUDPHeader(header *UDPHeader) []byte
- func EncodeVariableLengthHeader(header *RequestVariableLengthHeader) []byte
- func NewConn(c net.Conn, ciph core.ShadowCipher, users []core.UserConfig, role int) core.TCPConn
- func NewReader(r io.Reader, aead cipher.AEAD) io.Reader
- func NewWriter(w io.Writer, aead cipher.AEAD) io.Writer
- func PackUDP(c core.ShadowCipher, eih bool, separateHeaderKey, bodyKey []byte, ...) ([]byte, error)
- func UnpackUDP(ciph core.ShadowCipher, userTable map[core.EIHHash]core.UserConfig, ...) (*SeparateHeader, *UDPHeader, []byte, []byte, error)
- type ClientSession
- func (s *ClientSession) ClientAddr() netip.AddrPort
- func (s *ClientSession) Conn() net.PacketConn
- func (s *ClientSession) GetNextPacketID() uint64
- func (s *ClientSession) Hash() core.SessionHash
- func (s *ClientSession) LastUsed() time.Time
- func (s *ClientSession) SessionID() uint64
- func (s *ClientSession) SetConn(c net.PacketConn)
- func (s *ClientSession) Target() socks.Addr
- func (s *ClientSession) Touch()
- type ClientSessionManager
- type RequestFixedLengthHeader
- type RequestVariableLengthHeader
- type ResponseFixedLengthHeader
- type SaltFilter
- type SeparateHeader
- type ServerSession
- func (s *ServerSession) ClientAddr() netip.AddrPort
- func (s *ServerSession) ClientSessionID() uint64
- func (s *ServerSession) Conn() net.PacketConn
- func (s *ServerSession) GetNextPacketID() uint64
- func (s *ServerSession) Hash() core.SessionHash
- func (s *ServerSession) Key() []byte
- func (s *ServerSession) LastUsed() time.Time
- func (s *ServerSession) SessionID() uint64
- func (s *ServerSession) SetConn(c net.PacketConn)
- func (s *ServerSession) SetTarget(target socks.Addr)
- func (s *ServerSession) Target() socks.Addr
- func (s *ServerSession) Touch()
- func (s *ServerSession) UpdateClientAddr(addr netip.AddrPort)
- func (s *ServerSession) ValidatePacket(packetID uint64) error
- type ServerSessionManager
- func (m *ServerSessionManager) Close() error
- func (m *ServerSessionManager) Delete(clientSessionID uint64)
- func (m *ServerSessionManager) Get(clientSessionID uint64) *ServerSession
- func (m *ServerSessionManager) GetOrCreate(clientSessionID uint64, clientAddr netip.AddrPort, key []byte) *ServerSession
- func (m *ServerSessionManager) ValidatePacket(clientSessionID, packetID uint64, clientAddr netip.AddrPort, key []byte) (*ServerSession, error)
- type SlidingWindow
- type UDPHeader
- type UDPSessionManager
- func (m *UDPSessionManager) ClientHandleInbound(payload []byte, target socks.Addr, clientAddr netip.AddrPort) (core.UDPSession, []byte, error)
- func (m *UDPSessionManager) ClientHandleOutbound(encrypted []byte, udpSession core.UDPSession) ([]byte, error)
- func (m *UDPSessionManager) ServerHandleInbound(encrypted []byte, clientAddr netip.AddrPort) (core.UDPSession, socks.Addr, []byte, error)
- func (m *UDPSessionManager) ServerHandleOutbound(plaintext []byte, target socks.Addr, udpSession core.UDPSession) ([]byte, error)
- func (m *UDPSessionManager) SetServerConn(conn *net.UDPConn)
Constants ¶
const ( // TimestampTolerance is the maximum allowed timestamp difference (30 seconds) TimestampTolerance = 30 * time.Second // Stream type constants HeaderTypeClientStream = 0 HeaderTypeServerStream = 1 // Padding constraints MinPaddingLength = 0 MaxPaddingLength = 900 READER_STATE_INIT = 0 // reader has initialized, but not read any headers READER_STATE_FIXED_LENGTH_HEADER = 1 // reader has read fixed length headers READER_STATE_READY = 2 // reader has read variable length headers and can receive payload chunks WRITER_STATE_INIT = 0 WRITER_STATE_READY = 1 )
SIP022 constants
Variables ¶
var ( ErrShortPacket = errors.New("short packet") ErrInvalidSessionID = errors.New("invalid session ID") ErrReplayAttack = errors.New("replay attack detected") )
ErrShortPacket means that the packet is too short for a valid encrypted packet.
Functions ¶
func AESGCM ¶
func AESGCM(meta core.MetaCipher, password string) (core.ShadowCipher, error)
AESGCM creates a new Cipher with a pre-shared key. len(psk) must be one of 16, 32 to select AES-128/256-GCM.
func AdditionalHeaders ¶
func AdditionalHeaders(c core.ShadowCipher, seperateHeaderEncoding []byte) ([]byte, error)
Generate Extensible Identity Headers
func Chacha20Poly1305 ¶
func Chacha20Poly1305(meta core.MetaCipher, password string) (core.ShadowCipher, error)
Chacha20Poly1305 creates a new Cipher with a pre-shared key. len(psk) must be 32.
func EncodeFixedLengthHeader ¶
func EncodeFixedLengthHeader(header *RequestFixedLengthHeader) []byte
EncodeFixedLengthHeader encodes a fixed-length header for transmission
func EncodeResponseFixedLengthHeader ¶
func EncodeResponseFixedLengthHeader(header *ResponseFixedLengthHeader) []byte
EncodeResponseFixedLengthHeader encodes a response fixed-length header
func EncodeSeparateHeader ¶
func EncodeSeparateHeader(header *SeparateHeader) []byte
EncodeSeparateHeader encodes separate header to bytes
func EncodeUDPHeader ¶
EncodeUDPHeader encodes UDP header for both request and response
func EncodeVariableLengthHeader ¶
func EncodeVariableLengthHeader(header *RequestVariableLengthHeader) []byte
EncodeVariableLengthHeader encodes a variable-length header for transmission
func NewConn ¶
func NewConn(c net.Conn, ciph core.ShadowCipher, users []core.UserConfig, role int) core.TCPConn
NewConn wraps a stream-oriented net.Conn with cipher.
func PackUDP ¶
func PackUDP(c core.ShadowCipher, eih bool, separateHeaderKey, bodyKey []byte, payload []byte, target socks.Addr, sessionID, packetID, clientSessionID uint64) ([]byte, error)
PackUDP encrypts plaintext using SIP022 UDP format (both request and response) Format: AES(separate_header) + AEAD(body)
func UnpackUDP ¶
func UnpackUDP(ciph core.ShadowCipher, userTable map[core.EIHHash]core.UserConfig, encrypted []byte) (*SeparateHeader, *UDPHeader, []byte, []byte, error)
UnpackUDP decrypts pkt using SIP022 UDP format (both request and response) Format: AES(separate_header) + AEAD(body) Returns: (separateHeader, payloadHeader, payloadBody, key for decryption, error)
The workflow: 1. decrypt separateHeader. For server, use the first key of ciph. For client, use the last key of ciph 2. decrypt Extensible Identity Headers if userTable is not nil 3. decrypt body. For server, use the key from EIH. For client, use the last key of ciph NOTE: For server, there is only one key in the ciph
Types ¶
type ClientSession ¶
type ClientSession struct {
// contains filtered or unexported fields
}
ClientSession represents a UDP relay session on the client side. Each session corresponds to one local source address (client application).
In SIP022, the client: - Generates a random session ID for each source address - Maintains a monotonically increasing packet counter - Remembers the target address for this session
func NewClientSession ¶
func NewClientSession(clientAddr netip.AddrPort, target socks.Addr) *ClientSession
NewClientSession creates a new client session with a random session ID.
func (*ClientSession) ClientAddr ¶
func (s *ClientSession) ClientAddr() netip.AddrPort
func (*ClientSession) Conn ¶
func (s *ClientSession) Conn() net.PacketConn
func (*ClientSession) GetNextPacketID ¶
func (s *ClientSession) GetNextPacketID() uint64
GetNextPacketID returns the next packet ID and increments the counter. Thread-safe: can be called concurrently.
func (*ClientSession) Hash ¶
func (s *ClientSession) Hash() core.SessionHash
func (*ClientSession) LastUsed ¶
func (s *ClientSession) LastUsed() time.Time
LastUsed returns when this session was last used.
func (*ClientSession) SessionID ¶
func (s *ClientSession) SessionID() uint64
SessionID returns the session ID.
func (*ClientSession) SetConn ¶
func (s *ClientSession) SetConn(c net.PacketConn)
func (*ClientSession) Target ¶
func (s *ClientSession) Target() socks.Addr
Target returns the target address for this session.
func (*ClientSession) Touch ¶
func (s *ClientSession) Touch()
type ClientSessionManager ¶
type ClientSessionManager struct {
// contains filtered or unexported fields
}
ClientSessionManager manages UDP relay sessions on the client side. It maps source addresses (local applications) to sessions.
Key design principles: 1. One session per source address 2. Each session has its own outbound connection 3. Sessions timeout after inactivity 4. No special cases: simple map lookup
func NewClientSessionManager ¶
func NewClientSessionManager(timeout time.Duration) *ClientSessionManager
NewClientSessionManager creates a new client-side session manager.
func (*ClientSessionManager) Close ¶
func (m *ClientSessionManager) Close() error
Close stops the cleanup loop and closes all sessions.
func (*ClientSessionManager) Delete ¶
func (m *ClientSessionManager) Delete(sourceAddr netip.AddrPort)
Delete removes a session and closes its connection.
func (*ClientSessionManager) Get ¶
func (m *ClientSessionManager) Get(sourceAddr netip.AddrPort) *ClientSession
Get retrieves an existing session for the source address. Returns nil if no session exists.
func (*ClientSessionManager) GetOrCreate ¶
func (m *ClientSessionManager) GetOrCreate(sourceAddr netip.AddrPort, target socks.Addr) *ClientSession
GetOrCreate retrieves or creates a session for the source address.
type RequestFixedLengthHeader ¶
type RequestFixedLengthHeader struct {
Type byte // HeaderTypeClientStream or HeaderTypeServerStream
Timestamp int64 // Unix epoch timestamp (8 bytes)
Length uint16 // Next chunk's plaintext length
}
RequestFixedLengthHeader represents the SIP022 fixed-length header
func DecodeFixedLengthHeader ¶
func DecodeFixedLengthHeader(data []byte) (*RequestFixedLengthHeader, error)
DecodeFixedLengthHeader decodes a fixed-length header from encrypted data
type RequestVariableLengthHeader ¶
type RequestVariableLengthHeader struct {
Addr socks.Addr // Target address (includes type, address, and port)
PaddingLength uint16 // Padding length
Padding []byte // Random padding
Payload []byte // Initial payload
}
RequestVariableLengthHeader represents the SIP022 variable-length header
func DecodeVariableLengthHeader ¶
func DecodeVariableLengthHeader(data []byte) (*RequestVariableLengthHeader, error)
DecodeVariableLengthHeader decodes a variable-length header from encrypted data
type ResponseFixedLengthHeader ¶
type ResponseFixedLengthHeader struct {
Type byte // HeaderTypeServerStream
Timestamp int64 // Unix epoch timestamp (8 bytes)
RequestSalt []byte // 16 or 32 bytes depending on cipher
Length uint16 // Next chunk's plaintext length
}
ResponseFixedLengthHeader represents the SIP022 response fixed-length header
func DecodeResponseFixedLengthHeader ¶
func DecodeResponseFixedLengthHeader(data []byte, saltSize int) (*ResponseFixedLengthHeader, error)
DecodeResponseFixedLengthHeader decodes a response fixed-length header
type SaltFilter ¶
type SaltFilter struct {
// contains filtered or unexported fields
}
SaltFilter implements time-based salt filtering per SIP022 specification Salts are stored for exactly 60 seconds as required by the spec
func GetSaltFilter ¶
func GetSaltFilter() *SaltFilter
GetSaltFilter returns the global SIP022 salt filter instance
func NewSaltFilter ¶
func NewSaltFilter() *SaltFilter
NewSaltFilter creates a new SIP022-compliant salt filter
func (*SaltFilter) Check ¶
func (sf *SaltFilter) Check(salt []byte) bool
Check tests if salt exists, and if not, adds it. Returns true if salt was already present.
type SeparateHeader ¶
SeparateHeader represents the UDP separate header (16 bytes)
func DecodeSeparateHeader ¶
func DecodeSeparateHeader(data []byte) (*SeparateHeader, error)
DecodeSeparateHeader decodes separate header from bytes
type ServerSession ¶
type ServerSession struct {
// contains filtered or unexported fields
}
ServerSession represents a UDP relay session on the server side. Each session corresponds to one client session ID.
In SIP022, the server: - Tracks sessions by client's session ID - Validates packet IDs using sliding window (anti-replay) - Updates client address when NAT changes - Generates its own packet IDs for responses
func NewServerSession ¶
func NewServerSession(clientSessionID uint64, clientAddr netip.AddrPort, windowSize uint64, key []byte) *ServerSession
NewServerSession creates a new server session for a client session ID.
func (*ServerSession) ClientAddr ¶
func (s *ServerSession) ClientAddr() netip.AddrPort
GetClientAddr returns the current client address.
func (*ServerSession) ClientSessionID ¶
func (s *ServerSession) ClientSessionID() uint64
ClientSessionID returns the client's session ID.
func (*ServerSession) Conn ¶
func (s *ServerSession) Conn() net.PacketConn
func (*ServerSession) GetNextPacketID ¶
func (s *ServerSession) GetNextPacketID() uint64
GetNextPacketID returns the next packet ID for server responses.
func (*ServerSession) Hash ¶
func (s *ServerSession) Hash() core.SessionHash
func (*ServerSession) Key ¶
func (s *ServerSession) Key() []byte
func (*ServerSession) LastUsed ¶
func (s *ServerSession) LastUsed() time.Time
LastSeen returns when this session last received a packet.
func (*ServerSession) SessionID ¶
func (s *ServerSession) SessionID() uint64
ServerSessionID returns the server's session ID.
func (*ServerSession) SetConn ¶
func (s *ServerSession) SetConn(c net.PacketConn)
func (*ServerSession) SetTarget ¶
func (s *ServerSession) SetTarget(target socks.Addr)
SetTarget sets the target address for this session.
func (*ServerSession) Target ¶
func (s *ServerSession) Target() socks.Addr
GetTarget returns the target address.
func (*ServerSession) Touch ¶
func (s *ServerSession) Touch()
func (*ServerSession) UpdateClientAddr ¶
func (s *ServerSession) UpdateClientAddr(addr netip.AddrPort)
UpdateClientAddr updates the last seen client address. This handles NAT rebinding as per SIP022 spec.
func (*ServerSession) ValidatePacket ¶
func (s *ServerSession) ValidatePacket(packetID uint64) error
ValidatePacket validates a packet ID using the sliding window filter. Returns an error if the packet is a replay or too old. Thread-safe: can be called concurrently.
type ServerSessionManager ¶
type ServerSessionManager struct {
// contains filtered or unexported fields
}
ServerSessionManager manages UDP relay sessions on the server side. It maps client session IDs to server sessions.
Key design principles: 1. Sessions are keyed by client session ID (not address) 2. Each session has its own sliding window for replay protection 3. Client addresses update on every valid packet (NAT handling) 4. Sessions timeout after inactivity 5. No special cases: just a map lookup
func NewServerSessionManager ¶
func NewServerSessionManager(timeout time.Duration, windowSize uint64) *ServerSessionManager
NewServerSessionManager creates a new server-side session manager.
func (*ServerSessionManager) Close ¶
func (m *ServerSessionManager) Close() error
Close stops the cleanup loop and closes all sessions.
func (*ServerSessionManager) Delete ¶
func (m *ServerSessionManager) Delete(clientSessionID uint64)
Delete removes a session and closes its connection.
func (*ServerSessionManager) Get ¶
func (m *ServerSessionManager) Get(clientSessionID uint64) *ServerSession
Get retrieves an existing session by client session ID. Returns nil if no session exists.
func (*ServerSessionManager) GetOrCreate ¶
func (m *ServerSessionManager) GetOrCreate(clientSessionID uint64, clientAddr netip.AddrPort, key []byte) *ServerSession
GetOrCreate retrieves or creates a session for the client session ID.
func (*ServerSessionManager) ValidatePacket ¶
func (m *ServerSessionManager) ValidatePacket(clientSessionID, packetID uint64, clientAddr netip.AddrPort, key []byte) (*ServerSession, error)
ValidatePacket is a convenience method that combines session lookup and packet validation. It gets or creates the session, validates the packet ID, and updates the client address. Returns the session and an error if validation fails.
type SlidingWindow ¶
type SlidingWindow struct {
// contains filtered or unexported fields
}
SlidingWindow implements proper anti-replay protection using a bitmap-based sliding window. This is what the SIP022 spec actually requires: "employ a sliding window filter".
The window tracks received packet IDs using a bitmap. Each bit represents whether a specific packet ID has been received. The window slides forward as newer packets arrive.
func NewSlidingWindow ¶
func NewSlidingWindow(windowSize uint64) *SlidingWindow
NewSlidingWindow creates a sliding window filter for anti-replay protection. windowSize should be the maximum allowed gap between packet IDs (typically 2000).
func (*SlidingWindow) Count ¶
func (w *SlidingWindow) Count() int
Count returns the number of packets marked as received in the window. This is mainly useful for debugging and testing.
func (*SlidingWindow) Validate ¶
func (w *SlidingWindow) Validate(packetID uint64) bool
Validate checks if a packet ID is valid (not a replay and within window). Returns true if the packet should be accepted, false if it's a replay or too old.
This is the correct implementation: - Packets older than (maxPacketID - windowSize) are rejected (too old) - Packets already received are rejected (replay attack) - New packets update the bitmap and slide the window if necessary
type UDPHeader ¶
type UDPHeader struct {
Type byte // HeaderTypeClientStream (0) or HeaderTypeServerStream (1)
Timestamp int64 // Unix epoch timestamp (8 bytes)
ClientSessionID uint64 // Client session ID (8 bytes, only for response)
PaddingLength uint16 // Padding length (2 bytes)
Address socks.Addr // Target address (request) or Source address (response)
Padding []byte // Random padding
}
UDPHeader represents the UDP header for both request and response
func DecodeUDPHeader ¶
DecodeUDPHeader decodes UDP header for both request and response
type UDPSessionManager ¶
type UDPSessionManager struct {
// contains filtered or unexported fields
}
UDPSessionManager implements UDPSessionManager for Shadowsocks 2022 (UDP).
Design: Stateful session-based relay with anti-replay protection - Sessions keyed by session ID (not address) - Monotonic packet counters with sliding window validation - Handles NAT rebinding (client address can change) - Complex but secure: built for real-world hostile networks
func (*UDPSessionManager) ClientHandleInbound ¶
func (m *UDPSessionManager) ClientHandleInbound(payload []byte, target socks.Addr, clientAddr netip.AddrPort) (core.UDPSession, []byte, error)
func (*UDPSessionManager) ClientHandleOutbound ¶
func (m *UDPSessionManager) ClientHandleOutbound(encrypted []byte, udpSession core.UDPSession) ([]byte, error)
func (*UDPSessionManager) ServerHandleInbound ¶
func (m *UDPSessionManager) ServerHandleInbound(encrypted []byte, clientAddr netip.AddrPort) (core.UDPSession, socks.Addr, []byte, error)
HandleInbound processes an incoming encrypted packet and forwards it (server-side). UDP protocol flow: 1. Decrypt separate header (AES) to get session ID + packet ID 2. Validate session: anti-replay + NAT rebinding 3. Decrypt main body (AEAD) to get target address + payload
func (*UDPSessionManager) ServerHandleOutbound ¶
func (m *UDPSessionManager) ServerHandleOutbound(plaintext []byte, target socks.Addr, udpSession core.UDPSession) ([]byte, error)
UDP protocol: session ID + packet counter + target address.
func (*UDPSessionManager) SetServerConn ¶
func (m *UDPSessionManager) SetServerConn(conn *net.UDPConn)
SetServerConn sets the server-side listening connection (needed for sending encrypted responses)