Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VMess Proposal AEAD Based Packet Length #940

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions common/drain/drain.go
Original file line number Diff line number Diff line change
@@ -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 changes: 62 additions & 0 deletions common/drain/drainer.go
Original file line number Diff line number Diff line change
@@ -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{}
}
9 changes: 9 additions & 0 deletions common/drain/errors.generated.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package drain

import "github.com/v2fly/v2ray-core/v4/common/errors"

type errPathObjHolder struct{}

func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
2 changes: 2 additions & 0 deletions common/protocol/headers.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ const (
RequestOptionChunkMasking bitmask.Byte = 0x04

RequestOptionGlobalPadding bitmask.Byte = 0x08

RequestOptionAuthenticatedLength bitmask.Byte = 0x10
)

type RequestHeader struct {
Expand Down
8 changes: 5 additions & 3 deletions infra/conf/vmess.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ import (
)

type VMessAccount struct {
ID string `json:"id"`
AlterIds uint16 `json:"alterId"`
Security string `json:"security"`
ID string `json:"id"`
AlterIds uint16 `json:"alterId"`
Security string `json:"security"`
Experiments string `json:"experiments"`
}

// Build implements Buildable
Expand All @@ -42,6 +43,7 @@ func (a *VMessAccount) Build() *vmess.Account {
SecuritySettings: &protocol.SecurityConfig{
Type: st,
},
TestsEnabled: a.Experiments,
}
}

Expand Down
63 changes: 32 additions & 31 deletions proxy/shadowsocks/protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand All @@ -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()
Expand All @@ -53,19 +51,17 @@ 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)...)
}

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}

Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down
20 changes: 17 additions & 3 deletions proxy/vmess/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
package vmess

import (
"strings"

"github.com/v2fly/v2ray-core/v4/common/dice"
"github.com/v2fly/v2ray-core/v4/common/protocol"
"github.com/v2fly/v2ray-core/v4/common/uuid"
Expand All @@ -16,6 +18,9 @@ type MemoryAccount struct {
AlterIDs []*protocol.ID
// Security type of the account. Used for client connections.
Security protocol.SecurityType

AuthenticatedLengthExperiment bool
NoTerminationSignal bool
}

// AnyValidID returns an ID that is either the main ID or one of the alternative IDs if any.
Expand Down Expand Up @@ -43,9 +48,18 @@ func (a *Account) AsAccount() (protocol.Account, error) {
return nil, newError("failed to parse ID").Base(err).AtError()
}
protoID := protocol.NewID(id)
var AuthenticatedLength, NoTerminationSignal bool
if strings.Contains(a.TestsEnabled, "AuthenticatedLength") {
AuthenticatedLength = true
}
if strings.Contains(a.TestsEnabled, "NoTerminationSignal") {
NoTerminationSignal = true
}
return &MemoryAccount{
ID: protoID,
AlterIDs: protocol.NewAlterIDs(protoID, uint16(a.AlterId)),
Security: a.SecuritySettings.GetSecurityType(),
ID: protoID,
AlterIDs: protocol.NewAlterIDs(protoID, uint16(a.AlterId)),
Security: a.SecuritySettings.GetSecurityType(),
AuthenticatedLengthExperiment: AuthenticatedLength,
NoTerminationSignal: NoTerminationSignal,
}, nil
}
10 changes: 10 additions & 0 deletions proxy/vmess/encoding/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"encoding/binary"
"hash/fnv"

"github.com/v2fly/v2ray-core/v4/common/crypto"

"golang.org/x/crypto/sha3"

"github.com/v2fly/v2ray-core/v4/common"
Expand Down Expand Up @@ -117,3 +119,11 @@ func (s *ShakeSizeParser) NextPaddingLen() uint16 {
func (s *ShakeSizeParser) MaxPaddingLen() uint16 {
return 64
}

type AEADSizeParser struct {
crypto.AEADChunkSizeParser
}

func NewAEADSizeParser(auth *crypto.AEADAuthenticator) *AEADSizeParser {
return &AEADSizeParser{crypto.AEADChunkSizeParser{Auth: auth}}
}
Loading