113 lines
2.2 KiB
Go
113 lines
2.2 KiB
Go
package server
|
|
|
|
import (
|
|
"git.gitfish.de/ston1th/haproxy-lb/pkg/config"
|
|
"golang.org/x/crypto/bcrypt"
|
|
weakrand "math/rand"
|
|
"net/http"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
var cacheSize = 100
|
|
|
|
func init() {
|
|
weakrand.Seed(time.Now().UnixNano())
|
|
}
|
|
|
|
type cache struct {
|
|
cache map[string]bool
|
|
mtx sync.Mutex
|
|
}
|
|
|
|
func newCache() *cache {
|
|
return &cache{
|
|
cache: make(map[string]bool),
|
|
}
|
|
}
|
|
|
|
func (c *cache) get(key string) (bool, bool) {
|
|
c.mtx.Lock()
|
|
defer c.mtx.Unlock()
|
|
v, ok := c.cache[key]
|
|
return v, ok
|
|
}
|
|
|
|
func (c *cache) set(key string, value bool) {
|
|
c.mtx.Lock()
|
|
defer c.mtx.Unlock()
|
|
c.makeRoom()
|
|
c.cache[key] = value
|
|
}
|
|
|
|
func (c *cache) makeRoom() {
|
|
if len(c.cache) < cacheSize {
|
|
return
|
|
}
|
|
numToDelete := len(c.cache) / 10
|
|
if numToDelete < 1 {
|
|
numToDelete = 1
|
|
}
|
|
for deleted := 0; deleted <= numToDelete; deleted++ {
|
|
rnd := weakrand.Intn(len(c.cache))
|
|
i := 0
|
|
for key := range c.cache {
|
|
if i == rnd {
|
|
delete(c.cache, key)
|
|
break
|
|
}
|
|
i++
|
|
}
|
|
}
|
|
}
|
|
|
|
type auth struct {
|
|
users map[string]*creds
|
|
cache *cache
|
|
// bcryptMtx is there to ensure that bcrypt.CompareHashAndPassword is run
|
|
// only once in parallel as this is CPU intensive.
|
|
bcryptMtx sync.Mutex
|
|
}
|
|
|
|
func (a *auth) Auth(user, pass, path string) bool {
|
|
creds, valid := a.users[user]
|
|
hash := creds.Hash
|
|
|
|
if !valid {
|
|
// The user is not found. Use a fixed password hash to
|
|
// prevent user enumeration by timing requests.
|
|
// This is a bcrypt-hashed version of "fakepassword".
|
|
hash = "$2y$10$QOauhQNbBCuQDKes6eFzPeMqBSjb7Mr5DUmpZ/VcEd00UAV/LDeSi"
|
|
}
|
|
|
|
cacheKey := hex.EncodeToString(append(append([]byte(user), []byte(hash)...), []byte(pass)...))
|
|
authOk, ok := a.cache.get(cacheKey)
|
|
|
|
if !ok {
|
|
// This user, hashedPassword, password is not cached.
|
|
a.bcryptMtx.Lock()
|
|
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(pass))
|
|
a.bcryptMtx.Unlock()
|
|
|
|
authOk = err == nil
|
|
u.cache.set(cacheKey, authOk)
|
|
}
|
|
|
|
return authOk && valid && strings.HasPrefix(path, creds.Prefix)
|
|
}
|
|
|
|
type creds struct {
|
|
Hash string
|
|
Prefix string
|
|
}
|
|
|
|
func newAuth(conf config.Config) (a *auth) {
|
|
a = &auth{
|
|
users: make(map[string]creds),
|
|
cache: newCache(),
|
|
}
|
|
for _, u := range conf.BasicAuth {
|
|
a.users[u.User] = &creds{u.Hash, u.Prefix}
|
|
}
|
|
return
|
|
}
|