package server import ( "crypto/rand" "crypto/sha256" "crypto/subtle" "encoding/base64" "net" "net/http" "net/netip" "strings" "sync" "time" ) const ( cookieName = "urutau_session" sessionTTL = 12 * time.Hour loginMax = 5 loginWindow = 10 * time.Minute maxLimiterIP = 10000 ) // tokenEqual compares in constant time regardless of length. func tokenEqual(a, b string) bool { ha, hb := sha256.Sum256([]byte(a)), sha256.Sum256([]byte(b)) return subtle.ConstantTimeCompare(ha[:], hb[:]) == 1 } const maxSessions = 64 // sessions is the in-memory registry of signed-in browsers. The cookie carries // a random id; logging out deletes it, so a stolen cookie can be revoked. A // restart signs everybody out. type sessions struct { mu sync.Mutex ids map[string]time.Time } func newSessions() *sessions { return &sessions{ids: map[string]time.Time{}} } func (s *sessions) issue(now time.Time) (string, time.Time) { b := make([]byte, 32) if _, err := rand.Read(b); err != nil { panic(err) } id := base64.RawURLEncoding.EncodeToString(b) exp := now.Add(sessionTTL) s.mu.Lock() defer s.mu.Unlock() for k, e := range s.ids { if now.After(e) { delete(s.ids, k) } } for len(s.ids) >= maxSessions { // drop the oldest var oldK string var oldE time.Time for k, e := range s.ids { if oldK == "" || e.Before(oldE) { oldK, oldE = k, e } } delete(s.ids, oldK) } s.ids[id] = exp return id, exp } func (s *sessions) valid(id string, now time.Time) bool { s.mu.Lock() defer s.mu.Unlock() exp, ok := s.ids[id] if ok && now.After(exp) { delete(s.ids, id) return false } return ok } func (s *sessions) revoke(id string) { s.mu.Lock(); delete(s.ids, id); s.mu.Unlock() } // limiter allows loginMax failures per client inside loginWindow. IPv6 // clients are keyed by their /64. type limiter struct { mu sync.Mutex fail map[string][]time.Time busy map[string]bool // a blocked client gets one wrong attempt in flight at a time now func() time.Time } func newLimiter() *limiter { return &limiter{fail: map[string][]time.Time{}, busy: map[string]bool{}, now: time.Now} } // maxFailKept bounds the timestamps kept per client. const maxFailKept = 64 // maxBlockedDelay caps the progressive delay of a blocked client. var maxBlockedDelay = 30 * time.Second // a var so tests can shorten it // penalty is the delay of the next wrong attempt of a blocked client: 1 s, // doubling with every failure past the limit, at most maxBlockedDelay. func (l *limiter) penalty(ip string) time.Duration { l.mu.Lock() defer l.mu.Unlock() over := len(l.recent(limiterKey(ip))) - loginMax if over < 0 { return 0 } if over > 5 { return maxBlockedDelay } d := loginBlockedDelay << over if d > maxBlockedDelay { d = maxBlockedDelay } return d } // acquire marks the client's single slow slot as taken; false means another // wrong attempt of the same client is already waiting. func (l *limiter) acquire(ip string) (release func(), ok bool) { key := limiterKey(ip) l.mu.Lock() defer l.mu.Unlock() if l.busy[key] { return nil, false } l.busy[key] = true return func() { l.mu.Lock(); delete(l.busy, key); l.mu.Unlock() }, true } // limiterKey aggregates IPv6 by /64: one subscriber owns the whole prefix. func limiterKey(ip string) string { if a, err := netip.ParseAddr(ip); err == nil { a = a.WithZone("").Unmap() if a.Is6() { return netip.PrefixFrom(a, 64).Masked().String() } return a.String() } return ip } func (l *limiter) recent(key string) []time.Time { cut := l.now().Add(-loginWindow) list := l.fail[key] i := 0 for i < len(list) && list[i].Before(cut) { i++ } list = list[i:] if len(list) == 0 { delete(l.fail, key) } else { l.fail[key] = list } return list } // blocked returns how long the client must wait, or 0. func (l *limiter) blocked(ip string) time.Duration { l.mu.Lock() defer l.mu.Unlock() list := l.recent(limiterKey(ip)) if len(list) < loginMax { return 0 } return list[0].Add(loginWindow).Sub(l.now()) } func (l *limiter) failure(ip string) { l.mu.Lock() defer l.mu.Unlock() key := limiterKey(ip) if _, known := l.fail[key]; !known && len(l.fail) >= maxLimiterIP { // full: expire the stale entries, and if everybody is fresh drop the one // whose latest failure is the oldest (never forget all of them at once) var oldK string var oldT time.Time for k := range l.fail { list := l.recent(k) if len(list) == 0 { continue } if last := list[len(list)-1]; oldK == "" || last.Before(oldT) { oldK, oldT = k, last } } if len(l.fail) >= maxLimiterIP && oldK != "" { delete(l.fail, oldK) } } list := append(l.recent(key), l.now()) if len(list) > maxFailKept { list = list[len(list)-maxFailKept:] } l.fail[key] = list } func (l *limiter) reset(ip string) { l.mu.Lock(); delete(l.fail, limiterKey(ip)); l.mu.Unlock() } // clientIP is the address used for rate limiting and for the peer allow list. // X-Forwarded-For is only believed when the TCP peer is one of the trusted // proxies; the chain is then walked from the right, skipping trusted proxies, // so a client cannot choose its own address by sending the header. func clientIP(r *http.Request, trusted []netip.Prefix) string { host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { host = r.RemoteAddr } a, err := netip.ParseAddr(host) if err != nil || !prefixesContain(trusted, a) { return host } var hops []string for _, h := range r.Header.Values("X-Forwarded-For") { hops = append(hops, strings.Split(h, ",")...) } for i := len(hops) - 1; i >= 0; i-- { hop := strings.TrimSpace(hops[i]) ha, err := netip.ParseAddr(hop) if err != nil || ha.Zone() != "" { return host // garbage in the chain: fall back to the proxy itself } if !prefixesContain(trusted, ha) { return ha.Unmap().String() } } return host } func isHTTPS(r *http.Request) bool { return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") }