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

375 lines
11 KiB
Go
Raw Normal View History

2016-07-23 11:17:51 +00:00
package encoding
2016-02-26 23:05:53 +00:00
import (
2017-02-12 15:53:23 +00:00
"context"
2016-12-07 16:32:40 +00:00
"crypto/aes"
"crypto/cipher"
2016-02-26 23:05:53 +00:00
"crypto/md5"
"hash/fnv"
"io"
2017-02-12 12:57:36 +00:00
"sync"
"time"
2016-12-07 16:32:40 +00:00
"golang.org/x/crypto/chacha20poly1305"
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"
2017-01-13 22:42:39 +00:00
"v2ray.com/core/common/net"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/common/protocol"
"v2ray.com/core/common/serial"
2017-02-14 09:13:09 +00:00
"v2ray.com/core/common/signal"
2016-08-20 18:55:45 +00:00
"v2ray.com/core/proxy/vmess"
2016-02-26 23:05:53 +00:00
)
2017-02-12 12:57:36 +00:00
type sessionId struct {
user [16]byte
key [16]byte
nonce [16]byte
}
2017-02-12 15:53:23 +00:00
type SessionHistory struct {
2017-02-12 12:57:36 +00:00
sync.RWMutex
cache map[sessionId]time.Time
2017-02-14 09:13:09 +00:00
token *signal.Semaphore
ctx context.Context
2017-02-12 12:57:36 +00:00
}
2017-02-12 15:53:23 +00:00
func NewSessionHistory(ctx context.Context) *SessionHistory {
h := &SessionHistory{
2017-02-12 12:57:36 +00:00
cache: make(map[sessionId]time.Time, 128),
2017-02-14 09:13:09 +00:00
token: signal.NewSemaphore(1),
ctx: ctx,
2017-02-12 12:57:36 +00:00
}
return h
}
2017-02-12 15:53:23 +00:00
func (h *SessionHistory) add(session sessionId) {
2017-02-12 12:57:36 +00:00
h.Lock()
h.cache[session] = time.Now().Add(time.Minute * 3)
2017-02-14 09:13:09 +00:00
select {
case <-h.token.Wait():
go h.run()
default:
}
2017-02-12 12:57:36 +00:00
h.Unlock()
}
2017-02-12 15:53:23 +00:00
func (h *SessionHistory) has(session sessionId) bool {
2017-02-12 12:57:36 +00:00
h.RLock()
defer h.RUnlock()
if expire, found := h.cache[session]; found {
return expire.After(time.Now())
}
return false
}
2017-02-14 09:13:09 +00:00
func (h *SessionHistory) run() {
defer h.token.Signal()
2017-02-12 12:57:36 +00:00
for {
2017-02-12 15:53:23 +00:00
select {
2017-02-14 09:13:09 +00:00
case <-h.ctx.Done():
2017-02-12 15:53:23 +00:00
return
case <-time.After(time.Second * 30):
}
2017-02-12 12:57:36 +00:00
session2Remove := make([]sessionId, 0, 16)
now := time.Now()
h.Lock()
2017-02-14 09:13:09 +00:00
if len(h.cache) == 0 {
h.Unlock()
return
}
2017-02-12 12:57:36 +00:00
for session, expire := range h.cache {
if expire.Before(now) {
session2Remove = append(session2Remove, session)
}
}
for _, session := range session2Remove {
delete(h.cache, session)
}
h.Unlock()
}
}
2017-02-14 13:16:43 +00:00
func getSizeMask(b []byte) crypto.Uint16Generator {
return crypto.NewShakeUint16Generator(b)
2017-02-14 09:55:45 +00:00
}
2016-02-26 23:05:53 +00:00
type ServerSession struct {
userValidator protocol.UserValidator
2017-02-12 15:53:23 +00:00
sessionHistory *SessionHistory
2016-02-26 23:05:53 +00:00
requestBodyKey []byte
requestBodyIV []byte
responseBodyKey []byte
responseBodyIV []byte
responseHeader byte
responseWriter io.Writer
}
2016-04-28 20:31:33 +00:00
// NewServerSession creates a new ServerSession, using the given UserValidator.
// The ServerSession instance doesn't take ownership of the validator.
2017-02-12 15:53:23 +00:00
func NewServerSession(validator protocol.UserValidator, sessionHistory *SessionHistory) *ServerSession {
2016-02-27 16:28:21 +00:00
return &ServerSession{
2017-02-12 15:53:23 +00:00
userValidator: validator,
sessionHistory: sessionHistory,
2016-02-27 16:28:21 +00:00
}
}
2016-11-27 20:39:09 +00:00
func (v *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.RequestHeader, error) {
2016-07-16 10:11:45 +00:00
buffer := make([]byte, 512)
2016-02-26 23:05:53 +00:00
2016-07-16 10:11:45 +00:00
_, err := io.ReadFull(reader, buffer[:protocol.IDBytesLen])
2016-02-26 23:05:53 +00:00
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to read request header").Base(err)
2016-02-26 23:05:53 +00:00
}
2016-11-27 20:39:09 +00:00
user, timestamp, valid := v.userValidator.Get(buffer[:protocol.IDBytesLen])
2016-02-26 23:05:53 +00:00
if !valid {
2017-04-08 23:43:25 +00:00
return nil, newError("invalid user")
2016-02-26 23:05:53 +00:00
}
timestampHash := md5.New()
timestampHash.Write(hashTimestamp(timestamp))
iv := timestampHash.Sum(nil)
2016-10-16 12:22:21 +00:00
account, err := user.GetTypedAccount()
2016-09-17 22:41:21 +00:00
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to get user account").Base(err)
2016-09-17 22:41:21 +00:00
}
2017-02-12 12:57:36 +00:00
vmessAccount := account.(*vmess.InternalAccount)
2016-10-16 12:22:21 +00:00
2017-02-12 12:57:36 +00:00
aesStream := crypto.NewAesDecryptionStream(vmessAccount.ID.CmdKey(), iv)
2016-02-26 23:05:53 +00:00
decryptor := crypto.NewCryptionReader(aesStream, reader)
2016-07-16 10:11:45 +00:00
nBytes, err := io.ReadFull(decryptor, buffer[:41])
2016-02-26 23:05:53 +00:00
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to read request header").Base(err)
2016-02-26 23:05:53 +00:00
}
bufferLen := nBytes
request := &protocol.RequestHeader{
User: user,
2016-07-16 10:11:45 +00:00
Version: buffer[0],
2016-02-26 23:05:53 +00:00
}
if request.Version != Version {
2017-04-08 23:43:25 +00:00
return nil, newError("invalid protocol version ", request.Version)
2016-02-26 23:05:53 +00:00
}
2016-11-27 20:39:09 +00:00
v.requestBodyIV = append([]byte(nil), buffer[1:17]...) // 16 bytes
v.requestBodyKey = append([]byte(nil), buffer[17:33]...) // 16 bytes
2017-02-12 12:57:36 +00:00
var sid sessionId
copy(sid.user[:], vmessAccount.ID.Bytes())
copy(sid.key[:], v.requestBodyKey)
copy(sid.nonce[:], v.requestBodyIV)
2017-02-12 15:53:23 +00:00
if v.sessionHistory.has(sid) {
2017-04-08 23:43:25 +00:00
return nil, newError("duplicated session id, possibly under replay attack")
2017-02-12 12:57:36 +00:00
}
2017-02-12 15:53:23 +00:00
v.sessionHistory.add(sid)
2017-02-12 12:57:36 +00:00
v.responseHeader = buffer[33] // 1 byte
request.Option = protocol.RequestOption(buffer[34]) // 1 byte
2016-12-07 16:32:40 +00:00
padingLen := int(buffer[35] >> 4)
2016-12-13 09:45:21 +00:00
request.Security = protocol.NormSecurity(protocol.Security(buffer[35] & 0x0F))
2016-12-07 16:32:40 +00:00
// 1 bytes reserved
2016-07-16 10:11:45 +00:00
request.Command = protocol.RequestCommand(buffer[37])
2016-02-26 23:05:53 +00:00
2017-01-13 22:42:39 +00:00
request.Port = net.PortFromBytes(buffer[38:40])
2016-02-26 23:05:53 +00:00
2016-07-16 10:11:45 +00:00
switch buffer[40] {
2016-02-26 23:05:53 +00:00
case AddrTypeIPv4:
2016-11-27 20:43:20 +00:00
_, err = io.ReadFull(decryptor, buffer[41:45]) // 4 bytes
2016-02-26 23:05:53 +00:00
bufferLen += 4
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to read IPv4 address").Base(err)
2016-02-26 23:05:53 +00:00
}
2017-01-13 22:42:39 +00:00
request.Address = net.IPAddress(buffer[41:45])
2016-02-26 23:05:53 +00:00
case AddrTypeIPv6:
2016-11-27 20:43:20 +00:00
_, err = io.ReadFull(decryptor, buffer[41:57]) // 16 bytes
2016-02-26 23:05:53 +00:00
bufferLen += 16
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to read IPv6 address").Base(err)
2016-02-26 23:05:53 +00:00
}
2017-01-13 22:42:39 +00:00
request.Address = net.IPAddress(buffer[41:57])
2016-02-26 23:05:53 +00:00
case AddrTypeDomain:
2016-11-19 13:38:13 +00:00
_, err = io.ReadFull(decryptor, buffer[41:42])
2016-02-26 23:05:53 +00:00
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to read domain address").Base(err)
2016-02-26 23:05:53 +00:00
}
2016-07-16 10:11:45 +00:00
domainLength := int(buffer[41])
2016-02-26 23:05:53 +00:00
if domainLength == 0 {
2017-04-08 23:43:25 +00:00
return nil, newError("zero length domain").Base(err)
2016-02-26 23:05:53 +00:00
}
2016-11-27 20:43:20 +00:00
_, err = io.ReadFull(decryptor, buffer[42:42+domainLength])
2016-02-26 23:05:53 +00:00
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to read domain address").Base(err)
2016-02-26 23:05:53 +00:00
}
bufferLen += 1 + domainLength
2017-01-13 22:42:39 +00:00
request.Address = net.DomainAddress(string(buffer[42 : 42+domainLength]))
2016-02-26 23:05:53 +00:00
}
2016-12-07 16:32:40 +00:00
if padingLen > 0 {
_, err = io.ReadFull(decryptor, buffer[bufferLen:bufferLen+padingLen])
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to read padding").Base(err)
2016-12-07 16:32:40 +00:00
}
bufferLen += padingLen
}
2016-11-27 20:43:20 +00:00
_, err = io.ReadFull(decryptor, buffer[bufferLen:bufferLen+4])
2016-02-26 23:05:53 +00:00
if err != nil {
2017-04-08 23:43:25 +00:00
return nil, newError("failed to read checksum").Base(err)
2016-02-26 23:05:53 +00:00
}
fnv1a := fnv.New32a()
2016-07-16 10:11:45 +00:00
fnv1a.Write(buffer[:bufferLen])
2016-02-26 23:05:53 +00:00
actualHash := fnv1a.Sum32()
2016-07-16 10:11:45 +00:00
expectedHash := serial.BytesToUint32(buffer[bufferLen : bufferLen+4])
2016-02-26 23:05:53 +00:00
if actualHash != expectedHash {
2017-04-08 23:43:25 +00:00
return nil, newError("invalid auth")
2016-02-26 23:05:53 +00:00
}
2016-12-13 08:17:39 +00:00
if request.Address == nil {
2017-04-08 23:43:25 +00:00
return nil, newError("invalid remote address")
2016-12-13 08:17:39 +00:00
}
2016-02-26 23:05:53 +00:00
return request, nil
}
2016-12-09 12:17:34 +00:00
func (v *ServerSession) DecodeRequestBody(request *protocol.RequestHeader, reader io.Reader) buf.Reader {
2016-12-07 16:32:40 +00:00
var authReader io.Reader
2017-02-14 13:16:43 +00:00
var sizeMask crypto.Uint16Generator = crypto.StaticUint16Generator(0)
if request.Option.Has(protocol.RequestOptionChunkMasking) {
sizeMask = getSizeMask(v.requestBodyIV)
}
2016-12-07 16:32:40 +00:00
if request.Security.Is(protocol.SecurityType_NONE) {
if request.Option.Has(protocol.RequestOptionChunkStream) {
auth := &crypto.AEADAuthenticator{
2017-01-22 19:43:01 +00:00
AEAD: NoOpAuthenticator{},
2016-12-07 16:32:40 +00:00
NonceGenerator: crypto.NoOpBytesGenerator{},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-02-14 13:16:43 +00:00
authReader = crypto.NewAuthenticationReader(auth, reader, sizeMask)
2016-12-07 16:32:40 +00:00
} else {
authReader = reader
}
} else if request.Security.Is(protocol.SecurityType_LEGACY) {
aesStream := crypto.NewAesDecryptionStream(v.requestBodyKey, v.requestBodyIV)
cryptionReader := crypto.NewCryptionReader(aesStream, reader)
if request.Option.Has(protocol.RequestOptionChunkStream) {
auth := &crypto.AEADAuthenticator{
AEAD: new(FnvAuthenticator),
NonceGenerator: crypto.NoOpBytesGenerator{},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-02-14 13:16:43 +00:00
authReader = crypto.NewAuthenticationReader(auth, cryptionReader, sizeMask)
2016-12-07 16:32:40 +00:00
} else {
authReader = cryptionReader
}
} else if request.Security.Is(protocol.SecurityType_AES128_GCM) {
2016-12-07 21:52:56 +00:00
block, _ := aes.NewCipher(v.requestBodyKey)
2016-12-07 16:32:40 +00:00
aead, _ := cipher.NewGCM(block)
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: &ChunkNonceGenerator{
2016-12-07 21:52:56 +00:00
Nonce: append([]byte(nil), v.requestBodyIV...),
2016-12-07 16:32:40 +00:00
Size: aead.NonceSize(),
},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-02-14 13:16:43 +00:00
authReader = crypto.NewAuthenticationReader(auth, reader, sizeMask)
2016-12-07 16:32:40 +00:00
} else if request.Security.Is(protocol.SecurityType_CHACHA20_POLY1305) {
2016-12-07 21:52:56 +00:00
aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(v.requestBodyKey))
2016-12-07 16:32:40 +00:00
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: &ChunkNonceGenerator{
2016-12-07 21:52:56 +00:00
Nonce: append([]byte(nil), v.requestBodyIV...),
2016-12-07 16:32:40 +00:00
Size: aead.NonceSize(),
},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-02-14 13:16:43 +00:00
authReader = crypto.NewAuthenticationReader(auth, reader, sizeMask)
2016-12-07 16:32:40 +00:00
}
2016-12-09 12:17:34 +00:00
return buf.NewReader(authReader)
2016-02-26 23:05:53 +00:00
}
2016-11-27 20:39:09 +00:00
func (v *ServerSession) EncodeResponseHeader(header *protocol.ResponseHeader, writer io.Writer) {
responseBodyKey := md5.Sum(v.requestBodyKey)
responseBodyIV := md5.Sum(v.requestBodyIV)
v.responseBodyKey = responseBodyKey[:]
v.responseBodyIV = responseBodyIV[:]
2016-02-26 23:05:53 +00:00
2016-11-27 20:39:09 +00:00
aesStream := crypto.NewAesEncryptionStream(v.responseBodyKey, v.responseBodyIV)
2016-02-26 23:05:53 +00:00
encryptionWriter := crypto.NewCryptionWriter(aesStream, writer)
2016-11-27 20:39:09 +00:00
v.responseWriter = encryptionWriter
2016-02-26 23:05:53 +00:00
2016-11-27 20:39:09 +00:00
encryptionWriter.Write([]byte{v.responseHeader, byte(header.Option)})
2016-02-27 16:28:21 +00:00
err := MarshalCommand(header.Command, encryptionWriter)
if err != nil {
encryptionWriter.Write([]byte{0x00, 0x00})
}
2016-02-27 15:41:21 +00:00
}
2016-12-09 12:17:34 +00:00
func (v *ServerSession) EncodeResponseBody(request *protocol.RequestHeader, writer io.Writer) buf.Writer {
2016-12-07 16:32:40 +00:00
var authWriter io.Writer
2017-02-14 13:16:43 +00:00
var sizeMask crypto.Uint16Generator = crypto.StaticUint16Generator(0)
if request.Option.Has(protocol.RequestOptionChunkMasking) {
sizeMask = getSizeMask(v.responseBodyIV)
}
2016-12-07 16:32:40 +00:00
if request.Security.Is(protocol.SecurityType_NONE) {
if request.Option.Has(protocol.RequestOptionChunkStream) {
auth := &crypto.AEADAuthenticator{
2017-02-14 13:16:43 +00:00
AEAD: NoOpAuthenticator{},
2016-12-07 16:32:40 +00:00
NonceGenerator: crypto.NoOpBytesGenerator{},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-02-14 13:16:43 +00:00
authWriter = crypto.NewAuthenticationWriter(auth, writer, sizeMask)
2016-12-07 16:32:40 +00:00
} else {
authWriter = writer
}
} else if request.Security.Is(protocol.SecurityType_LEGACY) {
if request.Option.Has(protocol.RequestOptionChunkStream) {
auth := &crypto.AEADAuthenticator{
AEAD: new(FnvAuthenticator),
NonceGenerator: crypto.NoOpBytesGenerator{},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-02-14 13:16:43 +00:00
authWriter = crypto.NewAuthenticationWriter(auth, v.responseWriter, sizeMask)
2016-12-07 16:32:40 +00:00
} else {
authWriter = v.responseWriter
}
} else if request.Security.Is(protocol.SecurityType_AES128_GCM) {
block, _ := aes.NewCipher(v.responseBodyKey)
aead, _ := cipher.NewGCM(block)
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: &ChunkNonceGenerator{
Nonce: append([]byte(nil), v.responseBodyIV...),
Size: aead.NonceSize(),
},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-02-14 13:16:43 +00:00
authWriter = crypto.NewAuthenticationWriter(auth, writer, sizeMask)
2016-12-07 16:32:40 +00:00
} else if request.Security.Is(protocol.SecurityType_CHACHA20_POLY1305) {
2016-12-07 20:43:41 +00:00
aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(v.responseBodyKey))
2016-12-07 16:32:40 +00:00
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: &ChunkNonceGenerator{
Nonce: append([]byte(nil), v.responseBodyIV...),
Size: aead.NonceSize(),
},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-02-14 13:16:43 +00:00
authWriter = crypto.NewAuthenticationWriter(auth, writer, sizeMask)
2016-12-07 16:32:40 +00:00
}
2016-12-09 12:17:34 +00:00
return buf.NewWriter(authWriter)
2016-02-26 23:05:53 +00:00
}