server.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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(387) + 16 + 38
  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. //It is possible that we are under attack described in https://github.com/v2ray/v2ray-core/issues/2523
  132. return nil, drainConnection(newError("invalid user"))
  133. }
  134. iv := hashTimestamp(md5.New(), timestamp)
  135. vmessAccount := user.Account.(*vmess.MemoryAccount)
  136. aesStream := crypto.NewAesDecryptionStream(vmessAccount.ID.CmdKey(), iv[:])
  137. decryptor := crypto.NewCryptionReader(aesStream, reader)
  138. readSizeRemain -= int(buffer.Len())
  139. buffer.Clear()
  140. if _, err := buffer.ReadFullFrom(decryptor, 38); err != nil {
  141. return nil, newError("failed to read request header").Base(err)
  142. }
  143. request := &protocol.RequestHeader{
  144. User: user,
  145. Version: buffer.Byte(0),
  146. }
  147. copy(s.requestBodyIV[:], buffer.BytesRange(1, 17)) // 16 bytes
  148. copy(s.requestBodyKey[:], buffer.BytesRange(17, 33)) // 16 bytes
  149. var sid sessionId
  150. copy(sid.user[:], vmessAccount.ID.Bytes())
  151. sid.key = s.requestBodyKey
  152. sid.nonce = s.requestBodyIV
  153. if !s.sessionHistory.addIfNotExits(sid) {
  154. return nil, newError("duplicated session id, possibly under replay attack")
  155. }
  156. s.responseHeader = buffer.Byte(33) // 1 byte
  157. request.Option = bitmask.Byte(buffer.Byte(34)) // 1 byte
  158. padingLen := int(buffer.Byte(35) >> 4)
  159. request.Security = parseSecurityType(buffer.Byte(35) & 0x0F)
  160. // 1 bytes reserved
  161. request.Command = protocol.RequestCommand(buffer.Byte(37))
  162. switch request.Command {
  163. case protocol.RequestCommandMux:
  164. request.Address = net.DomainAddress("v1.mux.cool")
  165. request.Port = 0
  166. case protocol.RequestCommandTCP, protocol.RequestCommandUDP:
  167. if addr, port, err := addrParser.ReadAddressPort(buffer, decryptor); err == nil {
  168. request.Address = addr
  169. request.Port = port
  170. }
  171. }
  172. if padingLen > 0 {
  173. if _, err := buffer.ReadFullFrom(decryptor, int32(padingLen)); err != nil {
  174. return nil, newError("failed to read padding").Base(err)
  175. }
  176. }
  177. if _, err := buffer.ReadFullFrom(decryptor, 4); err != nil {
  178. return nil, newError("failed to read checksum").Base(err)
  179. }
  180. fnv1a := fnv.New32a()
  181. common.Must2(fnv1a.Write(buffer.BytesTo(-4)))
  182. actualHash := fnv1a.Sum32()
  183. expectedHash := binary.BigEndian.Uint32(buffer.BytesFrom(-4))
  184. if actualHash != expectedHash {
  185. //It is possible that we are under attack described in https://github.com/v2ray/v2ray-core/issues/2523
  186. return nil, drainConnection(newError("invalid auth"))
  187. }
  188. if request.Address == nil {
  189. return nil, newError("invalid remote address")
  190. }
  191. if request.Security == protocol.SecurityType_UNKNOWN || request.Security == protocol.SecurityType_AUTO {
  192. return nil, newError("unknown security type: ", request.Security)
  193. }
  194. return request, nil
  195. }
  196. // DecodeRequestBody returns Reader from which caller can fetch decrypted body.
  197. func (s *ServerSession) DecodeRequestBody(request *protocol.RequestHeader, reader io.Reader) buf.Reader {
  198. var sizeParser crypto.ChunkSizeDecoder = crypto.PlainChunkSizeParser{}
  199. if request.Option.Has(protocol.RequestOptionChunkMasking) {
  200. sizeParser = NewShakeSizeParser(s.requestBodyIV[:])
  201. }
  202. var padding crypto.PaddingLengthGenerator
  203. if request.Option.Has(protocol.RequestOptionGlobalPadding) {
  204. padding = sizeParser.(crypto.PaddingLengthGenerator)
  205. }
  206. switch request.Security {
  207. case protocol.SecurityType_NONE:
  208. if request.Option.Has(protocol.RequestOptionChunkStream) {
  209. if request.Command.TransferType() == protocol.TransferTypeStream {
  210. return crypto.NewChunkStreamReader(sizeParser, reader)
  211. }
  212. auth := &crypto.AEADAuthenticator{
  213. AEAD: new(NoOpAuthenticator),
  214. NonceGenerator: crypto.GenerateEmptyBytes(),
  215. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  216. }
  217. return crypto.NewAuthenticationReader(auth, sizeParser, reader, protocol.TransferTypePacket, padding)
  218. }
  219. return buf.NewReader(reader)
  220. case protocol.SecurityType_LEGACY:
  221. aesStream := crypto.NewAesDecryptionStream(s.requestBodyKey[:], s.requestBodyIV[:])
  222. cryptionReader := crypto.NewCryptionReader(aesStream, reader)
  223. if request.Option.Has(protocol.RequestOptionChunkStream) {
  224. auth := &crypto.AEADAuthenticator{
  225. AEAD: new(FnvAuthenticator),
  226. NonceGenerator: crypto.GenerateEmptyBytes(),
  227. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  228. }
  229. return crypto.NewAuthenticationReader(auth, sizeParser, cryptionReader, request.Command.TransferType(), padding)
  230. }
  231. return buf.NewReader(cryptionReader)
  232. case protocol.SecurityType_AES128_GCM:
  233. aead := crypto.NewAesGcm(s.requestBodyKey[:])
  234. auth := &crypto.AEADAuthenticator{
  235. AEAD: aead,
  236. NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
  237. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  238. }
  239. return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding)
  240. case protocol.SecurityType_CHACHA20_POLY1305:
  241. aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(s.requestBodyKey[:]))
  242. auth := &crypto.AEADAuthenticator{
  243. AEAD: aead,
  244. NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
  245. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  246. }
  247. return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding)
  248. default:
  249. panic("Unknown security type.")
  250. }
  251. }
  252. // EncodeResponseHeader writes encoded response header into the given writer.
  253. func (s *ServerSession) EncodeResponseHeader(header *protocol.ResponseHeader, writer io.Writer) {
  254. s.responseBodyKey = md5.Sum(s.requestBodyKey[:])
  255. s.responseBodyIV = md5.Sum(s.requestBodyIV[:])
  256. aesStream := crypto.NewAesEncryptionStream(s.responseBodyKey[:], s.responseBodyIV[:])
  257. encryptionWriter := crypto.NewCryptionWriter(aesStream, writer)
  258. s.responseWriter = encryptionWriter
  259. common.Must2(encryptionWriter.Write([]byte{s.responseHeader, byte(header.Option)}))
  260. err := MarshalCommand(header.Command, encryptionWriter)
  261. if err != nil {
  262. common.Must2(encryptionWriter.Write([]byte{0x00, 0x00}))
  263. }
  264. }
  265. // EncodeResponseBody returns a Writer that auto-encrypt content written by caller.
  266. func (s *ServerSession) EncodeResponseBody(request *protocol.RequestHeader, writer io.Writer) buf.Writer {
  267. var sizeParser crypto.ChunkSizeEncoder = crypto.PlainChunkSizeParser{}
  268. if request.Option.Has(protocol.RequestOptionChunkMasking) {
  269. sizeParser = NewShakeSizeParser(s.responseBodyIV[:])
  270. }
  271. var padding crypto.PaddingLengthGenerator
  272. if request.Option.Has(protocol.RequestOptionGlobalPadding) {
  273. padding = sizeParser.(crypto.PaddingLengthGenerator)
  274. }
  275. switch request.Security {
  276. case protocol.SecurityType_NONE:
  277. if request.Option.Has(protocol.RequestOptionChunkStream) {
  278. if request.Command.TransferType() == protocol.TransferTypeStream {
  279. return crypto.NewChunkStreamWriter(sizeParser, writer)
  280. }
  281. auth := &crypto.AEADAuthenticator{
  282. AEAD: new(NoOpAuthenticator),
  283. NonceGenerator: crypto.GenerateEmptyBytes(),
  284. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  285. }
  286. return crypto.NewAuthenticationWriter(auth, sizeParser, writer, protocol.TransferTypePacket, padding)
  287. }
  288. return buf.NewWriter(writer)
  289. case protocol.SecurityType_LEGACY:
  290. if request.Option.Has(protocol.RequestOptionChunkStream) {
  291. auth := &crypto.AEADAuthenticator{
  292. AEAD: new(FnvAuthenticator),
  293. NonceGenerator: crypto.GenerateEmptyBytes(),
  294. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  295. }
  296. return crypto.NewAuthenticationWriter(auth, sizeParser, s.responseWriter, request.Command.TransferType(), padding)
  297. }
  298. return &buf.SequentialWriter{Writer: s.responseWriter}
  299. case protocol.SecurityType_AES128_GCM:
  300. aead := crypto.NewAesGcm(s.responseBodyKey[:])
  301. auth := &crypto.AEADAuthenticator{
  302. AEAD: aead,
  303. NonceGenerator: GenerateChunkNonce(s.responseBodyIV[:], uint32(aead.NonceSize())),
  304. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  305. }
  306. return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding)
  307. case protocol.SecurityType_CHACHA20_POLY1305:
  308. aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(s.responseBodyKey[:]))
  309. auth := &crypto.AEADAuthenticator{
  310. AEAD: aead,
  311. NonceGenerator: GenerateChunkNonce(s.responseBodyIV[:], uint32(aead.NonceSize())),
  312. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  313. }
  314. return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding)
  315. default:
  316. panic("Unknown security type.")
  317. }
  318. }
  319. func (s *ServerSession) DrainConnN(reader io.Reader, n int) error {
  320. _, err := io.CopyN(ioutil.Discard, reader, int64(n))
  321. return err
  322. }