server.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. package encoding
  2. import (
  3. "crypto/md5"
  4. "encoding/binary"
  5. "hash/fnv"
  6. "io"
  7. "io/ioutil"
  8. "sync"
  9. "time"
  10. "v2ray.com/core/common/dice"
  11. "golang.org/x/crypto/chacha20poly1305"
  12. "v2ray.com/core/common"
  13. "v2ray.com/core/common/bitmask"
  14. "v2ray.com/core/common/buf"
  15. "v2ray.com/core/common/crypto"
  16. "v2ray.com/core/common/net"
  17. "v2ray.com/core/common/protocol"
  18. "v2ray.com/core/common/task"
  19. "v2ray.com/core/proxy/vmess"
  20. )
  21. type sessionId struct {
  22. user [16]byte
  23. key [16]byte
  24. nonce [16]byte
  25. }
  26. // SessionHistory keeps track of historical session ids, to prevent replay attacks.
  27. type SessionHistory struct {
  28. sync.RWMutex
  29. cache map[sessionId]time.Time
  30. task *task.Periodic
  31. }
  32. // NewSessionHistory creates a new SessionHistory object.
  33. func NewSessionHistory() *SessionHistory {
  34. h := &SessionHistory{
  35. cache: make(map[sessionId]time.Time, 128),
  36. }
  37. h.task = &task.Periodic{
  38. Interval: time.Second * 30,
  39. Execute: h.removeExpiredEntries,
  40. }
  41. return h
  42. }
  43. // Close implements common.Closable.
  44. func (h *SessionHistory) Close() error {
  45. return h.task.Close()
  46. }
  47. func (h *SessionHistory) addIfNotExits(session sessionId) bool {
  48. h.Lock()
  49. if expire, found := h.cache[session]; found && expire.After(time.Now()) {
  50. h.Unlock()
  51. return false
  52. }
  53. h.cache[session] = time.Now().Add(time.Minute * 3)
  54. h.Unlock()
  55. common.Must(h.task.Start())
  56. return true
  57. }
  58. func (h *SessionHistory) removeExpiredEntries() error {
  59. now := time.Now()
  60. h.Lock()
  61. defer h.Unlock()
  62. if len(h.cache) == 0 {
  63. return newError("nothing to do")
  64. }
  65. for session, expire := range h.cache {
  66. if expire.Before(now) {
  67. delete(h.cache, session)
  68. }
  69. }
  70. if len(h.cache) == 0 {
  71. h.cache = make(map[sessionId]time.Time, 128)
  72. }
  73. return nil
  74. }
  75. // ServerSession keeps information for a session in VMess server.
  76. type ServerSession struct {
  77. userValidator *vmess.TimedUserValidator
  78. sessionHistory *SessionHistory
  79. requestBodyKey [16]byte
  80. requestBodyIV [16]byte
  81. responseBodyKey [16]byte
  82. responseBodyIV [16]byte
  83. responseWriter io.Writer
  84. responseHeader byte
  85. }
  86. // NewServerSession creates a new ServerSession, using the given UserValidator.
  87. // The ServerSession instance doesn't take ownership of the validator.
  88. func NewServerSession(validator *vmess.TimedUserValidator, sessionHistory *SessionHistory) *ServerSession {
  89. return &ServerSession{
  90. userValidator: validator,
  91. sessionHistory: sessionHistory,
  92. }
  93. }
  94. func parseSecurityType(b byte) protocol.SecurityType {
  95. if _, f := protocol.SecurityType_name[int32(b)]; f {
  96. st := protocol.SecurityType(b)
  97. // For backward compatibility.
  98. if st == protocol.SecurityType_UNKNOWN {
  99. st = protocol.SecurityType_LEGACY
  100. }
  101. return st
  102. }
  103. return protocol.SecurityType_UNKNOWN
  104. }
  105. // DecodeRequestHeader decodes and returns (if successful) a RequestHeader from an input stream.
  106. func (s *ServerSession) DecodeRequestHeader(reader io.Reader) (*protocol.RequestHeader, error) {
  107. buffer := buf.New()
  108. behaviorRand := dice.NewDeterministicDice(int64(s.userValidator.GetBehaviorSeed()))
  109. DrainSize := behaviorRand.Roll(3266) + 16 + 38 + dice.Roll(behaviorRand.Roll(64)+1)
  110. readSizeRemain := DrainSize
  111. drainConnection := func(e error) error {
  112. //We read a deterministic generated length of data before closing the connection to offset padding read pattern
  113. readSizeRemain -= int(buffer.Len())
  114. if readSizeRemain > 0 {
  115. err := s.DrainConnN(reader, readSizeRemain)
  116. if err != nil {
  117. return newError("failed to drain connection").Base(err).Base(e)
  118. }
  119. return newError("connection drained DrainSize = ", DrainSize).Base(e)
  120. }
  121. return e
  122. }
  123. defer func() {
  124. buffer.Release()
  125. }()
  126. if _, err := buffer.ReadFullFrom(reader, protocol.IDBytesLen); err != nil {
  127. return nil, newError("failed to read request header").Base(err)
  128. }
  129. user, timestamp, valid := s.userValidator.Get(buffer.Bytes())
  130. if !valid {
  131. return nil, newError("invalid user")
  132. }
  133. iv := hashTimestamp(md5.New(), timestamp)
  134. vmessAccount := user.Account.(*vmess.MemoryAccount)
  135. aesStream := crypto.NewAesDecryptionStream(vmessAccount.ID.CmdKey(), iv[:])
  136. decryptor := crypto.NewCryptionReader(aesStream, reader)
  137. readSizeRemain -= int(buffer.Len())
  138. buffer.Clear()
  139. if _, err := buffer.ReadFullFrom(decryptor, 38); err != nil {
  140. return nil, newError("failed to read request header").Base(err)
  141. }
  142. request := &protocol.RequestHeader{
  143. User: user,
  144. Version: buffer.Byte(0),
  145. }
  146. copy(s.requestBodyIV[:], buffer.BytesRange(1, 17)) // 16 bytes
  147. copy(s.requestBodyKey[:], buffer.BytesRange(17, 33)) // 16 bytes
  148. var sid sessionId
  149. copy(sid.user[:], vmessAccount.ID.Bytes())
  150. sid.key = s.requestBodyKey
  151. sid.nonce = s.requestBodyIV
  152. if !s.sessionHistory.addIfNotExits(sid) {
  153. return nil, newError("duplicated session id, possibly under replay attack")
  154. }
  155. s.responseHeader = buffer.Byte(33) // 1 byte
  156. request.Option = bitmask.Byte(buffer.Byte(34)) // 1 byte
  157. padingLen := int(buffer.Byte(35) >> 4)
  158. request.Security = parseSecurityType(buffer.Byte(35) & 0x0F)
  159. // 1 bytes reserved
  160. request.Command = protocol.RequestCommand(buffer.Byte(37))
  161. switch request.Command {
  162. case protocol.RequestCommandMux:
  163. request.Address = net.DomainAddress("v1.mux.cool")
  164. request.Port = 0
  165. case protocol.RequestCommandTCP, protocol.RequestCommandUDP:
  166. if addr, port, err := addrParser.ReadAddressPort(buffer, decryptor); err == nil {
  167. request.Address = addr
  168. request.Port = port
  169. }
  170. }
  171. if padingLen > 0 {
  172. if _, err := buffer.ReadFullFrom(decryptor, int32(padingLen)); err != nil {
  173. return nil, newError("failed to read padding").Base(err)
  174. }
  175. }
  176. if _, err := buffer.ReadFullFrom(decryptor, 4); err != nil {
  177. return nil, newError("failed to read checksum").Base(err)
  178. }
  179. fnv1a := fnv.New32a()
  180. common.Must2(fnv1a.Write(buffer.BytesTo(-4)))
  181. actualHash := fnv1a.Sum32()
  182. expectedHash := binary.BigEndian.Uint32(buffer.BytesFrom(-4))
  183. if actualHash != expectedHash {
  184. //It is possible that we are under attack described in https://github.com/v2ray/v2ray-core/issues/2523
  185. return nil, drainConnection(newError("invalid auth"))
  186. }
  187. if request.Address == nil {
  188. return nil, newError("invalid remote address")
  189. }
  190. if request.Security == protocol.SecurityType_UNKNOWN || request.Security == protocol.SecurityType_AUTO {
  191. return nil, newError("unknown security type: ", request.Security)
  192. }
  193. return request, nil
  194. }
  195. // DecodeRequestBody returns Reader from which caller can fetch decrypted body.
  196. func (s *ServerSession) DecodeRequestBody(request *protocol.RequestHeader, reader io.Reader) buf.Reader {
  197. var sizeParser crypto.ChunkSizeDecoder = crypto.PlainChunkSizeParser{}
  198. if request.Option.Has(protocol.RequestOptionChunkMasking) {
  199. sizeParser = NewShakeSizeParser(s.requestBodyIV[:])
  200. }
  201. var padding crypto.PaddingLengthGenerator
  202. if request.Option.Has(protocol.RequestOptionGlobalPadding) {
  203. padding = sizeParser.(crypto.PaddingLengthGenerator)
  204. }
  205. switch request.Security {
  206. case protocol.SecurityType_NONE:
  207. if request.Option.Has(protocol.RequestOptionChunkStream) {
  208. if request.Command.TransferType() == protocol.TransferTypeStream {
  209. return crypto.NewChunkStreamReader(sizeParser, reader)
  210. }
  211. auth := &crypto.AEADAuthenticator{
  212. AEAD: new(NoOpAuthenticator),
  213. NonceGenerator: crypto.GenerateEmptyBytes(),
  214. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  215. }
  216. return crypto.NewAuthenticationReader(auth, sizeParser, reader, protocol.TransferTypePacket, padding)
  217. }
  218. return buf.NewReader(reader)
  219. case protocol.SecurityType_LEGACY:
  220. aesStream := crypto.NewAesDecryptionStream(s.requestBodyKey[:], s.requestBodyIV[:])
  221. cryptionReader := crypto.NewCryptionReader(aesStream, reader)
  222. if request.Option.Has(protocol.RequestOptionChunkStream) {
  223. auth := &crypto.AEADAuthenticator{
  224. AEAD: new(FnvAuthenticator),
  225. NonceGenerator: crypto.GenerateEmptyBytes(),
  226. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  227. }
  228. return crypto.NewAuthenticationReader(auth, sizeParser, cryptionReader, request.Command.TransferType(), padding)
  229. }
  230. return buf.NewReader(cryptionReader)
  231. case protocol.SecurityType_AES128_GCM:
  232. aead := crypto.NewAesGcm(s.requestBodyKey[:])
  233. auth := &crypto.AEADAuthenticator{
  234. AEAD: aead,
  235. NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
  236. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  237. }
  238. return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding)
  239. case protocol.SecurityType_CHACHA20_POLY1305:
  240. aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(s.requestBodyKey[:]))
  241. auth := &crypto.AEADAuthenticator{
  242. AEAD: aead,
  243. NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
  244. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  245. }
  246. return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding)
  247. default:
  248. panic("Unknown security type.")
  249. }
  250. }
  251. // EncodeResponseHeader writes encoded response header into the given writer.
  252. func (s *ServerSession) EncodeResponseHeader(header *protocol.ResponseHeader, writer io.Writer) {
  253. s.responseBodyKey = md5.Sum(s.requestBodyKey[:])
  254. s.responseBodyIV = md5.Sum(s.requestBodyIV[:])
  255. aesStream := crypto.NewAesEncryptionStream(s.responseBodyKey[:], s.responseBodyIV[:])
  256. encryptionWriter := crypto.NewCryptionWriter(aesStream, writer)
  257. s.responseWriter = encryptionWriter
  258. common.Must2(encryptionWriter.Write([]byte{s.responseHeader, byte(header.Option)}))
  259. err := MarshalCommand(header.Command, encryptionWriter)
  260. if err != nil {
  261. common.Must2(encryptionWriter.Write([]byte{0x00, 0x00}))
  262. }
  263. }
  264. // EncodeResponseBody returns a Writer that auto-encrypt content written by caller.
  265. func (s *ServerSession) EncodeResponseBody(request *protocol.RequestHeader, writer io.Writer) buf.Writer {
  266. var sizeParser crypto.ChunkSizeEncoder = crypto.PlainChunkSizeParser{}
  267. if request.Option.Has(protocol.RequestOptionChunkMasking) {
  268. sizeParser = NewShakeSizeParser(s.responseBodyIV[:])
  269. }
  270. var padding crypto.PaddingLengthGenerator
  271. if request.Option.Has(protocol.RequestOptionGlobalPadding) {
  272. padding = sizeParser.(crypto.PaddingLengthGenerator)
  273. }
  274. switch request.Security {
  275. case protocol.SecurityType_NONE:
  276. if request.Option.Has(protocol.RequestOptionChunkStream) {
  277. if request.Command.TransferType() == protocol.TransferTypeStream {
  278. return crypto.NewChunkStreamWriter(sizeParser, writer)
  279. }
  280. auth := &crypto.AEADAuthenticator{
  281. AEAD: new(NoOpAuthenticator),
  282. NonceGenerator: crypto.GenerateEmptyBytes(),
  283. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  284. }
  285. return crypto.NewAuthenticationWriter(auth, sizeParser, writer, protocol.TransferTypePacket, padding)
  286. }
  287. return buf.NewWriter(writer)
  288. case protocol.SecurityType_LEGACY:
  289. if request.Option.Has(protocol.RequestOptionChunkStream) {
  290. auth := &crypto.AEADAuthenticator{
  291. AEAD: new(FnvAuthenticator),
  292. NonceGenerator: crypto.GenerateEmptyBytes(),
  293. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  294. }
  295. return crypto.NewAuthenticationWriter(auth, sizeParser, s.responseWriter, request.Command.TransferType(), padding)
  296. }
  297. return &buf.SequentialWriter{Writer: s.responseWriter}
  298. case protocol.SecurityType_AES128_GCM:
  299. aead := crypto.NewAesGcm(s.responseBodyKey[:])
  300. auth := &crypto.AEADAuthenticator{
  301. AEAD: aead,
  302. NonceGenerator: GenerateChunkNonce(s.responseBodyIV[:], uint32(aead.NonceSize())),
  303. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  304. }
  305. return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding)
  306. case protocol.SecurityType_CHACHA20_POLY1305:
  307. aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(s.responseBodyKey[:]))
  308. auth := &crypto.AEADAuthenticator{
  309. AEAD: aead,
  310. NonceGenerator: GenerateChunkNonce(s.responseBodyIV[:], uint32(aead.NonceSize())),
  311. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  312. }
  313. return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding)
  314. default:
  315. panic("Unknown security type.")
  316. }
  317. }
  318. func (s *ServerSession) DrainConnN(reader io.Reader, n int) error {
  319. _, err := io.CopyN(ioutil.Discard, reader, int64(n))
  320. return err
  321. }