server.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. package encoding
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/sha256"
  7. "encoding/binary"
  8. "hash/fnv"
  9. "io"
  10. "sync"
  11. "time"
  12. "github.com/xtls/xray-core/common"
  13. "github.com/xtls/xray-core/common/bitmask"
  14. "github.com/xtls/xray-core/common/buf"
  15. "github.com/xtls/xray-core/common/crypto"
  16. "github.com/xtls/xray-core/common/drain"
  17. "github.com/xtls/xray-core/common/net"
  18. "github.com/xtls/xray-core/common/protocol"
  19. "github.com/xtls/xray-core/common/task"
  20. "github.com/xtls/xray-core/proxy/vmess"
  21. vmessaead "github.com/xtls/xray-core/proxy/vmess/aead"
  22. "golang.org/x/crypto/chacha20poly1305"
  23. )
  24. type sessionID struct {
  25. user [16]byte
  26. key [16]byte
  27. nonce [16]byte
  28. }
  29. // SessionHistory keeps track of historical session ids, to prevent replay attacks.
  30. type SessionHistory struct {
  31. sync.RWMutex
  32. cache map[sessionID]time.Time
  33. task *task.Periodic
  34. }
  35. // NewSessionHistory creates a new SessionHistory object.
  36. func NewSessionHistory() *SessionHistory {
  37. h := &SessionHistory{
  38. cache: make(map[sessionID]time.Time, 128),
  39. }
  40. h.task = &task.Periodic{
  41. Interval: time.Second * 30,
  42. Execute: h.removeExpiredEntries,
  43. }
  44. return h
  45. }
  46. // Close implements common.Closable.
  47. func (h *SessionHistory) Close() error {
  48. return h.task.Close()
  49. }
  50. func (h *SessionHistory) addIfNotExits(session sessionID) bool {
  51. h.Lock()
  52. if expire, found := h.cache[session]; found && expire.After(time.Now()) {
  53. h.Unlock()
  54. return false
  55. }
  56. h.cache[session] = time.Now().Add(time.Minute * 3)
  57. h.Unlock()
  58. common.Must(h.task.Start())
  59. return true
  60. }
  61. func (h *SessionHistory) removeExpiredEntries() error {
  62. now := time.Now()
  63. h.Lock()
  64. defer h.Unlock()
  65. if len(h.cache) == 0 {
  66. return newError("nothing to do")
  67. }
  68. for session, expire := range h.cache {
  69. if expire.Before(now) {
  70. delete(h.cache, session)
  71. }
  72. }
  73. if len(h.cache) == 0 {
  74. h.cache = make(map[sessionID]time.Time, 128)
  75. }
  76. return nil
  77. }
  78. // ServerSession keeps information for a session in VMess server.
  79. type ServerSession struct {
  80. userValidator *vmess.TimedUserValidator
  81. sessionHistory *SessionHistory
  82. requestBodyKey [16]byte
  83. requestBodyIV [16]byte
  84. responseBodyKey [16]byte
  85. responseBodyIV [16]byte
  86. responseWriter io.Writer
  87. responseHeader byte
  88. }
  89. // NewServerSession creates a new ServerSession, using the given UserValidator.
  90. // The ServerSession instance doesn't take ownership of the validator.
  91. func NewServerSession(validator *vmess.TimedUserValidator, sessionHistory *SessionHistory) *ServerSession {
  92. return &ServerSession{
  93. userValidator: validator,
  94. sessionHistory: sessionHistory,
  95. }
  96. }
  97. func parseSecurityType(b byte) protocol.SecurityType {
  98. if _, f := protocol.SecurityType_name[int32(b)]; f {
  99. st := protocol.SecurityType(b)
  100. // For backward compatibility.
  101. if st == protocol.SecurityType_UNKNOWN {
  102. st = protocol.SecurityType_AUTO
  103. }
  104. return st
  105. }
  106. return protocol.SecurityType_UNKNOWN
  107. }
  108. // DecodeRequestHeader decodes and returns (if successful) a RequestHeader from an input stream.
  109. func (s *ServerSession) DecodeRequestHeader(reader io.Reader, isDrain bool) (*protocol.RequestHeader, error) {
  110. buffer := buf.New()
  111. drainer, err := drain.NewBehaviorSeedLimitedDrainer(int64(s.userValidator.GetBehaviorSeed()), 16+38, 3266, 64)
  112. if err != nil {
  113. return nil, newError("failed to initialize drainer").Base(err)
  114. }
  115. drainConnection := func(e error) error {
  116. // We read a deterministic generated length of data before closing the connection to offset padding read pattern
  117. drainer.AcknowledgeReceive(int(buffer.Len()))
  118. if isDrain {
  119. return drain.WithError(drainer, reader, 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. var decryptor io.Reader
  130. var vmessAccount *vmess.MemoryAccount
  131. user, foundAEAD, errorAEAD := s.userValidator.GetAEAD(buffer.Bytes())
  132. var fixedSizeAuthID [16]byte
  133. copy(fixedSizeAuthID[:], buffer.Bytes())
  134. switch {
  135. case foundAEAD:
  136. vmessAccount = user.Account.(*vmess.MemoryAccount)
  137. var fixedSizeCmdKey [16]byte
  138. copy(fixedSizeCmdKey[:], vmessAccount.ID.CmdKey())
  139. aeadData, shouldDrain, bytesRead, errorReason := vmessaead.OpenVMessAEADHeader(fixedSizeCmdKey, fixedSizeAuthID, reader)
  140. if errorReason != nil {
  141. if shouldDrain {
  142. drainer.AcknowledgeReceive(bytesRead)
  143. return nil, drainConnection(newError("AEAD read failed").Base(errorReason))
  144. } else {
  145. return nil, drainConnection(newError("AEAD read failed, drain skipped").Base(errorReason))
  146. }
  147. }
  148. decryptor = bytes.NewReader(aeadData)
  149. default:
  150. return nil, drainConnection(newError("invalid user").Base(errorAEAD))
  151. }
  152. drainer.AcknowledgeReceive(int(buffer.Len()))
  153. buffer.Clear()
  154. if _, err := buffer.ReadFullFrom(decryptor, 38); err != nil {
  155. return nil, newError("failed to read request header").Base(err)
  156. }
  157. request := &protocol.RequestHeader{
  158. User: user,
  159. Version: buffer.Byte(0),
  160. }
  161. copy(s.requestBodyIV[:], buffer.BytesRange(1, 17)) // 16 bytes
  162. copy(s.requestBodyKey[:], buffer.BytesRange(17, 33)) // 16 bytes
  163. var sid sessionID
  164. copy(sid.user[:], vmessAccount.ID.Bytes())
  165. sid.key = s.requestBodyKey
  166. sid.nonce = s.requestBodyIV
  167. if !s.sessionHistory.addIfNotExits(sid) {
  168. return nil, newError("duplicated session id, possibly under replay attack, but this is a AEAD request")
  169. }
  170. s.responseHeader = buffer.Byte(33) // 1 byte
  171. request.Option = bitmask.Byte(buffer.Byte(34)) // 1 byte
  172. paddingLen := int(buffer.Byte(35) >> 4)
  173. request.Security = parseSecurityType(buffer.Byte(35) & 0x0F)
  174. // 1 bytes reserved
  175. request.Command = protocol.RequestCommand(buffer.Byte(37))
  176. switch request.Command {
  177. case protocol.RequestCommandMux:
  178. request.Address = net.DomainAddress("v1.mux.cool")
  179. request.Port = 0
  180. case protocol.RequestCommandTCP, protocol.RequestCommandUDP:
  181. if addr, port, err := addrParser.ReadAddressPort(buffer, decryptor); err == nil {
  182. request.Address = addr
  183. request.Port = port
  184. }
  185. }
  186. if paddingLen > 0 {
  187. if _, err := buffer.ReadFullFrom(decryptor, int32(paddingLen)); err != nil {
  188. return nil, newError("failed to read padding").Base(err)
  189. }
  190. }
  191. if _, err := buffer.ReadFullFrom(decryptor, 4); err != nil {
  192. return nil, newError("failed to read checksum").Base(err)
  193. }
  194. fnv1a := fnv.New32a()
  195. common.Must2(fnv1a.Write(buffer.BytesTo(-4)))
  196. actualHash := fnv1a.Sum32()
  197. expectedHash := binary.BigEndian.Uint32(buffer.BytesFrom(-4))
  198. if actualHash != expectedHash {
  199. return nil, newError("invalid auth, but this is a AEAD request")
  200. }
  201. if request.Address == nil {
  202. return nil, newError("invalid remote address")
  203. }
  204. if request.Security == protocol.SecurityType_UNKNOWN || request.Security == protocol.SecurityType_AUTO {
  205. return nil, newError("unknown security type: ", request.Security)
  206. }
  207. return request, nil
  208. }
  209. // DecodeRequestBody returns Reader from which caller can fetch decrypted body.
  210. func (s *ServerSession) DecodeRequestBody(request *protocol.RequestHeader, reader io.Reader) (buf.Reader, error) {
  211. var sizeParser crypto.ChunkSizeDecoder = crypto.PlainChunkSizeParser{}
  212. if request.Option.Has(protocol.RequestOptionChunkMasking) {
  213. sizeParser = NewShakeSizeParser(s.requestBodyIV[:])
  214. }
  215. var padding crypto.PaddingLengthGenerator
  216. if request.Option.Has(protocol.RequestOptionGlobalPadding) {
  217. var ok bool
  218. padding, ok = sizeParser.(crypto.PaddingLengthGenerator)
  219. if !ok {
  220. return nil, newError("invalid option: RequestOptionGlobalPadding")
  221. }
  222. }
  223. switch request.Security {
  224. case protocol.SecurityType_NONE:
  225. if request.Option.Has(protocol.RequestOptionChunkStream) {
  226. if request.Command.TransferType() == protocol.TransferTypeStream {
  227. return crypto.NewChunkStreamReader(sizeParser, reader), nil
  228. }
  229. auth := &crypto.AEADAuthenticator{
  230. AEAD: new(NoOpAuthenticator),
  231. NonceGenerator: crypto.GenerateEmptyBytes(),
  232. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  233. }
  234. return crypto.NewAuthenticationReader(auth, sizeParser, reader, protocol.TransferTypePacket, padding), nil
  235. }
  236. return buf.NewReader(reader), nil
  237. case protocol.SecurityType_AES128_GCM:
  238. aead := crypto.NewAesGcm(s.requestBodyKey[:])
  239. auth := &crypto.AEADAuthenticator{
  240. AEAD: aead,
  241. NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
  242. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  243. }
  244. if request.Option.Has(protocol.RequestOptionAuthenticatedLength) {
  245. AuthenticatedLengthKey := vmessaead.KDF16(s.requestBodyKey[:], "auth_len")
  246. AuthenticatedLengthKeyAEAD := crypto.NewAesGcm(AuthenticatedLengthKey)
  247. lengthAuth := &crypto.AEADAuthenticator{
  248. AEAD: AuthenticatedLengthKeyAEAD,
  249. NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
  250. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  251. }
  252. sizeParser = NewAEADSizeParser(lengthAuth)
  253. }
  254. return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding), nil
  255. case protocol.SecurityType_CHACHA20_POLY1305:
  256. aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(s.requestBodyKey[:]))
  257. auth := &crypto.AEADAuthenticator{
  258. AEAD: aead,
  259. NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
  260. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  261. }
  262. if request.Option.Has(protocol.RequestOptionAuthenticatedLength) {
  263. AuthenticatedLengthKey := vmessaead.KDF16(s.requestBodyKey[:], "auth_len")
  264. AuthenticatedLengthKeyAEAD, err := chacha20poly1305.New(GenerateChacha20Poly1305Key(AuthenticatedLengthKey))
  265. common.Must(err)
  266. lengthAuth := &crypto.AEADAuthenticator{
  267. AEAD: AuthenticatedLengthKeyAEAD,
  268. NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
  269. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  270. }
  271. sizeParser = NewAEADSizeParser(lengthAuth)
  272. }
  273. return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding), nil
  274. default:
  275. return nil, newError("invalid option: Security")
  276. }
  277. }
  278. // EncodeResponseHeader writes encoded response header into the given writer.
  279. func (s *ServerSession) EncodeResponseHeader(header *protocol.ResponseHeader, writer io.Writer) {
  280. var encryptionWriter io.Writer
  281. BodyKey := sha256.Sum256(s.requestBodyKey[:])
  282. copy(s.responseBodyKey[:], BodyKey[:16])
  283. BodyIV := sha256.Sum256(s.requestBodyIV[:])
  284. copy(s.responseBodyIV[:], BodyIV[:16])
  285. aesStream := crypto.NewAesEncryptionStream(s.responseBodyKey[:], s.responseBodyIV[:])
  286. encryptionWriter = crypto.NewCryptionWriter(aesStream, writer)
  287. s.responseWriter = encryptionWriter
  288. aeadEncryptedHeaderBuffer := bytes.NewBuffer(nil)
  289. encryptionWriter = aeadEncryptedHeaderBuffer
  290. common.Must2(encryptionWriter.Write([]byte{s.responseHeader, byte(header.Option)}))
  291. err := MarshalCommand(header.Command, encryptionWriter)
  292. if err != nil {
  293. common.Must2(encryptionWriter.Write([]byte{0x00, 0x00}))
  294. }
  295. aeadResponseHeaderLengthEncryptionKey := vmessaead.KDF16(s.responseBodyKey[:], vmessaead.KDFSaltConstAEADRespHeaderLenKey)
  296. aeadResponseHeaderLengthEncryptionIV := vmessaead.KDF(s.responseBodyIV[:], vmessaead.KDFSaltConstAEADRespHeaderLenIV)[:12]
  297. aeadResponseHeaderLengthEncryptionKeyAESBlock := common.Must2(aes.NewCipher(aeadResponseHeaderLengthEncryptionKey)).(cipher.Block)
  298. aeadResponseHeaderLengthEncryptionAEAD := common.Must2(cipher.NewGCM(aeadResponseHeaderLengthEncryptionKeyAESBlock)).(cipher.AEAD)
  299. aeadResponseHeaderLengthEncryptionBuffer := bytes.NewBuffer(nil)
  300. decryptedResponseHeaderLengthBinaryDeserializeBuffer := uint16(aeadEncryptedHeaderBuffer.Len())
  301. common.Must(binary.Write(aeadResponseHeaderLengthEncryptionBuffer, binary.BigEndian, decryptedResponseHeaderLengthBinaryDeserializeBuffer))
  302. AEADEncryptedLength := aeadResponseHeaderLengthEncryptionAEAD.Seal(nil, aeadResponseHeaderLengthEncryptionIV, aeadResponseHeaderLengthEncryptionBuffer.Bytes(), nil)
  303. common.Must2(io.Copy(writer, bytes.NewReader(AEADEncryptedLength)))
  304. aeadResponseHeaderPayloadEncryptionKey := vmessaead.KDF16(s.responseBodyKey[:], vmessaead.KDFSaltConstAEADRespHeaderPayloadKey)
  305. aeadResponseHeaderPayloadEncryptionIV := vmessaead.KDF(s.responseBodyIV[:], vmessaead.KDFSaltConstAEADRespHeaderPayloadIV)[:12]
  306. aeadResponseHeaderPayloadEncryptionKeyAESBlock := common.Must2(aes.NewCipher(aeadResponseHeaderPayloadEncryptionKey)).(cipher.Block)
  307. aeadResponseHeaderPayloadEncryptionAEAD := common.Must2(cipher.NewGCM(aeadResponseHeaderPayloadEncryptionKeyAESBlock)).(cipher.AEAD)
  308. aeadEncryptedHeaderPayload := aeadResponseHeaderPayloadEncryptionAEAD.Seal(nil, aeadResponseHeaderPayloadEncryptionIV, aeadEncryptedHeaderBuffer.Bytes(), nil)
  309. common.Must2(io.Copy(writer, bytes.NewReader(aeadEncryptedHeaderPayload)))
  310. }
  311. // EncodeResponseBody returns a Writer that auto-encrypt content written by caller.
  312. func (s *ServerSession) EncodeResponseBody(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
  313. var sizeParser crypto.ChunkSizeEncoder = crypto.PlainChunkSizeParser{}
  314. if request.Option.Has(protocol.RequestOptionChunkMasking) {
  315. sizeParser = NewShakeSizeParser(s.responseBodyIV[:])
  316. }
  317. var padding crypto.PaddingLengthGenerator
  318. if request.Option.Has(protocol.RequestOptionGlobalPadding) {
  319. var ok bool
  320. padding, ok = sizeParser.(crypto.PaddingLengthGenerator)
  321. if !ok {
  322. return nil, newError("invalid option: RequestOptionGlobalPadding")
  323. }
  324. }
  325. switch request.Security {
  326. case protocol.SecurityType_NONE:
  327. if request.Option.Has(protocol.RequestOptionChunkStream) {
  328. if request.Command.TransferType() == protocol.TransferTypeStream {
  329. return crypto.NewChunkStreamWriter(sizeParser, writer), nil
  330. }
  331. auth := &crypto.AEADAuthenticator{
  332. AEAD: new(NoOpAuthenticator),
  333. NonceGenerator: crypto.GenerateEmptyBytes(),
  334. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  335. }
  336. return crypto.NewAuthenticationWriter(auth, sizeParser, writer, protocol.TransferTypePacket, padding), nil
  337. }
  338. return buf.NewWriter(writer), nil
  339. case protocol.SecurityType_AES128_GCM:
  340. aead := crypto.NewAesGcm(s.responseBodyKey[:])
  341. auth := &crypto.AEADAuthenticator{
  342. AEAD: aead,
  343. NonceGenerator: GenerateChunkNonce(s.responseBodyIV[:], uint32(aead.NonceSize())),
  344. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  345. }
  346. if request.Option.Has(protocol.RequestOptionAuthenticatedLength) {
  347. AuthenticatedLengthKey := vmessaead.KDF16(s.requestBodyKey[:], "auth_len")
  348. AuthenticatedLengthKeyAEAD := crypto.NewAesGcm(AuthenticatedLengthKey)
  349. lengthAuth := &crypto.AEADAuthenticator{
  350. AEAD: AuthenticatedLengthKeyAEAD,
  351. NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
  352. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  353. }
  354. sizeParser = NewAEADSizeParser(lengthAuth)
  355. }
  356. return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding), nil
  357. case protocol.SecurityType_CHACHA20_POLY1305:
  358. aead, _ := chacha20poly1305.New(GenerateChacha20Poly1305Key(s.responseBodyKey[:]))
  359. auth := &crypto.AEADAuthenticator{
  360. AEAD: aead,
  361. NonceGenerator: GenerateChunkNonce(s.responseBodyIV[:], uint32(aead.NonceSize())),
  362. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  363. }
  364. if request.Option.Has(protocol.RequestOptionAuthenticatedLength) {
  365. AuthenticatedLengthKey := vmessaead.KDF16(s.requestBodyKey[:], "auth_len")
  366. AuthenticatedLengthKeyAEAD, err := chacha20poly1305.New(GenerateChacha20Poly1305Key(AuthenticatedLengthKey))
  367. common.Must(err)
  368. lengthAuth := &crypto.AEADAuthenticator{
  369. AEAD: AuthenticatedLengthKeyAEAD,
  370. NonceGenerator: GenerateChunkNonce(s.requestBodyIV[:], uint32(aead.NonceSize())),
  371. AdditionalDataGenerator: crypto.GenerateEmptyBytes(),
  372. }
  373. sizeParser = NewAEADSizeParser(lengthAuth)
  374. }
  375. return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding), nil
  376. default:
  377. return nil, newError("invalid option: Security")
  378. }
  379. }