ss2022

package
v1.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 22, 2025 License: AGPL-3.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HeaderTypeClientStream = 0
	HeaderTypeServerStream = 1

	HeaderTypeClientPacket = 0
	HeaderTypeServerPacket = 1

	MinPaddingLength = 0
	MaxPaddingLength = 900

	IdentityHeaderLength = 16

	// type + unix epoch timestamp + u16be length
	TCPRequestFixedLengthHeaderLength = 1 + 8 + 2

	// SOCKS address + padding length + padding
	TCPRequestVariableLengthHeaderNoPayloadMaxLength = socks5.MaxAddrLen + 2 + MaxPaddingLength

	// type + unix epoch timestamp + request salt + u16be length
	TCPResponseHeaderMaxLength = 1 + 8 + 32 + 2

	// session ID + packet ID
	UDPSeparateHeaderLength = 8 + 8

	// type + unix epoch timestamp + padding length
	UDPClientMessageHeaderFixedLength = 1 + 8 + 2

	// type + unix epoch timestamp + client session id + padding length
	UDPServerMessageHeaderFixedLength = 1 + 8 + 8 + 2

	// type + unix epoch timestamp + padding length + padding + SOCKS address
	UDPClientMessageHeaderMaxLength = UDPClientMessageHeaderFixedLength + MaxPaddingLength + socks5.MaxAddrLen

	// type + unix epoch timestamp + client session id + padding length + padding + SOCKS address
	UDPServerMessageHeaderMaxLength = UDPServerMessageHeaderFixedLength + MaxPaddingLength + socks5.IPv6AddrLen

	// MaxEpochDiff is the maximum allowed time difference between a received timestamp and system time.
	MaxEpochDiff = 30

	// MaxTimeDiff is the maximum allowed time difference between a received timestamp and system time.
	MaxTimeDiff = MaxEpochDiff * time.Second

	// ReplayWindowDuration defines the amount of time during which a salt check is necessary.
	ReplayWindowDuration = MaxTimeDiff * 2

	// DefaultSlidingWindowFilterSize is the default size of the sliding window filter.
	DefaultSlidingWindowFilterSize = 256
)

Variables

View Source
var (
	ErrIncompleteHeaderInFirstChunk  = errors.New("header in first chunk is missing or incomplete")
	ErrPaddingExceedChunkBorder      = errors.New("padding in first chunk is shorter than advertised")
	ErrZeroResponsePayloadLength     = errors.New("payload length in response header is zero")
	ErrBadTimestamp                  = errors.New("time diff is over 30 seconds")
	ErrTypeMismatch                  = errors.New("header type mismatch")
	ErrClientSaltMismatch            = errors.New("client salt in response header does not match request")
	ErrClientSessionIDMismatch       = errors.New("client session ID in server message header does not match current session")
	ErrTooManyServerSessions         = errors.New("server session changed more than once during the last minute")
	ErrPacketIncompleteHeader        = errors.New("packet contains incomplete header")
	ErrReplay                        = errors.New("detected replay")
	ErrIdentityHeaderUserPSKNotFound = errors.New("decrypted identity header does not match any known uPSK")
)
View Source
var (
	ErrZeroLengthChunk = errors.New("length in length chunk is zero")
	ErrFirstRead       = errors.New("failed to read fixed-length header in one read call")
	ErrRepeatedSalt    = errors.New("detected replay: repeated salt")
)
View Source
var ErrUnsafeStreamPrefixMismatch = errors.New("unsafe stream prefix mismatch")
View Source
var ShadowPacketServerMessageHeadroom = zerocopy.Headroom{
	Front: UDPSeparateHeaderLength + UDPServerMessageHeaderMaxLength,
	Rear:  16,
}

ShadowPacketServerMessageHeadroom is the headroom required by an encrypted Shadowsocks server message.

Functions

func AppendTCPResponseHeader added in v1.14.0

func AppendTCPResponseHeader(b []byte, now time.Time, requestSalt []byte, length int) []byte

AppendTCPResponseHeader appends a TCP response fixed-length header to the buffer.

To avoid allocations, the buffer must have 1 + 8 + len(requestSalt) + 2 bytes of extra capacity.

func CheckPSKLength added in v1.6.0

func CheckPSKLength(method string, psk []byte, psks [][]byte) error

CheckPSKLength checks that the PSK is the correct length for the given method.

func CloseWriteDrain added in v1.14.0

func CloseWriteDrain(c *net.TCPConn, logger *zap.Logger)

CloseWriteDrain closes the write end of the TCP connection, then drain the read end.

func ForceReset added in v1.14.0

func ForceReset(c *net.TCPConn, logger *zap.Logger)

ForceReset forces a reset of the TCP connection, regardless of whether there's unread data or not.

func JustClose added in v1.14.0

func JustClose(_ *net.TCPConn, _ *zap.Logger)

JustClose closes the TCP connection without any special handling.

func NoPadding

func NoPadding(_ conn.Addr) bool

