1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2026-02-08 09:15:23 -05:00

move encoding to vmess

This commit is contained in:
v2ray
2016-07-23 13:17:51 +02:00
parent e304e2761d
commit 6f5b54747e
10 changed files with 16 additions and 41 deletions

View File

@@ -0,0 +1,11 @@
package encoding
import (
"hash/fnv"
)
func Authenticate(b []byte) uint32 {
fnv1hash := fnv.New32a()
fnv1hash.Write(b)
return fnv1hash.Sum32()
}

View File

@@ -0,0 +1,138 @@
package encoding
import (
"crypto/md5"
"crypto/rand"
"hash/fnv"
"io"
"github.com/v2ray/v2ray-core/common/crypto"
"github.com/v2ray/v2ray-core/common/log"
"github.com/v2ray/v2ray-core/common/protocol"
"github.com/v2ray/v2ray-core/transport"
)
func hashTimestamp(t protocol.Timestamp) []byte {
bytes := make([]byte, 0, 32)
t.Bytes(bytes)
t.Bytes(bytes)
t.Bytes(bytes)
t.Bytes(bytes)
return bytes
}
type ClientSession struct {
requestBodyKey []byte
requestBodyIV []byte
responseHeader byte
responseBodyKey []byte
responseBodyIV []byte
responseReader io.Reader
idHash protocol.IDHash
}
func NewClientSession(idHash protocol.IDHash) *ClientSession {
randomBytes := make([]byte, 33) // 16 + 16 + 1
rand.Read(randomBytes)
session := &ClientSession{}
session.requestBodyKey = randomBytes[:16]
session.requestBodyIV = randomBytes[16:32]
session.responseHeader = randomBytes[32]
responseBodyKey := md5.Sum(session.requestBodyKey)
responseBodyIV := md5.Sum(session.requestBodyIV)
session.responseBodyKey = responseBodyKey[:]
session.responseBodyIV = responseBodyIV[:]
session.idHash = idHash
return session
}
func (this *ClientSession) EncodeRequestHeader(header *protocol.RequestHeader, writer io.Writer) {
timestamp := protocol.NewTimestampGenerator(protocol.NowTime(), 30)()
idHash := this.idHash(header.User.Account.(*protocol.VMessAccount).AnyValidID().Bytes())
idHash.Write(timestamp.Bytes(nil))
writer.Write(idHash.Sum(nil))
buffer := make([]byte, 0, 512)
buffer = append(buffer, Version)
buffer = append(buffer, this.requestBodyIV...)
buffer = append(buffer, this.requestBodyKey...)
buffer = append(buffer, this.responseHeader, byte(header.Option), byte(0), byte(0), byte(header.Command))
buffer = header.Port.Bytes(buffer)
switch {
case header.Address.IsIPv4():
buffer = append(buffer, AddrTypeIPv4)
buffer = append(buffer, header.Address.IP()...)
case header.Address.IsIPv6():
buffer = append(buffer, AddrTypeIPv6)
buffer = append(buffer, header.Address.IP()...)
case header.Address.IsDomain():
buffer = append(buffer, AddrTypeDomain, byte(len(header.Address.Domain())))
buffer = append(buffer, header.Address.Domain()...)
}
fnv1a := fnv.New32a()
fnv1a.Write(buffer)
buffer = fnv1a.Sum(buffer)
timestampHash := md5.New()
timestampHash.Write(hashTimestamp(timestamp))
iv := timestampHash.Sum(nil)
account := header.User.Account.(*protocol.VMessAccount)
aesStream := crypto.NewAesEncryptionStream(account.ID.CmdKey(), iv)
aesStream.XORKeyStream(buffer, buffer)
writer.Write(buffer)
return
}
func (this *ClientSession) EncodeRequestBody(writer io.Writer) io.Writer {
aesStream := crypto.NewAesEncryptionStream(this.requestBodyKey, this.requestBodyIV)
return crypto.NewCryptionWriter(aesStream, writer)
}
func (this *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.ResponseHeader, error) {
aesStream := crypto.NewAesDecryptionStream(this.responseBodyKey, this.responseBodyIV)
this.responseReader = crypto.NewCryptionReader(aesStream, reader)
buffer := make([]byte, 256)
_, err := io.ReadFull(this.responseReader, buffer[:4])
if err != nil {
log.Info("Raw: Failed to read response header: ", err)
return nil, err
}
if buffer[0] != this.responseHeader {
log.Info("Raw: Unexpected response header. Expecting ", this.responseHeader, " but actually ", buffer[0])
return nil, transport.ErrCorruptedPacket
}
header := &protocol.ResponseHeader{
Option: protocol.ResponseOption(buffer[1]),
}
if buffer[2] != 0 {
cmdId := buffer[2]
dataLen := int(buffer[3])
_, err := io.ReadFull(this.responseReader, buffer[:dataLen])
if err != nil {
log.Info("Raw: Failed to read response command: ", err)
return nil, err
}
data := buffer[:dataLen]
command, err := UnmarshalCommand(cmdId, data)
if err == nil {
header.Command = command
}
}
return header, nil
}
func (this *ClientSession) DecodeResponseBody(reader io.Reader) io.Reader {
return this.responseReader
}

