Files
urutau/internal/server/probes.go
T
Lucas RayanandClaude Sonnet 5.5 aefdcea8d2 feat(ingress): firewall telemetry of inbound attempts (host kit --ingress)
Observation-only nftables table (prerouting -150, counters and a
rate-limited log, never drops or modifies), a per-minute counters file,
probe sources ingress and ingresscnt, a per-host hourly aggregate in the
hub (exact totals, sampled ports/ASNs/countries, banned share by the
hub's own ban state, no ban feedback loop), GET /api/v1/ingress, a
Defense section, doctor check, docs EN/pt-BR and tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 09:09:16 -03:00

168 lines
5.6 KiB
Go

package server
import (
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/hub"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ingress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
)
// ProbeAPI is the hub side of the probe protocol and of probe management
// (implemented by *hub.Manager).
type ProbeAPI interface {
Authenticate(r *http.Request) (string, bool)
Hello(w http.ResponseWriter, r *http.Request, name string)
Push(w http.ResponseWriter, r *http.Request, name string)
Commands(w http.ResponseWriter, r *http.Request, name string)
List() []hub.ProbeInfo
Info(name string) (hub.ProbeInfo, bool)
Create(name string) (string, error)
Revoke(name string) error
UpdateProbe(name string, u hub.Update) error
}
// NodeSet gives access to the per-probe engines and ticket stores. Hosts lists
// every node, the primary first.
type NodeSet interface {
Hosts() []string
Enforce(host string) *enforce.Engine
Egress(host string) *egress.Engine
Ingress(host string) *ingress.Agg
Incidents(host string) *incidents.Store
}
// probeIngest wraps an ingest handler with the probe token check and the same
// attempt limiter as the user API. Errors carry no detail.
func (s *Server) probeIngest(h func(w http.ResponseWriter, r *http.Request, name string)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ip := clientIP(r, s.opt.TrustedProxy)
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
}
name, ok := s.opt.Probes.Authenticate(r)
if !ok {
s.lim.failure(ip)
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Cache-Control", "no-store")
h(w, r, name)
}
}
func (s *Server) probeRoutes(m *http.ServeMux) {
if s.opt.Probes == nil {
return
}
p := s.opt.Probes
m.HandleFunc("POST "+wire.PathHello, s.probeIngest(p.Hello))
m.HandleFunc("POST "+wire.PathPush, s.probeIngest(p.Push))
m.HandleFunc("GET "+wire.PathCommands, s.probeIngest(p.Commands))
m.HandleFunc("GET /api/v1/probes", s.api(func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{"probes": p.List()})
}))
m.HandleFunc("POST /api/v1/probes", s.api(func(w http.ResponseWriter, r *http.Request) {
var in struct {
Name string `json:"name"`
}
if !s.adminBody(w, r, &in) {
return
}
tok, err := p.Create(in.Name)
switch {
case errors.Is(err, hub.ErrName):
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
case errors.Is(err, hub.ErrExists):
writeJSON(w, http.StatusConflict, map[string]string{"error": err.Error()})
case err != nil:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
default:
writeJSON(w, http.StatusCreated, map[string]string{"name": in.Name, "token": tok})
}
}))
m.HandleFunc("DELETE /api/v1/probes/{name}", s.api(func(w http.ResponseWriter, r *http.Request) {
if !sameOrigin(r) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
return
}
switch err := p.Revoke(r.PathValue("name")); {
case errors.Is(err, hub.ErrNotFound):
writeJSON(w, http.StatusNotFound, map[string]string{"error": err.Error()})
case err != nil:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
default:
writeJSON(w, 200, map[string]bool{"ok": true})
}
}))
m.HandleFunc("PUT /api/v1/probes/{name}", s.api(func(w http.ResponseWriter, r *http.Request) {
var in hub.Update
if !s.adminBody(w, r, &in) {
return
}
name := r.PathValue("name")
switch err := p.UpdateProbe(name, in); {
case errors.Is(err, hub.ErrNotFound):
writeJSON(w, http.StatusNotFound, map[string]string{"error": err.Error()})
case err != nil:
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
default:
info, _ := p.Info(name)
writeJSON(w, 200, info)
}
}))
}
func (s *Server) adminBody(w http.ResponseWriter, r *http.Request, v any) bool {
if !sameOrigin(r) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
return false
}
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10))
dec.DisallowUnknownFields()
if err := dec.Decode(v); err != nil || dec.More() {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON body"})
return false
}
return true
}
// ---- per-host lookups (fall back to the package level engines, i.e. the primary) ----
func (s *Server) primaryName() string { return s.opt.Store.Name() }
// enforceFor returns the engine of a host ("" or the primary: the primary's).
func (s *Server) enforceFor(host string) *enforce.Engine {
if host == "" || strings.Contains(host, ",") || host == s.primaryName() || s.opt.Nodes == nil {
return enforceEngine.Load()
}
return s.opt.Nodes.Enforce(host)
}
func (s *Server) incStore(host string) *incidents.Store {
if host == "" || host == s.primaryName() || s.opt.Nodes == nil {
return s.opt.Incidents
}
return s.opt.Nodes.Incidents(host)
}
// incHosts lists the hosts that have a ticket store, the primary first.
func (s *Server) incHosts() []string {
if s.opt.Nodes == nil {
if s.opt.Incidents != nil {
return []string{s.primaryName()}
}
return nil
}
return s.opt.Nodes.Hosts()
}