NoPadding is a PaddingPolicy that never adds padding.

func PSKHash added in v1.6.0

func PSKHash(psk []byte) [IdentityHeaderLength]byte

PSKHash returns the given PSK's BLAKE3 hash truncated to IdentityHeaderLength bytes.

func PSKLengthForMethod added in v1.6.0

func PSKLengthForMethod(method string) (int, error)

PSKLengthForMethod returns the required length of the PSK for the given method.

func PadAll

func PadAll(_ conn.Addr) bool

PadAll is a PaddingPolicy that adds padding to all traffic.

func PadPlainDNS

func PadPlainDNS(targetAddr conn.Addr) bool

PadPlainDNS is a PaddingPolicy that adds padding to plain DNS traffic.

func ParseSessionIDAndPacketID

func ParseSessionIDAndPacketID(b []byte) (sid, pid uint64)

ParseSessionIDAndPacketID parses the session ID and packet ID segment of a decrypted UDP packet.

The buffer must be exactly 16 bytes long. No buffer length checks are performed.

Session ID and packet ID segment:

+------------+-----------+
| session ID | packet ID |
+------------+-----------+
|     8B     |   u64be   |
+------------+-----------+

func ParseTCPRequestFixedLengthHeader

func ParseTCPRequestFixedLengthHeader(b []byte, now time.Time) (n int, err error)

ParseTCPRequestFixedLengthHeader parses a TCP request fixed-length header and returns the length of the variable-length header, or an error if header validation fails.

The buffer must be exactly 11 bytes long. No buffer length checks are performed.

Request fixed-length header:

+------+---------------+--------+
| type |   timestamp   | length |
+------+---------------+--------+
|  1B  | 8B unix epoch |  u16be |
+------+---------------+--------+

func ParseTCPRequestVariableLengthHeader

func ParseTCPRequestVariableLengthHeader(b []byte) (targetAddr conn.Addr, payload []byte, err error)

ParseTCPRequestVariableLengthHeader parses a TCP request variable-length header and returns the target address, the initial payload if available, or an error if header validation fails.

This function does buffer length checks and returns ErrIncompleteHeaderInFirstChunk if the buffer is too short.

Request variable-length header:

+------+----------+-------+----------------+----------+-----------------+
| ATYP |  address |  port | padding length |  padding | initial payload |
+------+----------+-------+----------------+----------+-----------------+
|  1B  | variable | u16be |     u16be      | variable |    variable     |
+------+----------+-------+----------------+----------+-----------------+

func ParseTCPResponseHeader

func ParseTCPResponseHeader(b []byte, now time.Time, requestSalt []byte) (n int, err error)

ParseTCPResponseHeader parses a TCP response fixed-length header and returns the length of the next payload chunk, or an error if header validation fails.

The buffer must be exactly 1 + 8 + salt length + 2 bytes long. No buffer length checks are performed.

Response fixed-length header:

+------+---------------+----------------+--------+
| type |   timestamp   |  request salt  | length |
+------+---------------+----------------+--------+
|  1B  | 8B unix epoch |     16/32B     |  u16be |
+------+---------------+----------------+--------+

func ParseUDPClientMessageHeader

func ParseUDPClientMessageHeader(b []byte, now time.Time, cachedDomain string) (targetAddr conn.Addr, updatedCachedDomain string, payloadStart, payloadLen int, err error)

ParseUDPClientMessageHeader parses a UDP client message header and returns the target address and payload, or an error if header validation fails or no payload is in the buffer.

This function accepts buffers of arbitrary lengths.

The buffer is expected to contain a decrypted client message in the following format:

+------+---------------+----------------+----------+------+----------+-------+----------+
| type |   timestamp   | padding length |  padding | ATYP |  address |  port |  payload |
+------+---------------+----------------+----------+------+----------+-------+----------+
|  1B  | 8B unix epoch |     u16be      | variable |  1B  | variable | u16be | variable |
+------+---------------+----------------+----------+------+----------+-------+----------+

func ParseUDPServerMessageHeader

func ParseUDPServerMessageHeader(b []byte, now time.Time, csid uint64) (payloadSourceAddrPort netip.AddrPort, payloadStart, payloadLen int, err error)

ParseUDPServerMessageHeader parses a UDP server message header and returns the payload source address and payload, or an error if header validation fails or no payload is in the buffer.

This function accepts buffers of arbitrary lengths.

The buffer is expected to contain a decrypted server message in the following format:

+------+---------------+-------------------+----------------+----------+------+----------+-------+----------+
| type |   timestamp   | client session ID | padding length |  padding | ATYP |  address |  port |  payload |
+------+---------------+-------------------+----------------+----------+------+----------+-------+----------+
|  1B  | 8B unix epoch |         8B        |     u16be      | variable |  1B  | variable | u16be | variable |
+------+---------------+-------------------+----------------+----------+------+----------+-------+----------+

func PutSessionIDAndPacketID added in v1.14.0

func PutSessionIDAndPacketID(b []byte, sid, pid uint64)