View File

@@ -0,0 +1,149 @@
package encoding
import (
"errors"
"io"
"github.com/v2ray/v2ray-core/common/alloc"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/common/protocol"
"github.com/v2ray/v2ray-core/common/serial"
"github.com/v2ray/v2ray-core/common/uuid"
"github.com/v2ray/v2ray-core/transport"
)
var (
ErrCommandTypeMismatch = errors.New("Command type mismatch.")
ErrUnknownCommand = errors.New("Unknown command.")
ErrCommandTooLarge = errors.New("Command too large.")
)
func MarshalCommand(command interface{}, writer io.Writer) error {
if command == nil {
return ErrUnknownCommand
}
var cmdId byte
var factory CommandFactory
switch command.(type) {
case *protocol.CommandSwitchAccount:
factory = new(CommandSwitchAccountFactory)
cmdId = 1
default:
return ErrUnknownCommand
}
buffer := alloc.NewLocalBuffer(512).Clear()
defer buffer.Release()
err := factory.Marshal(command, buffer)
if err != nil {
return err
}
auth := Authenticate(buffer.Value)
len := buffer.Len() + 4
if len > 255 {
return ErrCommandTooLarge
}
writer.Write([]byte{cmdId, byte(len), byte(auth >> 24), byte(auth >> 16), byte(auth >> 8), byte(auth)})
writer.Write(buffer.Value)
return nil
}
func UnmarshalCommand(cmdId byte, data []byte) (protocol.ResponseCommand, error) {
if len(data) <= 4 {
return nil, transport.ErrCorruptedPacket
}
expectedAuth := Authenticate(data[4:])
actualAuth := serial.BytesToUint32(data[:4])
if expectedAuth != actualAuth {
return nil, transport.ErrCorruptedPacket
}
var factory CommandFactory
switch cmdId {
case 1:
factory = new(CommandSwitchAccountFactory)
default:
return nil, ErrUnknownCommand
}
return factory.Unmarshal(data[4:])
}
type CommandFactory interface {
Marshal(command interface{}, writer io.Writer) error
Unmarshal(data []byte) (interface{}, error)
}
type CommandSwitchAccountFactory struct {
}
func (this *CommandSwitchAccountFactory) Marshal(command interface{}, writer io.Writer) error {
cmd, ok := command.(*protocol.CommandSwitchAccount)
if !ok {
return ErrCommandTypeMismatch
}
hostStr := ""
if cmd.Host != nil {
hostStr = cmd.Host.String()
}
writer.Write([]byte{byte(len(hostStr))})
if len(hostStr) > 0 {
writer.Write([]byte(hostStr))
}
writer.Write(cmd.Port.Bytes(nil))
idBytes := cmd.ID.Bytes()
writer.Write(idBytes)
writer.Write(serial.Uint16ToBytes(cmd.AlterIds, nil))
writer.Write([]byte{byte(cmd.Level)})
writer.Write([]byte{cmd.ValidMin})
return nil
}
func (this *CommandSwitchAccountFactory) Unmarshal(data []byte) (interface{}, error) {
cmd := new(protocol.CommandSwitchAccount)
if len(data) == 0 {
return nil, transport.ErrCorruptedPacket
}
lenHost := int(data[0])
if len(data) < lenHost+1 {
return nil, transport.ErrCorruptedPacket
}
if lenHost > 0 {
cmd.Host = v2net.ParseAddress(string(data[1 : 1+lenHost]))
}
portStart := 1 + lenHost
if len(data) < portStart+2 {
return nil, transport.ErrCorruptedPacket
}
cmd.Port = v2net.PortFromBytes(data[portStart : portStart+2])
idStart := portStart + 2
if len(data) < idStart+16 {
return nil, transport.ErrCorruptedPacket
}
cmd.ID, _ = uuid.ParseBytes(data[idStart : idStart+16])
alterIdStart := idStart + 16
if len(data) < alterIdStart+2 {
return nil, transport.ErrCorruptedPacket
}
cmd.AlterIds = serial.BytesToUint16(data[alterIdStart : alterIdStart+2])
levelStart := alterIdStart + 2
if len(data) < levelStart+1 {
return nil, transport.ErrCorruptedPacket
}
cmd.Level = protocol.UserLevel(data[levelStart])
timeStart := levelStart + 1
if len(data) < timeStart {
return nil, transport.ErrCorruptedPacket
}
cmd.ValidMin = data[timeStart]
return cmd, nil
}

