Files
EasyDNS-Web/internal/server/auth.go
T
Mateusz Gruszczyński de13d851a8
Go quality gates / test (push) Waiting to run
v0.1.1
2026-11-30 14:44:28 +01:00

201 lines
5.6 KiB
Go

package server
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"errors"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
"git.linuxiarz.pl/gru/EasyDNS-Web/internal/config"
)
const sessionCookie = "easydns_ui_session"
const sessionTTL = 12 * time.Hour
type auth struct {
key []byte
password []byte
username string
secure bool
mu sync.Mutex
fail map[string][]time.Time
}
func newAuth(cfg config.Config) (*auth, error) {
secret := cfg.Password
if secret == "" {
p, err := os.ReadFile(cfg.PasswordFile)
if err != nil {
return nil, err
}
secret = strings.TrimSpace(string(p))
}
if len(secret) < 16 {
return nil, errors.New("panel password must have at least 16 characters")
}
if cfg.SessionAuto {
if err := ensureSessionKey(cfg.SessionKeyFile); err != nil {
return nil, err
}
}
k, err := os.ReadFile(cfg.SessionKeyFile)
if err != nil {
return nil, err
}
k = bytesTrimSpace(k)
if decoded, e := hex.DecodeString(string(k)); e == nil && len(decoded) >= 32 {
k = decoded
}
if len(k) < 32 {
return nil, errors.New("session key must contain at least 32 bytes")
}
// Derive the signing key from the persisted session secret and current
// login credentials. Password/username changes invalidate old sessions.
mac := hmac.New(sha256.New, k)
mac.Write([]byte("easydns-ui-session-v1:" + cfg.Username + ":" + secret))
return &auth{key: mac.Sum(nil), password: []byte(secret), username: cfg.Username, secure: cfg.CookieSecure, fail: make(map[string][]time.Time)}, nil
}
// Creates the session secret only when explicitly enabled (Docker mode).
// The same secret is reused across container recreations through a volume.
func ensureSessionKey(path string) error {
if _, err := os.Stat(path); err == nil {
return nil
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return err
}
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
return err
}
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if errors.Is(err, os.ErrExist) {
return nil
}
if err != nil {
return err
}
if _, err = f.WriteString(hex.EncodeToString(key) + "\n"); err != nil {
f.Close()
os.Remove(path)
return err
}
return f.Close()
}
func bytesTrimSpace(v []byte) []byte { return []byte(strings.TrimSpace(string(v))) }
func (a *auth) sign(v string) string {
mac := hmac.New(sha256.New, a.key)
mac.Write([]byte(v))
return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}
func (a *auth) makeSession() string {
r := make([]byte, 24)
_, _ = rand.Read(r)
v := base64.RawURLEncoding.EncodeToString(r) + "." + time.Now().UTC().Format("20060102150405")
return v + "." + a.sign(v)
}
func (a *auth) parseSession(r *http.Request) (string, bool) {
c, err := r.Cookie(sessionCookie)
if err != nil {
return "", false
}
parts := strings.Split(c.Value, ".")
if len(parts) != 3 {
return "", false
}
v := parts[0] + "." + parts[1]
if subtle.ConstantTimeCompare([]byte(a.sign(v)), []byte(parts[2])) != 1 {
return "", false
}
t, err := time.Parse("20060102150405", parts[1])
if err != nil {
return "", false
}
if time.Since(t) > sessionTTL || time.Until(t) > time.Minute {
return "", false
}
return v, true
}
func (a *auth) csrf(session string) string { return a.sign("csrf:" + session) }
func (a *auth) checkCSRF(r *http.Request, session string) bool {
if !sameOrigin(r) {
return false
}
provided := r.FormValue("_csrf")
if provided == "" {
provided = r.Header.Get("X-CSRF-Token")
}
return subtle.ConstantTimeCompare([]byte(provided), []byte(a.csrf(session))) == 1
}
func sameOrigin(r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin == "" {
return true
} // non-browser tools still need valid CSRF
u, err := url.Parse(origin)
if err != nil {
return false
}
return strings.EqualFold(u.Host, r.Host) && (u.Scheme == "https" || u.Scheme == "http")
}
func (a *auth) setCookie(w http.ResponseWriter, value string, maxAge int) {
http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: value, Path: "/", HttpOnly: true, Secure: a.secure, SameSite: http.SameSiteStrictMode, MaxAge: maxAge})
}
func (a *auth) allowedLogin(ip string) bool {
a.mu.Lock()
defer a.mu.Unlock()
now := time.Now()
v := a.fail[ip][:0]
for _, t := range a.fail[ip] {
if now.Sub(t) < 15*time.Minute {
v = append(v, t)
}
}
a.fail[ip] = v
return len(v) < 8
}
func (a *auth) failLogin(ip string) {
a.mu.Lock()
defer a.mu.Unlock()
a.fail[ip] = append(a.fail[ip], time.Now())
}
func (a *auth) clearFailure(ip string) { a.mu.Lock(); defer a.mu.Unlock(); delete(a.fail, ip) }
func remoteIP(r *http.Request) string {
h, _, e := net.SplitHostPort(r.RemoteAddr)
if e != nil {
return r.RemoteAddr
}
return h
}
func (a *auth) verify(user, pass string) bool {
u := subtle.ConstantTimeCompare([]byte(user), []byte(a.username))
ph := sha256.Sum256([]byte(pass))
eh := sha256.Sum256(a.password)
p := subtle.ConstantTimeCompare(ph[:], eh[:])
return u == 1 && p == 1
}
func secureHeaders(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "same-origin")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'")
h.ServeHTTP(w, r)
})
}