PutSessionIDAndPacketID stores the session ID and packet ID into the buffer.

The buffer must be exactly 16 bytes long. No buffer length checks are performed.

func PutTCPRequestFixedLengthHeader added in v1.14.0

func PutTCPRequestFixedLengthHeader(b []byte, now time.Time, length int)

PutTCPRequestFixedLengthHeader stores a TCP request fixed-length header into the buffer.

The buffer must be at least 11 bytes long. No buffer length checks are performed.

func PutTCPRequestVariableLengthHeader added in v1.14.0

func PutTCPRequestVariableLengthHeader(b []byte, targetAddr conn.Addr, payload []byte)

PutTCPRequestVariableLengthHeader stores a TCP request variable-length header into the buffer.

The header fills the whole buffer. Excess bytes are used as padding.

The buffer size can be calculated with:

socks5.LengthOfAddrFromConnAddr(targetAddr) + 2 + len(payload) + paddingLen

The buffer size must not exceed [streamMaxPayloadSize]. The excess space in the buffer must not be larger than MaxPaddingLength bytes.

func PutTCPResponseHeader added in v1.14.0

func PutTCPResponseHeader(b []byte, now time.Time, requestSalt []byte, length int)

PutTCPResponseHeader stores a TCP response fixed-length header into the buffer.

The buffer size must be exactly 1 + 8 + len(requestSalt) + 2 bytes.

func PutUDPClientMessageHeader added in v1.14.0

func PutUDPClientMessageHeader(b []byte, now time.Time, paddingLen int, targetAddr conn.Addr)

PutUDPClientMessageHeader stores a UDP client message header into the buffer.

The buffer size must be exactly 1 + 8 + 2 + paddingLen + socks5.LengthOfAddrFromConnAddr(targetAddr) bytes.

func PutUDPServerMessageHeader added in v1.14.0

func PutUDPServerMessageHeader(b []byte, now time.Time, csid uint64, paddingLen int, sourceAddrPort netip.AddrPort)

PutUDPServerMessageHeader stores a UDP server message header into the buffer.

The buffer size must be exactly 1 + 8 + 8 + 2 + paddingLen + socks5.LengthOfAddrFromAddrPort(sourceAddrPort) bytes.

func ReplyWithGibberish added in v1.14.0

func ReplyWithGibberish(c *net.TCPConn, logger *zap.Logger)

ReplyWithGibberish keeps reading and replying with random garbage until EOF or error.

func ShadowPacketClientMessageHeadroom added in v1.4.0

func ShadowPacketClientMessageHeadroom(identityHeadersLen int) zerocopy.Headroom

ShadowPacketClientMessageHeadroom returns the headroom required by an encrypted Shadowsocks client message.

func ValidateUnixEpochTimestamp

func ValidateUnixEpochTimestamp(b []byte, now time.Time) error

ValidateUnixEpochTimestamp validates the Unix Epoch timestamp in the buffer and returns an error if the timestamp exceeds the allowed time difference from system time.

This function does not check buffer length. Make sure it's exactly 8 bytes long.

Types

type ClientCipherConfig added in v1.6.0

type ClientCipherConfig struct {
	UserCipherConfig
	// contains filtered or unexported fields
}

ClientCipherConfig stores cipher configuration for a client.

func NewClientCipherConfig added in v1.6.0

func NewClientCipherConfig(psk []byte, iPSKs [][]byte, enableUDP bool) (c *ClientCipherConfig, err error)

NewClientCipherConfig returns a new ClientCipherConfig.

func (*ClientCipherConfig) EIHPSKHashes added in v1.6.0

func (c *ClientCipherConfig) EIHPSKHashes() [][IdentityHeaderLength]byte

EIHPSKHashes returns the truncated BLAKE3 hashes of c.iPSKs[1:] and c.PSK.

func (*ClientCipherConfig) TCPIdentityHeaderCiphers added in v1.6.0

func (c *ClientCipherConfig) TCPIdentityHeaderCiphers(salt []byte) ([]cipher.Block, error)

TCPIdentityHeaderCiphers creates block ciphers for a client TCP session's identity headers.

func (*ClientCipherConfig) UDPIdentityHeaderCiphers added in v1.6.0

func (c *ClientCipherConfig) UDPIdentityHeaderCiphers() []cipher.Block

UDPIdentityHeaderCiphers returns the block ciphers for a client UDP service's identity headers.

func (*ClientCipherConfig) UDPSeparateHeaderPackerCipher added in v1.6.0

func (c *ClientCipherConfig) UDPSeparateHeaderPackerCipher() cipher.Block

UDPSeparateHeaderPackerCipher returns the block cipher used by the client packer to encrypt the separate header.

type CredStore added in v1.6.0

type CredStore struct {
	// contains filtered or unexported fields
}

CredStore stores credentials for a Shadowsocks 2022 server.

func (*CredStore) LookupUser added in v1.14.0

func (s *CredStore) LookupUser(uPSKHash [IdentityHeaderLength]byte) (ServerUserCipherConfig, bool)

LookupUser looks up the user in the user lookup map.

func (*CredStore) ReplaceUserLookupMap added in v1.6.0

func (s *CredStore) ReplaceUserLookupMap(ulm UserLookupMap)

ReplaceUserLookupMap replaces the current user lookup map with the given one.

func (*CredStore) UpdateUserLookupMap added in v1.6.0

func (s *CredStore) UpdateUserLookupMap(f func(ulm UserLookupMap))

UpdateUserLookupMap calls the given function with the current user lookup map.

type HeaderError

type HeaderError[T any] struct {
	Err      error
	Expected T
	Got      T
}

func (*HeaderError[T]) Error

func (e *HeaderError[T]) Error() string

func (*HeaderError[T]) Unwrap

func (e *HeaderError[T]) Unwrap() error

type PSKLengthError added in v1.6.0

type PSKLengthError struct {
	PSK            []byte
	ExpectedLength int
}

func (PSKLengthError) Error added in v1.6.0

func (e PSKLengthError) Error() string

type PaddingPolicy

type PaddingPolicy func(targetAddr conn.Addr) (shouldPad bool)

PaddingPolicy is a function that takes the target address and returns whether padding should be added.

func ParsePaddingPolicy

func ParsePaddingPolicy(s string) (PaddingPolicy, error)

ParsePaddingPolicy returns the padding policy represented by s.

func (*PaddingPolicy) UnmarshalText added in v1.14.0

func (p *PaddingPolicy) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type PaddingPolicyField added in v1.14.0

type PaddingPolicyField struct {
	// contains filtered or unexported fields
}

PaddingPolicyField provides textual representation for a padding policy function.

PaddingPolicyField implements encoding.TextAppender, encoding.TextMarshaler, and encoding.TextUnmarshaler.

func NewPaddingPolicyField added in v1.14.0

func NewPaddingPolicyField(name string) (PaddingPolicyField, error)

NewPaddingPolicyField returns a PaddingPolicyField for the given padding policy name.

func (PaddingPolicyField) AppendText added in v1.14.0

func (p PaddingPolicyField) AppendText(b []byte) ([]byte, error)

AppendText implements encoding.TextAppender.

func (PaddingPolicyField) MarshalText added in v1.14.0

func (p PaddingPolicyField) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (PaddingPolicyField) Name added in v1.14.0

func (p PaddingPolicyField) Name() string

Name returns the name of the padding policy.

func (PaddingPolicyField) Policy added in v1.14.0

func (p PaddingPolicyField) Policy() PaddingPolicy

Policy returns the padding policy function.

func (*PaddingPolicyField) UnmarshalText added in v1.14.0

func (p *PaddingPolicyField) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type RejectPolicy added in v1.14.0

type RejectPolicy func(c *net.TCPConn, logger *zap.Logger)

RejectPolicy is a function that handles a potentially malicious TCP connection. Upon returning, it's safe to close the connection.

func ParseRejectPolicy added in v1.14.0

func ParseRejectPolicy(s string) (RejectPolicy, error)

ParseRejectPolicy returns the reject policy represented by s.

func (*RejectPolicy) UnmarshalText added in v1.14.0

func (p *RejectPolicy) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type RejectPolicyField added in v1.14.0

type RejectPolicyField struct {
	// contains filtered or unexported fields
}

RejectPolicyField provides textual representation for a reject policy function.

RejectPolicyField implements encoding.TextAppender, encoding.TextMarshaler, and encoding.TextUnmarshaler.

func NewRejectPolicyField added in v1.14.0

func NewRejectPolicyField(name string) (RejectPolicyField, error)

NewRejectPolicyField returns a RejectPolicyField for the given reject policy name.

func (RejectPolicyField) AppendText added in v1.14.0

func (p RejectPolicyField) AppendText(b []byte) ([]byte, error)

AppendText implements encoding.TextAppender.

func (RejectPolicyField) MarshalText added in v1.14.0

func (p RejectPolicyField) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (RejectPolicyField) Name added in v1.14.0

func (p RejectPolicyField) Name() string

Name returns the name of the reject policy.

func (RejectPolicyField) Policy added in v1.14.0

func (p RejectPolicyField) Policy() RejectPolicy

Policy returns the reject policy function.

func (*RejectPolicyField) UnmarshalText added in v1.14.0

func (p *RejectPolicyField) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type SaltPool

type SaltPool[T comparable] struct {
	// contains filtered or unexported fields
}

SaltPool stores salts for [retention, 2*retention) to protect against replay attacks during the replay window.

func NewSaltPool

func NewSaltPool[T comparable](retention time.Duration) *SaltPool[T]

NewSaltPool returns a new salt pool with the given retention as the minimum amount of time for which an added salt is guaranteed to be kept in the pool.

func (*SaltPool[T]) Add

func (p *SaltPool[T]) Add(now time.Time, salt T) bool

