// SPDX-License-Identifier: GPL-3.0-or-later package fleet import ( "context" "encoding/json" "fmt" "io" "sort" "strings" "time" ) // genericActions are re-run audits, not fixes; they are never listed. var genericActions = map[string]bool{"security-audit-host": true, "security-validate-host": true} // QueueRef is the newest queue entry for an (action, host) pair. type QueueRef struct { ID string `json:"id"` Status string `json:"status"` } // FlagFinding is one active flag on a host. type FlagFinding struct { Flag string `json:"flag"` Weight int `json:"weight"` OpenedAt string `json:"opened_at,omitempty"` OpenSeconds *int64 `json:"open_seconds,omitempty"` Hint string `json:"hint"` } // ActionFinding is a suggested approval action with its queue state. type ActionFinding struct { ActionID string `json:"action_id"` Queue *QueueRef `json:"queue,omitempty"` } // BackupFinding is a flagged backup job reported by the host. type BackupFinding struct { Job string `json:"job"` State string `json:"state"` Overdue bool `json:"overdue"` Reason string `json:"reason,omitempty"` } // FleetFlag is a flag present on every non-stale host, shown once. type FleetFlag struct { Flag string `json:"flag"` Weight int `json:"weight"` Hosts int `json:"hosts"` Hint string `json:"hint"` } // HostFindings is the view of one host. type HostFindings struct { Host string `json:"host"` Severity string `json:"severity"` Score int `json:"score"` Stale bool `json:"stale"` LastReportAt string `json:"last_report_at"` Flags []FlagFinding `json:"flags"` Actions []ActionFinding `json:"actions"` Backups []BackupFinding `json:"backups"` Culprits []Culprit `json:"culprits,omitempty"` } // maxCulprits bounds the known-exploited package lines printed per host. const maxCulprits = 3 const kevFlag = "known_exploited_vulnerable_package" // Findings is the model `hub findings` prints (--json prints it as is). type Findings struct { GeneratedAt string `json:"generated_at"` FleetWide []FleetFlag `json:"fleet_wide"` Hosts []HostFindings `json:"hosts"` Notes []string `json:"notes"` } type postureHost struct { Severity string `json:"severity"` Score float64 `json:"score"` Stale bool `json:"stale"` LastReportAt string `json:"last_report_at"` ActiveFlags []string `json:"active_flags"` ActionIDs []string `json:"action_ids"` } type alertRow struct { Host string `json:"host"` Flag string `json:"flag"` OpenedAt string `json:"opened_at"` Duration *float64 `json:"duration_seconds"` } type queueRow struct { ID string `json:"id"` ActionID string `json:"action_id"` Target string `json:"target"` Status string `json:"status"` CreatedAt string `json:"created_at"` UpdatedAt string `json:"updated_at"` } // RankFlags orders flags by weight descending, then name. func RankFlags(flags []string) []string { out := append([]string(nil), flags...) sort.Slice(out, func(i, j int) bool { wi, wj := FlagWeight(out[i]), FlagWeight(out[j]) if wi != wj { return wi > wj } return out[i] < out[j] }) return out } func severityRank(s string) int { switch s { case "critical_priority": return 0 case "high_priority": return 1 case "stale_audit": return 2 } return 3 } func queueStamp(q queueRow) string { if q.UpdatedAt != "" { return q.UpdatedAt } return q.CreatedAt } // BuildFindings joins the four API sections. Alerts, queue and backups may be nil (unavailable). func BuildFindings(generatedAt string, posture map[string]postureHost, alerts []alertRow, queue []queueRow, backups map[string]any, now time.Time) *Findings { f := &Findings{GeneratedAt: generatedAt, FleetWide: []FleetFlag{}, Hosts: []HostFindings{}, Notes: []string{}} // fleet-wide: on every non-stale host, with at least two such hosts fresh := 0 counts := map[string]int{} for _, h := range posture { if h.Stale { continue } fresh++ seen := map[string]bool{} for _, fl := range h.ActiveFlags { if !seen[fl] { seen[fl] = true counts[fl]++ } } } wide := map[string]bool{} if fresh >= 2 { for fl, n := range counts { if n == fresh { wide[fl] = true } } } for _, fl := range RankFlags(keysOf(wide)) { f.FleetWide = append(f.FleetWide, FleetFlag{Flag: fl, Weight: FlagWeight(fl), Hosts: fresh, Hint: FlagHint(fl)}) } // alert join: the longest-open alert per (host, flag) opened := map[[2]string]alertRow{} for _, a := range alerts { k := [2]string{a.Host, a.Flag} if old, ok := opened[k]; !ok || (a.OpenedAt != "" && (old.OpenedAt == "" || a.OpenedAt < old.OpenedAt)) { opened[k] = a } } // queue join: the newest entry per (action, target) newest := map[[2]string]queueRow{} for _, q := range queue { k := [2]string{q.ActionID, q.Target} if old, ok := newest[k]; !ok || queueStamp(q) > queueStamp(old) || (queueStamp(q) == queueStamp(old) && q.ID > old.ID) { newest[k] = q } } for name, h := range posture { hf := HostFindings{Host: name, Severity: h.Severity, Score: int(h.Score), Stale: h.Stale, LastReportAt: h.LastReportAt, Flags: []FlagFinding{}, Actions: []ActionFinding{}, Backups: []BackupFinding{}} if !h.Stale { for _, fl := range RankFlags(h.ActiveFlags) { if wide[fl] { continue } ff := FlagFinding{Flag: fl, Weight: FlagWeight(fl), Hint: FlagHint(fl)} if a, ok := opened[[2]string{name, fl}]; ok { ff.OpenedAt = a.OpenedAt switch { case a.Duration != nil: d := int64(*a.Duration) ff.OpenSeconds = &d default: if t, ok := parseTime(a.OpenedAt); ok { d := int64(now.Sub(t).Seconds()) if d < 0 { d = 0 } ff.OpenSeconds = &d } } } hf.Flags = append(hf.Flags, ff) } ids := append([]string(nil), h.ActionIDs...) sort.Strings(ids) prev := "" for _, id := range ids { if genericActions[id] || id == prev { continue } prev = id af := ActionFinding{ActionID: id} if q, ok := newest[[2]string{id, name}]; ok { af.Queue = &QueueRef{ID: q.ID, Status: q.Status} } hf.Actions = append(hf.Actions, af) } if bh, _ := backups["host"].(string); bh == name { jobs, _ := backups["jobs"].(map[string]any) for _, job := range sortedKeys(jobs) { m, _ := jobs[job].(map[string]any) if m == nil || !backupFlagged(m) { continue } bf := BackupFinding{Job: job} bf.State, _ = m["state"].(string) bf.Overdue, _ = m["overdue"].(bool) bf.Reason, _ = m["reason"].(string) hf.Backups = append(hf.Backups, bf) } } } f.Hosts = append(f.Hosts, hf) } sort.Slice(f.Hosts, func(i, j int) bool { a, b := f.Hosts[i], f.Hosts[j] if ra, rb := severityRank(a.Severity), severityRank(b.Severity); ra != rb { return ra < rb } if a.Score != b.Score { return a.Score > b.Score } return a.Host < b.Host }) return f } func hasFlag(flags []string, flag string) bool { for _, f := range flags { if f == flag { return true } } return false } func keysOf(m map[string]bool) []string { out := make([]string, 0, len(m)) for k := range m { out = append(out, k) } return out } // HumanDuration renders seconds as 5m, 3h12m or 2d4h. func HumanDuration(secs int64) string { if secs < 0 { secs = 0 } d := time.Duration(secs) * time.Second switch { case d >= 24*time.Hour: return fmt.Sprintf("%dd%dh", secs/86400, secs%86400/3600) case d >= time.Hour: return fmt.Sprintf("%dh%dm", secs/3600, secs%3600/60) } return fmt.Sprintf("%dm", secs/60) } // FindingsView fetches posture (required), alerts, queue and backups (each optional on a 404) and prints the // ranked view. Exit 0 when no host has a flag and none is stale, else 1. An unknown --host is a ConfigError. func FindingsView(ctx context.Context, c *Client, w io.Writer, asJSON bool, host string, now time.Time) (int, error) { penv, err := c.Posture(ctx) if err != nil { return 0, err } var pdata struct { Hosts map[string]postureHost `json:"hosts"` } if err := json.Unmarshal(penv.Data, &pdata); err != nil || pdata.Hosts == nil { return 0, &TransportError{"posture: unexpected response"} } if host != "" { if _, ok := pdata.Hosts[host]; !ok { return 0, &ConfigError{fmt.Sprintf("host %q is not in the fleet posture", host)} } } var notes []string var alerts []alertRow if env, err := c.Alerts(ctx, "open", host, 200); err != nil { if !isNotFound(err) { return 0, err } notes = append(notes, "alerts: the fleet API does not have /v1/alerts yet; open times are not shown") } else { var d struct { Alerts []alertRow `json:"alerts"` } _ = json.Unmarshal(env.Data, &d) alerts = d.Alerts } var queue []queueRow if env, err := c.Queue(ctx); err != nil { if !isNotFound(err) { return 0, err } notes = append(notes, "queue: the fleet API does not have /v1/queue yet; queue state is not shown") } else { var d struct { Entries []queueRow `json:"entries"` } _ = json.Unmarshal(env.Data, &d) queue = d.Entries } var backups map[string]any if env, err := c.Get(ctx, "/v1/backups", nil); err != nil { if !isNotFound(err) { return 0, err } notes = append(notes, "backups: the fleet API does not have /v1/backups yet; backup jobs are not shown") } else if d := obj(env.Raw["data"]); d["status"] == "ok" { backups = d } gen, _ := penv.Raw["generated_at"].(string) if t, ok := parseTime(gen); ok { now = t } f := BuildFindings(gen, pdata.Hosts, alerts, queue, backups, now) if host != "" { kept := f.Hosts[:0] for _, h := range f.Hosts { if h.Host == host { kept = append(kept, h) } } f.Hosts = kept } // One extra request, only when a fresh host carries the known-exploited flag. Any failure degrades to a note. wanted := false for _, h := range f.Hosts { if p := pdata.Hosts[h.Host]; !p.Stale && hasFlag(p.ActiveFlags, kevFlag) { wanted = true } } if wanted { if tenv, err := c.Telemetry(ctx, host); err != nil { notes = append(notes, "culprits: telemetry unavailable ("+err.Error()+"); no package lines") } else if td := obj(tenv.Raw["data"]); str(td["status"]) != "ok" { notes = append(notes, "culprits: telemetry status "+dashStr(str(td["status"]))+"; no package lines") } else { th := obj(td["hosts"]) for i, h := range f.Hosts { if p := pdata.Hosts[h.Host]; p.Stale || !hasFlag(p.ActiveFlags, kevFlag) { continue } cs := culprits(obj(th[h.Host])) if len(cs) > maxCulprits { cs = cs[:maxCulprits] } f.Hosts[i].Culprits = cs } } } if len(notes) > 0 { f.Notes = notes } code := ExitOK if len(f.FleetWide) > 0 { code = ExitDrift } for _, h := range f.Hosts { if h.Stale || len(h.Flags) > 0 { code = ExitDrift } } if asJSON { return code, WriteJSON(w, f) } for _, ff := range f.FleetWide { fmt.Fprintf(w, "fleet-wide: %s (w%d) on %d hosts -- %s\n", ff.Flag, ff.Weight, ff.Hosts, ff.Hint) } for _, h := range f.Hosts { if h.Stale { fmt.Fprintf(w, "%s STALE last_report=%s\n", h.Host, dashStr(h.LastReportAt)) continue } fmt.Fprintf(w, "%s %s score=%d\n", h.Host, dashStr(h.Severity), h.Score) for _, ff := range h.Flags { open := "-" if ff.OpenSeconds != nil { open = HumanDuration(*ff.OpenSeconds) } fmt.Fprintf(w, " %-34s w%d open %-7s %s\n", ff.Flag, ff.Weight, open, ff.Hint) } for _, cu := range h.Culprits { fmt.Fprintf(w, " culprit %s\n", cu) } // Fleet-wide flags are on every fresh host, so a host with none left has only those (teacher fix RS10-B-T). if len(h.Flags) == 0 && len(h.Backups) == 0 && len(f.FleetWide) > 0 { fmt.Fprintln(w, " fleet-wide flags only") } for _, b := range h.Backups { line := fmt.Sprintf(" backup %s %s", b.Job, b.State) if b.Overdue { line += " OVERDUE" } if b.Reason != "" { line += " reason=" + b.Reason } fmt.Fprintln(w, line) } if len(h.Actions) > 0 { parts := make([]string, 0, len(h.Actions)) for _, a := range h.Actions { if a.Queue != nil { parts = append(parts, fmt.Sprintf("%s (%s %s)", a.ActionID, a.Queue.ID, a.Queue.Status)) } else { parts = append(parts, a.ActionID) } } fmt.Fprintf(w, " actions: %s\n", strings.Join(parts, ", ")) } } for _, n := range notes { fmt.Fprintf(w, "note: %s\n", n) } return code, nil } func dashStr(s string) string { if s == "" { return "-" } return s }