v2ray-core/proxy/vmess/encoding/client.go

364 lines
13 KiB
Go
Raw Normal View History

2016-07-23 11:17:51 +00:00
package encoding
2016-02-25 20:50:38 +00:00
import (
2020-06-06 09:11:30 +00:00
"bytes"
"context"
2020-06-06 09:11:30 +00:00
"crypto/aes"
"crypto/cipher"
2016-02-25 20:50:38 +00:00
"crypto/md5"
"crypto/rand"
2020-06-06 09:11:30 +00:00
"crypto/sha256"
2018-11-02 17:20:02 +00:00
"encoding/binary"
2020-06-06 09:11:30 +00:00
"fmt"
2018-11-02 17:20:02 +00:00
"hash"
2016-02-25 20:50:38 +00:00
"hash/fnv"
"io"
2020-06-06 09:11:30 +00:00
"os"
"strings"
2020-06-06 09:11:30 +00:00
vmessaead "v2ray.com/core/proxy/vmess/aead"
2016-12-07 16:32:40 +00:00
"golang.org/x/crypto/chacha20poly1305"
2017-09-19 21:27:49 +00:00
"v2ray.com/core/common"
2017-10-21 19:04:24 +00:00
"v2ray.com/core/common/bitmask"
2016-12-09 12:17:34 +00:00
"v2ray.com/core/common/buf"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/common/crypto"
2016-12-07 16:32:40 +00:00
"v2ray.com/core/common/dice"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/common/protocol"
2018-11-03 12:03:02 +00:00
"v2ray.com/core/common/serial"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/proxy/vmess"
2016-02-25 20:50:38 +00:00
)
2018-11-02 17:20:02 +00:00
func hashTimestamp(h hash.Hash, t protocol.Timestamp) []byte {
2018-11-13 22:19:58 +00:00
common.Must2(serial.WriteUint64(h, uint64(t)))
common.Must2(serial.WriteUint64(h, uint64(t)))
common.Must2(serial.WriteUint64(h, uint64(t)))
common.Must2(serial.WriteUint64(h, uint64(t)))
2018-11-02 17:20:02 +00:00
return h.Sum(nil)
2016-02-25 20:50:38 +00:00
}
2016-12-13 08:32:29 +00:00
// ClientSession stores connection session info for VMess client.
2016-02-25 20:50:38 +00:00
type ClientSession struct {
idHash protocol.IDHash
requestBodyKey [16]byte
requestBodyIV [16]byte
responseBodyKey [16]byte
responseBodyIV [16]byte
responseReader io.Reader
responseHeader byte
2020-06-06 09:11:30 +00:00
isAEADRequest bool
2016-02-25 20:50:38 +00:00
}
2016-12-13 08:32:29 +00:00
// NewClientSession creates a new ClientSession.
func NewClientSession(idHash protocol.IDHash, ctx context.Context) *ClientSession {
randomBytes := make([]byte, 33) // 16 + 16 + 1
2017-09-19 21:27:49 +00:00
common.Must2(rand.Read(randomBytes))
2016-02-25 20:50:38 +00:00
session := &ClientSession{}
2020-06-06 09:11:30 +00:00
session.isAEADRequest = false
if ctxValueTestsEnabled := ctx.Value(vmess.TestsEnabled); ctxValueTestsEnabled != nil {
testsEnabled := ctxValueTestsEnabled.(string)
if strings.Contains(testsEnabled, "VMessAEAD") {
session.isAEADRequest = true
}
}
2020-06-06 09:11:30 +00:00
if vmessexp, vmessexp_found := os.LookupEnv("VMESSAEADEXPERIMENT"); vmessexp_found {
if vmessexp == "y" {
session.isAEADRequest = true
}
2020-06-06 12:37:30 +00:00
if vmessexp == "n" {
session.isAEADRequest = false
}
}
if session.isAEADRequest {
fmt.Println("=======VMESSAEADEXPERIMENT ENABLED========")
2020-06-06 09:11:30 +00:00
}
copy(session.requestBodyKey[:], randomBytes[:16])
copy(session.requestBodyIV[:], randomBytes[16:32])
2016-02-25 20:50:38 +00:00
session.responseHeader = randomBytes[32]
2020-06-06 09:11:30 +00:00
if !session.isAEADRequest {
session.responseBodyKey = md5.Sum(session.requestBodyKey[:])
session.responseBodyIV = md5.Sum(session.requestBodyIV[:])
} else {
BodyKey := sha256.Sum256(session.requestBodyKey[:])
copy(session.responseBodyKey[:], BodyKey[:16])
BodyIV := sha256.Sum256(session.requestBodyKey[:])
copy(session.responseBodyIV[:], BodyIV[:16])
}
2016-02-25 20:50:38 +00:00
session.idHash = idHash
return session
}
func (c *ClientSession) EncodeRequestHeader(header *protocol.RequestHeader, writer io.Writer) error {
2016-02-25 20:50:38 +00:00
timestamp := protocol.NewTimestampGenerator(protocol.NowTime(), 30)()
2018-10-18 07:25:58 +00:00
account := header.User.Account.(*vmess.MemoryAccount)
2020-06-06 09:11:30 +00:00
if !c.isAEADRequest {
idHash := c.idHash(account.AnyValidID().Bytes())
common.Must2(serial.WriteUint64(idHash, uint64(timestamp)))
common.Must2(writer.Write(idHash.Sum(nil)))
}
2016-02-25 20:50:38 +00:00
2017-10-27 19:11:45 +00:00
buffer := buf.New()
defer buffer.Release()
2018-11-14 21:55:20 +00:00
common.Must(buffer.WriteByte(Version))
2018-07-30 20:45:06 +00:00
common.Must2(buffer.Write(c.requestBodyIV[:]))
common.Must2(buffer.Write(c.requestBodyKey[:]))
2018-11-14 21:55:20 +00:00
common.Must(buffer.WriteByte(c.responseHeader))
common.Must(buffer.WriteByte(byte(header.Option)))
2017-10-27 19:11:45 +00:00
2016-12-07 16:32:40 +00:00
padingLen := dice.Roll(16)
security := byte(padingLen<<4) | byte(header.Security)
2018-11-14 21:55:20 +00:00
common.Must2(buffer.Write([]byte{security, byte(0), byte(header.Command)}))
2017-05-17 19:13:01 +00:00
if header.Command != protocol.RequestCommandMux {
2018-02-23 22:42:01 +00:00
if err := addrParser.WriteAddressPort(buffer, header.Address, header.Port); err != nil {
return newError("failed to writer address and port").Base(err)
2017-05-17 19:13:01 +00:00
}
2016-02-25 20:50:38 +00:00
}
2016-12-10 00:05:55 +00:00
if padingLen > 0 {
2018-11-02 14:01:33 +00:00
common.Must2(buffer.ReadFullFrom(rand.Reader, int32(padingLen)))
2016-12-10 00:05:55 +00:00
}
2016-12-07 16:32:40 +00:00
2018-07-30 20:54:24 +00:00
{
fnv1a := fnv.New32a()
common.Must2(fnv1a.Write(buffer.Bytes()))
2018-11-02 20:34:04 +00:00
hashBytes := buffer.Extend(int32(fnv1a.Size()))
fnv1a.Sum(hashBytes[:0])
2018-07-30 20:54:24 +00:00
}
2016-02-25 20:50:38 +00:00
2020-06-06 09:11:30 +00:00
if !c.isAEADRequest {
iv := hashTimestamp(md5.New(), timestamp)
aesStream := crypto.NewAesEncryptionStream(account.ID.CmdKey(), iv[:])
aesStream.XORKeyStream(buffer.Bytes(), buffer.Bytes())
common.Must2(writer.Write(buffer.Bytes()))
} else {
var fixedLengthCmdKey [16]byte
copy(fixedLengthCmdKey[:], account.ID.CmdKey())
vmessout := vmessaead.SealVMessAEADHeader(fixedLengthCmdKey, buffer.Bytes())
common.Must2(io.Copy(writer, bytes.NewReader(vmessout)))
}
return nil
2016-02-25 20:50:38 +00:00
}
2017-09-19 21:27:49 +00:00
func (c *ClientSession) EncodeRequestBody(request *protocol.RequestHeader, writer io.Writer) buf.Writer {
2017-04-23 11:30:08 +00:00
var sizeParser crypto.ChunkSizeEncoder = crypto.PlainChunkSizeParser{}
2017-02-14 13:16:43 +00:00
if request.Option.Has(protocol.RequestOptionChunkMasking) {
sizeParser = NewShakeSizeParser(c.requestBodyIV[:])
2017-02-14 13:16:43 +00:00
}
2018-11-13 08:51:55 +00:00
var padding crypto.PaddingLengthGenerator
2018-07-07 13:42:24 +00:00
if request.Option.Has(protocol.RequestOptionGlobalPadding) {
padding = sizeParser.(crypto.PaddingLengthGenerator)
}
switch request.Security {
case protocol.SecurityType_NONE:
2016-12-07 16:32:40 +00:00
if request.Option.Has(protocol.RequestOptionChunkStream) {
2018-02-09 21:29:30 +00:00
if request.Command.TransferType() == protocol.TransferTypeStream {
2017-05-01 22:28:16 +00:00
return crypto.NewChunkStreamWriter(sizeParser, writer)
}
auth := &crypto.AEADAuthenticator{
AEAD: new(NoOpAuthenticator),
2018-04-14 11:10:12 +00:00
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
2017-05-01 22:28:16 +00:00
}
2018-07-07 13:42:24 +00:00
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, protocol.TransferTypePacket, padding)
2016-12-07 16:32:40 +00:00
}
2017-04-23 11:30:08 +00:00
return buf.NewWriter(writer)
case protocol.SecurityType_LEGACY:
aesStream := crypto.NewAesEncryptionStream(c.requestBodyKey[:], c.requestBodyIV[:])
2016-12-07 16:32:40 +00:00
cryptionWriter := crypto.NewCryptionWriter(aesStream, writer)
if request.Option.Has(protocol.RequestOptionChunkStream) {
auth := &crypto.AEADAuthenticator{
AEAD: new(FnvAuthenticator),
2018-04-14 11:10:12 +00:00
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
2016-12-07 16:32:40 +00:00
}
2018-07-07 13:42:24 +00:00
return crypto.NewAuthenticationWriter(auth, sizeParser, cryptionWriter, request.Command.TransferType(), padding)
2016-12-07 16:32:40 +00:00
}
2017-04-23 11:30:08 +00:00
return &buf.SequentialWriter{Writer: cryptionWriter}
case protocol.SecurityType_AES128_GCM:
2018-09-12 13:43:36 +00:00
aead := crypto.NewAesGcm(c.requestBodyKey[:])
2016-12-07 16:32:40 +00:00
auth := &crypto.AEADAuthenticator{
2018-04-14 11:10:12 +00:00
AEAD: aead,
NonceGenerator: GenerateChunkNonce(c.requestBodyIV[:], uint32(aead.NonceSize())),
2018-04-14 11:10:12 +00:00
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
2016-12-07 16:32:40 +00:00
}
2018-07-07 13:42:24 +00:00
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding)
case protocol.SecurityType_CHACHA20_POLY1305:
2018-09-12 13:43:36 +00:00
aead, err := chacha20poly1305.New(GenerateChacha20Poly1305Key(c.requestBodyKey[:]))
common.Must(err)
2016-12-07 16:32:40 +00:00
auth := &crypto.AEADAuthenticator{
2018-04-14 11:10:12 +00:00
AEAD: aead,
NonceGenerator: GenerateChunkNonce(c.requestBodyIV[:], uint32(aead.NonceSize())),
2018-04-14 11:10:12 +00:00
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
2016-12-07 16:32:40 +00:00
}
2018-07-07 13:42:24 +00:00
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding)
default:
panic("Unknown security type.")
2016-12-07 16:32:40 +00:00
}
2016-02-25 20:50:38 +00:00
}
2017-07-25 20:21:59 +00:00
func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.ResponseHeader, error) {
2020-06-06 09:11:30 +00:00
if !c.isAEADRequest {
aesStream := crypto.NewAesDecryptionStream(c.responseBodyKey[:], c.responseBodyIV[:])
c.responseReader = crypto.NewCryptionReader(aesStream, reader)
} else {
2020-06-08 05:21:59 +00:00
aeadResponseHeaderLengthEncryptionKey := vmessaead.KDF16(c.responseBodyKey[:], vmessaead.KDFSaltConst_AEADRespHeaderLenKey)
aeadResponseHeaderLengthEncryptionIV := vmessaead.KDF(c.responseBodyIV[:], vmessaead.KDFSaltConst_AEADRespHeaderLenIV)[:12]
2020-06-06 09:11:30 +00:00
2020-06-08 05:21:59 +00:00
aeadResponseHeaderLengthEncryptionKeyAESBlock := common.Must2(aes.NewCipher(aeadResponseHeaderLengthEncryptionKey)).(cipher.Block)
aeadResponseHeaderLengthEncryptionAEAD := common.Must2(cipher.NewGCM(aeadResponseHeaderLengthEncryptionKeyAESBlock)).(cipher.AEAD)
2020-06-06 09:11:30 +00:00
2020-06-08 05:21:59 +00:00
var aeadEncryptedResponseHeaderLength [18]byte
var decryptedResponseHeaderLength int
var decryptedResponseHeaderLengthBinaryDeserializeBuffer uint16
2020-06-06 09:11:30 +00:00
2020-06-08 05:21:59 +00:00
if _, err := io.ReadFull(reader, aeadEncryptedResponseHeaderLength[:]); err != nil {
2020-06-06 09:11:30 +00:00
return nil, newError("Unable to Read Header Len").Base(err)
}
2020-06-08 05:21:59 +00:00
if decryptedResponseHeaderLengthBinaryBuffer, err := aeadResponseHeaderLengthEncryptionAEAD.Open(nil, aeadResponseHeaderLengthEncryptionIV, aeadEncryptedResponseHeaderLength[:], nil); err != nil {
2020-06-06 09:11:30 +00:00
return nil, newError("Failed To Decrypt Length").Base(err)
} else {
2020-06-08 05:21:59 +00:00
common.Must(binary.Read(bytes.NewReader(decryptedResponseHeaderLengthBinaryBuffer), binary.BigEndian, &decryptedResponseHeaderLengthBinaryDeserializeBuffer))
decryptedResponseHeaderLength = int(decryptedResponseHeaderLengthBinaryDeserializeBuffer)
2020-06-06 09:11:30 +00:00
}
2020-06-08 05:21:59 +00:00
aeadResponseHeaderPayloadEncryptionKey := vmessaead.KDF16(c.responseBodyKey[:], vmessaead.KDFSaltConst_AEADRespHeaderPayloadKey)
aeadResponseHeaderPayloadEncryptionIV := vmessaead.KDF(c.responseBodyIV[:], vmessaead.KDFSaltConst_AEADRespHeaderPayloadIV)[:12]
2020-06-06 09:11:30 +00:00
2020-06-08 05:21:59 +00:00
aeadResponseHeaderPayloadEncryptionKeyAESBlock := common.Must2(aes.NewCipher(aeadResponseHeaderPayloadEncryptionKey)).(cipher.Block)
aeadResponseHeaderPayloadEncryptionAEAD := common.Must2(cipher.NewGCM(aeadResponseHeaderPayloadEncryptionKeyAESBlock)).(cipher.AEAD)
2020-06-06 09:11:30 +00:00
2020-06-08 05:21:59 +00:00
encryptedResponseHeaderBuffer := make([]byte, decryptedResponseHeaderLength+16)
2020-06-06 09:11:30 +00:00
2020-06-08 05:21:59 +00:00
if _, err := io.ReadFull(reader, encryptedResponseHeaderBuffer); err != nil {
2020-06-06 09:11:30 +00:00
return nil, newError("Unable to Read Header Data").Base(err)
}
2020-06-08 05:21:59 +00:00
if decryptedResponseHeaderBuffer, err := aeadResponseHeaderPayloadEncryptionAEAD.Open(nil, aeadResponseHeaderPayloadEncryptionIV, encryptedResponseHeaderBuffer, nil); err != nil {
2020-06-06 09:11:30 +00:00
return nil, newError("Failed To Decrypt Payload").Base(err)
} else {
2020-06-08 05:21:59 +00:00
c.responseReader = bytes.NewReader(decryptedResponseHeaderBuffer)
2020-06-06 09:11:30 +00:00
}
}
2016-02-26 23:05:53 +00:00
2018-11-15 20:32:27 +00:00
buffer := buf.StackNew()
2017-10-27 19:11:45 +00:00
defer buffer.Release()
2016-02-26 23:05:53 +00:00
2018-11-02 14:01:33 +00:00
if _, err := buffer.ReadFullFrom(c.responseReader, 4); err != nil {
return nil, newError("failed to read response header").Base(err).AtWarning()
2016-02-26 23:05:53 +00:00
}
2017-10-27 19:11:45 +00:00
if buffer.Byte(0) != c.responseHeader {
return nil, newError("unexpected response header. Expecting ", int(c.responseHeader), " but actually ", int(buffer.Byte(0)))
2016-02-26 23:05:53 +00:00
}
2016-06-02 19:34:25 +00:00
header := &protocol.ResponseHeader{
2017-10-27 19:11:45 +00:00
Option: bitmask.Byte(buffer.Byte(1)),
2016-06-02 19:34:25 +00:00
}
2016-02-26 23:05:53 +00:00
2017-10-27 19:11:45 +00:00
if buffer.Byte(2) != 0 {
cmdID := buffer.Byte(2)
2018-04-01 22:44:47 +00:00
dataLen := int32(buffer.Byte(3))
2017-10-27 19:11:45 +00:00
2018-11-02 14:01:33 +00:00
buffer.Clear()
if _, err := buffer.ReadFullFrom(c.responseReader, dataLen); err != nil {
2018-02-22 14:26:00 +00:00
return nil, newError("failed to read response command").Base(err)
2016-02-26 23:05:53 +00:00
}
2017-10-27 19:11:45 +00:00
command, err := UnmarshalCommand(cmdID, buffer.Bytes())
2016-04-25 22:46:04 +00:00
if err == nil {
header.Command = command
}
2016-02-26 23:05:53 +00:00
}
2020-06-06 09:11:30 +00:00
if c.isAEADRequest {
aesStream := crypto.NewAesDecryptionStream(c.responseBodyKey[:], c.responseBodyIV[:])
c.responseReader = crypto.NewCryptionReader(aesStream, reader)
}
2016-02-26 23:05:53 +00:00
return header, nil
}
2017-07-25 20:21:59 +00:00
func (c *ClientSession) DecodeResponseBody(request *protocol.RequestHeader, reader io.Reader) buf.Reader {
2017-04-23 11:30:08 +00:00
var sizeParser crypto.ChunkSizeDecoder = crypto.PlainChunkSizeParser{}
2017-02-14 13:16:43 +00:00
if request.Option.Has(protocol.RequestOptionChunkMasking) {
sizeParser = NewShakeSizeParser(c.responseBodyIV[:])
2017-02-14 13:16:43 +00:00
}
2018-11-13 08:51:55 +00:00
var padding crypto.PaddingLengthGenerator
2018-07-07 13:42:24 +00:00
if request.Option.Has(protocol.RequestOptionGlobalPadding) {
padding = sizeParser.(crypto.PaddingLengthGenerator)
}
switch request.Security {
case protocol.SecurityType_NONE:
2016-12-07 16:32:40 +00:00
if request.Option.Has(protocol.RequestOptionChunkStream) {
2018-02-09 21:29:30 +00:00
if request.Command.TransferType() == protocol.TransferTypeStream {
2017-05-01 22:28:16 +00:00
return crypto.NewChunkStreamReader(sizeParser, reader)
}
auth := &crypto.AEADAuthenticator{
AEAD: new(NoOpAuthenticator),
2018-04-14 11:10:12 +00:00
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
2017-05-01 22:28:16 +00:00
}
2018-07-07 13:42:24 +00:00
return crypto.NewAuthenticationReader(auth, sizeParser, reader, protocol.TransferTypePacket, padding)
2016-12-07 16:32:40 +00:00
}
2017-04-23 11:30:08 +00:00
return buf.NewReader(reader)
case protocol.SecurityType_LEGACY:
2016-12-07 16:32:40 +00:00
if request.Option.Has(protocol.RequestOptionChunkStream) {
auth := &crypto.AEADAuthenticator{
AEAD: new(FnvAuthenticator),
2018-04-14 11:10:12 +00:00
NonceGenerator: crypto.GenerateEmptyBytes(),
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
2016-12-07 16:32:40 +00:00
}
2018-07-07 13:42:24 +00:00
return crypto.NewAuthenticationReader(auth, sizeParser, c.responseReader, request.Command.TransferType(), padding)
2016-12-07 16:32:40 +00:00
}
2017-04-23 11:30:08 +00:00
2017-07-25 20:21:59 +00:00
return buf.NewReader(c.responseReader)
case protocol.SecurityType_AES128_GCM:
2018-09-12 13:43:36 +00:00
aead := crypto.NewAesGcm(c.responseBodyKey[:])
2016-12-07 16:32:40 +00:00
auth := &crypto.AEADAuthenticator{
2018-04-14 11:10:12 +00:00
AEAD: aead,
NonceGenerator: GenerateChunkNonce(c.responseBodyIV[:], uint32(aead.NonceSize())),
2018-04-14 11:10:12 +00:00
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
2016-12-07 16:32:40 +00:00
}
2018-07-07 13:42:24 +00:00
return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding)
case protocol.SecurityType_CHACHA20_POLY1305:
aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(c.responseBodyKey[:]))
2016-12-07 16:32:40 +00:00
auth := &crypto.AEADAuthenticator{
2018-04-14 11:10:12 +00:00
AEAD: aead,
NonceGenerator: GenerateChunkNonce(c.responseBodyIV[:], uint32(aead.NonceSize())),
2018-04-14 11:10:12 +00:00
AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
2016-12-07 16:32:40 +00:00
}
2018-07-07 13:42:24 +00:00
return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding)
default:
panic("Unknown security type.")
2016-12-07 16:32:40 +00:00
}
}
2018-04-14 11:10:12 +00:00
func GenerateChunkNonce(nonce []byte, size uint32) crypto.BytesGenerator {
c := append([]byte(nil), nonce...)
count := uint16(0)
return func() []byte {
2018-11-02 17:20:02 +00:00
binary.BigEndian.PutUint16(c, count)
2018-04-14 11:10:12 +00:00
count++
return c[:size]
}
2016-02-26 23:05:53 +00:00
}