vmess.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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, err := v2crypto.NewAesDecryptionStream(userObj.ID.CmdKey(), iv)
  87. if err != nil {
  88. log.Debug("VMess: Failed to create AES stream: ", err)
  89. return nil, err
  90. }
  91. decryptor := v2crypto.NewCryptionReader(aesStream, reader)
  92. nBytes, err = io.ReadFull(decryptor, buffer.Value[:41])
  93. if err != nil {
  94. log.Debug("VMess: Failed to read request header (", nBytes, " bytes): ", err)
  95. return nil, err
  96. }
  97. bufferLen := nBytes
  98. request := &VMessRequest{
  99. User: userObj,
  100. Version: buffer.Value[0],
  101. }
  102. if request.Version != Version {
  103. log.Warning("VMess: Invalid protocol version ", request.Version)
  104. return nil, proxy.ErrorInvalidProtocolVersion
  105. }
  106. request.RequestIV = append([]byte(nil), buffer.Value[1:17]...) // 16 bytes
  107. request.RequestKey = append([]byte(nil), buffer.Value[17:33]...) // 16 bytes
  108. request.ResponseHeader = buffer.Value[33] // 1 byte
  109. request.Option = buffer.Value[34] // 1 byte + 2 bytes reserved
  110. request.Command = buffer.Value[37]
  111. request.Port = v2net.PortFromBytes(buffer.Value[38:40])
  112. switch buffer.Value[40] {
  113. case addrTypeIPv4:
  114. nBytes, err = io.ReadFull(decryptor, buffer.Value[41:45]) // 4 bytes
  115. bufferLen += 4
  116. if err != nil {
  117. log.Debug("VMess: Failed to read target IPv4 (", nBytes, " bytes): ", err)
  118. return nil, err
  119. }
  120. request.Address = v2net.IPAddress(buffer.Value[41:45])
  121. case addrTypeIPv6:
  122. nBytes, err = io.ReadFull(decryptor, buffer.Value[41:57]) // 16 bytes
  123. bufferLen += 16
  124. if err != nil {
  125. log.Debug("VMess: Failed to read target IPv6 (", nBytes, " bytes): ", nBytes, err)
  126. return nil, err
  127. }
  128. request.Address = v2net.IPAddress(buffer.Value[41:57])
  129. case addrTypeDomain:
  130. nBytes, err = io.ReadFull(decryptor, buffer.Value[41:42])
  131. if err != nil {
  132. log.Debug("VMess: Failed to read target domain (", nBytes, " bytes): ", nBytes, err)
  133. return nil, err
  134. }
  135. domainLength := int(buffer.Value[41])
  136. if domainLength == 0 {
  137. return nil, transport.ErrorCorruptedPacket
  138. }
  139. nBytes, err = io.ReadFull(decryptor, buffer.Value[42:42+domainLength])
  140. if err != nil {
  141. log.Debug("VMess: Failed to read target domain (", nBytes, " bytes): ", nBytes, err)
  142. return nil, err
  143. }
  144. bufferLen += 1 + domainLength
  145. domainBytes := append([]byte(nil), buffer.Value[42:42+domainLength]...)
  146. request.Address = v2net.DomainAddress(string(domainBytes))
  147. }
  148. nBytes, err = io.ReadFull(decryptor, buffer.Value[bufferLen:bufferLen+4])
  149. if err != nil {
  150. log.Debug("VMess: Failed to read checksum (", nBytes, " bytes): ", nBytes, err)
  151. return nil, err
  152. }
  153. fnv1a := fnv.New32a()
  154. fnv1a.Write(buffer.Value[:bufferLen])
  155. actualHash := fnv1a.Sum32()
  156. expectedHash := binary.BigEndian.Uint32(buffer.Value[bufferLen : bufferLen+4])
  157. if actualHash != expectedHash {
  158. return nil, transport.ErrorCorruptedPacket
  159. }
  160. return request, nil
  161. }
  162. // ToBytes returns a VMessRequest in the form of byte array.
  163. func (this *VMessRequest) ToBytes(timestampGenerator proto.TimestampGenerator, buffer *alloc.Buffer) (*alloc.Buffer, error) {
  164. if buffer == nil {
  165. buffer = alloc.NewSmallBuffer().Clear()
  166. }
  167. timestamp := timestampGenerator()
  168. idHash := IDHash(this.User.AnyValidID().Bytes())
  169. idHash.Write(timestamp.Bytes())
  170. hashStart := buffer.Len()
  171. buffer.Slice(0, hashStart+16)
  172. idHash.Sum(buffer.Value[hashStart:hashStart])
  173. encryptionBegin := buffer.Len()
  174. buffer.AppendBytes(this.Version)
  175. buffer.Append(this.RequestIV)
  176. buffer.Append(this.RequestKey)
  177. buffer.AppendBytes(this.ResponseHeader, this.Option, byte(0), byte(0))
  178. buffer.AppendBytes(this.Command)
  179. buffer.Append(this.Port.Bytes())
  180. switch {
  181. case this.Address.IsIPv4():
  182. buffer.AppendBytes(addrTypeIPv4)
  183. buffer.Append(this.Address.IP())
  184. case this.Address.IsIPv6():
  185. buffer.AppendBytes(addrTypeIPv6)
  186. buffer.Append(this.Address.IP())
  187. case this.Address.IsDomain():
  188. buffer.AppendBytes(addrTypeDomain, byte(len(this.Address.Domain())))
  189. buffer.Append([]byte(this.Address.Domain()))
  190. }
  191. encryptionEnd := buffer.Len()
  192. fnv1a := fnv.New32a()
  193. fnv1a.Write(buffer.Value[encryptionBegin:encryptionEnd])
  194. fnvHash := fnv1a.Sum32()
  195. buffer.AppendBytes(byte(fnvHash>>24), byte(fnvHash>>16), byte(fnvHash>>8), byte(fnvHash))
  196. encryptionEnd += 4
  197. timestampHash := md5.New()
  198. timestampHash.Write(hashTimestamp(timestamp))
  199. iv := timestampHash.Sum(nil)
  200. aesStream, err := v2crypto.NewAesEncryptionStream(this.User.ID.CmdKey(), iv)
  201. if err != nil {
  202. return nil, err
  203. }
  204. aesStream.XORKeyStream(buffer.Value[encryptionBegin:encryptionEnd], buffer.Value[encryptionBegin:encryptionEnd])
  205. return buffer, nil
  206. }