Add cleans the pool, checks if the salt already exists in the pool, and adds the salt to the pool if the salt is not already in the pool. It returns true if the salt was added, false if it already exists.

func (*SaltPool[T]) Check added in v1.6.0

func (p *SaltPool[T]) Check(salt T) bool

Check returns whether the given salt is valid (not in the pool).

func (*SaltPool[T]) TryCheck added in v1.14.0

func (p *SaltPool[T]) TryCheck(salt T) bool

TryCheck is like Check, but it immediately returns true if the pool is contended.

type ServerIdentityCipherConfig added in v1.6.0

type ServerIdentityCipherConfig struct {
	IPSK []byte
	// contains filtered or unexported fields
}

ServerIdentityCipherConfig stores cipher configuration for a server's identity header.

func NewServerIdentityCipherConfig added in v1.6.0

func NewServerIdentityCipherConfig(iPSK []byte, enableUDP bool) (c ServerIdentityCipherConfig, err error)

NewServerIdentityCipherConfig returns a new ServerIdentityCipherConfig.

func (ServerIdentityCipherConfig) TCP added in v1.6.0

TCP creates a block cipher for a server TCP session's identity header.

func (ServerIdentityCipherConfig) UDP added in v1.6.0

UDP returns the block cipher for a server UDP service's identity header.

type ServerUserCipherConfig added in v1.6.0

type ServerUserCipherConfig struct {
	UserCipherConfig
	Name string
}

ServerUserCipherConfig stores cipher configuration for a server's EIH user.

func NewServerUserCipherConfig added in v1.6.0

func NewServerUserCipherConfig(name string, psk []byte, enableUDP bool) (c ServerUserCipherConfig, err error)

NewServerUserCipherConfig returns a new ServerUserCipherConfig.

type ShadowPacketClientPacker

type ShadowPacketClientPacker struct {
	// contains filtered or unexported fields
}

ShadowPacketClientPacker packs UDP packets into authenticated and encrypted Shadowsocks packets.

ShadowPacketClientPacker implements the zerocopy.Packer interface.

Packet format:

+---------------------------+-----+-----+---------------------------+
| encrypted separate header | EIH | ... |       encrypted body      |
+---------------------------+-----+-----+---------------------------+
|            16B            | 16B | ... | variable length + 16B tag |
+---------------------------+-----+-----+---------------------------+

func (*ShadowPacketClientPacker) ClientPackerInfo added in v1.6.0

func (p *ShadowPacketClientPacker) ClientPackerInfo() zerocopy.ClientPackerInfo

ClientPackerInfo implements the zerocopy.ClientPacker ClientPackerInfo method.

func (*ShadowPacketClientPacker) PackInPlace

func (p *ShadowPacketClientPacker) PackInPlace(ctx context.Context, b []byte, targetAddr conn.Addr, payloadStart, payloadLen int) (destAddrPort netip.AddrPort, packetStart, packetLen int, err error)

PackInPlace implements the zerocopy.ClientPacker PackInPlace method.

type ShadowPacketClientUnpacker

type ShadowPacketClientUnpacker struct {
	// contains filtered or unexported fields
}

ShadowPacketClientUnpacker unpacks Shadowsocks server packets and returns target address and plaintext payload.

When a server session changes, there's a replay window of less than 60 seconds, during which an adversary can replay packets with a valid timestamp from the old session. To protect against such attacks, and to simplify implementation and save resources, we only save information for one previous session.

In an unlikely event where the server session changed more than once within 60s, we simply drop new server sessions.

ShadowPacketClientUnpacker implements the zerocopy.Unpacker interface.

func (*ShadowPacketClientUnpacker) ClientUnpackerInfo added in v1.6.0

func (p *ShadowPacketClientUnpacker) ClientUnpackerInfo() zerocopy.ClientUnpackerInfo

ClientUnpackerInfo implements the zerocopy.ClientUnpacker ClientUnpackerInfo method.

func (*ShadowPacketClientUnpacker) UnpackInPlace

func (p *ShadowPacketClientUnpacker) UnpackInPlace(b []byte, packetSourceAddrPort netip.AddrPort, packetStart, packetLen int) (payloadSourceAddrPort netip.AddrPort, payloadStart, payloadLen int, err error)

UnpackInPlace implements the zerocopy.ClientUnpacker UnpackInPlace method.

type ShadowPacketReplayError

type ShadowPacketReplayError struct {
	// contains filtered or unexported fields
}

func (*ShadowPacketReplayError) Error

func (e *ShadowPacketReplayError) Error() string

func (*ShadowPacketReplayError) Unwrap

func (e *ShadowPacketReplayError) Unwrap() error

type ShadowPacketServerPacker

type ShadowPacketServerPacker struct {
	// contains filtered or unexported fields
}

ShadowPacketServerPacker packs UDP packets into authenticated and encrypted Shadowsocks packets.

ShadowPacketServerPacker implements the zerocopy.Packer interface.

func (*ShadowPacketServerPacker) PackInPlace

