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

400 lines
12 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 (
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
2018-02-09 16:48:09 +00:00
"v2ray.com/core/common/dice"
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"
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
2018-02-08 14:39:46 +00:00
task *signal.PeriodicTask
2017-02-12 12:57:36 +00:00
}
2018-02-07 15:35:22 +00:00
func NewSessionHistory() *SessionHistory {
2017-02-12 15:53:23 +00:00
h := &SessionHistory{
2017-02-12 12:57:36 +00:00
cache: make(map[sessionId]time.Time, 128),
}
2018-02-08 14:39:46 +00:00
h.task = &signal.PeriodicTask{
Interval: time.Second * 30,
Execute: func() error {
h.removeExpiredEntries()
return nil
},
}
common.Must(h.task.Start())
2017-02-12 12:57:36 +00:00
return h
}
2018-02-08 14:39:46 +00:00
// Close implements common.Closable.
func (h *SessionHistory) Close() error {
return h.task.Close()
}
2017-02-12 15:53:23 +00:00
func (h *SessionHistory) add(session sessionId) {
2017-02-12 12:57:36 +00:00
h.Lock()
2018-02-07 15:35:22 +00:00
defer h.Unlock()
2017-02-14 09:13:09 +00:00
2018-02-07 15:35:22 +00:00
h.cache[session] = time.Now().Add(time.Minute * 3)
2017-02-12 12:57:36 +00:00
}
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
}
2018-02-07 15:35:22 +00:00
func (h *SessionHistory) removeExpiredEntries() {
now := time.Now()
2017-02-14 09:13:09 +00:00
2018-02-07 15:35:22 +00:00
h.Lock()
defer h.Unlock()
for session, expire := range h.cache {
if expire.Before(now) {
2017-02-12 12:57:36 +00:00
delete(h.cache, session)
}
2018-02-07 15:35:22 +00:00
}
2017-02-12 12:57:36 +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
}
}
2018-02-09 16:48:09 +00:00
func readAddress(buffer *buf.Buffer, reader io.Reader) (net.Address, net.Port, error) {
var address net.Address
var port net.Port
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, 3)); err != nil {
return address, port, newError("failed to read port and address type").Base(err)
}
port = net.PortFromBytes(buffer.BytesRange(-3, -1))
addressType := protocol.AddressType(buffer.Byte(buffer.Len() - 1))
switch addressType {
case protocol.AddressTypeIPv4:
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, 4)); err != nil {
return address, port, newError("failed to read IPv4 address").Base(err)
}
address = net.IPAddress(buffer.BytesFrom(-4))
case protocol.AddressTypeIPv6:
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, 16)); err != nil {
return address, port, newError("failed to read IPv6 address").Base(err)
}
address = net.IPAddress(buffer.BytesFrom(-16))
case protocol.AddressTypeDomain:
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, 1)); err != nil {
return address, port, newError("failed to read domain address").Base(err)
}
domainLength := int(buffer.Byte(buffer.Len() - 1))
if domainLength == 0 {
return address, port, newError("zero length domain")
}
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, domainLength)); err != nil {
return address, port, newError("failed to read domain address").Base(err)
}
address = net.DomainAddress(string(buffer.BytesFrom(-domainLength)))
default:
return address, port, newError("invalid address type", addressType)
}
return address, port, nil
}
2017-07-25 20:21:59 +00:00
func (s *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.RequestHeader, error) {
2017-10-27 19:11:45 +00:00
buffer := buf.New()
defer buffer.Release()
2016-02-26 23:05:53 +00:00
2017-10-27 19:11:45 +00:00
if err := buffer.AppendSupplier(buf.ReadFullFrom(reader, protocol.IDBytesLen)); 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
}
2017-10-27 19:11:45 +00:00
user, timestamp, valid := s.userValidator.Get(buffer.Bytes())
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()
2017-09-19 21:27:49 +00:00
common.Must2(timestampHash.Write(hashTimestamp(timestamp)))
2016-02-26 23:05:53 +00:00
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)
2018-02-09 16:48:09 +00:00
if err := buffer.Reset(buf.ReadFullFrom(decryptor, 38)); 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
}
request := &protocol.RequestHeader{
User: user,
2017-10-27 19:11:45 +00:00
Version: buffer.Byte(0),
2016-02-26 23:05:53 +00:00
}
2017-10-27 19:11:45 +00:00
s.requestBodyIV = append([]byte(nil), buffer.BytesRange(1, 17)...) // 16 bytes
s.requestBodyKey = append([]byte(nil), buffer.BytesRange(17, 33)...) // 16 bytes
2017-02-12 12:57:36 +00:00
var sid sessionId
copy(sid.user[:], vmessAccount.ID.Bytes())
2017-07-25 20:21:59 +00:00
copy(sid.key[:], s.requestBodyKey)
copy(sid.nonce[:], s.requestBodyIV)
if s.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-07-25 20:21:59 +00:00
s.sessionHistory.add(sid)
2017-02-12 12:57:36 +00:00
2017-10-27 19:11:45 +00:00
s.responseHeader = buffer.Byte(33) // 1 byte
request.Option = bitmask.Byte(buffer.Byte(34)) // 1 byte
padingLen := int(buffer.Byte(35) >> 4)
request.Security = protocol.NormSecurity(protocol.Security(buffer.Byte(35) & 0x0F))
2016-12-07 16:32:40 +00:00
// 1 bytes reserved
2017-10-27 19:11:45 +00:00
request.Command = protocol.RequestCommand(buffer.Byte(37))
2016-02-26 23:05:53 +00:00
2018-02-09 16:48:09 +00:00
invalidRequest := false
switch request.Command {
case protocol.RequestCommandMux:
request.Address = net.DomainAddress("v1.mux.cool")
request.Port = 0
case protocol.RequestCommandTCP, protocol.RequestCommandUDP:
if addr, port, err := readAddress(buffer, decryptor); err == nil {
request.Address = addr
request.Port = port
} else {
invalidRequest = true
newError("failed to read address").Base(err).WriteToLog()
2016-02-26 23:05:53 +00:00
}
2018-02-09 16:48:09 +00:00
default:
invalidRequest = true
}
if invalidRequest {
2018-02-09 16:56:39 +00:00
randomLen := dice.Roll(32) + 1
2018-02-09 16:48:09 +00:00
// Read random number of bytes for prevent detection.
buffer.AppendSupplier(buf.ReadFullFrom(decryptor, randomLen))
return nil, newError("invalid request")
2016-02-26 23:05:53 +00:00
}
2016-12-07 16:32:40 +00:00
if padingLen > 0 {
2017-10-27 19:11:45 +00:00
if err := buffer.AppendSupplier(buf.ReadFullFrom(decryptor, padingLen)); 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
}
}
2017-10-27 19:11:45 +00:00
if err := buffer.AppendSupplier(buf.ReadFullFrom(decryptor, 4)); 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()
2017-10-27 19:11:45 +00:00
common.Must2(fnv1a.Write(buffer.BytesTo(-4)))
2016-02-26 23:05:53 +00:00
actualHash := fnv1a.Sum32()
2017-10-27 19:11:45 +00:00
expectedHash := serial.BytesToUint32(buffer.BytesFrom(-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
}
2017-07-25 20:21:59 +00:00
func (s *ServerSession) DecodeRequestBody(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) {
2017-07-25 20:21:59 +00:00
sizeParser = NewShakeSizeParser(s.requestBodyIV)
2017-02-14 13:16:43 +00:00
}
2016-12-07 16:32:40 +00:00
if request.Security.Is(protocol.SecurityType_NONE) {
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),
NonceGenerator: crypto.NoOpBytesGenerator{},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-05-02 20:23:07 +00:00
return crypto.NewAuthenticationReader(auth, sizeParser, reader, protocol.TransferTypePacket)
2016-12-07 16:32:40 +00:00
}
2017-04-23 11:30:08 +00:00
return buf.NewReader(reader)
}
if request.Security.Is(protocol.SecurityType_LEGACY) {
2017-07-25 20:21:59 +00:00
aesStream := crypto.NewAesDecryptionStream(s.requestBodyKey, s.requestBodyIV)
2016-12-07 16:32:40 +00:00
cryptionReader := crypto.NewCryptionReader(aesStream, reader)
if request.Option.Has(protocol.RequestOptionChunkStream) {
auth := &crypto.AEADAuthenticator{
AEAD: new(FnvAuthenticator),
NonceGenerator: crypto.NoOpBytesGenerator{},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-05-02 20:23:07 +00:00
return crypto.NewAuthenticationReader(auth, sizeParser, cryptionReader, request.Command.TransferType())
2016-12-07 16:32:40 +00:00
}
2017-04-23 11:30:08 +00:00
return buf.NewReader(cryptionReader)
}
if request.Security.Is(protocol.SecurityType_AES128_GCM) {
2017-07-25 20:21:59 +00:00
block, _ := aes.NewCipher(s.requestBodyKey)
2016-12-07 16:32:40 +00:00
aead, _ := cipher.NewGCM(block)
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: &ChunkNonceGenerator{
2017-07-25 20:21:59 +00:00
Nonce: append([]byte(nil), s.requestBodyIV...),
2016-12-07 16:32:40 +00:00
Size: aead.NonceSize(),
},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-05-02 20:23:07 +00:00
return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType())
2017-04-23 11:30:08 +00:00
}
if request.Security.Is(protocol.SecurityType_CHACHA20_POLY1305) {
2017-07-25 20:21:59 +00:00
aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(s.requestBodyKey))
2016-12-07 16:32:40 +00:00
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: &ChunkNonceGenerator{
2017-07-25 20:21:59 +00:00
Nonce: append([]byte(nil), s.requestBodyIV...),
2016-12-07 16:32:40 +00:00
Size: aead.NonceSize(),
},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-05-02 20:23:07 +00:00
return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType())
2016-12-07 16:32:40 +00:00
}
2017-04-23 11:30:08 +00:00
panic("Unknown security type.")
2016-02-26 23:05:53 +00:00
}
2017-07-25 20:21:59 +00:00
func (s *ServerSession) EncodeResponseHeader(header *protocol.ResponseHeader, writer io.Writer) {
responseBodyKey := md5.Sum(s.requestBodyKey)
responseBodyIV := md5.Sum(s.requestBodyIV)
s.responseBodyKey = responseBodyKey[:]
s.responseBodyIV = responseBodyIV[:]
2016-02-26 23:05:53 +00:00
2017-07-25 20:21:59 +00:00
aesStream := crypto.NewAesEncryptionStream(s.responseBodyKey, s.responseBodyIV)
2016-02-26 23:05:53 +00:00
encryptionWriter := crypto.NewCryptionWriter(aesStream, writer)
2017-07-25 20:21:59 +00:00
s.responseWriter = encryptionWriter
2016-02-26 23:05:53 +00:00
2017-09-19 21:27:49 +00:00
common.Must2(encryptionWriter.Write([]byte{s.responseHeader, byte(header.Option)}))
2016-02-27 16:28:21 +00:00
err := MarshalCommand(header.Command, encryptionWriter)
if err != nil {
2017-09-19 21:27:49 +00:00
common.Must2(encryptionWriter.Write([]byte{0x00, 0x00}))
2016-02-27 16:28:21 +00:00
}
2016-02-27 15:41:21 +00:00
}
2017-07-25 20:21:59 +00:00
func (s *ServerSession) EncodeResponseBody(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) {
2017-07-25 20:21:59 +00:00
sizeParser = NewShakeSizeParser(s.responseBodyIV)
2017-02-14 13:16:43 +00:00
}
2016-12-07 16:32:40 +00:00
if request.Security.Is(protocol.SecurityType_NONE) {
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),
NonceGenerator: &crypto.NoOpBytesGenerator{},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-05-02 20:23:07 +00:00
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, protocol.TransferTypePacket)
2016-12-07 16:32:40 +00:00
}
2017-04-23 11:30:08 +00:00
return buf.NewWriter(writer)
}
if request.Security.Is(protocol.SecurityType_LEGACY) {
2016-12-07 16:32:40 +00:00
if request.Option.Has(protocol.RequestOptionChunkStream) {
auth := &crypto.AEADAuthenticator{
AEAD: new(FnvAuthenticator),
NonceGenerator: crypto.NoOpBytesGenerator{},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-07-25 20:21:59 +00:00
return crypto.NewAuthenticationWriter(auth, sizeParser, s.responseWriter, request.Command.TransferType())
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.NewWriter(s.responseWriter)
2017-04-23 11:30:08 +00:00
}
if request.Security.Is(protocol.SecurityType_AES128_GCM) {
2017-07-25 20:21:59 +00:00
block, _ := aes.NewCipher(s.responseBodyKey)
2016-12-07 16:32:40 +00:00
aead, _ := cipher.NewGCM(block)
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: &ChunkNonceGenerator{
2017-07-25 20:21:59 +00:00
Nonce: append([]byte(nil), s.responseBodyIV...),
2016-12-07 16:32:40 +00:00
Size: aead.NonceSize(),
},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-05-02 20:23:07 +00:00
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType())
2017-04-23 11:30:08 +00:00
}
if request.Security.Is(protocol.SecurityType_CHACHA20_POLY1305) {
2017-07-25 20:21:59 +00:00
aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(s.responseBodyKey))
2016-12-07 16:32:40 +00:00
auth := &crypto.AEADAuthenticator{
AEAD: aead,
NonceGenerator: &ChunkNonceGenerator{
2017-07-25 20:21:59 +00:00
Nonce: append([]byte(nil), s.responseBodyIV...),
2016-12-07 16:32:40 +00:00
Size: aead.NonceSize(),
},
AdditionalDataGenerator: crypto.NoOpBytesGenerator{},
}
2017-05-02 20:23:07 +00:00
return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType())
2016-12-07 16:32:40 +00:00
}
2017-04-23 11:30:08 +00:00
panic("Unknown security type.")
2016-02-26 23:05:53 +00:00
}