server.go 12 KB

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