1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-14 06:06:39 -05:00

unified drain support for vmess and shadowsockets

This commit is contained in:
Shelikhoo 2021-04-30 12:08:15 +01:00
parent 73ee3b0b1c
commit 79174ab2a0
No known key found for this signature in database
GPG Key ID: C4D5E79D22B25316
7 changed files with 153 additions and 66 deletions

10
common/drain/drain.go Normal file
View File

@ -0,0 +1,10 @@
package drain
import "io"
//go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen
type Drainer interface {
AcknowledgeReceive(size int)
Drain(reader io.Reader) error
}

62
common/drain/drainer.go Normal file
View File

@ -0,0 +1,62 @@
package drain
import (
"io"
"io/ioutil"
"github.com/v2fly/v2ray-core/v4/common/dice"
)
type BehaviorSeedLimitedDrainer struct {
DrainSize int
}
func NewBehaviorSeedLimitedDrainer(behaviorSeed int64, drainFoundation, maxBaseDrainSize, maxRandDrain int) (Drainer, error) {
behaviorRand := dice.NewDeterministicDice(behaviorSeed)
BaseDrainSize := behaviorRand.Roll(maxBaseDrainSize)
RandDrainMax := behaviorRand.Roll(maxRandDrain) + 1
RandDrainRolled := dice.Roll(RandDrainMax)
DrainSize := drainFoundation + BaseDrainSize + RandDrainRolled
return &BehaviorSeedLimitedDrainer{DrainSize: DrainSize}, nil
}
func (d *BehaviorSeedLimitedDrainer) AcknowledgeReceive(size int) {
d.DrainSize -= size
}
func (d *BehaviorSeedLimitedDrainer) Drain(reader io.Reader) error {
if d.DrainSize > 0 {
err := drainReadN(reader, d.DrainSize)
if err == nil {
return newError("drained connection")
}
return newError("unable to drain connection").Base(err)
}
return nil
}
func drainReadN(reader io.Reader, n int) error {
_, err := io.CopyN(ioutil.Discard, reader, int64(n))
return err
}
func WithError(drainer Drainer, reader io.Reader, err error) error {
drainErr := drainer.Drain(reader)
if drainErr == nil {
return err
}
return newError(drainErr).Base(err)
}
type NopDrainer struct{}
func (n NopDrainer) AcknowledgeReceive(size int) {
}
func (n NopDrainer) Drain(reader io.Reader) error {
return nil
}
func NewNopDrainer() Drainer {
return &NopDrainer{}
}

View File

