// Package server exposes the dashboard and the JSON API. package server import ( "context" "embed" "encoding/json" "fmt" "io/fs" "net" "net/http" "net/netip" "net/url" "regexp" "sort" "strconv" "strings" "sync" "sync/atomic" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" ) //go:embed web var webFS embed.FS // maxSSE bounds the simultaneous live streams. const maxSSE = 20 // maxPeerSSE bounds the simultaneous hub subscriptions to /api/v1/peer/stream. const maxPeerSSE = 10 // sseHeartbeat is how often a live stream pings and revalidates its session. var sseHeartbeat = 20 * time.Second // loginBlockedDelay is the fixed delay applied to login attempts from a blocked client. var loginBlockedDelay = time.Second // HTTPServer wraps a handler with the timeouts and limits of the daemon. The // SSE handler lifts the write deadline of its own connection. func HTTPServer(h http.Handler, base context.Context) *http.Server { return &http.Server{Handler: h, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second, IdleTimeout: 120 * time.Second, MaxHeaderBytes: 16 << 10, BaseContext: func(net.Listener) context.Context { return base }} } // Options configure the handler. type Options struct { Token string // PeerTokens are the federation tokens accepted by /api/v1/peer/export. PeerTokens []string // Ignore lists networks that must never appear in the blocklist (ignore + trusted). Ignore []netip.Prefix // AllowHosts: with NoAuth, only requests whose Host is one of these are served // (anti DNS rebinding). AllowHosts []string // PeerAllow, when not empty, restricts /api/v1/peer/export to these source // networks. TrustedProxy lists the reverse proxies whose X-Forwarded-For is believed. PeerAllow []netip.Prefix TrustedProxy []netip.Prefix NoAuth bool // LocalBlocklist makes the blocklist use only this instance's IPs (--peer-blocklist=off). LocalBlocklist bool Version string Store *store.Store Hub *fed.Hub Now func() time.Time } // Server is the HTTP handler. type Server struct { sse atomic.Int32 exp exportCache opt Options ses *sessions lim *limiter mux *http.ServeMux assets fs.FS geo geoCache psse atomic.Int32 study chan struct{} user chan struct{} // user-side studies (period, metrics) running at once } // New builds the handler. func New(opt Options) http.Handler { if opt.Now == nil { opt.Now = time.Now } sub, _ := fs.Sub(webFS, "web") s := &Server{opt: opt, ses: newSessions(), lim: newLimiter(), mux: http.NewServeMux(), assets: sub, study: make(chan struct{}, 2), user: make(chan struct{}, 4)} m := s.mux m.HandleFunc("GET /api/health", s.health) m.HandleFunc("GET /login", s.loginPage) m.HandleFunc("POST /login", s.login) m.HandleFunc("POST /logout", s.logout) m.HandleFunc("GET /{$}", s.index) m.HandleFunc("GET /{file}", s.asset) m.HandleFunc("GET /api/v1/peer/export", s.peerExport) m.HandleFunc("GET /api/v1/peer/stream", s.peerStream) m.HandleFunc("GET /api/v1/peer/period", s.peerPeriod) m.HandleFunc("GET /api/v1/peer/egress", s.peerEgress) m.HandleFunc("GET /api/v1/geo", s.api(s.geoAPI)) m.HandleFunc("GET /api/v1/live/recent", s.api(s.liveRecent)) m.HandleFunc("GET /api/v1/summary", s.api(s.summary)) m.HandleFunc("GET /api/v1/traffic", s.api(s.traffic)) m.HandleFunc("GET /api/v1/ips", s.api(s.ips)) m.HandleFunc("GET /api/v1/ip/{ip}", s.api(s.ipDetail)) m.HandleFunc("GET /api/v1/period", s.api(s.periodAPI)) m.HandleFunc("GET /api/v1/period/events", s.api(s.periodEvents)) m.HandleFunc("GET /api/v1/metrics", s.api(s.metricsAPI)) m.HandleFunc("GET /api/v1/ip/{ip}/stix", s.api(s.stixAPI)) m.HandleFunc("GET /api/v1/events", s.api(s.eventsAPI)) m.HandleFunc("GET /api/v1/events/sessions", s.api(s.sessionsAPI)) // Analysis routes added by api_.go files through registerUserRoute // (init): user auth only, same wrapper as every /api/v1 route. for _, r := range userRoutes { m.HandleFunc(r.pattern, s.api(r.handler(s))) } for _, r := range peerRoutes { // peer-token routes of api_.go files m.HandleFunc(r.pattern, r.handler(s)) } m.HandleFunc("GET /api/v1/events/stream", s.api(s.stream)) m.HandleFunc("GET /api/v1/blocklist.txt", s.api(s.blocklist(false))) m.HandleFunc("GET /api/v1/blocklist.json", s.api(s.blocklist(true))) return s.headers(m) } func (s *Server) headers(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if s.opt.NoAuth && !hostAllowed(r.Host, s.opt.AllowHosts) { http.Error(w, "host not allowed", http.StatusForbidden) // DNS rebinding guard return } h := w.Header() h.Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'") h.Set("X-Content-Type-Options", "nosniff") h.Set("X-Frame-Options", "DENY") h.Set("Referrer-Policy", "same-origin") h.Set("Cross-Origin-Opener-Policy", "same-origin") h.Set("Cross-Origin-Resource-Policy", "same-origin") h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()") if isHTTPS(r) { h.Set("Strict-Transport-Security", "max-age=31536000") } next.ServeHTTP(w, r) }) } func writeJSON(w http.ResponseWriter, code int, v any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Cache-Control", "no-store") w.WriteHeader(code) json.NewEncoder(w).Encode(v) } func (s *Server) health(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, map[string]string{"status": "ok"}) } // authKind returns "session" or "bearer" for a valid user credential (cookie or // URUTAU_TOKEN), "peer" for the federation token, "" otherwise. func (s *Server) authKind(r *http.Request) string { if s.opt.NoAuth { return "session" } if a := r.Header.Get("Authorization"); strings.HasPrefix(a, "Bearer ") { tok := strings.TrimSpace(a[7:]) if tokenEqual(tok, s.opt.Token) { return "bearer" } if s.peerTokenOK(tok) { return "peer" } return "" } if c, err := r.Cookie(cookieName); err == nil && s.ses.valid(c.Value, s.opt.Now()) { return "session" } return "" } func (s *Server) peerTokenOK(tok string) bool { ok := false for _, t := range s.opt.PeerTokens { // no early exit: constant work per token if tokenEqual(tok, t) { ok = true } } return ok } // api wraps a user endpoint: only a session or URUTAU_TOKEN opens it. The peer // token is refused with 403 (it is a valid credential, for another route). func (s *Server) api(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { switch s.authKind(r) { case "session", "bearer": case "peer": writeJSON(w, http.StatusForbidden, map[string]string{"error": "the peer token only opens /api/v1/peer/export, /api/v1/peer/stream, /api/v1/peer/period and /api/v1/peer/egress"}) return default: ip := clientIP(r, s.opt.TrustedProxy) wait := s.lim.blocked(ip) if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") { delay := s.lim.penalty(ip) // measured before this failure is counted s.lim.failure(ip) // guessing the token on the API counts like on the login form if wait > 0 { s.slowFail(ip, delay) } } if wait = s.lim.blocked(ip); wait > 0 { w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1)) writeJSON(w, http.StatusTooManyRequests, map[string]string{"error": "too many attempts"}) return } w.Header().Set("WWW-Authenticate", `Bearer realm="urutau"`) writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"}) return } w.Header().Set("Cache-Control", "no-store") h(w, r) } } // slowFail delays a wrong attempt of a blocked client. Only one attempt per // client waits at a time; concurrent ones return at once (and get 429), so // parallel requests do not multiply the guessing rate. func (s *Server) slowFail(ip string, d time.Duration) { release, ok := s.lim.acquire(ip) if !ok { return } defer release() if d > 0 { time.Sleep(d) } } type exportCache struct { mu sync.Mutex at map[string]time.Time v map[string][]byte } // peerGate admits only the federation token (and --peer-allow sources); it // answers the request itself and returns false when it refuses. func (s *Server) peerGate(w http.ResponseWriter, r *http.Request) bool { if len(s.opt.PeerTokens) == 0 && !s.opt.NoAuth { writeJSON(w, http.StatusNotFound, map[string]string{"error": "federation is not enabled"}) return false } if len(s.opt.PeerAllow) > 0 { a, err := netip.ParseAddr(clientIP(r, s.opt.TrustedProxy)) if err != nil || !prefixesContain(s.opt.PeerAllow, a) { writeJSON(w, http.StatusForbidden, map[string]string{"error": "source not allowed"}) return false } } if !s.opt.NoAuth && s.authKind(r) != "peer" { if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") { s.lim.failure(clientIP(r, s.opt.TrustedProxy)) } w.Header().Set("WWW-Authenticate", `Bearer realm="urutau-peer"`) writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"}) return false } return true } // rangeOf resolves the range parameters of a request (range, from, to); it // answers 400 itself and returns false on garbage. func (s *Server) rangeOf(w http.ResponseWriter, r *http.Request) (store.Range, bool) { q := r.URL.Query() rg, err := s.opt.Store.ResolveRange(q.Get("range"), q.Get("from"), q.Get("to")) if err != nil { writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()}) return rg, false } return rg, true } // peerExport: GET /api/v1/peer/export, opened by the peer token. func (s *Server) peerExport(w http.ResponseWriter, r *http.Request) { if !s.peerGate(w, r) { return } rg, ok := s.rangeOf(w, r) if !ok { return } key := rg.Key() s.exp.mu.Lock() if s.exp.v == nil || len(s.exp.v) >= 24 { s.exp.v, s.exp.at = map[string][]byte{}, map[string]time.Time{} } b, ok := s.exp.v[key] if !ok || time.Since(s.exp.at[key]) > 5*time.Second { b, _ = json.Marshal(s.opt.Store.ExportFor(rg)) s.exp.v[key], s.exp.at[key] = b, time.Now() } s.exp.mu.Unlock() w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Cache-Control", "no-store") w.Write(b) } func prefixesContain(ps []netip.Prefix, a netip.Addr) bool { a = a.Unmap() for _, p := range ps { if p.Contains(a) { return true } } return false } var assetRe = regexp.MustCompile(`^[a-z0-9-]+\.(js|css|png|svg|json)$`) // asset serves a top-level file of the embedded web directory by name. func (s *Server) asset(w http.ResponseWriter, r *http.Request) { name := r.PathValue("file") if !assetRe.MatchString(name) { http.NotFound(w, r) return } if st, err := fs.Stat(s.assets, name); err != nil || !st.Mode().IsRegular() { http.NotFound(w, r) return } s.static(w, r, name) } func (s *Server) static(w http.ResponseWriter, r *http.Request, name string) { b, err := fs.ReadFile(s.assets, name) if err != nil { http.NotFound(w, r) return } ct := "application/octet-stream" switch { case strings.HasSuffix(name, ".css"): ct = "text/css; charset=utf-8" case strings.HasSuffix(name, ".js"): ct = "text/javascript; charset=utf-8" case strings.HasSuffix(name, ".png"): ct = "image/png" case strings.HasSuffix(name, ".svg"): ct = "image/svg+xml" case strings.HasSuffix(name, ".json"): ct = "application/json; charset=utf-8" case strings.HasSuffix(name, ".html"): ct = "text/html; charset=utf-8" } w.Header().Set("Content-Type", ct) w.Header().Set("Cache-Control", "no-cache") w.Write(b) } func (s *Server) index(w http.ResponseWriter, r *http.Request) { if s.authKind(r) == "" { http.Redirect(w, r, "/login", http.StatusSeeOther) return } s.static(w, r, "index.html") } func (s *Server) loginPage(w http.ResponseWriter, r *http.Request) { if s.authKind(r) != "" { http.Redirect(w, r, "/", http.StatusSeeOther) return } s.static(w, r, "login.html") } // sameOrigin rejects cross-site form posts: browsers send Sec-Fetch-Site and // Origin; SameSite=Strict on the cookie is the first line, this is the second. func sameOrigin(r *http.Request) bool { switch r.Header.Get("Sec-Fetch-Site") { case "cross-site": return false case "same-origin": return true // browsers that send Fetch Metadata state it reliably } if o := r.Header.Get("Origin"); o != "" { u, err := url.Parse(o) if err != nil || u.Host == "" || !strings.EqualFold(u.Host, r.Host) { return false } } return true } func (s *Server) login(w http.ResponseWriter, r *http.Request) { if !sameOrigin(r) { http.Error(w, "cross-site request refused", http.StatusForbidden) return } ip := clientIP(r, s.opt.TrustedProxy) r.Body = http.MaxBytesReader(w, r.Body, 4096) if err := r.ParseForm(); err != nil { http.Error(w, "bad request", http.StatusBadRequest) return } // The correct token is always accepted at once, so an attacker who burns // the limit cannot lock the administrator out. Guessing stays infeasible: // tokens carry at least 128 bits (checkToken). Wrong attempts of a blocked // client are serialized and progressively delayed (s.slowFail). if s.opt.NoAuth || !tokenEqual(r.PostForm.Get("token"), s.opt.Token) { wait := s.lim.blocked(ip) delay := s.lim.penalty(ip) // measured before this failure is counted s.lim.failure(ip) if wait > 0 { s.slowFail(ip, delay) w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1)) w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-store") w.WriteHeader(http.StatusTooManyRequests) if b, err := fs.ReadFile(s.assets, "login.html"); err == nil { w.Write(b) } return } http.Redirect(w, r, "/login?e=bad", http.StatusSeeOther) return } s.lim.reset(ip) val, exp := s.ses.issue(s.opt.Now()) http.SetCookie(w, &http.Cookie{Name: cookieName, Value: val, Path: "/", Expires: exp, MaxAge: int(sessionTTL.Seconds()), HttpOnly: true, Secure: isHTTPS(r), SameSite: http.SameSiteStrictMode}) http.Redirect(w, r, "/", http.StatusSeeOther) } func (s *Server) logout(w http.ResponseWriter, r *http.Request) { if !sameOrigin(r) { http.Error(w, "cross-site request refused", http.StatusForbidden) return } if c, err := r.Cookie(cookieName); err == nil { s.ses.revoke(c.Value) } http.SetCookie(w, &http.Cookie{Name: cookieName, Value: "", Path: "/", MaxAge: -1, HttpOnly: true, Secure: isHTTPS(r), SameSite: http.SameSiteStrictMode}) http.Redirect(w, r, "/login", http.StatusSeeOther) } // parts returns the summaries to merge for a host selection. func (s *Server) parts(ctx context.Context, rg store.Range, host string) (parts []store.Summary, all []store.HostInfo) { self := s.opt.Store.Name() local := s.opt.Store.SummaryFor(rg) all = append(all, local.Hosts...) if s.opt.Hub != nil { all = append(all, s.opt.Hub.Hosts()...) } if host == "" || host == "all" || host == self { parts = append(parts, local) } if s.opt.Hub != nil && host != self { only := "" if host != "" && host != "all" { only = host } parts = append(parts, s.opt.Hub.SummariesFor(ctx, rg, only)...) } return } func (s *Server) knownHost(w http.ResponseWriter, host string) bool { if host != "all" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) { writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"}) return false } return true } func (s *Server) summary(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() rg, ok := s.rangeOf(w, r) if !ok { return } host := q.Get("host") if host == "" { host = "all" } if !s.knownHost(w, host) { return } parts, hosts := s.parts(r.Context(), rg, host) var out store.Summary switch len(parts) { case 0: out = store.Summary{Version: s.opt.Version, Host: host, Range: rg.Info(s.opt.Now().Unix()), Generated: s.opt.Now().Unix()} default: out = store.Merge(host, parts) } out.Hosts = hosts // Peers' sources are in the merge; keep a stable order: by host then name. sort.SliceStable(out.Sources, func(i, j int) bool { if out.Sources[i].Host != out.Sources[j].Host { return out.Sources[i].Host < out.Sources[j].Host } return out.Sources[i].Name < out.Sources[j].Name }) writeJSON(w, 200, out) } // allIPs returns the merged IP table for the requested host selection. func (s *Server) allIPs(ctx context.Context, rg store.Range, host string) []store.IPSummary { return s.ipsOf(ctx, rg, host, false) } func (s *Server) ipsOf(ctx context.Context, rg store.Range, host string, localOnly bool) []store.IPSummary { var lists [][]store.IPSummary self := s.opt.Store.Name() if host == "" || host == "all" || host == self { lists = append(lists, s.opt.Store.AllIPs(rg, false)) } if s.opt.Hub != nil && host != self && !localOnly { only := "" if host != "" && host != "all" { only = host } for _, p := range s.opt.Hub.SummariesFor(ctx, rg, only) { lists = append(lists, p.IPs) } } return store.MergeIPs(lists...) } func (s *Server) ips(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() rg, ok := s.rangeOf(w, r) if !ok { return } list := s.allIPs(r.Context(), rg, q.Get("host")) minScore, _ := strconv.ParseFloat(q.Get("min_score"), 64) level, needle := q.Get("level"), strings.ToLower(strings.TrimSpace(q.Get("q"))) banned := q.Get("banned") == "1" filtered := list[:0:0] for _, x := range list { if x.Score < minScore || (level != "" && string(x.Level) != level) || (banned && !x.Banned) { continue } if needle != "" && !strings.Contains(x.IP, needle) && !strings.Contains(strings.ToLower(x.RDNS), needle) { continue } filtered = append(filtered, x) } switch q.Get("sort") { case "score", "last", "first", "events", "ip": store.SortIPs(filtered, q.Get("sort"), q.Get("order") != "asc") } per, _ := strconv.Atoi(q.Get("per")) if per < 1 || per > 200 { per = 50 } page, _ := strconv.Atoi(q.Get("page")) if page < 1 { page = 1 } if page > 100000 { page = 100000 } from := (page - 1) * per if from > len(filtered) { from = len(filtered) } to := from + per if to > len(filtered) { to = len(filtered) } items := filtered[from:to] for i := range items { s.opt.Store.Enrich(&items[i]) if items[i].RDNS == "" { items[i].RDNS = s.opt.Store.RDNSOf(items[i].IP) } } writeJSON(w, 200, map[string]any{"range": rg.Info(s.opt.Now().Unix()), "total": len(filtered), "page": page, "per": per, "items": items}) } func (s *Server) ipDetail(w http.ResponseWriter, r *http.Request) { raw := r.PathValue("ip") if _, ok := blockAddr(raw); !ok { writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip"}) return } var rg store.Range if q := r.URL.Query(); q.Get("range") == "" && q.Get("from") == "" && q.Get("to") == "" { rg = store.Ranges["30d"] } else { var ok bool if rg, ok = s.rangeOf(w, r); !ok { return } } ip := store.KeyOf(raw) var lists [][]store.IPSummary if d, ok := s.opt.Store.IP(ip); ok { lists = append(lists, []store.IPSummary{d}) } if s.opt.Hub != nil { lists = append(lists, s.opt.Hub.IPDetail(ip)) } m := store.MergeIPs(lists...) if len(m) == 0 { writeJSON(w, http.StatusNotFound, map[string]string{"error": "not found"}) return } writeJSON(w, 200, s.buildIPDetail(m[0], ip, rg)) } func (s *Server) stream(w http.ResponseWriter, r *http.Request) { fl, ok := w.(http.Flusher) if !ok { http.Error(w, "streaming unsupported", 500) return } if s.sse.Add(1) > maxSSE { s.sse.Add(-1) w.Header().Set("Retry-After", "10") http.Error(w, "too many live streams", http.StatusServiceUnavailable) return } defer s.sse.Add(-1) rc := http.NewResponseController(w) _ = rc.SetWriteDeadline(time.Time{}) h := w.Header() h.Set("Content-Type", "text/event-stream") h.Set("Cache-Control", "no-store") h.Set("X-Accel-Buffering", "no") ch, stop := s.opt.Store.Subscribe() defer stop() var hubCh <-chan store.LiveEvent // nil blocks forever: no hub, no peer events if s.opt.Hub != nil { c, stopHub := s.opt.Hub.Subscribe() defer stopHub() hubCh = c } // ?visits=1 also streams the legitimate visits (no address in them); nil blocks forever var visCh, hubVisCh <-chan store.VisitMsg if r.URL.Query().Get("visits") == "1" { c, stopV := s.opt.Store.SubscribeVisits() defer stopV() visCh = c if s.opt.Hub != nil { c, stopHV := s.opt.Hub.SubscribeVisits() defer stopHV() hubVisCh = c } } fmt.Fprint(w, "retry: 3000\n: connected\n\n") fl.Flush() tick := time.NewTicker(sseHeartbeat) defer tick.Stop() sendAs := func(name string, e any) bool { if k := s.authKind(r); k != "session" && k != "bearer" { return false } b, _ := json.Marshal(e) if _, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", name, b); err != nil { return false } fl.Flush() return true } send := func(e store.LiveEvent) bool { return sendAs("ev", e) } for { select { case <-r.Context().Done(): return case <-tick.C: if k := s.authKind(r); k != "session" && k != "bearer" { return // the session expired or was revoked: close the stream } if _, err := fmt.Fprint(w, ": ping\n\n"); err != nil { return } fl.Flush() case e := <-ch: if !send(s.opt.Store.Live(e)) { return } case e := <-hubCh: if !send(e) { return } case e := <-visCh: if !sendAs("visit", e) { return } case e := <-hubVisCh: if !sendAs("visit", e) { return } } } } // peerStream: GET /api/v1/peer/stream, SSE of this instance's own malicious // events for a hub. Opened only by the peer token, like the export. func (s *Server) peerStream(w http.ResponseWriter, r *http.Request) { if !s.peerGate(w, r) { return } fl, ok := w.(http.Flusher) if !ok { http.Error(w, "streaming unsupported", 500) return } if s.psse.Add(1) > maxPeerSSE { s.psse.Add(-1) w.Header().Set("Retry-After", "10") http.Error(w, "too many peer streams", http.StatusServiceUnavailable) return } defer s.psse.Add(-1) _ = http.NewResponseController(w).SetWriteDeadline(time.Time{}) h := w.Header() h.Set("Content-Type", "text/event-stream") h.Set("Cache-Control", "no-store") h.Set("X-Accel-Buffering", "no") ch, stop := s.opt.Store.Subscribe() defer stop() var visCh <-chan store.VisitMsg // only with ?visits=1; carries no address if r.URL.Query().Get("visits") == "1" { c, stopV := s.opt.Store.SubscribeVisits() defer stopV() visCh = c } fmt.Fprint(w, "retry: 3000\n: connected\n\n") fl.Flush() tick := time.NewTicker(sseHeartbeat) defer tick.Stop() for { select { case <-r.Context().Done(): return case v := <-visCh: b, _ := json.Marshal(v) if _, err := fmt.Fprintf(w, "event: visit\ndata: %s\n\n", b); err != nil { return } fl.Flush() case <-tick.C: if !s.opt.NoAuth && s.authKind(r) != "peer" { return } if _, err := fmt.Fprint(w, ": ping\n\n"); err != nil { return } fl.Flush() case e := <-ch: if !core.Category(e.Cat).IsMalicious() { continue } b, _ := json.Marshal(s.opt.Store.Live(e)) if _, err := fmt.Fprintf(w, "event: ev\ndata: %s\n\n", b); err != nil { return } fl.Flush() } } } // liveRecent: GET /api/v1/live/recent?limit=200 (max 500), newest first, local and peers. func (s *Server) liveRecent(w http.ResponseWriter, r *http.Request) { n, _ := strconv.Atoi(r.URL.Query().Get("limit")) if n < 1 { n = 200 } if n > 500 { n = 500 } list := s.opt.Store.LiveRecent(n) if s.opt.Hub != nil { list = append(list, s.opt.Hub.Recent(n)...) } sort.SliceStable(list, func(i, j int) bool { return list[i].T > list[j].T }) if len(list) > n { list = list[:n] } writeJSON(w, 200, map[string]any{"events": list}) } func (s *Server) blocklist(asJSON bool) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() min := 50.0 if v, err := strconv.ParseFloat(q.Get("min_score"), 64); err == nil && v >= 0 { min = v } if q.Get("range") == "" && q.Get("from") == "" { q.Set("range", "7d") r.URL.RawQuery = q.Encode() } rg, ok := s.rangeOf(w, r) if !ok { return } // family=4 gives plain IPv4 addresses only (for ipset hash:ip and similar); // family=6 gives only the IPv6 /64 prefixes; the default lists both. family := q.Get("family") if family != "4" && family != "6" { family = "all" } var out []store.IPSummary for _, x := range s.ipsOf(r.Context(), rg, q.Get("host"), s.opt.LocalBlocklist) { if x.Score < min || !x.Strong || x.Admin { continue } // every row is revalidated here, whatever its origin (a peer included) addr, ok := blockAddr(x.IP) if !ok || !core.IsGlobal(addr) || core.Ignored(s.opt.Ignore, addr.String()) { continue } if (family == "4" && !addr.Is4()) || (family == "6" && addr.Is4()) { continue } out = append(out, x) } if q.Get("download") == "1" { ext := "txt" if asJSON { ext = "json" } w.Header().Set("Content-Disposition", `attachment; filename="urutau-blocklist.`+ext+`"`) } if asJSON { type row struct { IP string `json:"ip"` Score float64 `json:"score"` Last int64 `json:"last"` Hosts []string `json:"hosts"` CC string `json:"cc,omitempty"` Country string `json:"country,omitempty"` City string `json:"city,omitempty"` ASN uint32 `json:"asn,omitempty"` ASOrg string `json:"as_org,omitempty"` } rows := make([]row, 0, len(out)) for _, x := range out { s.opt.Store.Enrich(&x) rows = append(rows, row{x.IP, x.Score, x.Last, x.Hosts, x.CC, x.Country, x.City, x.ASN, x.ASOrg}) } writeJSON(w, 200, map[string]any{"generated": s.opt.Now().Unix(), "range": rg.Info(s.opt.Now().Unix()), "min_score": min, "count": len(rows), "ips": rows}) return } w.Header().Set("Content-Type", "text/plain; charset=utf-8") var b strings.Builder for _, x := range out { b.WriteString(x.IP) b.WriteByte('\n') } w.Write([]byte(b.String())) } } func (s *Server) traffic(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() rg, ok := s.rangeOf(w, r) if !ok { return } domain := q.Get("domain") if domain == "" { domain = "all" } host := q.Get("host") if host == "" { host = "all" } self := s.opt.Store.Name() if !s.knownHost(w, host) { return } var parts []store.TrafficData if host == "all" || host == self { parts = append(parts, s.opt.Store.TrafficFor(rg, domain)) } if s.opt.Hub != nil && host != self { only := "" if host != "all" { only = host } parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, domain, only)...) } out := store.MergeTraffic(host, parts) out.Domain = domain writeJSON(w, 200, out) } // blockAddr parses a table key (address or IPv6 /64 prefix) into the address // that represents it. Zones and garbage are refused. func blockAddr(key string) (netip.Addr, bool) { if a, err := netip.ParseAddr(key); err == nil { return a, a.Zone() == "" } if p, err := netip.ParsePrefix(key); err == nil && p.Addr().Is6() && p.Bits() == 64 && p.Addr().Zone() == "" { return p.Addr(), true } return netip.Addr{}, false } // hostAllowed checks the Host header against loopback names and the extra list. func hostAllowed(host string, extra []string) bool { h := strings.ToLower(host) if i := strings.LastIndexByte(h, ':'); i >= 0 && !strings.HasSuffix(h, "]") { h = h[:i] } h = strings.Trim(h, "[]") switch h { case "localhost", "127.0.0.1", "::1": return true } for _, e := range extra { if h == strings.ToLower(e) { return true } } return false }