validator.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. // +build !confonly
  2. package vmess
  3. import (
  4. "crypto/hmac"
  5. "crypto/sha256"
  6. "hash/crc64"
  7. "strings"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "github.com/v2fly/v2ray-core/v4/common"
  12. "github.com/v2fly/v2ray-core/v4/common/dice"
  13. "github.com/v2fly/v2ray-core/v4/common/protocol"
  14. "github.com/v2fly/v2ray-core/v4/common/serial"
  15. "github.com/v2fly/v2ray-core/v4/common/task"
  16. "github.com/v2fly/v2ray-core/v4/proxy/vmess/aead"
  17. )
  18. const (
  19. updateInterval = 10 * time.Second
  20. cacheDurationSec = 120
  21. )
  22. type user struct {
  23. user protocol.MemoryUser
  24. lastSec protocol.Timestamp
  25. }
  26. // TimedUserValidator is a user Validator based on time.
  27. type TimedUserValidator struct {
  28. sync.RWMutex
  29. users []*user
  30. userHash map[[16]byte]indexTimePair
  31. hasher protocol.IDHash
  32. baseTime protocol.Timestamp
  33. task *task.Periodic
  34. behaviorSeed uint64
  35. behaviorFused bool
  36. aeadDecoderHolder *aead.AuthIDDecoderHolder
  37. legacyWarnShown bool
  38. }
  39. type indexTimePair struct {
  40. user *user
  41. timeInc uint32
  42. taintedFuse *uint32
  43. }
  44. // NewTimedUserValidator creates a new TimedUserValidator.
  45. func NewTimedUserValidator(hasher protocol.IDHash) *TimedUserValidator {
  46. tuv := &TimedUserValidator{
  47. users: make([]*user, 0, 16),
  48. userHash: make(map[[16]byte]indexTimePair, 1024),
  49. hasher: hasher,
  50. baseTime: protocol.Timestamp(time.Now().Unix() - cacheDurationSec*2),
  51. aeadDecoderHolder: aead.NewAuthIDDecoderHolder(),
  52. }
  53. tuv.task = &task.Periodic{
  54. Interval: updateInterval,
  55. Execute: func() error {
  56. tuv.updateUserHash()
  57. return nil
  58. },
  59. }
  60. common.Must(tuv.task.Start())
  61. return tuv
  62. }
  63. func (v *TimedUserValidator) generateNewHashes(nowSec protocol.Timestamp, user *user) {
  64. var hashValue [16]byte
  65. genEndSec := nowSec + cacheDurationSec
  66. genHashForID := func(id *protocol.ID) {
  67. idHash := v.hasher(id.Bytes())
  68. genBeginSec := user.lastSec
  69. if genBeginSec < nowSec-cacheDurationSec {
  70. genBeginSec = nowSec - cacheDurationSec
  71. }
  72. for ts := genBeginSec; ts <= genEndSec; ts++ {
  73. common.Must2(serial.WriteUint64(idHash, uint64(ts)))
  74. idHash.Sum(hashValue[:0])
  75. idHash.Reset()
  76. v.userHash[hashValue] = indexTimePair{
  77. user: user,
  78. timeInc: uint32(ts - v.baseTime),
  79. taintedFuse: new(uint32),
  80. }
  81. }
  82. }
  83. account := user.user.Account.(*MemoryAccount)
  84. genHashForID(account.ID)
  85. for _, id := range account.AlterIDs {
  86. genHashForID(id)
  87. }
  88. user.lastSec = genEndSec
  89. }
  90. func (v *TimedUserValidator) removeExpiredHashes(expire uint32) {
  91. for key, pair := range v.userHash {
  92. if pair.timeInc < expire {
  93. delete(v.userHash, key)
  94. }
  95. }
  96. }
  97. func (v *TimedUserValidator) updateUserHash() {
  98. now := time.Now()
  99. nowSec := protocol.Timestamp(now.Unix())
  100. v.Lock()
  101. defer v.Unlock()
  102. for _, user := range v.users {
  103. v.generateNewHashes(nowSec, user)
  104. }
  105. expire := protocol.Timestamp(now.Unix() - cacheDurationSec)
  106. if expire > v.baseTime {
  107. v.removeExpiredHashes(uint32(expire - v.baseTime))
  108. }
  109. }
  110. func (v *TimedUserValidator) Add(u *protocol.MemoryUser) error {
  111. v.Lock()
  112. defer v.Unlock()
  113. nowSec := time.Now().Unix()
  114. uu := &user{
  115. user: *u,
  116. lastSec: protocol.Timestamp(nowSec - cacheDurationSec),
  117. }
  118. v.users = append(v.users, uu)
  119. v.generateNewHashes(protocol.Timestamp(nowSec), uu)
  120. account := uu.user.Account.(*MemoryAccount)
  121. if !v.behaviorFused {
  122. hashkdf := hmac.New(sha256.New, []byte("VMESSBSKDF"))
  123. hashkdf.Write(account.ID.Bytes())
  124. v.behaviorSeed = crc64.Update(v.behaviorSeed, crc64.MakeTable(crc64.ECMA), hashkdf.Sum(nil))
  125. }
  126. var cmdkeyfl [16]byte
  127. copy(cmdkeyfl[:], account.ID.CmdKey())
  128. v.aeadDecoderHolder.AddUser(cmdkeyfl, u)
  129. return nil
  130. }
  131. func (v *TimedUserValidator) Get(userHash []byte) (*protocol.MemoryUser, protocol.Timestamp, bool, error) {
  132. v.RLock()
  133. defer v.RUnlock()
  134. v.behaviorFused = true
  135. var fixedSizeHash [16]byte
  136. copy(fixedSizeHash[:], userHash)
  137. pair, found := v.userHash[fixedSizeHash]
  138. if found {
  139. user := pair.user.user
  140. if atomic.LoadUint32(pair.taintedFuse) == 0 {
  141. return &user, protocol.Timestamp(pair.timeInc) + v.baseTime, true, nil
  142. }
  143. return nil, 0, false, ErrTainted
  144. }
  145. return nil, 0, false, ErrNotFound
  146. }
  147. func (v *TimedUserValidator) GetAEAD(userHash []byte) (*protocol.MemoryUser, bool, error) {
  148. v.RLock()
  149. defer v.RUnlock()
  150. var userHashFL [16]byte
  151. copy(userHashFL[:], userHash)
  152. userd, err := v.aeadDecoderHolder.Match(userHashFL)
  153. if err != nil {
  154. return nil, false, err
  155. }
  156. return userd.(*protocol.MemoryUser), true, err
  157. }
  158. func (v *TimedUserValidator) Remove(email string) bool {
  159. v.Lock()
  160. defer v.Unlock()
  161. email = strings.ToLower(email)
  162. idx := -1
  163. for i, u := range v.users {
  164. if strings.EqualFold(u.user.Email, email) {
  165. idx = i
  166. var cmdkeyfl [16]byte
  167. copy(cmdkeyfl[:], u.user.Account.(*MemoryAccount).ID.CmdKey())
  168. v.aeadDecoderHolder.RemoveUser(cmdkeyfl)
  169. break
  170. }
  171. }
  172. if idx == -1 {
  173. return false
  174. }
  175. ulen := len(v.users)
  176. v.users[idx] = v.users[ulen-1]
  177. v.users[ulen-1] = nil
  178. v.users = v.users[:ulen-1]
  179. return true
  180. }
  181. // Close implements common.Closable.
  182. func (v *TimedUserValidator) Close() error {
  183. return v.task.Close()
  184. }
  185. func (v *TimedUserValidator) GetBehaviorSeed() uint64 {
  186. v.Lock()
  187. defer v.Unlock()
  188. v.behaviorFused = true
  189. if v.behaviorSeed == 0 {
  190. v.behaviorSeed = dice.RollUint64()
  191. }
  192. return v.behaviorSeed
  193. }
  194. func (v *TimedUserValidator) BurnTaintFuse(userHash []byte) error {
  195. v.RLock()
  196. defer v.RUnlock()
  197. var userHashFL [16]byte
  198. copy(userHashFL[:], userHash)
  199. pair, found := v.userHash[userHashFL]
  200. if found {
  201. if atomic.CompareAndSwapUint32(pair.taintedFuse, 0, 1) {
  202. return nil
  203. }
  204. return ErrTainted
  205. }
  206. return ErrNotFound
  207. }
  208. /* ShouldShowLegacyWarn will return whether a Legacy Warning should be shown
  209. Not guaranteed to only return true once for every inbound, but it is okay.
  210. */
  211. func (v *TimedUserValidator) ShouldShowLegacyWarn() bool {
  212. if v.legacyWarnShown {
  213. return false
  214. }
  215. v.legacyWarnShown = true
  216. return true
  217. }
  218. var ErrNotFound = newError("Not Found")
  219. var ErrTainted = newError("ErrTainted")