@ -8,11 +8,10 @@ import (
"crypto/sha256"
"hash/crc32"
"io"
"io/ioutil"
"github.com/v2fly/v2ray-core/v4/common"
"github.com/v2fly/v2ray-core/v4/common/buf"
"github.com/v2fly/v2ray-core/v4/common/dice"
"github.com/v2fly/v2ray-core/v4/common/drain"
"github.com/v2fly/v2ray-core/v4/common/net"
"github.com/v2fly/v2ray-core/v4/common/protocol"
)
@ -39,12 +38,11 @@ func ReadTCPSession(user *protocol.MemoryUser, reader io.Reader) (*protocol.Requ
behaviorSeed := crc32.ChecksumIEEE(hashkdf.Sum(nil))
behaviorRand := dice.NewDeterministicDice(int64(behaviorSeed))
BaseDrainSize := behaviorRand.Roll(3266)
RandDrainMax := behaviorRand.Roll(64) + 1
RandDrainRolled := dice.Roll(RandDrainMax)
DrainSize := BaseDrainSize + 16 + 38 + RandDrainRolled
readSizeRemain := DrainSize
drainer, err := drain.NewBehaviorSeedLimitedDrainer(int64(behaviorSeed), 16+38, 3266, 64)
if err != nil {
return nil, nil, newError("failed to initialize drainer").Base(err)
}
buffer := buf.New()
defer buffer.Release()
@ -53,9 +51,8 @@ func ReadTCPSession(user *protocol.MemoryUser, reader io.Reader) (*protocol.Requ
var iv []byte
if ivLen > 0 {
if _, err := buffer.ReadFullFrom(reader, ivLen); err != nil {
readSizeRemain -= int(buffer.Len())
DrainConnN(reader, readSizeRemain)
return nil, nil, newError("failed to read IV").Base(err)
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, newError("failed to read IV").Base(err))
}
iv = append([]byte(nil), buffer.BytesTo(ivLen)...)
@ -63,9 +60,8 @@ func ReadTCPSession(user *protocol.MemoryUser, reader io.Reader) (*protocol.Requ
r, err := account.Cipher.NewDecryptionReader(account.Key, iv, reader)
if err != nil {
readSizeRemain -= int(buffer.Len())
DrainConnN(reader, readSizeRemain)
return nil, nil, newError("failed to initialize decoding stream").Base(err).AtError()
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, newError("failed to initialize decoding stream").Base(err).AtError())
}
br := &buf.BufferedReader{Reader: r}
@ -75,39 +71,31 @@ func ReadTCPSession(user *protocol.MemoryUser, reader io.Reader) (*protocol.Requ
Command: protocol.RequestCommandTCP,
}
readSizeRemain -= int(buffer.Len())
drainer.AcknowledgeReceive(int(buffer.Len()))
buffer.Clear()
addr, port, err := addrParser.ReadAddressPort(buffer, br)
if err != nil {
readSizeRemain -= int(buffer.Len())
DrainConnN(reader, readSizeRemain)
return nil, nil, newError("failed to read address").Base(err)
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, newError("failed to read address").Base(err))
}
request.Address = addr
request.Port = port
if request.Address == nil {
readSizeRemain -= int(buffer.Len())
DrainConnN(reader, readSizeRemain)
return nil, nil, newError("invalid remote address.")
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, newError("invalid remote address."))
}
if ivError := account.CheckIV(iv); ivError != nil {
readSizeRemain -= int(buffer.Len())
DrainConnN(reader, readSizeRemain)
return nil, nil, newError("failed iv check").Base(ivError)
drainer.AcknowledgeReceive(int(buffer.Len()))
return nil, nil, drain.WithError(drainer, reader, newError("failed iv check").Base(ivError))
}
return request, br, nil
}
func DrainConnN(reader io.Reader, n int) error {
_, err := io.CopyN(ioutil.Discard, reader, int64(n))
return err
}
// WriteTCPRequest writes Shadowsocks request into the given writer, and returns a writer for body.
func WriteTCPRequest(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
user := request.User
@ -146,16 +134,29 @@ func WriteTCPRequest(request *protocol.RequestHeader, writer io.Writer) (buf.Wri
func ReadTCPResponse(user *protocol.MemoryUser, reader io.Reader) (buf.Reader, error) {
account := user.Account.(*MemoryAccount)
hashkdf := hmac.New(sha256.New, []byte("SSBSKDF"))
hashkdf.Write(account.Key)
behaviorSeed := crc32.ChecksumIEEE(hashkdf.Sum(nil))
drainer, err := drain.NewBehaviorSeedLimitedDrainer(int64(behaviorSeed), 16+38, 3266, 64)
if err != nil {
return nil, newError("failed to initialize drainer").Base(err)
}
var iv []byte
if account.Cipher.IVSize() > 0 {
iv = make([]byte, account.Cipher.IVSize())
if _, err := io.ReadFull(reader, iv); err != nil {
if n, err := io.ReadFull(reader, iv); err != nil {
return nil, newError("failed to read IV").Base(err)
} else { // nolint: golint
drainer.AcknowledgeReceive(n)
}
}
if ivError := account.CheckIV(iv); ivError != nil {
return nil, newError("failed iv check").Base(ivError)
return nil, drain.WithError(drainer, reader, newError("failed iv check").Base(ivError))
}
return account.Cipher.NewDecryptionReader(account.Key, iv, reader)

View File

@ -13,6 +13,8 @@ import (
"hash/fnv"
"io"
"github.com/v2fly/v2ray-core/v4/common/drain"
"golang.org/x/crypto/chacha20poly1305"
"github.com/v2fly/v2ray-core/v4/common"
@ -44,10 +46,12 @@ type ClientSession struct {
responseBodyIV [16]byte
responseReader io.Reader
responseHeader byte
readDrainer drain.Drainer
}
// NewClientSession creates a new ClientSession.
func NewClientSession(ctx context.Context, isAEAD bool, idHash protocol.IDHash) *ClientSession {
func NewClientSession(ctx context.Context, isAEAD bool, idHash protocol.IDHash, behaviorSeed int64) *ClientSession {
session := &ClientSession{
isAEAD: isAEAD,
idHash: idHash,
@ -68,6 +72,14 @@ func NewClientSession(ctx context.Context, isAEAD bool, idHash protocol.IDHash)
BodyIV := sha256.Sum256(session.requestBodyIV[:])
copy(session.responseBodyIV[:], BodyIV[:16])
}
{
var err error
session.readDrainer, err = drain.NewBehaviorSeedLimitedDrainer(behaviorSeed, 18, 3266, 64)
if err != nil {
newError("unable to initialize drainer").Base(err).WriteToLog()
session.readDrainer = drain.NewNopDrainer()
}
}
return session
}
@ -225,11 +237,14 @@ func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.Respon
var decryptedResponseHeaderLength int
var decryptedResponseHeaderLengthBinaryDeserializeBuffer uint16
if _, err := io.ReadFull(reader, aeadEncryptedResponseHeaderLength[:]); err != nil {
return nil, newError("Unable to Read Header Len").Base(err)
if n, err := io.ReadFull(reader, aeadEncryptedResponseHeaderLength[:]); err != nil {
c.readDrainer.AcknowledgeReceive(n)
return nil, drain.WithError(c.readDrainer, reader, newError("Unable to Read Header Len").Base(err))
} else { // nolint: golint
c.readDrainer.AcknowledgeReceive(n)
}
if decryptedResponseHeaderLengthBinaryBuffer, err := aeadResponseHeaderLengthEncryptionAEAD.Open(nil, aeadResponseHeaderLengthEncryptionIV, aeadEncryptedResponseHeaderLength[:], nil); err != nil {
return nil, newError("Failed To Decrypt Length").Base(err)
return nil, drain.WithError(c.readDrainer, reader, newError("Failed To Decrypt Length").Base(err))
} else { // nolint: golint
common.Must(binary.Read(bytes.NewReader(decryptedResponseHeaderLengthBinaryBuffer), binary.BigEndian, &decryptedResponseHeaderLengthBinaryDeserializeBuffer))
decryptedResponseHeaderLength = int(decryptedResponseHeaderLengthBinaryDeserializeBuffer)
@ -243,12 +258,15 @@ func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.Respon
encryptedResponseHeaderBuffer := make([]byte, decryptedResponseHeaderLength+16)
if _, err := io.ReadFull(reader, encryptedResponseHeaderBuffer); err != nil {
return nil, newError("Unable to Read Header Data").Base(err)
if n, err := io.ReadFull(reader, encryptedResponseHeaderBuffer); err != nil {
c.readDrainer.AcknowledgeReceive(n)
return nil, drain.WithError(c.readDrainer, reader, newError("Unable to Read Header Data").Base(err))
} else { // nolint: golint
c.readDrainer.AcknowledgeReceive(n)
}
if decryptedResponseHeaderBuffer, err := aeadResponseHeaderPayloadEncryptionAEAD.Open(nil, aeadResponseHeaderPayloadEncryptionIV, encryptedResponseHeaderBuffer, nil); err != nil {
return nil, newError("Failed To Decrypt Payload").Base(err)
return nil, drain.WithError(c.readDrainer, reader, newError("Failed To Decrypt Payload").Base(err))
} else { // nolint: golint
c.responseReader = bytes.NewReader(decryptedResponseHeaderBuffer)
}

View File

@ -43,7 +43,7 @@ func TestRequestSerialization(t *testing.T) {
}
buffer := buf.New()
client := NewClientSession(context.TODO(), true, protocol.DefaultIDHash)
client := NewClientSession(context.TODO(), true, protocol.DefaultIDHash, 0)
common.Must(client.EncodeRequestHeader(expectedRequest, buffer))
buffer2 := buf.New()
@ -93,7 +93,7 @@ func TestInvalidRequest(t *testing.T) {
}
buffer := buf.New()
client := NewClientSession(context.TODO(), true, protocol.DefaultIDHash)
client := NewClientSession(context.TODO(), true, protocol.DefaultIDHash, 0)
common.Must(client.EncodeRequestHeader(expectedRequest, buffer))
buffer2 := buf.New()
@ -134,7 +134,7 @@ func TestMuxRequest(t *testing.T) {
}
buffer := buf.New()
client := NewClientSession(context.TODO(), true, protocol.DefaultIDHash)
client := NewClientSession(context.TODO(), true, protocol.DefaultIDHash, 0)
common.Must(client.EncodeRequestHeader(expectedRequest, buffer))
buffer2 := buf.New()

View File

@ -9,17 +9,17 @@ import (
"encoding/binary"
"hash/fnv"
"io"
"io/ioutil"
"sync"
"time"
"github.com/v2fly/v2ray-core/v4/common/drain"
"golang.org/x/crypto/chacha20poly1305"
"github.com/v2fly/v2ray-core/v4/common"
"github.com/v2fly/v2ray-core/v4/common/bitmask"
"github.com/v2fly/v2ray-core/v4/common/buf"
"github.com/v2fly/v2ray-core/v4/common/crypto"
"github.com/v2fly/v2ray-core/v4/common/dice"
"github.com/v2fly/v2ray-core/v4/common/net"
"github.com/v2fly/v2ray-core/v4/common/protocol"
"github.com/v2fly/v2ray-core/v4/common/task"
@ -139,24 +139,17 @@ func parseSecurityType(b byte) protocol.SecurityType {
// DecodeRequestHeader decodes and returns (if successful) a RequestHeader from an input stream.
func (s *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.RequestHeader, error) {
buffer := buf.New()
behaviorRand := dice.NewDeterministicDice(int64(s.userValidator.GetBehaviorSeed()))
BaseDrainSize := behaviorRand.Roll(3266)
RandDrainMax := behaviorRand.Roll(64) + 1
RandDrainRolled := dice.Roll(RandDrainMax)
DrainSize := BaseDrainSize + 16 + 38 + RandDrainRolled
readSizeRemain := DrainSize
drainer, err := drain.NewBehaviorSeedLimitedDrainer(int64(s.userValidator.GetBehaviorSeed()), 16+38, 3266, 64)
if err != nil {
return nil, newError("failed to initialize drainer").Base(err)
}
drainConnection := func(e error) error {
// We read a deterministic generated length of data before closing the connection to offset padding read pattern
readSizeRemain -= int(buffer.Len())
if readSizeRemain > 0 {
err := s.DrainConnN(reader, readSizeRemain)
if err != nil {
return newError("failed to drain connection DrainSize = ", BaseDrainSize, " ", RandDrainMax, " ", RandDrainRolled).Base(err).Base(e)
}
return newError("connection drained DrainSize = ", BaseDrainSize, " ", RandDrainMax, " ", RandDrainRolled).Base(e)
}
return e
drainer.AcknowledgeReceive(int(buffer.Len()))
return drain.WithError(drainer, reader, e)
}
defer func() {
@ -183,7 +176,7 @@ func (s *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.Request
aeadData, shouldDrain, bytesRead, errorReason := vmessaead.OpenVMessAEADHeader(fixedSizeCmdKey, fixedSizeAuthID, reader)
if errorReason != nil {
if shouldDrain {
readSizeRemain -= bytesRead
drainer.AcknowledgeReceive(bytesRead)
return nil, drainConnection(newError("AEAD read failed").Base(errorReason))
}
return nil, drainConnection(newError("AEAD read failed, drain skipped").Base(errorReason))
@ -213,7 +206,7 @@ func (s *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.Request
return nil, drainConnection(newError("invalid user").Base(errorAEAD))
}
readSizeRemain -= int(buffer.Len())
drainer.AcknowledgeReceive(int(buffer.Len()))
buffer.Clear()
if _, err := buffer.ReadFullFrom(decryptor, 38); err != nil {
return nil, newError("failed to read request header").Base(err)
@ -540,8 +533,3 @@ func (s *ServerSession) EncodeResponseBody(request *protocol.RequestHeader, writ
panic("Unknown security type.")
}
}
func (s *ServerSession) DrainConnN(reader io.Reader, n int) error {
_, err := io.CopyN(ioutil.Discard, reader, int64(n))
return err
}

View File

@ -6,6 +6,9 @@ package outbound
import (
"context"
"crypto/hmac"
"crypto/sha256"
"hash/crc64"
"time"
core "github.com/v2fly/v2ray-core/v4"
@ -128,7 +131,12 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
isAEAD = true
}
session := encoding.NewClientSession(ctx, isAEAD, protocol.DefaultIDHash)
hashkdf := hmac.New(sha256.New, []byte("VMessBF"))
hashkdf.Write(account.ID.Bytes())
behaviorSeed := crc64.Checksum(hashkdf.Sum(nil), crc64.MakeTable(crc64.ISO))
session := encoding.NewClientSession(ctx, isAEAD, protocol.DefaultIDHash, int64(behaviorSeed))
sessionPolicy := h.policyManager.ForLevel(request.User.Level)
ctx, cancel := context.WithCancel(ctx)