vmess.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. // Package vmess contains protocol definition, io lib for VMess.
  2. package protocol
  3. import (
  4. "crypto/md5"
  5. "encoding/binary"
  6. "hash/fnv"
  7. "io"
  8. "github.com/v2ray/v2ray-core/common/alloc"
  9. v2crypto "github.com/v2ray/v2ray-core/common/crypto"
  10. "github.com/v2ray/v2ray-core/common/log"
  11. v2net "github.com/v2ray/v2ray-core/common/net"
  12. proto "github.com/v2ray/v2ray-core/common/protocol"
  13. "github.com/v2ray/v2ray-core/proxy"
  14. "github.com/v2ray/v2ray-core/transport"
  15. )
  16. const (
  17. addrTypeIPv4 = byte(0x01)
  18. addrTypeIPv6 = byte(0x03)
  19. addrTypeDomain = byte(0x02)
  20. CmdTCP = byte(0x01)
  21. CmdUDP = byte(0x02)
  22. Version = byte(0x01)
  23. OptionChunk = byte(0x01)
  24. blockSize = 16
  25. )
  26. func hashTimestamp(t proto.Timestamp) []byte {
  27. once := t.Bytes()
  28. bytes := make([]byte, 0, 32)
  29. bytes = append(bytes, once...)
  30. bytes = append(bytes, once...)
  31. bytes = append(bytes, once...)
  32. bytes = append(bytes, once...)
  33. return bytes
  34. }
  35. // VMessRequest implements the request message of VMess protocol. It only contains the header of a
  36. // request message. The data part will be handled by connection handler directly, in favor of data
  37. // streaming.
  38. type VMessRequest struct {
  39. Version byte
  40. User *proto.User
  41. RequestIV []byte
  42. RequestKey []byte
  43. ResponseHeader byte
  44. Command byte
  45. Option byte
  46. Address v2net.Address
  47. Port v2net.Port
  48. }
  49. // Destination is the final destination of this request.
  50. func (this *VMessRequest) Destination() v2net.Destination {
  51. if this.Command == CmdTCP {
  52. return v2net.TCPDestination(this.Address, this.Port)
  53. } else {
  54. return v2net.UDPDestination(this.Address, this.Port)
  55. }
  56. }
  57. func (this *VMessRequest) IsChunkStream() bool {
  58. return (this.Option & OptionChunk) == OptionChunk
  59. }
  60. // VMessRequestReader is a parser to read VMessRequest from a byte stream.
  61. type VMessRequestReader struct {
  62. vUserSet proto.UserValidator
  63. }
  64. // NewVMessRequestReader creates a new VMessRequestReader with a given UserSet
  65. func NewVMessRequestReader(vUserSet proto.UserValidator) *VMessRequestReader {
  66. return &VMessRequestReader{
  67. vUserSet: vUserSet,
  68. }
  69. }
  70. // Read reads a VMessRequest from a byte stream.
  71. func (this *VMessRequestReader) Read(reader io.Reader) (*VMessRequest, error) {
  72. buffer := alloc.NewSmallBuffer()
  73. defer buffer.Release()
  74. nBytes, err := io.ReadFull(reader, buffer.Value[:proto.IDBytesLen])
  75. if err != nil {
  76. log.Debug("VMess: Failed to read request ID (", nBytes, " bytes): ", err)
  77. return nil, err
  78. }
  79. userObj, timeSec, valid := this.vUserSet.Get(buffer.Value[:nBytes])
  80. if !valid {
  81. return nil, proxy.ErrorInvalidAuthentication
  82. }
  83. timestampHash := TimestampHash()
  84. timestampHash.Write(hashTimestamp(timeSec))
  85. iv := timestampHash.Sum(nil)
  86. aesStream := v2crypto.NewAesDecryptionStream(userObj.ID.CmdKey(), iv)
  87. decryptor := v2crypto.NewCryptionReader(aesStream, reader)
  88. nBytes, err = io.ReadFull(decryptor, buffer.Value[:41])
  89. if err != nil {
  90. log.Debug("VMess: Failed to read request header (", nBytes, " bytes): ", err)
  91. return nil, err
  92. }
  93. bufferLen := nBytes
  94. request := &VMessRequest{
  95. User: userObj,
  96. Version: buffer.Value[0],
  97. }
  98. if request.Version != Version {
  99. log.Warning("VMess: Invalid protocol version ", request.Version)
  100. return nil, proxy.ErrorInvalidProtocolVersion
  101. }
  102. request.RequestIV = append([]byte(nil), buffer.Value[1:17]...) // 16 bytes
  103. request.RequestKey = append([]byte(nil), buffer.Value[17:33]...) // 16 bytes
  104. request.ResponseHeader = buffer.Value[33] // 1 byte
  105. request.Option = buffer.Value[34] // 1 byte + 2 bytes reserved
  106. request.Command = buffer.Value[37]
  107. request.Port = v2net.PortFromBytes(buffer.Value[38:40])
  108. switch buffer.Value[40] {
  109. case addrTypeIPv4:
  110. nBytes, err = io.ReadFull(decryptor, buffer.Value[41:45]) // 4 bytes
  111. bufferLen += 4
  112. if err != nil {
  113. log.Debug("VMess: Failed to read target IPv4 (", nBytes, " bytes): ", err)
  114. return nil, err
  115. }
  116. request.Address = v2net.IPAddress(buffer.Value[41:45])
  117. case addrTypeIPv6:
  118. nBytes, err = io.ReadFull(decryptor, buffer.Value[41:57]) // 16 bytes
  119. bufferLen += 16
  120. if err != nil {
  121. log.Debug("VMess: Failed to read target IPv6 (", nBytes, " bytes): ", nBytes, err)
  122. return nil, err
  123. }
  124. request.Address = v2net.IPAddress(buffer.Value[41:57])
  125. case addrTypeDomain:
  126. nBytes, err = io.ReadFull(decryptor, buffer.Value[41:42])
  127. if err != nil {
  128. log.Debug("VMess: Failed to read target domain (", nBytes, " bytes): ", nBytes, err)
  129. return nil, err
  130. }
  131. domainLength := int(buffer.Value[41])
  132. if domainLength == 0 {
  133. return nil, transport.ErrorCorruptedPacket
  134. }
  135. nBytes, err = io.ReadFull(decryptor, buffer.Value[42:42+domainLength])
  136. if err != nil {
  137. log.Debug("VMess: Failed to read target domain (", nBytes, " bytes): ", nBytes, err)
  138. return nil, err
  139. }
  140. bufferLen += 1 + domainLength
  141. domainBytes := append([]byte(nil), buffer.Value[42:42+domainLength]...)
  142. request.Address = v2net.DomainAddress(string(domainBytes))
  143. }
  144. nBytes, err = io.ReadFull(decryptor, buffer.Value[bufferLen:bufferLen+4])
  145. if err != nil {
  146. log.Debug("VMess: Failed to read checksum (", nBytes, " bytes): ", nBytes, err)
  147. return nil, err
  148. }
  149. fnv1a := fnv.New32a()
  150. fnv1a.Write(buffer.Value[:bufferLen])
  151. actualHash := fnv1a.Sum32()
  152. expectedHash := binary.BigEndian.Uint32(buffer.Value[bufferLen : bufferLen+4])
  153. if actualHash != expectedHash {
  154. return nil, transport.ErrorCorruptedPacket
  155. }
  156. return request, nil
  157. }
  158. // ToBytes returns a VMessRequest in the form of byte array.
  159. func (this *VMessRequest) ToBytes(timestampGenerator proto.TimestampGenerator, buffer *alloc.Buffer) (*alloc.Buffer, error) {
  160. if buffer == nil {
  161. buffer = alloc.NewSmallBuffer().Clear()
  162. }
  163. timestamp := timestampGenerator()
  164. idHash := IDHash(this.User.AnyValidID().Bytes())
  165. idHash.Write(timestamp.Bytes())
  166. hashStart := buffer.Len()
  167. buffer.Slice(0, hashStart+16)
  168. idHash.Sum(buffer.Value[hashStart:hashStart])
  169. encryptionBegin := buffer.Len()
  170. buffer.AppendBytes(this.Version)
  171. buffer.Append(this.RequestIV)
  172. buffer.Append(this.RequestKey)
  173. buffer.AppendBytes(this.ResponseHeader, this.Option, byte(0), byte(0))
  174. buffer.AppendBytes(this.Command)
  175. buffer.Append(this.Port.Bytes())
  176. switch {
  177. case this.Address.IsIPv4():
  178. buffer.AppendBytes(addrTypeIPv4)
  179. buffer.Append(this.Address.IP())
  180. case this.Address.IsIPv6():
  181. buffer.AppendBytes(addrTypeIPv6)
  182. buffer.Append(this.Address.IP())
  183. case this.Address.IsDomain():
  184. buffer.AppendBytes(addrTypeDomain, byte(len(this.Address.Domain())))
  185. buffer.Append([]byte(this.Address.Domain()))
  186. }
  187. encryptionEnd := buffer.Len()
  188. fnv1a := fnv.New32a()
  189. fnv1a.Write(buffer.Value[encryptionBegin:encryptionEnd])
  190. fnvHash := fnv1a.Sum32()
  191. buffer.AppendBytes(byte(fnvHash>>24), byte(fnvHash>>16), byte(fnvHash>>8), byte(fnvHash))
  192. encryptionEnd += 4
  193. timestampHash := md5.New()
  194. timestampHash.Write(hashTimestamp(timestamp))
  195. iv := timestampHash.Sum(nil)
  196. aesStream := v2crypto.NewAesEncryptionStream(this.User.ID.CmdKey(), iv)
  197. aesStream.XORKeyStream(buffer.Value[encryptionBegin:encryptionEnd], buffer.Value[encryptionBegin:encryptionEnd])
  198. return buffer, nil
  199. }