func (p *ShadowPacketServerPacker) PackInPlace(b []byte, sourceAddrPort netip.AddrPort, payloadStart, payloadLen, maxPacketLen int) (packetStart, packetLen int, err error)

PackInPlace implements the zerocopy.ServerPacker PackInPlace method.

func (*ShadowPacketServerPacker) ServerPackerInfo added in v1.6.0

func (p *ShadowPacketServerPacker) ServerPackerInfo() zerocopy.ServerPackerInfo

ServerPackerInfo implements the zerocopy.ServerPacker ServerPackerInfo method.

type ShadowPacketServerUnpacker

type ShadowPacketServerUnpacker struct {
	// contains filtered or unexported fields
}

ShadowPacketServerUnpacker unpacks Shadowsocks client packets and returns target address and plaintext payload.

ShadowPacketServerUnpacker implements the zerocopy.ServerUnpacker interface.

func (*ShadowPacketServerUnpacker) NewPacker added in v1.6.0

NewPacker implements the zerocopy.ServerUnpacker NewPacker method.

func (*ShadowPacketServerUnpacker) ServerUnpackerInfo added in v1.6.0

func (p *ShadowPacketServerUnpacker) ServerUnpackerInfo() zerocopy.ServerUnpackerInfo

ServerUnpackerInfo implements the zerocopy.ServerUnpacker ServerUnpackerInfo method.

func (*ShadowPacketServerUnpacker) UnpackInPlace

func (p *ShadowPacketServerUnpacker) UnpackInPlace(b []byte, sourceAddr netip.AddrPort, packetStart, packetLen int) (targetAddr conn.Addr, payloadStart, payloadLen int, err error)

UnpackInPlace unpacks the AEAD encrypted part of a Shadowsocks client packet and returns target address, payload start offset and payload length, or an error.

UnpackInPlace implements the zerocopy.ServerUnpacker UnpackInPlace method.

type ShadowStreamCipher

type ShadowStreamCipher struct {
	// contains filtered or unexported fields
}

ShadowStreamCipher wraps an AEAD cipher and provides methods that transparently increments the nonce after each AEAD operation.

func NewShadowStreamCipher added in v1.6.0

func NewShadowStreamCipher(aead cipher.AEAD) *ShadowStreamCipher

NewShadowStreamCipher wraps the given AEAD cipher into a new ShadowStreamCipher.

func (*ShadowStreamCipher) DecryptAppend added in v1.14.0

func (c *ShadowStreamCipher) DecryptAppend(dst, ciphertext []byte) (plaintext []byte, err error)

DecryptAppend decrypts and authenticates ciphertext and appends the plaintext to dst.

func (*ShadowStreamCipher) DecryptInPlace

func (c *ShadowStreamCipher) DecryptInPlace(ciphertext []byte) (plaintext []byte, err error)

DecryptInplace decrypts and authenticates ciphertext in-place.

func (*ShadowStreamCipher) DecryptTo

func (c *ShadowStreamCipher) DecryptTo(dst, ciphertext []byte) (plaintext []byte, err error)

DecryptTo decrypts and authenticates the ciphertext and saves the plaintext to dst.

func (*ShadowStreamCipher) EncryptAppend added in v1.14.0

func (c *ShadowStreamCipher) EncryptAppend(dst, plaintext []byte) (ciphertext []byte)

EncryptAppend encrypts and authenticates plaintext and appends the ciphertext to dst.

func (*ShadowStreamCipher) EncryptInPlace

func (c *ShadowStreamCipher) EncryptInPlace(plaintext []byte) (ciphertext []byte)

EncryptInPlace encrypts and authenticates plaintext in-place.

func (*ShadowStreamCipher) EncryptTo

func (c *ShadowStreamCipher) EncryptTo(dst, plaintext []byte) (ciphertext []byte)

EncryptTo encrypts and authenticates the plaintext and saves the ciphertext to dst.

type ShadowStreamClientConn added in v1.14.0

type ShadowStreamClientConn struct {
	ShadowStreamConn
	// contains filtered or unexported fields
}

ShadowStreamClientConn is a client stream connection.

func (*ShadowStreamClientConn) Read added in v1.14.0

func (c *ShadowStreamClientConn) Read(b []byte) (n int, err error)

Read implements netio.Conn.Read.

func (*ShadowStreamClientConn) ReadFrom added in v1.14.0

func (c *ShadowStreamClientConn) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom implements io.ReaderFrom.

func (*ShadowStreamClientConn) WriteTo added in v1.14.0

func (c *ShadowStreamClientConn) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements io.WriterTo.

type ShadowStreamConn added in v1.14.0

type ShadowStreamConn struct {
	netio.Conn
	// contains filtered or unexported fields
}

ShadowStreamConn wraps a netio.Conn and provides an encrypted Shadowsocks stream over it.

Wire format:

+------------------------+---------------------------+
| encrypted length chunk |  encrypted payload chunk  |
+------------------------+---------------------------+
|  2B length + 16B tag   | variable length + 16B tag |
+------------------------+---------------------------+