View File

@@ -0,0 +1,40 @@
package encoding_test
import (
"testing"
"github.com/v2ray/v2ray-core/common/alloc"
"github.com/v2ray/v2ray-core/common/protocol"
"github.com/v2ray/v2ray-core/common/uuid"
. "github.com/v2ray/v2ray-core/proxy/vmess/encoding"
"github.com/v2ray/v2ray-core/testing/assert"
)
func TestSwitchAccount(t *testing.T) {
assert := assert.On(t)
sa := &protocol.CommandSwitchAccount{
Port: 1234,
ID: uuid.New(),
AlterIds: 1024,
Level: 128,
ValidMin: 16,
}
buffer := alloc.NewBuffer().Clear()
err := MarshalCommand(sa, buffer)
assert.Error(err).IsNil()
cmd, err := UnmarshalCommand(1, buffer.Value[2:])
assert.Error(err).IsNil()
sa2, ok := cmd.(*protocol.CommandSwitchAccount)
assert.Bool(ok).IsTrue()
assert.Pointer(sa.Host).IsNil()
assert.Pointer(sa2.Host).IsNil()
assert.Port(sa.Port).Equals(sa2.Port)
assert.String(sa.ID.String()).Equals(sa2.ID.String())
assert.Uint16(sa.AlterIds).Equals(sa2.AlterIds)
assert.Byte(byte(sa.Level)).Equals(byte(sa2.Level))
assert.Byte(sa.ValidMin).Equals(sa2.ValidMin)
}

View File

@@ -0,0 +1,9 @@
package encoding
const (
Version = byte(1)
AddrTypeIPv4 = byte(0x01)
AddrTypeIPv6 = byte(0x03)
AddrTypeDomain = byte(0x02)
)

View File

@@ -0,0 +1,50 @@
package encoding_test
import (
"testing"
"github.com/v2ray/v2ray-core/common/alloc"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/common/protocol"
"github.com/v2ray/v2ray-core/common/uuid"
. "github.com/v2ray/v2ray-core/proxy/vmess/encoding"
"github.com/v2ray/v2ray-core/testing/assert"
)
func TestRequestSerialization(t *testing.T) {
assert := assert.On(t)
user := protocol.NewUser(
&protocol.VMessAccount{
ID: protocol.NewID(uuid.New()),
AlterIDs: nil,
},
protocol.UserLevelUntrusted,
"test@v2ray.com")
expectedRequest := &protocol.RequestHeader{
Version: 1,
User: user,
Command: protocol.RequestCommandTCP,
Option: protocol.RequestOption(0),
Address: v2net.DomainAddress("www.v2ray.com"),
Port: v2net.Port(443),
}
buffer := alloc.NewBuffer().Clear()
client := NewClientSession(protocol.DefaultIDHash)
client.EncodeRequestHeader(expectedRequest, buffer)
userValidator := protocol.NewTimedUserValidator(protocol.DefaultIDHash)
userValidator.Add(user)
server := NewServerSession(userValidator)
actualRequest, err := server.DecodeRequestHeader(buffer)
assert.Error(err).IsNil()
assert.Byte(expectedRequest.Version).Equals(actualRequest.Version)
assert.Byte(byte(expectedRequest.Command)).Equals(byte(actualRequest.Command))
assert.Byte(byte(expectedRequest.Option)).Equals(byte(actualRequest.Option))
assert.Address(expectedRequest.Address).Equals(actualRequest.Address)
assert.Port(expectedRequest.Port).Equals(actualRequest.Port)
}

View File

@@ -0,0 +1,168 @@
package encoding
import (
"crypto/md5"
"hash/fnv"
"io"
"github.com/v2ray/v2ray-core/common/crypto"
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/common/protocol"
"github.com/v2ray/v2ray-core/common/serial"
"github.com/v2ray/v2ray-core/transport"
)
type ServerSession struct {
userValidator protocol.UserValidator
requestBodyKey []byte
requestBodyIV []byte
responseBodyKey []byte
responseBodyIV []byte
responseHeader byte
responseWriter io.Writer
}
// NewServerSession creates a new ServerSession, using the given UserValidator.
// The ServerSession instance doesn't take ownership of the validator.
func NewServerSession(validator protocol.UserValidator) *ServerSession {
return &ServerSession{
userValidator: validator,
}
}
// Release implements common.Releaseable.
func (this *ServerSession) Release() {
this.userValidator = nil
this.requestBodyIV = nil
this.requestBodyKey = nil
this.responseBodyIV = nil
this.responseBodyKey = nil
this.responseWriter = nil
}
func (this *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.RequestHeader, error) {
buffer := make([]byte, 512)
_, err := io.ReadFull(reader, buffer[:protocol.IDBytesLen])
if err != nil {
log.Info("Raw: Failed to read request header: ", err)
return nil, io.EOF
}
user, timestamp, valid := this.userValidator.Get(buffer[:protocol.IDBytesLen])
if !valid {
return nil, protocol.ErrInvalidUser
}
timestampHash := md5.New()
timestampHash.Write(hashTimestamp(timestamp))
iv := timestampHash.Sum(nil)
account := user.Account.(*protocol.VMessAccount)
aesStream := crypto.NewAesDecryptionStream(account.ID.CmdKey(), iv)
decryptor := crypto.NewCryptionReader(aesStream, reader)
nBytes, err := io.ReadFull(decryptor, buffer[:41])
if err != nil {
log.Debug("Raw: Failed to read request header (", nBytes, " bytes): ", err)
return nil, err
}
bufferLen := nBytes
request := &protocol.RequestHeader{
User: user,
Version: buffer[0],
}
if request.Version != Version {
log.Info("Raw: Invalid protocol version ", request.Version)
return nil, protocol.ErrInvalidVersion
}
this.requestBodyIV = append([]byte(nil), buffer[1:17]...) // 16 bytes
this.requestBodyKey = append([]byte(nil), buffer[17:33]...) // 16 bytes
this.responseHeader = buffer[33] // 1 byte
request.Option = protocol.RequestOption(buffer[34]) // 1 byte + 2 bytes reserved
request.Command = protocol.RequestCommand(buffer[37])
request.Port = v2net.PortFromBytes(buffer[38:40])
switch buffer[40] {
case AddrTypeIPv4:
nBytes, err = io.ReadFull(decryptor, buffer[41:45]) // 4 bytes
bufferLen += 4
if err != nil {
log.Debug("VMess: Failed to read target IPv4 (", nBytes, " bytes): ", err)
return nil, err
}
request.Address = v2net.IPAddress(buffer[41:45])
case AddrTypeIPv6:
nBytes, err = io.ReadFull(decryptor, buffer[41:57]) // 16 bytes
bufferLen += 16
if err != nil {
log.Debug("VMess: Failed to read target IPv6 (", nBytes, " bytes): ", nBytes, err)
return nil, err
}
request.Address = v2net.IPAddress(buffer[41:57])
case AddrTypeDomain:
nBytes, err = io.ReadFull(decryptor, buffer[41:42])
if err != nil {
log.Debug("VMess: Failed to read target domain (", nBytes, " bytes): ", nBytes, err)
return nil, err
}
domainLength := int(buffer[41])
if domainLength == 0 {
return nil, transport.ErrCorruptedPacket
}
nBytes, err = io.ReadFull(decryptor, buffer[42:42+domainLength])
if err != nil {
log.Debug("VMess: Failed to read target domain (", nBytes, " bytes): ", nBytes, err)
return nil, err
}
bufferLen += 1 + domainLength
request.Address = v2net.DomainAddress(string(buffer[42 : 42+domainLength]))
}
nBytes, err = io.ReadFull(decryptor, buffer[bufferLen:bufferLen+4])
if err != nil {
log.Debug("VMess: Failed to read checksum (", nBytes, " bytes): ", nBytes, err)
return nil, err
}
fnv1a := fnv.New32a()
fnv1a.Write(buffer[:bufferLen])
actualHash := fnv1a.Sum32()
expectedHash := serial.BytesToUint32(buffer[bufferLen : bufferLen+4])
if actualHash != expectedHash {
return nil, transport.ErrCorruptedPacket
}
return request, nil
}
func (this *ServerSession) DecodeRequestBody(reader io.Reader) io.Reader {
aesStream := crypto.NewAesDecryptionStream(this.requestBodyKey, this.requestBodyIV)
return crypto.NewCryptionReader(aesStream, reader)
}
func (this *ServerSession) EncodeResponseHeader(header *protocol.ResponseHeader, writer io.Writer) {
responseBodyKey := md5.Sum(this.requestBodyKey)
responseBodyIV := md5.Sum(this.requestBodyIV)
this.responseBodyKey = responseBodyKey[:]
this.responseBodyIV = responseBodyIV[:]
aesStream := crypto.NewAesEncryptionStream(this.responseBodyKey, this.responseBodyIV)
encryptionWriter := crypto.NewCryptionWriter(aesStream, writer)
this.responseWriter = encryptionWriter
encryptionWriter.Write([]byte{this.responseHeader, byte(header.Option)})
err := MarshalCommand(header.Command, encryptionWriter)
if err != nil {
encryptionWriter.Write([]byte{0x00, 0x00})
}
}
func (this *ServerSession) EncodeResponseBody(writer io.Writer) io.Writer {
return this.responseWriter
}

View File

@@ -12,10 +12,10 @@ import (
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/common/protocol"
"github.com/v2ray/v2ray-core/common/protocol/raw"
"github.com/v2ray/v2ray-core/common/uuid"
"github.com/v2ray/v2ray-core/proxy"
"github.com/v2ray/v2ray-core/proxy/internal"
"github.com/v2ray/v2ray-core/proxy/vmess/encoding"
vmessio "github.com/v2ray/v2ray-core/proxy/vmess/io"
"github.com/v2ray/v2ray-core/transport/internet"
)
@@ -142,7 +142,7 @@ func (this *VMessInboundHandler) HandleConnection(connection internet.Connection
this.RUnlock()
return
}
session := raw.NewServerSession(this.clients)
session := encoding.NewServerSession(this.clients)
defer session.Release()
request, err := session.DecodeRequestHeader(reader)

View File

@@ -10,10 +10,10 @@ import (
"github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/common/protocol"
"github.com/v2ray/v2ray-core/common/protocol/raw"
"github.com/v2ray/v2ray-core/common/retry"
"github.com/v2ray/v2ray-core/proxy"
"github.com/v2ray/v2ray-core/proxy/internal"
"github.com/v2ray/v2ray-core/proxy/vmess/encoding"
vmessio "github.com/v2ray/v2ray-core/proxy/vmess/io"
"github.com/v2ray/v2ray-core/transport/internet"
"github.com/v2ray/v2ray-core/transport/ray"
@@ -52,7 +52,7 @@ func (this *VMessOutboundHandler) Dispatch(target v2net.Destination, payload *al
command = protocol.RequestCommandUDP
}
request := &protocol.RequestHeader{
Version: raw.Version,
Version: encoding.Version,
User: rec.PickUser(),
Command: command,
Address: target.Address(),
@@ -74,7 +74,7 @@ func (this *VMessOutboundHandler) Dispatch(target v2net.Destination, payload *al
requestFinish.Lock()
responseFinish.Lock()
session := raw.NewClientSession(protocol.DefaultIDHash)
session := encoding.NewClientSession(protocol.DefaultIDHash)
go this.handleRequest(session, conn, request, payload, input, &requestFinish)
go this.handleResponse(session, conn, request, rec.Destination, output, &responseFinish)
@@ -84,7 +84,7 @@ func (this *VMessOutboundHandler) Dispatch(target v2net.Destination, payload *al
return nil
}
func (this *VMessOutboundHandler) handleRequest(session *raw.ClientSession, conn internet.Connection, request *protocol.RequestHeader, payload *alloc.Buffer, input v2io.Reader, finish *sync.Mutex) {
func (this *VMessOutboundHandler) handleRequest(session *encoding.ClientSession, conn internet.Connection, request *protocol.RequestHeader, payload *alloc.Buffer, input v2io.Reader, finish *sync.Mutex) {
defer finish.Unlock()
writer := v2io.NewBufferedWriter(conn)
@@ -116,7 +116,7 @@ func (this *VMessOutboundHandler) handleRequest(session *raw.ClientSession, conn
return
}
func (this *VMessOutboundHandler) handleResponse(session *raw.ClientSession, conn internet.Connection, request *protocol.RequestHeader, dest v2net.Destination, output v2io.Writer, finish *sync.Mutex) {
func (this *VMessOutboundHandler) handleResponse(session *encoding.ClientSession, conn internet.Connection, request *protocol.RequestHeader, dest v2net.Destination, output v2io.Writer, finish *sync.Mutex) {
defer finish.Unlock()
reader := v2io.NewBufferedReader(conn)