Files
urutau/internal/server/investigate.go
T
Lucas RayanandClaude Opus 5.5 432f521ed1
Release / Publish tags (push) Successful in 18s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 1m47s
Release / Build image (amd64) (push) Successful in 21s
Release / Build image (arm64) (push) Successful in 28s
CI / Format and vet (push) Successful in 23s
CI / Tests (Linux, race detector) (push) Successful in 1m24s
CI / Dependency audit (push) Successful in 24s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 5s
feat: 1.4.1 pagination, network probes, survival by blocker, report polish
Backend pagination with one pager for sessions, IPs, campaigns and events;
network probe source (port-scan, T1046, second firewall reason port-scan);
host kit logs inbound probes; urutau call on the report cover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:21:43 -03:00

884 lines
27 KiB
Go

package server
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/netip"
"net/url"
"sort"
"strconv"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func badRequest(w http.ResponseWriter, msg string) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": msg})
}
// eventFilter parses the filters shared by the registry endpoints.
func (s *Server) eventFilter(w http.ResponseWriter, r *http.Request, defaultSpan time.Duration) (store.EventsQuery, bool) {
q := r.URL.Query()
var eq store.EventsQuery
if q.Get("range") == "" && q.Get("from") == "" {
now := s.opt.Now().Unix()
q.Set("from", strconv.FormatInt(now-int64(defaultSpan/time.Second), 10))
r.URL.RawQuery = q.Encode()
}
rg, ok := s.rangeOf(w, r)
if !ok {
return eq, false
}
eq.From, eq.To = rg.Bounds(s.opt.Now().Unix())
eq.Host = q.Get("host")
if eq.Host == "all" {
eq.Host = ""
}
if len(eq.Host) > 64 {
badRequest(w, "invalid host")
return eq, false
}
if ip := q.Get("ip"); ip != "" {
_, err1 := netip.ParseAddr(ip)
_, err2 := netip.ParsePrefix(ip)
if err1 != nil && err2 != nil {
badRequest(w, "invalid ip")
return eq, false
}
eq.IP = ip
}
if cats := q.Get("cat"); cats != "" {
for _, c := range strings.Split(cats, ",") {
if core.Category(c).Index() < 0 {
badRequest(w, "invalid cat")
return eq, false
}
}
eq.Cat = cats
}
if eq.Q = q.Get("q"); len(eq.Q) > 200 {
badRequest(w, "q too long")
return eq, false
}
if eq.Fam = q.Get("fam"); len(eq.Fam) > 40 {
badRequest(w, "invalid fam")
return eq, false
}
return eq, true
}
// eventsAPI: GET /api/v1/events (also /api/v1/period/events, ascending by default).
func (s *Server) eventsAPI(w http.ResponseWriter, r *http.Request) { s.eventsPage(w, r, true) }
func (s *Server) periodEvents(w http.ResponseWriter, r *http.Request) { s.eventsPage(w, r, false) }
func (s *Server) eventsPage(w http.ResponseWriter, r *http.Request, desc bool) {
eq, ok := s.eventFilter(w, r, 24*time.Hour)
if !ok {
return
}
q := r.URL.Query()
eq.Desc = desc
switch q.Get("order") {
case "":
case "asc":
eq.Desc = false
case "desc":
eq.Desc = true
default:
badRequest(w, "invalid order")
return
}
eq.Limit = 200
if v := q.Get("limit"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
badRequest(w, "invalid limit")
return
}
eq.Limit = min(n, evlog.MaxLimit)
}
eq.Cursor = q.Get("cursor")
if len(eq.Cursor) > 100 {
badRequest(w, "invalid cursor")
return
}
if q.Get("page") != "" {
s.eventsNumbered(w, q, eq)
return
}
page, err := s.opt.Store.QueryEvents(eq)
if errors.Is(err, evlog.ErrBusy) {
w.Header().Set("Retry-After", "5")
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "busy"})
return
}
if err != nil {
badRequest(w, "invalid cursor")
return
}
writeJSON(w, 200, page)
}
// eventsNumbered answers /api/v1/events?page=N&per_page=M: the Nth page of the
// same ordered log. The log is cursor-addressed, so the first (N-1)*M rows are
// walked to find the cursor (at most evlog.MaxLimit of them: deeper pages are
// empty and the client narrows the filter). total is the log's estimate.
func (s *Server) eventsNumbered(w http.ResponseWriter, q url.Values, eq store.EventsQuery) {
page, per := pageParams(q)
eq.Cursor = ""
skip := (page - 1) * per
fail := func(err error) {
if errors.Is(err, evlog.ErrBusy) {
w.Header().Set("Retry-After", "5")
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "busy"})
return
}
badRequest(w, "invalid cursor")
}
var out store.EventsPage
if skip <= evlog.MaxLimit {
cur := ""
if skip > 0 {
eq.Limit = skip
head, err := s.opt.Store.QueryEvents(eq)
if err != nil {
fail(err)
return
}
out.TotalEstimate = head.TotalEstimate
out.Enabled = head.Enabled
if len(head.Events) >= skip && head.Next != "" {
cur = head.Next
}
}
if skip == 0 || cur != "" {
eq.Limit, eq.Cursor = per, cur
var err error
if out, err = s.opt.Store.QueryEvents(eq); err != nil {
fail(err)
return
}
}
}
if out.Events == nil {
out.Events = []json.RawMessage{}
}
total := int(max(out.TotalEstimate, 0))
if !out.Truncated && total < skip+len(out.Events) {
total = skip + len(out.Events)
}
writeJSON(w, 200, struct {
store.EventsPage
pageTotal
}{out, pageTotal{metaOf(total, page, per), total}})
}
// sessionsAPI: GET /api/v1/events/sessions?from&to&host&gap=900
func (s *Server) sessionsAPI(w http.ResponseWriter, r *http.Request) {
eq, ok := s.eventFilter(w, r, 24*time.Hour)
if !ok {
return
}
gap := int64(900)
if v := r.URL.Query().Get("gap"); v != "" {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n < 30 || n > 86400 {
badRequest(w, "gap must be 30..86400 seconds")
return
}
gap = n
}
list, trunc := s.opt.Store.Sessions(eq.From, eq.To, eq.Host, eq.IP, gap)
sort.SliceStable(list, func(i, j int) bool {
a, b := list[i], list[j]
if a.Start != b.Start {
return a.Start < b.Start
}
if a.IP != b.IP {
return a.IP < b.IP
}
return a.End < b.End
})
page, per := pageParams(r.URL.Query())
from, to := window(len(list), page, per)
writeJSON(w, 200, struct {
Sessions []store.Session `json:"sessions"`
Gap int64 `json:"gap"`
Truncated bool `json:"truncated"`
Enabled bool `json:"enabled"`
pageTotal
}{list[from:to], gap, trunc, s.opt.Store.EventLog() != nil, pageTotal{metaOf(len(list), page, per), len(list)}})
}
// studyHosts resolves the host selection of period and metrics: whether the
// local study is wanted and which peers to ask. It answers 404 itself.
func (s *Server) studyHosts(w http.ResponseWriter, host string) (local bool, peers bool, only string, ok bool) {
self := s.opt.Store.Name()
if host == "" || host == "all" {
return true, s.opt.Hub != nil, "", true
}
if host == self {
return true, false, "", true
}
if s.opt.Hub == nil || !s.opt.Hub.Has(host) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
return false, false, "", false
}
return false, true, host, true
}
// userSlot admits one more user-side study (503 with Retry-After when four run).
func (s *Server) userSlot(w http.ResponseWriter) bool {
select {
case s.user <- struct{}{}:
return true
default:
w.Header().Set("Retry-After", "5")
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "busy"})
return false
}
}
// periodAPI: GET /api/v1/period (local, merged with the peers' studies)
func (s *Server) periodAPI(w http.ResponseWriter, r *http.Request) {
eq, ok := s.eventFilter(w, r, 24*time.Hour)
if !ok {
return
}
if !s.userSlot(w) {
return
}
defer func() { <-s.user }()
pq := store.PeriodQuery{From: eq.From, To: eq.To, IP: eq.IP, Cat: eq.Cat, Fam: eq.Fam}
if v := r.URL.Query().Get("gap"); v != "" {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n < 60 || n > 86400 {
badRequest(w, "gap must be 60..86400 seconds")
return
}
pq.Gap = n
}
local, peers, only, ok := s.studyHosts(w, eq.Host)
if !ok {
return
}
var parts []store.PeriodOut
var studies map[string]store.PeerStudy
if peers {
studies = s.opt.Hub.StudiesFor(r.Context(), pq, only)
}
if local || len(studies) == 0 {
lq := pq
switch {
case !local: // a peer that did not answer: what was relayed from it to this hub
lq.Host = only
case s.opt.Hub != nil:
lq.Host = s.opt.Store.Name() // events relayed from peers are theirs: no double counting
}
parts = append(parts, s.opt.Store.Period(lq))
}
for _, p := range s.opt.Hub.PeerNames() {
if st, ok := studies[p]; ok {
parts = append(parts, st.Period)
}
}
out := store.MergePeriods(parts)
rg, _ := s.opt.Store.ResolveRange(r.URL.Query().Get("range"), r.URL.Query().Get("from"), r.URL.Query().Get("to"))
out.Range = rg.Info(s.opt.Now().Unix())
if len(parts) > 1 || peers {
out.EventsCursor = parts[0].EventsCursor
}
writeJSON(w, 200, out)
}
// metricsAPI: GET /api/v1/metrics?range=&host=
func (s *Server) metricsAPI(w http.ResponseWriter, r *http.Request) {
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
local, peers, only, ok := s.studyHosts(w, r.URL.Query().Get("host"))
if !ok {
return
}
if !s.userSlot(w) {
return
}
defer func() { <-s.user }()
var parts []store.MetricsOut
var studies map[string]store.PeerStudy
if peers {
now := s.opt.Now().Unix()
from, to := rg.Bounds(now)
studies = s.opt.Hub.StudiesFor(r.Context(), store.PeriodQuery{From: from, To: to}, only)
}
if local || len(studies) == 0 {
parts = append(parts, s.opt.Store.Metrics(rg))
}
for _, p := range s.opt.Hub.PeerNames() {
if st, ok := studies[p]; ok {
parts = append(parts, st.Metrics)
}
}
out := store.MergeMetrics(parts)
out.Range = rg.Info(s.opt.Now().Unix())
writeJSON(w, 200, out)
}
// peerPeriod: GET /api/v1/peer/period, the study a hub merges; opened only by
// the peer token (and --peer-allow). At most two run at once.
func (s *Server) peerPeriod(w http.ResponseWriter, r *http.Request) {
if !s.peerGate(w, r) {
return
}
select {
case s.study <- struct{}{}:
defer func() { <-s.study }()
default:
w.Header().Set("Retry-After", "5")
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "busy"})
return
}
eq, ok := s.eventFilter(w, r, 24*time.Hour)
if !ok {
return
}
pq := store.PeriodQuery{From: eq.From, To: eq.To, Host: s.opt.Store.Name(), IP: eq.IP, Cat: eq.Cat, Fam: eq.Fam}
if v := r.URL.Query().Get("gap"); v != "" {
if n, err := strconv.ParseInt(v, 10, 64); err == nil && n >= 30 && n <= 86400 {
pq.Gap = n
}
}
writeJSON(w, 200, s.opt.Store.StudyFor(pq))
}
// listed reproduces the blocklist rule for one row.
func (s *Server) listed(x store.IPSummary) bool {
if x.Score < 50 || !x.Strong || x.Admin {
return false
}
addr, ok := blockAddr(x.IP)
return ok && core.IsGlobal(addr) && !core.Ignored(s.opt.Ignore, addr.String())
}
func linksFor(ip string) map[string]string {
a := ip
if p, err := netip.ParsePrefix(ip); err == nil {
a = p.Addr().String()
}
e := url.PathEscape(a)
return map[string]string{
"abuseipdb": "https://www.abuseipdb.com/check/" + e,
"greynoise": "https://viz.greynoise.io/ip/" + e,
"shodan": "https://www.shodan.io/host/" + e,
"censys": "https://search.censys.io/hosts/" + e,
"virustotal": "https://www.virustotal.com/gui/ip-address/" + e,
"bgphe": "https://bgp.he.net/ip/" + e,
"ripestat": "https://stat.ripe.net/" + e,
}
}
type countsOut = []store.Count
type exposureOut struct {
T int64 `json:"t"`
Host string `json:"host"`
Domain string `json:"domain"`
Path string `json:"path"`
Status int `json:"status"`
Bytes int64 `json:"bytes"`
Fam string `json:"fam"`
}
type ipDetailOut struct {
store.IPSummary
Hosts countsOut `json:"hosts"`
Domains countsOut `json:"domains"`
UAs countsOut `json:"uas"`
Admin bool `json:"admin"`
Range store.RangeInfo `json:"range"`
Verdict map[string]any `json:"verdict"`
Exposure []exposureOut `json:"exposure"`
Actions []intel.Action `json:"actions"`
Identity map[string]any `json:"identity"`
Geo map[string]any `json:"geo"`
Time map[string]any `json:"time"`
Cadence intel.Cadence `json:"cadence"`
Techniques []map[string]any `json:"techniques"`
Families []map[string]any `json:"families"`
Targets []map[string]any `json:"targets"`
Tools map[string]any `json:"tools"`
SSH map[string]any `json:"ssh"`
StatusHist map[string]uint32 `json:"status_hist"`
Timeline *store.IPTimeline `json:"timeline"`
TimelineSource string `json:"timeline_source"`
Statuses countsOut `json:"statuses"`
Methods countsOut `json:"methods"`
Paths countsOut `json:"paths"`
Users countsOut `json:"users"`
Sessions []intel.Session `json:"sessions"`
Escalation []intel.Step `json:"escalation"`
Related map[string]any `json:"related"`
Neighbors map[string]any `json:"neighbors"`
Bans []store.BanEvent `json:"bans"`
BanHistory []store.BanEvent `json:"ban_history"`
TTBs int64 `json:"ttb_s"`
Blocklisted bool `json:"blocklisted"`
Blocklist map[string]any `json:"blocklist"`
ScoreBreakdown map[string]float64 `json:"score_breakdown"`
StrongReasons []string `json:"strong_reasons"`
Links map[string]string `json:"links"`
Log map[string]any `json:"log"`
Events []map[string]any `json:"events"`
BansSource string `json:"bans_source"`
SessionsSource string `json:"sessions_source"`
EventsSource string `json:"events_source"`
TechniquesSource string `json:"techniques_source"`
FamiliesSource string `json:"families_source"`
SSHSource string `json:"ssh_source"`
}
func orEmpty[T any](l []T) []T {
if l == nil {
return []T{}
}
return l
}
func (s *Server) buildIPDetail(m store.IPSummary, key string, rg store.Range) ipDetailOut {
st := s.opt.Store
now := s.opt.Now().Unix()
from, to := rg.Bounds(now)
il := st.IPLogOf(key, from, to)
info, _ := st.IPInfoOf(key)
d := ipDetailOut{IPSummary: m, Range: rg.Info(now)}
d.Admin = m.Admin
d.Hosts, d.Domains, d.UAs = orEmpty(il.Hosts), orEmpty(il.Domains), orEmpty(il.UAs)
if len(il.Hosts) == 0 { // no registry: fall back to what the table keeps
for _, h := range m.Hosts {
d.Hosts = append(d.Hosts, store.Count{Key: h})
}
for _, x := range m.Domains {
d.Domains = append(d.Domains, store.Count{Key: x})
}
for _, x := range m.UAs {
d.UAs = append(d.UAs, store.Count{Key: x, Label: st.UALabel(x)})
}
}
d.TimelineSource = il.Source
d.Timeline, d.Statuses, d.Methods, d.Paths, d.Users = il.Timeline, orEmpty(il.Statuses), orEmpty(il.Methods), orEmpty(il.Paths), orEmpty(il.Users)
if len(il.Users) == 0 {
for _, u := range info.Users {
d.Users = append(d.Users, store.Count{Key: u.U, N: u.N})
}
}
d.Sessions, d.Escalation, d.Cadence = orEmpty(il.Sessions), orEmpty(il.Escalation), il.Cadence
d.Bans = activeBans(il.Bans, info, st.Name())
d.BanHistory = d.Bans
d.BansSource = "events"
if len(il.Bans) == 0 && len(d.Bans) > 0 {
d.BansSource = "counters"
}
d.SessionsSource, d.EventsSource, d.TechniquesSource, d.FamiliesSource, d.SSHSource = "events", "events", "events", "events", "events"
covered := il.Events > 0
if !covered {
// the registry has nothing for this address (it began after the events,
// or the data directory was replaced): derive from the record's counters
d.EventsSource = "counters"
d.Sessions = counterSessions(key, info, st.Name())
d.SessionsSource = "counters"
d.Events = counterEvents(info)
} else {
d.Events = []map[string]any{}
if page, err := st.QueryEvents(store.EventsQuery{From: from, To: to, IP: key, Desc: true, Limit: 50}); err == nil {
for _, raw := range page.Events {
var ev map[string]any
if json.Unmarshal(raw, &ev) == nil {
d.Events = append(d.Events, ev)
}
}
}
}
d.TTBs = info.TTB
d.ScoreBreakdown, d.StrongReasons = info.ScoreBreakdown, orEmpty(info.StrongReasons)
d.Links = linksFor(key)
var recorded uint32
for _, c := range []core.Category{core.Scanner, core.Exploit, core.BruteForce, core.SSHFail, core.SSHProbe, core.SSHOK, core.Ban} {
recorded += info.Counts[c.Index()]
}
d.Log = map[string]any{"available": il.Available, "events": il.Events, "truncated": il.Truncated, "sessions_n": il.SessionsN, "sessions_events": il.SessionsEv,
"partial": il.Events > 0 && float64(il.Events) < 0.9*float64(recorded)}
d.Blocklisted = s.listed(m)
bl := map[string]any{"listed": d.Blocklisted}
if d.Blocklisted {
bl["since"] = m.First
if info.ListedSince > 0 {
bl["since"] = info.ListedSince
}
}
d.Blocklist = bl
g := st.GeoOf(key)
rdns := m.RDNS
netType, netReason := intel.NetType(g.ASN, g.ASOrg, rdns)
if a, err := netip.ParseAddr(strings.SplitN(key, "/", 2)[0]); err == nil {
netType, netReason = intel.NetTypeIP(a, g.ASN, g.ASOrg, rdns)
}
prefix := ""
if a, err := netip.ParseAddr(key); err == nil {
bits := 24
if !a.Is4() {
bits = 48
}
if p, err := a.Prefix(bits); err == nil {
prefix = p.String()
}
}
var fcr any
uaKeys := make([]string, 0, len(d.UAs))
for _, u := range d.UAs {
uaKeys = append(uaKeys, u.Key)
}
if v := st.FCrDNS(key, uaKeys); v != nil {
fcr = *v
}
d.Identity = map[string]any{"rdns": rdns, "fcrdns_ok": fcr, "asn": g.ASN, "as_org": g.ASOrg, "net_type": netType, "net_type_reason": netReason, "prefix": prefix}
d.Geo = map[string]any{"cc": g.CC, "country": g.Country, "region": g.Region, "city": g.City, "approx": true}
// exposure
d.Exposure = []exposureOut{}
expo := map[string]int{}
for _, e := range info.Expo {
d.Exposure = append(d.Exposure, exposureOut{e.T, e.Host, e.Domain, e.Path, e.Status, e.Bytes, e.Fam})
if e.Fam != "" {
expo[e.Fam]++
}
}
// reasons and actions
refused := map[string]int{}
for _, f := range info.Fams {
if n := f.S[2] + f.S[3]; n > 0 {
refused[f.Fam] = int(n)
}
}
tool := ""
for _, u := range d.UAs {
if l := st.UALabel(u.Key); strings.HasSuffix(l, "(tool)") {
tool = l
break
}
}
cats := 0
for _, c := range []core.Category{core.Scanner, core.Exploit, core.BruteForce, core.SSHFail, core.SSHProbe} {
if m.Counts[string(c)] > 0 {
cats++
}
}
sshOK := m.Counts[string(core.SSHOK)] > 0 && m.Counts[string(core.SSHFail)] > 0
reasons := intel.Reasons(intel.ReasonInput{ExploitsRefused: refused, ToolUA: tool, BannedJails: m.Jails, Categories: cats,
Exposure: expo, SSHOKAfterBrute: sshOK, Admin: m.Admin})
stage := ""
for _, ss := range d.Sessions {
if intel.StageRank(ss.Stage) > intel.StageRank(stage) {
stage = ss.Stage
}
}
acts := intel.Actions(intel.ActionInput{Reasons: reasons, Banned: m.Banned, Admin: m.Admin, Stage: stage})
has := map[string]bool{}
for _, a := range acts {
has[a.Code] = true
}
top := ""
if len(reasons) > 0 {
top = reasons[0].Code
}
if !m.Admin {
if !has[intel.ActionReport] && intel.StageRank(stage) >= intel.StageRank(intel.StageProbe) {
switch netType {
case "hosting", "research-scanner", "isp-cn":
acts = append(acts, intel.Action{Code: intel.ActionReport, Priority: 4, Reason: top})
}
}
if !has[intel.ActionBlock] && m.Level == core.LevelHostile && !d.Blocklisted {
acts = append(acts, intel.Action{Code: intel.ActionBlock, Priority: 3, Reason: top})
}
if m.Level == core.LevelHostile {
if m.Banned {
acts = append(acts, intel.Action{Code: "keep_blocked", Priority: 5, Reason: top})
}
acts = append(acts, intel.Action{Code: "replay", Priority: 6, Reason: top})
}
}
d.Actions = orEmpty(acts)
d.Verdict = map[string]any{"level": m.Level, "score": m.Score, "strong": m.Strong, "admin": m.Admin, "reasons": orEmpty(reasons)}
// techniques, families, targets, tools, ssh, status
d.Techniques = []map[string]any{}
d.Families = []map[string]any{}
fams, techs := info.Fams, info.Techs
if len(fams) == 0 || len(techs) == 0 {
// a record saved before families and techniques were counted: read them from the samples
sf, stc := sampleDetail(info)
if len(fams) == 0 && len(sf) > 0 {
fams, d.FamiliesSource = sf, "samples"
}
if len(techs) == 0 && len(stc) > 0 {
techs, d.TechniquesSource = stc, "samples"
}
}
for _, t := range techs {
d.Techniques = append(d.Techniques, map[string]any{"id": t.ID, "name": intel.TechniqueName(t.ID), "n": t.N, "first": t.First, "last": t.Last})
}
for _, f := range fams {
d.Families = append(d.Families, map[string]any{"fam": f.Fam, "n": f.N,
"status": map[string]uint32{"2xx": f.S[0], "3xx": f.S[1], "4xx": f.S[2], "5xx": f.S[3]}, "examples": orEmpty(f.Ex)})
}
d.Targets = []map[string]any{}
tg := map[[2]string]int{}
for _, e := range il.Evs {
if e.Domain != "" {
tg[[2]string{e.Host, e.Domain}]++
}
}
for k, n := range tg {
d.Targets = append(d.Targets, map[string]any{"host": k[0], "domain": k[1], "service": "http", "n": n})
}
d.Targets = sortTargets(d.Targets)
labels := []string{}
uas := []string{}
for i, u := range d.UAs {
if i < 8 {
uas = append(uas, u.Key)
}
if l := st.UALabel(u.Key); l != "" && i < 8 {
labels = append(labels, l)
}
}
d.Tools = map[string]any{"uas": uas, "labels": labels, "forged": il.Forged, "rotation": len(il.UAs) > 3}
udist := []map[string]any{}
for _, u := range info.Users {
udist = append(udist, map[string]any{"user": u.U, "n": u.N, "first": u.First, "admin": st.IsAdminUser(u.U)})
}
if len(udist) == 0 && m.Counts[string(core.SSHFail)] > 0 {
// users were not counted for this record: the samples still name some
for _, sm := range info.Samples {
if u, ok := strings.CutPrefix(sm, "ssh user "); ok {
udist = append(udist, map[string]any{"user": u, "n": 0, "first": info.First, "admin": st.IsAdminUser(u)})
d.SSHSource = "samples"
}
}
}
d.SSH = map[string]any{"users": udist, "fails": m.Counts[string(core.SSHFail)], "ok_after_fail": sshOK}
d.StatusHist = map[string]uint32{"none": info.Status[0], "2xx": info.Status[1], "3xx": info.Status[2], "4xx": info.Status[3], "5xx": info.Status[4], "other": info.Status[5]}
sess, returning := len(d.Sessions), info.ActiveDays > 1
if il.Events > 0 {
sess = il.SessionsN
}
span := int((m.Last-m.First)/86400) + 1
ad := min(info.ActiveDays, span)
d.Time = map[string]any{"first": m.First, "last": m.Last, "active_days": ad, "span_days": span, "sessions_n": sess, "returning": returning, "estimated": info.Estimated}
// related
sub, asn, asnN := st.Neighbors(key, from, to)
d.Neighbors = map[string]any{"subnet": sub, "asn": asn, "asn_n": asnN}
same := []map[string]any{}
for _, n := range sub {
same = append(same, map[string]any{"ip": n.IP, "level": n.Level, "last": n.Last})
}
camps := []map[string]any{}
// campaigns of the window (cached study, window rounded to 5 minutes)
if st.EventLog() != nil {
pf, pt := from/3600*3600, (to+3599)/3600*3600 // hour-aligned: one study serves a whole hour of visits
for _, c := range st.PeriodSlow(store.PeriodQuery{From: pf, To: pt}).Campaigns {
for _, ip := range c.IPs {
if ip == key {
camps = append(camps, map[string]any{"id": c.ID, "ips_n": c.IPsN, "first": c.First, "last": c.Last, "techs": c.Techs, "signature": c.Signature})
break
}
}
}
}
d.Related = map[string]any{"same_prefix": same, "same_asn_n": asnN, "campaigns": camps}
return d
}
func sortTargets(l []map[string]any) []map[string]any {
for i := 1; i < len(l); i++ {
for j := i; j > 0 && l[j]["n"].(int) > l[j-1]["n"].(int); j-- {
l[j], l[j-1] = l[j-1], l[j]
}
}
if len(l) > 20 {
l = l[:20]
}
return l
}
// stixAPI: GET /api/v1/ip/{ip}/stix
func (s *Server) stixAPI(w http.ResponseWriter, r *http.Request) {
raw := r.PathValue("ip")
if _, ok := blockAddr(raw); !ok {
badRequest(w, "invalid ip")
return
}
key := store.KeyOf(raw)
d, ok := s.opt.Store.IP(key)
if !ok {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
return
}
info, _ := s.opt.Store.IPInfoOf(key)
var fams, techs []string
for _, f := range info.Fams {
fams = append(fams, f.Fam)
}
for _, t := range info.Techs {
techs = append(techs, t.ID)
}
n := 0
for _, c := range d.Counts {
n += int(c)
}
b, err := intel.STIXBundle(key, time.Unix(d.First, 0), time.Unix(d.Last, 0), n, fams, techs, "", s.opt.Now())
if err != nil {
badRequest(w, "cannot build the bundle")
return
}
w.Header().Set("Content-Type", "application/stix+json;version=2.1")
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="urutau-%s.stix.json"`, strings.NewReplacer(":", "_", "/", "_").Replace(key)))
w.Header().Set("Cache-Control", "no-store")
w.Write(b)
}
// activeBans marks the bans in force and makes sure an active ban is always
// listed, also when it began before the window or before the registry existed.
func activeBans(reg []store.BanEvent, info store.IPInfo, host string) []store.BanEvent {
out := append([]store.BanEvent{}, reg...)
for _, jail := range info.Jails {
last := -1
for i, b := range out {
if b.Jail == jail {
last = i
}
}
if last >= 0 && !out[last].Unban {
out[last].Active = true
continue
}
t := info.BanSince
if t == 0 {
t = info.Last
}
out = append(out, store.BanEvent{T: t, Jail: jail, Host: host, Active: true})
}
sort.SliceStable(out, func(i, j int) bool { return out[i].T < out[j].T })
return out
}
func stageOfCats(c [core.NumCats]uint16) string {
has := func(cat core.Category) bool { return c[cat.Index()] > 0 }
switch {
case has(core.Ban):
return intel.StageBanned
case has(core.SSHOK):
return intel.StageAccess
case has(core.Exploit):
return intel.StageExploit
case has(core.Scanner) || has(core.BruteForce) || has(core.SSHFail):
return intel.StageProbe
}
return intel.StageRecon
}
// counterSessions builds one session per active day from the per-day counters
// (used only when the registry has no events of the address).
func counterSessions(key string, info store.IPInfo, host string) []intel.Session {
out := []intel.Session{}
for k, row := range info.DayCats {
day := info.DayBase - int64(k)
var n int
cats := map[string]int{}
for ci, v := range row {
if v > 0 {
n += int(v)
cats[string(core.Categories[ci])] = int(v)
}
}
if n == 0 {
continue
}
start, end := day*86400, day*86400+86399
if info.First > start && info.First <= end {
start = info.First
}
if info.Last >= start && info.Last < end {
end = info.Last
}
out = append(out, intel.Session{ID: fmt.Sprintf("d-%d", day), IP: key, Start: time.Unix(start, 0).UTC(), End: time.Unix(end, 0).UTC(),
DurS: end - start, N: n, Cats: cats, Fams: map[string]int{}, Techs: []string{}, Hosts: []string{host}, Domains: orEmpty(info.Domains),
Stage: stageOfCats(row)})
}
sort.SliceStable(out, func(i, j int) bool { return out[i].Start.Before(out[j].Start) })
return out
}
// counterEvents summarises the record's events per category (what the
// registry cannot list for an address it does not cover).
func counterEvents(info store.IPInfo) []map[string]any {
out := []map[string]any{}
for i, n := range info.Counts {
if n > 0 {
out = append(out, map[string]any{"cat": string(core.Categories[i]), "n": n, "first": info.First, "last": info.Last})
}
}
return out
}
// sampleDetail derives families and techniques from the request samples kept
// in the record ("GET /path").
func sampleDetail(info store.IPInfo) ([]store.FamN, []store.TechN) {
var fams []store.FamN
techs := map[string]*store.TechN{}
for _, sm := range info.Samples {
_, path, ok := strings.Cut(sm, " ")
if !ok || !strings.HasPrefix(path, "/") {
continue
}
path, _, _ = strings.Cut(path, " [")
fam := intel.PathFamily(path)
if fam == "" {
continue
}
found := false
for i := range fams {
if fams[i].Fam == fam {
fams[i].N++
fams[i].Ex = append(fams[i].Ex, sm)
found = true
}
}
if !found {
fams = append(fams, store.FamN{Fam: fam, N: 1, Ex: []string{sm}})
}
for _, t := range intel.Techniques("scanner", fam, intel.TechCtx{Path: path}) {
if techs[t] == nil {
techs[t] = &store.TechN{ID: t, First: info.First, Last: info.Last}
}
techs[t].N++
}
}
var tl []store.TechN
for _, t := range techs {
tl = append(tl, *t)
}
sort.Slice(tl, func(i, j int) bool { return tl[i].ID < tl[j].ID })
return fams, tl
}