func (*ShadowStreamConn) Read added in v1.14.0

func (c *ShadowStreamConn) Read(b []byte) (n int, err error)

Read implements netio.Conn.Read.

func (*ShadowStreamConn) ReadFrom added in v1.14.0

func (c *ShadowStreamConn) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom implements io.ReaderFrom.

func (*ShadowStreamConn) Write added in v1.14.0

func (c *ShadowStreamConn) Write(b []byte) (n int, err error)

Write implements netio.Conn.Write.

func (*ShadowStreamConn) WriteTo added in v1.14.0

func (c *ShadowStreamConn) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements io.WriterTo.

type ShadowStreamServerConn added in v1.14.0

type ShadowStreamServerConn struct {
	ShadowStreamConn
	// contains filtered or unexported fields
}

ShadowStreamServerConn is a server stream connection.

func (*ShadowStreamServerConn) ReadFrom added in v1.14.0

func (c *ShadowStreamServerConn) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom implements io.ReaderFrom.

func (*ShadowStreamServerConn) Write added in v1.14.0

func (c *ShadowStreamServerConn) Write(b []byte) (n int, err error)

Write implements netio.Conn.Write.

func (*ShadowStreamServerConn) WriteTo added in v1.14.0

func (c *ShadowStreamServerConn) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements io.WriterTo.

type SlidingWindowFilter added in v1.8.0

type SlidingWindowFilter struct {
	// contains filtered or unexported fields
}

SlidingWindowFilter maintains a sliding window of uint64 counters.

func NewSlidingWindowFilter added in v1.8.0

func NewSlidingWindowFilter(size uint64) *SlidingWindowFilter

NewSlidingWindowFilter returns a new sliding window filter with the given size.

func (*SlidingWindowFilter) Add added in v1.8.0

func (f *SlidingWindowFilter) Add(counter uint64) bool

Add attempts to add counter to the sliding window and returns whether the counter is successfully added to the sliding window.

func (*SlidingWindowFilter) IsOk added in v1.8.0

func (f *SlidingWindowFilter) IsOk(counter uint64) bool

IsOk checks whether counter can be accepted by the sliding window filter.

func (*SlidingWindowFilter) MustAdd added in v1.8.0

func (f *SlidingWindowFilter) MustAdd(counter uint64)

MustAdd adds counter to the sliding window without checking if the counter is valid. Call IsOk beforehand to make sure the counter is valid.

func (*SlidingWindowFilter) Reset added in v1.8.0

func (f *SlidingWindowFilter) Reset()

Reset resets the filter to its initial state.

func (*SlidingWindowFilter) Size added in v1.8.0

func (f *SlidingWindowFilter) Size() uint64

Size returns the size of the sliding window.

type StreamClient added in v1.14.0

type StreamClient struct {
	// contains filtered or unexported fields
}

StreamClient is a Shadowsocks 2022 stream client.

StreamClient implements netio.StreamClient and netio.StreamDialer.

func (*StreamClient) DialStream added in v1.14.0

func (c *StreamClient) DialStream(ctx context.Context, targetAddr conn.Addr, payload []byte) (clientConn netio.Conn, err error)

DialStream implements netio.StreamDialer.DialStream.

func (*StreamClient) NewStreamDialer added in v1.14.0

func (c *StreamClient) NewStreamDialer() (netio.StreamDialer, netio.StreamDialerInfo)

NewStreamDialer implements netio.StreamClient.NewStreamDialer.

type StreamClientConfig added in v1.14.0

type StreamClientConfig struct {
	// Name is the name of the client.
	Name string

	// InnerClient is the underlying stream client.
	InnerClient netio.StreamClient

	// Addr is the address of the Shadowsocks 2022 server.
	Addr conn.Addr

	// AllowSegmentedFixedLengthHeader controls whether to allow segmented fixed-length header.
	//
	// Setting it to true disables the requirement that the fixed-length header must be read in
	// a single read call. This is useful when the underlying stream transport does not exhibit
	// typical TCP behavior.
	AllowSegmentedFixedLengthHeader bool

	// CipherConfig is the cipher configuration.
	CipherConfig *ClientCipherConfig

	// UnsafeRequestStreamPrefix is the prefix bytes prepended to the request stream.
	UnsafeRequestStreamPrefix []byte

	// UnsafeResponseStreamPrefix is the prefix bytes prepended to the response stream.
	UnsafeResponseStreamPrefix []byte
}

StreamClientConfig is the configuration for a Shadowsocks 2022 stream client.

func (*StreamClientConfig) NewStreamClient added in v1.14.0

func (c *StreamClientConfig) NewStreamClient() *StreamClient

NewStreamClient returns a new Shadowsocks 2022 stream client.

type StreamServer added in v1.14.0

type StreamServer struct {
	CredStore
	// contains filtered or unexported fields
}

StreamServer is a Shadowsocks 2022 stream server.

StreamServer implements netio.StreamServer.

