diff --git a/CHANGELOG.md b/CHANGELOG.md index 26b34ad..f6ce06d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow SemVer. +## [1.5.0] - 2026-11-15 + +### Added + +- Incident management: every egress finding (severity above info) becomes a ticket `INC-` keyed by `host|kind|workload|dst|dport|proto`, created by a sync on each merged egress report and every 60 s. Tickets have status (`open`, `investigating`, `true_positive`, `false_positive`, `benign`, `resolved`), severity, assignee, tags, verdict, comments and a change history; a resolved ticket reopens when the finding reappears. Stored in `/incidents.json` (atomic write, 0600; a corrupt file is moved to `.corrupt`); limits of 5000 tickets, 200 comments and 500 history entries each. Every write is also logged (id, field, author). +- A ticket in `false_positive` or `benign` can suppress the findings with exactly its key: they leave `/api/v1/egress` (and the egress report) unless `?suppressed=1`. Findings now carry `ticket_id`, `ticket_status` and `suppressed`, and the response has `suppressed_count`. +- API: `GET /api/v1/incidents`, `GET /api/v1/incidents/{id}`, `POST /api/v1/incidents`, `PATCH /api/v1/incidents/{id}`, `POST /api/v1/incidents/{id}/comments` and `GET /api/v1/incidents/export.csv` (not open to the peer token; writes refuse cross-site requests). + ## [1.4.8] - 2026-11-15 ### Fixed diff --git a/CHANGELOG.pt-BR.md b/CHANGELOG.pt-BR.md index 6cf53b2..eec5586 100644 --- a/CHANGELOG.pt-BR.md +++ b/CHANGELOG.pt-BR.md @@ -4,6 +4,14 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/); versionamento segue SemVer. +## [1.5.0] - 2026-11-15 + +### Adicionado + +- Gestão de incidentes: cada achado de egress (severidade acima de info) vira um chamado `INC-` com chave `host|kind|workload|dst|dport|proto`, criado por uma sincronização a cada relatório de egress mesclado e a cada 60 s. O chamado tem status (`open`, `investigating`, `true_positive`, `false_positive`, `benign`, `resolved`), severidade, responsável, etiquetas, conclusão, comentários e histórico de mudanças; um chamado resolvido reabre quando o achado reaparece. Fica em `/incidents.json` (escrita atômica, 0600; arquivo corrompido vai para `.corrupt`); limites de 5000 chamados, 200 comentários e 500 entradas de histórico cada. Toda escrita também vai para o log (id, campo, autor). +- Um chamado em `false_positive` ou `benign` pode suprimir os achados com exatamente a sua chave: eles saem de `/api/v1/egress` (e do relatório de egress), salvo com `?suppressed=1`. Os achados agora trazem `ticket_id`, `ticket_status` e `suppressed`, e a resposta tem `suppressed_count`. +- API: `GET /api/v1/incidents`, `GET /api/v1/incidents/{id}`, `POST /api/v1/incidents`, `PATCH /api/v1/incidents/{id}`, `POST /api/v1/incidents/{id}/comments` e `GET /api/v1/incidents/export.csv` (fechada ao token de peer; escritas recusam requisições cross-site). + ## [1.4.8] - 2026-11-15 ### Corrigido diff --git a/docs/interface.md b/docs/interface.md index 5215204..6278fd7 100644 --- a/docs/interface.md +++ b/docs/interface.md @@ -138,6 +138,12 @@ State and city boundaries on the Geography page are from [Natural Earth](https:/ | `GET /api/v1/events/stream` | session or bearer | Server-Sent Events, event `ev`, a ping every 20 s. With `visits=1` it also sends anonymous `visit` events (no address, at most 20 per second) | | `GET /api/v1/blocklist.txt` | session or bearer | one IP per line. Query: `min_score` (default 50), `range` (default `7d`), `host`, `family` (`4`, `6`; default both; `4` suits `ipset hash:ip`), `download=1` | | `GET /api/v1/blocklist.json` | session or bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; the `ip` of an IPv6 entry is a `/64` prefix | +| `GET /api/v1/incidents` | session or bearer | incident tickets (no comments or history, with `comment_count`). Query: `status` (comma list), `severity`, `host`, `q`, `sort` (`updated`, `severity`, `last_seen`), `page`, `per_page` (max 200). Returns `{items,total,counts}` | +| `GET /api/v1/incidents/{id}` | session or bearer | full ticket with `comments` and `history` | +| `GET /api/v1/incidents/export.csv` | session or bearer | the filtered list as CSV | +| `POST /api/v1/incidents` | session or bearer | opens a manual ticket `{title,detail,severity,host,tags,author}` (body up to 64 KiB, unknown fields refused; cross-site refused) | +| `PATCH /api/v1/incidents/{id}` | session or bearer | partial update `{status,severity,assignee,tags,title,verdict,suppress,author}`; each change is a history entry. `suppress` only in `false_positive` or `benign`, and hides findings with the exact same key in `/api/v1/egress` (add `suppressed=1` to see them) | +| `POST /api/v1/incidents/{id}/comments` | session or bearer | adds a comment `{text,author}` | An invalid `range` or period answers 400, and `range` in the responses is an object `{name,from,to,step,clipped}` (`step` is the timeline granularity in seconds). diff --git a/docs/pt-BR/interface.md b/docs/pt-BR/interface.md index ee48645..d062f4e 100644 --- a/docs/pt-BR/interface.md +++ b/docs/pt-BR/interface.md @@ -135,6 +135,12 @@ Os limites de estados e cidades da página Geografia são do [Natural Earth](htt | `GET /api/v1/events/stream` | sessão ou bearer | Server-Sent Events, evento `ev`, um ping a cada 20 s. Com `visits=1` também envia eventos `visit` anônimos (sem endereço, no máximo 20 por segundo) | | `GET /api/v1/blocklist.txt` | sessão ou bearer | um IP por linha. Query: `min_score` (padrão 50), `range` (padrão `7d`), `host`, `family` (`4`, `6`; padrão ambos; `4` serve ao `ipset hash:ip`), `download=1` | | `GET /api/v1/blocklist.json` | sessão ou bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; o `ip` de uma entrada IPv6 é um prefixo `/64` | +| `GET /api/v1/incidents` | sessão ou bearer | chamados de incidente (sem comentários e histórico, com `comment_count`). Query: `status` (lista separada por vírgula), `severity`, `host`, `q`, `sort` (`updated`, `severity`, `last_seen`), `page`, `per_page` (máx. 200). Devolve `{items,total,counts}` | +| `GET /api/v1/incidents/{id}` | sessão ou bearer | chamado completo, com `comments` e `history` | +| `GET /api/v1/incidents/export.csv` | sessão ou bearer | a lista filtrada em CSV | +| `POST /api/v1/incidents` | sessão ou bearer | abre um chamado manual `{title,detail,severity,host,tags,author}` (corpo até 64 KiB, campos desconhecidos recusados; cross-site recusado) | +| `PATCH /api/v1/incidents/{id}` | sessão ou bearer | atualização parcial `{status,severity,assignee,tags,title,verdict,suppress,author}`; cada mudança vira uma entrada no histórico. `suppress` só em `false_positive` ou `benign`, e esconde de `/api/v1/egress` os achados com exatamente a mesma chave (use `suppressed=1` para vê-los) | +| `POST /api/v1/incidents/{id}/comments` | sessão ou bearer | adiciona um comentário `{text,author}` | Um `range` ou período inválido responde 400, e `range` nas respostas é um objeto `{name,from,to,step,clipped}` (`step` é a granularidade da linha do tempo em segundos). diff --git a/internal/app/serve.go b/internal/app/serve.go index d925812..8d8abbb 100644 --- a/internal/app/serve.go +++ b/internal/app/serve.go @@ -20,6 +20,7 @@ import ( "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/rdns" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" @@ -99,8 +100,13 @@ func Serve(c Config) error { tproxy, _ := core.ParseCIDRs(c.TrustedProxy) ign, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted) bindHost, _, _ := net.SplitHostPort(c.Bind) + incStore, err := incidents.Open(filepath.Join(c.DataDir, "incidents.json"), log) + if err != nil { + return err + } h := server.New(server.Options{Token: token, PeerTokens: c.PeerTokens, PeerAllow: allow, TrustedProxy: tproxy, Ignore: ign, - AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: st, Hub: hub}) + AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: st, Hub: hub, + Incidents: incStore}) egressSrc, err := newEgress(c, st, log) if err != nil { return err @@ -132,6 +138,7 @@ func Serve(c Config) error { go func() { defer wg.Done(); elog.Run(ctx) }() } runner.Start(ctx, offsets, &wg) + server.StartIncidentSync(ctx, &wg) if egressSrc != nil { egressSrc.Start(ctx, &wg) } diff --git a/internal/app/version.go b/internal/app/version.go index 6e71e37..15e6dec 100644 --- a/internal/app/version.go +++ b/internal/app/version.go @@ -2,4 +2,4 @@ package app // Version is the release version (SemVer). Release builds may override it with // -ldflags "-X .../internal/app.Version=...". -var Version = "1.4.8" +var Version = "1.5.0" diff --git a/internal/egress/report.go b/internal/egress/report.go index ed6d8e3..a7f1558 100644 --- a/internal/egress/report.go +++ b/internal/egress/report.go @@ -22,6 +22,10 @@ type Finding struct { Last int64 `json:"last"` Detail string `json:"detail"` Host string `json:"host,omitempty"` + // Ticket fields are filled by the server from the incident store. + TicketID string `json:"ticket_id"` + TicketStatus string `json:"ticket_status"` + Suppressed bool `json:"suppressed"` // Samples are the unix times of the last connections (beacons only, at most MaxSamples). Samples []int64 `json:"samples,omitempty"` } @@ -286,6 +290,15 @@ func clip(s string) string { } // Sanitize bounds an untrusted peer report and stamps it with the peer name. +// KnownKind reports whether k is a finding kind produced by the engine. +func KnownKind(k string) bool { + switch k { + case "scan", "bad_dst", "tor", "port", "dns_bypass", "new_geo", "beacon", "infra": + return true + } + return false +} + func (r *Report) Sanitize(host string) { if len(r.Workloads) > maxPeerWorkloads { r.Workloads = r.Workloads[:maxPeerWorkloads] @@ -303,6 +316,14 @@ func (r *Report) Sanitize(host string) { w := &r.Workloads[i] w.Name, w.Role, w.Host = clip(w.Name), clip(w.Role), host } + // a peer may send only the kinds this package produces; the rest is dropped + kept := r.Findings[:0] + for _, f := range r.Findings { + if KnownKind(f.Kind) { + kept = append(kept, f) + } + } + r.Findings = kept for i := range r.Findings { f := &r.Findings[i] f.ID, f.Kind, f.Severity = host+":"+clip(f.ID), clip(f.Kind), clip(f.Severity) diff --git a/internal/incidents/incidents.go b/internal/incidents/incidents.go new file mode 100644 index 0000000..34fc1b4 --- /dev/null +++ b/internal/incidents/incidents.go @@ -0,0 +1,1002 @@ +// Package incidents keeps the tickets ("chamados") opened from egress findings +// or by hand: status, verdict, comments and a change history, persisted in +// /incidents.json. A ticket in false_positive or benign may suppress +// the findings with exactly its key. +package incidents + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log/slog" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + "time" + "unicode/utf8" +) + +// Limits. +const ( + MaxTickets = 5000 + MaxComments = 200 + MaxHistory = 500 + MaxTags = 10 + MaxTagLen = 32 + MaxTitle = 200 + MaxLong = 4000 // verdict, detail + MaxComment = 5000 + MaxShort = 64 // author, assignee + MaxHost = 253 + DefaultAuth = "operator" + Robot = "urutau" +) + +var ( + // ErrNotFound: no ticket with that id. + ErrNotFound = errors.New("incident not found") + // ErrInvalid wraps every validation failure (HTTP 400). + ErrInvalid = errors.New("invalid") + // ErrConflict: a refused suppression or a stale expected_updated_at (HTTP 409). + ErrConflict = errors.New("conflict") +) + +func conflict(format string, a ...any) error { + return fmt.Errorf("%w: %s", ErrConflict, fmt.Sprintf(format, a...)) +} + +// Suppression and flood policy. +const ( + SuppressTTL = 30 * 24 * time.Hour + SuppressMax = 90 * 24 * time.Hour + HostQuota = 300 // active (open/investigating) tickets per host before grouping + SaveDebounce = 30 * time.Second + floodTailKeep = 5 + floodHead = "last grouped destinations:" +) + +func invalid(format string, a ...any) error { + return fmt.Errorf("%w: %s", ErrInvalid, fmt.Sprintf(format, a...)) +} + +var ( + statuses = []string{"open", "investigating", "true_positive", "false_positive", "benign", "resolved"} + severities = []string{"info", "low", "medium", "high", "critical"} +) + +// Statuses lists the valid statuses. +func Statuses() []string { return append([]string(nil), statuses...) } + +func inList(l []string, v string) bool { + for _, x := range l { + if x == v { + return true + } + } + return false +} + +// SevRank orders severities (unknown = -1). +func SevRank(s string) int { + for i, x := range severities { + if x == s { + return i + } + } + return -1 +} + +func suppressible(status string) bool { return status == "false_positive" || status == "benign" } +func closed(status string) bool { + return status == "resolved" || status == "false_positive" || status == "benign" +} + +// Comment is one note on a ticket. +type Comment struct { + ID int `json:"id"` + At int64 `json:"at"` + Author string `json:"author"` + Text string `json:"text"` +} + +// Change is one history entry. +type Change struct { + At int64 `json:"at"` + Author string `json:"author"` + Field string `json:"field"` + From string `json:"from"` + To string `json:"to"` +} + +type base struct { + ID string `json:"id"` + Key string `json:"key"` + Source string `json:"source"` + Host string `json:"host"` + Kind string `json:"kind"` + Severity string `json:"severity"` + MaxSeverity string `json:"max_severity"` + Workload string `json:"workload"` + Dst string `json:"dst"` + DPort uint16 `json:"dport"` + Proto string `json:"proto"` + Title string `json:"title"` + Detail string `json:"detail"` + FirstSeen int64 `json:"first_seen"` + LastSeen int64 `json:"last_seen"` + Count int `json:"count"` + Status string `json:"status"` + Verdict string `json:"verdict"` + Assignee string `json:"assignee"` + Tags []string `json:"tags"` + Suppress bool `json:"suppress"` + CreatedAt int64 `json:"created_at"` + UpdatedAt int64 `json:"updated_at"` + // SuppressedSev is the highest severity when the ticket was closed as FP/benign; + // a worse finding reopens it. SuppressUntil ends a suppression (unix s). + SuppressedSev string `json:"suppressed_sev"` + SuppressedAt int64 `json:"suppressed_at"` + SuppressUntil int64 `json:"suppress_until"` + SeverityManual bool `json:"severity_manual"` +} + +// Ticket is a full incident. +type Ticket struct { + base + Comments []Comment `json:"comments"` + History []Change `json:"history"` +} + +// Summary is a ticket without comments and history. +type Summary struct { + base + CommentCount int `json:"comment_count"` +} + +// Finding is what Sync reads from an egress finding. +type Finding struct { + Host, Kind, Severity, Workload, Dst, Proto, Detail string + DPort uint16 + First, Last int64 + Count int +} + +// Key identifies a finding: sha256 (hex) of host, kind, workload, dst, dport and +// proto, each with its length in front so no value can mimic a separator. +func Key(host, kind, workload, dst string, dport uint16, proto string) string { + h := sha256.New() + for _, f := range []string{host, kind, workload, dst, strconv.Itoa(int(dport)), proto} { + h.Write([]byte(strconv.Itoa(len(f)) + ":" + f)) + } + return hex.EncodeToString(h.Sum(nil)) +} + +func floodKey(host string) string { return Key(host, "flood", "", "", 0, "") } + +// Key of the finding. +func (f Finding) Key() string { return Key(f.Host, f.Kind, f.Workload, f.Dst, f.DPort, f.Proto) } + +// Ref is the light view of a ticket used to annotate findings. +type Ref struct { + ID string + Status string + Suppress bool +} + +// Store is the persistent set of tickets. +type Store struct { + mu sync.Mutex + path string + log *slog.Logger + now func() time.Time + byID map[string]*Ticket + byKey map[string]*Ticket + next int + + untracked int // findings dropped because the store was full + dirty bool // counters changed, not yet written + lastSave time.Time // of the last write + flooded map[string]bool // keys grouped into flood tickets (not persisted) +} + +type disk struct { + Next int `json:"next"` + Tickets []*Ticket `json:"tickets"` +} + +// Open loads path (created on the first write). A corrupt file is renamed to +// path+".corrupt-