1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-17 18:06:15 -05:00
v2fly/proxy/vmess/encoding/client.go
Darien Raymond 4fcb39ded9
comments
2018-10-18 09:25:58 +02:00

265 lines
9.1 KiB
Go

package encoding
import (
"crypto/md5"
"crypto/rand"
"hash/fnv"
"io"
"golang.org/x/crypto/chacha20poly1305"
"v2ray.com/core/common"
"v2ray.com/core/common/bitmask"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/crypto"
"v2ray.com/core/common/dice"
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
"v2ray.com/core/proxy/vmess"
)
func hashTimestamp(t protocol.Timestamp) []byte {
bytes := make([]byte, 0, 32)
bytes = t.Bytes(bytes)
bytes = t.Bytes(bytes)
bytes = t.Bytes(bytes)
bytes = t.Bytes(bytes)
return bytes
}
// ClientSession stores connection session info for VMess client.
type ClientSession struct {
idHash protocol.IDHash
requestBodyKey [16]byte
requestBodyIV [16]byte
responseBodyKey [16]byte
responseBodyIV [16]byte
responseReader io.Reader
responseHeader byte
}
// NewClientSession creates a new ClientSession.
func NewClientSession(idHash protocol.IDHash) *ClientSession {
randomBytes := make([]byte, 33) // 16 + 16 + 1
common.Must2(rand.Read(randomBytes))
session := &ClientSession{}
copy(session.requestBodyKey[:], randomBytes[:16])
copy(session.requestBodyIV[:], randomBytes[16:32])
session.responseHeader = randomBytes[32]
session.responseBodyKey = md5.Sum(session.requestBodyKey[:])
session.responseBodyIV = md5.Sum(session.requestBodyIV[:])
session.idHash = idHash
return session
}
func (c *ClientSession) EncodeRequestHeader(header *protocol.RequestHeader, writer io.Writer) error {
timestamp := protocol.NewTimestampGenerator(protocol.NowTime(), 30)()
account := header.User.Account.(*vmess.MemoryAccount)
idHash := c.idHash(account.AnyValidID().Bytes())
common.Must2(idHash.Write(timestamp.Bytes(nil)))
common.Must2(writer.Write(idHash.Sum(nil)))
buffer := buf.New()
defer buffer.Release()
common.Must2(buffer.WriteBytes(Version))
common.Must2(buffer.Write(c.requestBodyIV[:]))
common.Must2(buffer.Write(c.requestBodyKey[:]))
common.Must2(buffer.WriteBytes(c.responseHeader, byte(header.Option)))
padingLen := dice.Roll(16)
security := byte(padingLen<<4) | byte(header.Security)
common.Must2(buffer.WriteBytes(security, byte(0), byte(header.Command)))
if header.Command != protocol.RequestCommandMux {
if err := addrParser.WriteAddressPort(buffer, header.Address, header.Port); err != nil {
return newError("failed to writer address and port").Base(err)
}
}
if padingLen > 0 {
common.Must(buffer.AppendSupplier(buf.ReadFullFrom(rand.Reader, int32(padingLen))))
}
{
fnv1a := fnv.New32a()
common.Must2(fnv1a.Write(buffer.Bytes()))
common.Must(buffer.AppendSupplier(serial.WriteHash(fnv1a)))
}
iv := md5.Sum(hashTimestamp(timestamp))
aesStream := crypto.NewAesEncryptionStream(account.ID.CmdKey(), iv[:])
aesStream.XORKeyStream(buffer.Bytes(), buffer.Bytes())
common.Must2(writer.Write(buffer.Bytes()))
return nil
}
func (c *ClientSession) EncodeRequestBody(request *protocol.RequestHeader, writer io.Writer) buf.Writer {
var sizeParser crypto.ChunkSizeEncoder = crypto.PlainChunkSizeParser{}
if request.Option.Has(protocol.RequestOptionChunkMasking) {
sizeParser = NewShakeSizeParser(c.requestBodyIV[:])
}
var padding crypto.PaddingLengthGenerator = nil
if request.Option.Has(protocol.RequestOptionGlobalPadding) {
padding = sizeParser.(crypto.PaddingLengthGenerator)
}
switch request.Security {
case protocol.SecurityType_NONE:
if request.Option.Has(protocol.RequestOptionChunkStream) {
if request.Command.TransferType() == protocol.TransferTypeStream {
return crypto.NewChunkStreamWriter(sizeParser, writer)
}
auth := &crypto.AEADAuthenticator{
AEAD: new(NoOpAuthenticator),
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, protocol.TransferTypePacket, padding)
}
return buf.NewWriter(writer)
case protocol.SecurityType_LEGACY:
aesStream := crypto.NewAesEncryptionStream(c.requestBodyKey[:], c.requestBodyIV[:])
cryptionWriter := crypto.NewCryptionWriter(aesStream, writer)
if request.Option.Has(protocol.RequestOptionChunkStream) {
auth := &crypto.AEADAuthenticator{
AEAD: new(FnvAuthenticator),
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationWriter(auth, sizeParser, cryptionWriter, request.Command.TransferType(), padding)
}
return &buf.SequentialWriter{Writer: cryptionWriter}
case protocol.SecurityType_AES128_GCM:
aead := crypto.NewAesGcm(c.requestBodyKey[:])
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: GenerateChunkNonce(c.requestBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding)
case protocol.SecurityType_CHACHA20_POLY1305:
aead, err := chacha20poly1305.New(GenerateChacha20Poly1305Key(c.requestBodyKey[:]))
common.Must(err)
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: GenerateChunkNonce(c.requestBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding)
default:
panic("Unknown security type.")
}
}
func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.ResponseHeader, error) {
aesStream := crypto.NewAesDecryptionStream(c.responseBodyKey[:], c.responseBodyIV[:])
c.responseReader = crypto.NewCryptionReader(aesStream, reader)
buffer := buf.New()
defer buffer.Release()
if err := buffer.AppendSupplier(buf.ReadFullFrom(c.responseReader, 4)); err != nil {
return nil, newError("failed to read response header").Base(err)
}
if buffer.Byte(0) != c.responseHeader {
return nil, newError("unexpected response header. Expecting ", int(c.responseHeader), " but actually ", int(buffer.Byte(0)))
}
header := &protocol.ResponseHeader{
Option: bitmask.Byte(buffer.Byte(1)),
}
if buffer.Byte(2) != 0 {
cmdID := buffer.Byte(2)
dataLen := int32(buffer.Byte(3))
if err := buffer.Reset(buf.ReadFullFrom(c.responseReader, dataLen)); err != nil {
return nil, newError("failed to read response command").Base(err)
}
command, err := UnmarshalCommand(cmdID, buffer.Bytes())
if err == nil {
header.Command = command
}
}
return header, nil
}
func (c *ClientSession) DecodeResponseBody(request *protocol.RequestHeader, reader io.Reader) buf.Reader {
var sizeParser crypto.ChunkSizeDecoder = crypto.PlainChunkSizeParser{}
if request.Option.Has(protocol.RequestOptionChunkMasking) {
sizeParser = NewShakeSizeParser(c.responseBodyIV[:])
}
var padding crypto.PaddingLengthGenerator = nil
if request.Option.Has(protocol.RequestOptionGlobalPadding) {
padding = sizeParser.(crypto.PaddingLengthGenerator)
}
switch request.Security {
case protocol.SecurityType_NONE:
if request.Option.Has(protocol.RequestOptionChunkStream) {
if request.Command.TransferType() == protocol.TransferTypeStream {
return crypto.NewChunkStreamReader(sizeParser, reader)
}
auth := &crypto.AEADAuthenticator{
AEAD: new(NoOpAuthenticator),
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationReader(auth, sizeParser, reader, protocol.TransferTypePacket, padding)
}
return buf.NewReader(reader)
case protocol.SecurityType_LEGACY:
if request.Option.Has(protocol.RequestOptionChunkStream) {
auth := &crypto.AEADAuthenticator{
AEAD: new(FnvAuthenticator),
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationReader(auth, sizeParser, c.responseReader, request.Command.TransferType(), padding)
}
return buf.NewReader(c.responseReader)
case protocol.SecurityType_AES128_GCM:
aead := crypto.NewAesGcm(c.responseBodyKey[:])
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: GenerateChunkNonce(c.responseBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding)
case protocol.SecurityType_CHACHA20_POLY1305:
aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(c.responseBodyKey[:]))
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: GenerateChunkNonce(c.responseBodyIV[:], uint32(aead.NonceSize())),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
}
return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding)
default:
panic("Unknown security type.")
}
}
func GenerateChunkNonce(nonce []byte, size uint32) crypto.BytesGenerator {
c := append([]byte(nil), nonce...)
count := uint16(0)
return func() []byte {
serial.Uint16ToBytes(count, c[:0])
count++
return c[:size]
}
}