func (*StreamServer) HandleStream added in v1.14.0

func (s *StreamServer) HandleStream(rawRW netio.Conn, logger *zap.Logger) (req netio.ConnRequest, err error)

HandleStream implements netio.StreamServer.HandleStream.

func (*StreamServer) StreamServerInfo added in v1.14.0

func (s *StreamServer) StreamServerInfo() netio.StreamServerInfo

StreamServerInfo implements netio.StreamServer.StreamServerInfo.

type StreamServerConfig added in v1.14.0

type StreamServerConfig struct {
	// AllowSegmentedFixedLengthHeader controls whether to allow segmented fixed-length header.
	//
	// Setting it to true disables the requirement that the fixed-length header must be read in
	// a single read call. This is useful when the underlying stream transport does not exhibit
	// typical TCP behavior.
	AllowSegmentedFixedLengthHeader bool

	// UserCipherConfig is the non-EIH cipher configuration.
	UserCipherConfig UserCipherConfig

	// IdentityCipherConfig is the cipher configuration for the identity header.
	IdentityCipherConfig ServerIdentityCipherConfig

	// RejectPolicy takes care of incoming connections that cannot be authenticated.
	RejectPolicy RejectPolicy

	// UnsafeFallbackAddr is the optional fallback destination address for unauthenticated connections.
	UnsafeFallbackAddr conn.Addr

	// UnsafeRequestStreamPrefix is the prefix bytes prepended to the request stream.
	UnsafeRequestStreamPrefix []byte

	// UnsafeResponseStreamPrefix is the prefix bytes prepended to the response stream.
	UnsafeResponseStreamPrefix []byte
}

StreamServerConfig is the configuration for a Shadowsocks 2022 stream server.

func (*StreamServerConfig) NewStreamServer added in v1.14.0

func (c *StreamServerConfig) NewStreamServer() *StreamServer

NewStreamServer returns a new Shadowsocks 2022 stream server.

type UDPClient

type UDPClient struct {
	// contains filtered or unexported fields
}

UDPClient is a Shadowsocks 2022 UDP client.

UDPClient implements zerocopy.UDPClient.

func NewUDPClient

func NewUDPClient(name, network string, addr conn.Addr, mtu int, listenConfig conn.ListenConfig, filterSize uint64, cipherConfig *ClientCipherConfig, shouldPad PaddingPolicy) *UDPClient

NewUDPClient creates a new Shadowsocks 2022 UDP client.

func (*UDPClient) Info added in v1.6.0

func (c *UDPClient) Info() zerocopy.UDPClientInfo

Info implements zerocopy.UDPClient.Info.

func (*UDPClient) NewSession

NewSession implements zerocopy.UDPClient.NewSession.

type UDPServer

type UDPServer struct {
	CredStore
	// contains filtered or unexported fields
}

UDPServer is a Shadowsocks 2022 UDP server.

UDPServer implements zerocopy.UDPSessionServer.

func NewUDPServer

func NewUDPServer(filterSize uint64, userCipherConfig UserCipherConfig, identityCipherConfig ServerIdentityCipherConfig, shouldPad PaddingPolicy) *UDPServer

NewUDPServer creates a new Shadowsocks 2022 UDP server.

func (*UDPServer) Info added in v1.6.0

Info implements zerocopy.UDPSessionServer.Info.

func (*UDPServer) NewUnpacker

func (s *UDPServer) NewUnpacker(b []byte, csid uint64) (zerocopy.ServerUnpacker, string, error)

NewUnpacker implements zerocopy.UDPSessionServer.NewUnpacker.

func (*UDPServer) SessionInfo

func (s *UDPServer) SessionInfo(b []byte) (csid uint64, err error)

SessionInfo implements zerocopy.UDPSessionServer.SessionInfo.

type UserCipherConfig added in v1.6.0

type UserCipherConfig struct {
	PSK []byte
	// contains filtered or unexported fields
}

UserCipherConfig stores cipher configuration for a non-EIH client/server or an EIH user.

func NewUserCipherConfig added in v1.6.0

func NewUserCipherConfig(psk []byte, enableUDP bool) (c UserCipherConfig, err error)

NewUserCipherConfig returns a new UserCipherConfig.

func (UserCipherConfig) AEAD added in v1.6.0

func (c UserCipherConfig) AEAD(salt []byte) (cipher.AEAD, error)

AEAD derives a subkey from the salt and returns a new AEAD cipher.

func (UserCipherConfig) Block added in v1.6.0

func (c UserCipherConfig) Block() cipher.Block

Block returns the block cipher for UDP separate header.

func (UserCipherConfig) ShadowStreamCipher added in v1.6.0

func (c UserCipherConfig) ShadowStreamCipher(salt []byte) (*ShadowStreamCipher, error)

type UserLookupMap added in v1.6.0

UserLookupMap is a map of uPSK hashes to ServerUserCipherConfig. Upon decryption of an identity header, the uPSK hash is looked up in this map.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL