2018-04-05 22:05:28 +02:00
|
|
|
package dht
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/sha256"
|
|
|
|
"net"
|
|
|
|
"strconv"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2021-10-06 20:00:59 +02:00
|
|
|
"github.com/lbryio/lbry.go/v3/dht/bits"
|
|
|
|
"github.com/lbryio/lbry.go/v3/extras/stop"
|
2018-04-05 22:05:28 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type tokenManager struct {
|
|
|
|
secret []byte
|
|
|
|
prevSecret []byte
|
|
|
|
lock *sync.RWMutex
|
2018-06-25 22:49:40 +02:00
|
|
|
stop *stop.Group
|
2018-04-05 22:05:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (tm *tokenManager) Start(interval time.Duration) {
|
|
|
|
tm.secret = make([]byte, 64)
|
|
|
|
tm.prevSecret = make([]byte, 64)
|
|
|
|
tm.lock = &sync.RWMutex{}
|
2018-06-25 22:49:40 +02:00
|
|
|
tm.stop = stop.New()
|
2018-04-05 22:05:28 +02:00
|
|
|
|
|
|
|
tm.rotateSecret()
|
|
|
|
|
2018-05-24 23:49:43 +02:00
|
|
|
tm.stop.Add(1)
|
2018-04-05 22:05:28 +02:00
|
|
|
go func() {
|
2018-05-24 23:49:43 +02:00
|
|
|
defer tm.stop.Done()
|
2018-04-05 22:05:28 +02:00
|
|
|
tick := time.NewTicker(interval)
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-tick.C:
|
|
|
|
tm.rotateSecret()
|
2018-05-24 23:49:43 +02:00
|
|
|
case <-tm.stop.Ch():
|
2018-04-05 22:05:28 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (tm *tokenManager) Stop() {
|
2018-05-24 23:49:43 +02:00
|
|
|
tm.stop.StopAndWait()
|
2018-04-05 22:05:28 +02:00
|
|
|
}
|
|
|
|
|
2018-06-14 17:48:02 +02:00
|
|
|
func (tm *tokenManager) Get(nodeID bits.Bitmap, addr *net.UDPAddr) string {
|
2018-04-05 22:05:28 +02:00
|
|
|
return genToken(tm.secret, nodeID, addr)
|
|
|
|
}
|
|
|
|
|
2018-06-14 17:48:02 +02:00
|
|
|
func (tm *tokenManager) Verify(token string, nodeID bits.Bitmap, addr *net.UDPAddr) bool {
|
2018-04-05 22:05:28 +02:00
|
|
|
return token == genToken(tm.secret, nodeID, addr) || token == genToken(tm.prevSecret, nodeID, addr)
|
|
|
|
}
|
|
|
|
|
2018-06-14 17:48:02 +02:00
|
|
|
func genToken(secret []byte, nodeID bits.Bitmap, addr *net.UDPAddr) string {
|
2018-04-05 22:05:28 +02:00
|
|
|
buf := bytes.Buffer{}
|
|
|
|
buf.Write(nodeID[:])
|
|
|
|
buf.Write(addr.IP)
|
|
|
|
buf.WriteString(strconv.Itoa(addr.Port))
|
|
|
|
buf.Write(secret)
|
|
|
|
t := sha256.Sum256(buf.Bytes())
|
|
|
|
return string(t[:])
|
|
|
|
}
|
|
|
|
|
|
|
|
func (tm *tokenManager) rotateSecret() {
|
|
|
|
tm.lock.Lock()
|
|
|
|
defer tm.lock.Unlock()
|
|
|
|
|
|
|
|
copy(tm.prevSecret, tm.secret)
|
|
|
|
|
|
|
|
_, err := rand.Read(tm.secret)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|