mirror of https://github.com/v2ray/v2ray-core
Time based user hash
parent
89f9332abd
commit
097915bf7e
59
id.go
59
id.go
|
@ -1,27 +1,68 @@
|
|||
package core
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"hash"
|
||||
mrand "math/rand"
|
||||
"time"
|
||||
|
||||
"github.com/v2ray/v2ray-core/log"
|
||||
)
|
||||
|
||||
// The ID of en entity, in the form of an UUID.
|
||||
type ID [16]byte
|
||||
const (
|
||||
IDBytesLen = 16
|
||||
)
|
||||
|
||||
// Hash generates a MD5 hash based on current ID and a suffix string.
|
||||
func (v ID) Hash(suffix []byte) []byte {
|
||||
md5 := md5.New()
|
||||
md5.Write(v[:])
|
||||
md5.Write(suffix)
|
||||
return md5.Sum(nil)
|
||||
// The ID of en entity, in the form of an UUID.
|
||||
type ID struct {
|
||||
String string
|
||||
Bytes []byte
|
||||
hasher hash.Hash
|
||||
}
|
||||
|
||||
func NewID(id string) (ID, error) {
|
||||
idBytes, err := UUIDToID(id)
|
||||
if err != nil {
|
||||
return ID{}, log.Error("Failed to parse id %s", id)
|
||||
}
|
||||
hasher := hmac.New(md5.New, idBytes)
|
||||
return ID{id, idBytes, hasher}, nil
|
||||
}
|
||||
|
||||
func (v ID) TimeRangeHash(rangeSec int) []byte {
|
||||
nowSec := time.Now().UTC().Unix()
|
||||
delta := mrand.Intn(rangeSec*2) - rangeSec
|
||||
|
||||
targetSec := nowSec + int64(delta)
|
||||
return v.TimeHash(targetSec)
|
||||
}
|
||||
|
||||
func (v ID) TimeHash(timeSec int64) []byte {
|
||||
buffer := []byte{
|
||||
byte(timeSec >> 56),
|
||||
byte(timeSec >> 48),
|
||||
byte(timeSec >> 40),
|
||||
byte(timeSec >> 32),
|
||||
byte(timeSec >> 24),
|
||||
byte(timeSec >> 16),
|
||||
byte(timeSec >> 8),
|
||||
byte(timeSec),
|
||||
}
|
||||
return v.Hash(buffer)
|
||||
}
|
||||
|
||||
func (v ID) Hash(data []byte) []byte {
|
||||
return v.hasher.Sum(data)
|
||||
}
|
||||
|
||||
var byteGroups = []int{8, 4, 4, 4, 12}
|
||||
|
||||
// TODO: leverage a full functional UUID library
|
||||
func UUIDToID(uuid string) (v ID, err error) {
|
||||
func UUIDToID(uuid string) (v []byte, err error) {
|
||||
v = make([]byte, 16)
|
||||
|
||||
text := []byte(uuid)
|
||||
if len(text) < 32 {
|
||||
err = log.Error("uuid: invalid UUID string: %s", text)
|
||||
|
|
|
@ -13,5 +13,5 @@ func TestUUIDToID(t *testing.T) {
|
|||
expectedBytes := []byte{0x24, 0x18, 0xd0, 0x87, 0x64, 0x8d, 0x49, 0x90, 0x86, 0xe8, 0x19, 0xdc, 0xa1, 0xd0, 0x06, 0xd3}
|
||||
|
||||
actualBytes, _ := UUIDToID(uuid)
|
||||
assert.Bytes(actualBytes[:]).Named("UUID").Equals(expectedBytes)
|
||||
assert.Bytes(actualBytes.Bytes()).Named("UUID").Equals(expectedBytes)
|
||||
}
|
||||
|
|
|
@ -24,6 +24,8 @@ const (
|
|||
Version = byte(0x01)
|
||||
|
||||
blockSize = 16
|
||||
|
||||
CryptoMessage = "c48619fe-8f02-49e0-b9e9-edf763e17e21"
|
||||
)
|
||||
|
||||
var (
|
||||
|
@ -67,7 +69,7 @@ func (r *VMessRequestReader) Read(reader io.Reader) (*VMessRequest, error) {
|
|||
// TODO: verify version number
|
||||
request.Version = buffer[0]
|
||||
|
||||
nBytes, err = reader.Read(buffer[:len(request.UserId)])
|
||||
nBytes, err = reader.Read(buffer[:core.IDBytesLen])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -78,7 +80,7 @@ func (r *VMessRequestReader) Read(reader io.Reader) (*VMessRequest, error) {
|
|||
}
|
||||
request.UserId = *userId
|
||||
|
||||
aesCipher, err := aes.NewCipher(userId.Hash([]byte("PWD")))
|
||||
aesCipher, err := aes.NewCipher(userId.Hash([]byte(CryptoMessage)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -181,7 +183,7 @@ func NewVMessRequestWriter() *VMessRequestWriter {
|
|||
func (w *VMessRequestWriter) Write(writer io.Writer, request *VMessRequest) error {
|
||||
buffer := make([]byte, 0, 300)
|
||||
buffer = append(buffer, request.Version)
|
||||
buffer = append(buffer, request.UserId.Hash([]byte("ASK"))...)
|
||||
buffer = append(buffer, request.UserId.TimeRangeHash(30)...)
|
||||
|
||||
encryptionBegin := len(buffer)
|
||||
|
||||
|
@ -229,7 +231,7 @@ func (w *VMessRequestWriter) Write(writer io.Writer, request *VMessRequest) erro
|
|||
buffer = append(buffer, paddingBuffer...)
|
||||
encryptionEnd := len(buffer)
|
||||
|
||||
aesCipher, err := aes.NewCipher(request.UserId.Hash([]byte("PWD")))
|
||||
aesCipher, err := aes.NewCipher(request.UserId.Hash([]byte(CryptoMessage)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
|
@ -53,7 +53,7 @@ func (vconn *FreedomConnection) CloseConn(conn net.Conn, readFinish <-chan bool,
|
|||
<-writeFinish
|
||||
if tcpConn, ok := conn.(*net.TCPConn); ok {
|
||||
log.Debug("Closing freedom write.")
|
||||
tcpConn.CloseWrite();
|
||||
tcpConn.CloseWrite()
|
||||
}
|
||||
<-readFinish
|
||||
conn.Close()
|
||||
|
|
|
@ -14,7 +14,7 @@ type VMessUser struct {
|
|||
}
|
||||
|
||||
func (u *VMessUser) ToUser() (core.User, error) {
|
||||
id, err := core.UUIDToID(u.Id)
|
||||
id, err := core.NewID(u.Id)
|
||||
return core.User{id}, err
|
||||
}
|
||||
|
||||
|
|
|
@ -93,7 +93,7 @@ func (handler *VMessInboundHandler) HandleConnection(connection net.Conn) error
|
|||
<-writeFinish
|
||||
if tcpConn, ok := connection.(*net.TCPConn); ok {
|
||||
log.Debug("VMessIn closing write")
|
||||
tcpConn.CloseWrite();
|
||||
tcpConn.CloseWrite()
|
||||
}
|
||||
<-readFinish
|
||||
|
||||
|
@ -113,7 +113,6 @@ func (handler *VMessInboundHandler) dumpOutput(writer io.Writer, output <-chan [
|
|||
finish <- true
|
||||
}
|
||||
|
||||
|
||||
type VMessInboundHandlerFactory struct {
|
||||
}
|
||||
|
||||
|
|
56
userset.go
56
userset.go
|
@ -1,38 +1,70 @@
|
|||
package core
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
updateIntervalSec = 10
|
||||
cacheDurationSec = 120
|
||||
)
|
||||
|
||||
type UserSet struct {
|
||||
validUserIds []ID
|
||||
userIdsAskHash map[string]int
|
||||
userHashes map[string]int
|
||||
}
|
||||
|
||||
type hashEntry struct {
|
||||
hash string
|
||||
timeSec int64
|
||||
}
|
||||
|
||||
func NewUserSet() *UserSet {
|
||||
vuSet := new(UserSet)
|
||||
vuSet.validUserIds = make([]ID, 0, 16)
|
||||
vuSet.userIdsAskHash = make(map[string]int)
|
||||
vuSet.userHashes = make(map[string]int)
|
||||
|
||||
go vuSet.updateUserHash(time.Tick(updateIntervalSec * time.Second))
|
||||
return vuSet
|
||||
}
|
||||
|
||||
func hashBytesToString(hash []byte) string {
|
||||
return base64.StdEncoding.EncodeToString(hash)
|
||||
func (us *UserSet) updateUserHash(tick <-chan time.Time) {
|
||||
now := time.Now().UTC()
|
||||
lastSec := now.Unix() - cacheDurationSec
|
||||
|
||||
hash2Remove := make(chan hashEntry, updateIntervalSec*2)
|
||||
lastSec2Remove := now.Unix() + cacheDurationSec
|
||||
for {
|
||||
now := <-tick
|
||||
nowSec := now.UTC().Unix()
|
||||
|
||||
remove2Sec := nowSec - cacheDurationSec
|
||||
if remove2Sec > lastSec2Remove {
|
||||
for lastSec2Remove+1 < remove2Sec {
|
||||
entry := <-hash2Remove
|
||||
lastSec2Remove = entry.timeSec
|
||||
delete(us.userHashes, entry.hash)
|
||||
}
|
||||
}
|
||||
|
||||
for i := lastSec + 1; i <= nowSec; i++ {
|
||||
for idx, id := range us.validUserIds {
|
||||
idHash := id.TimeHash(i)
|
||||
hash2Remove <- hashEntry{string(idHash), i}
|
||||
us.userHashes[string(idHash)] = idx
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (us *UserSet) AddUser(user User) error {
|
||||
id := user.Id
|
||||
us.validUserIds = append(us.validUserIds, id)
|
||||
|
||||
idBase64 := hashBytesToString(id.Hash([]byte("ASK")))
|
||||
us.userIdsAskHash[idBase64] = len(us.validUserIds) - 1
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (us UserSet) IsValidUserId(askHash []byte) (*ID, bool) {
|
||||
askBase64 := hashBytesToString(askHash)
|
||||
idIndex, found := us.userIdsAskHash[askBase64]
|
||||
func (us UserSet) IsValidUserId(userHash []byte) (*ID, bool) {
|
||||
idIndex, found := us.userHashes[string(userHash)]
|
||||
if found {
|
||||
return &us.validUserIds[idIndex], true
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue