hub/internal/suggest/suggest.go
trvon 0d7a219c5d
Some checks failed
release / build (push) Failing after 2m13s
hub: operator CLI with signed self-update
2026-11-10 20:32:32 -07:00

445 lines
14 KiB
Go

// SPDX-License-Identifier: GPL-3.0-or-later
// Package suggest turns a host profile plus the inventory into adoption suggestions: inventory groups, a pillar
// snippet, BLOCKERS (must be resolved before onboarding) and CANDIDATES (hand-made things to decide on).
package suggest
import (
"fmt"
"net/netip"
"os"
"regexp"
"sort"
"strconv"
"strings"
"git.trevon.dev/trevon/hub/internal/inventory"
"git.trevon.dev/trevon/hub/internal/pillar"
"git.trevon.dev/trevon/hub/internal/probe"
)
// MaxAllowedPortsList: a project that publishes more distinct ports than this is treated as an open lab and
// gets no allowed_ports suggestion (absent means no port rule), with a comment saying so.
const MaxAllowedPortsList = 16
// Finding is one blocker or candidate. ID is stable for tests and for scripts reading --json.
type Finding struct {
ID string `json:"id"`
Message string `json:"message"`
}
// GroupHint suggests an inventory group.
type GroupHint struct {
Name string `json:"name"`
Reason string `json:"reason"`
Present bool `json:"present"` // the host is already in that group
}
// InventoryInfo echoes what the inventory says about the host.
type InventoryInfo struct {
Address string `json:"address"`
User string `json:"user"`
Port int `json:"port"`
SyslogHostname string `json:"syslog_hostname"`
Groups []string `json:"groups"`
}
// Suggestion is the full result.
type Suggestion struct {
Host string `json:"host"`
Inventory InventoryInfo `json:"inventory"`
Groups []GroupHint `json:"groups"`
ComposeProjects []pillar.ComposeProject `json:"compose_projects"`
ExpectedNopasswdUsers []string `json:"expected_nopasswd_users"`
Pillar string `json:"pillar"`
Blockers []Finding `json:"blockers"`
Candidates []Finding `json:"candidates"`
}
// Build computes the suggestion. salted is the set of absolute paths Salt already installs (see SaltManagedPaths and DefaultSaltManagedPaths).
func Build(name string, host *inventory.Host, p *probe.Profile, salted map[string]bool) *Suggestion {
s := &Suggestion{
Host: name,
Inventory: InventoryInfo{
Address: host.Address(), User: host.User(), Port: host.Port(),
SyslogHostname: host.SyslogHostname(), Groups: append([]string{}, host.Groups...),
},
Blockers: []Finding{}, Candidates: []Finding{},
}
sec := p.Sections
s.Groups = groupHints(host, sec)
s.ComposeProjects, s.ExpectedNopasswdUsers = composePillar(sec)
s.Pillar = pillar.Render(name, s.ComposeProjects, s.ExpectedNopasswdUsers)
s.Blockers = blockers(name, host, sec)
s.Candidates = candidates(sec, p.Unreadable, salted)
return s
}
func blockers(name string, host *inventory.Host, sec probe.Sections) []Finding {
var out []Finding
add := func(id, format string, args ...any) { out = append(out, Finding{id, fmt.Sprintf(format, args...)}) }
ts := sec.Identity.Tailscale0
addr := host.Address()
switch {
case len(ts) == 0:
add("address", "host has no tailscale0 address; inventory address is %s", addr)
case !contains(ts, addr):
add("address", "inventory address %s is not a tailscale0 address of the host (%s); update ansible_host", addr, strings.Join(ts, ", "))
}
if !sec.Access.SudoNopasswd {
add("sudo", "no passwordless sudo for %s (`sudo -n true` failed); add a sudoers drop-in before onboarding", sec.Access.User)
}
if u := sec.Access.Sshd.AllowUsers; len(u) > 0 {
add("sshd-allowusers", "sshd AllowUsers is set (%s); the Salt/Ansible users must be listed or a drop-in added", strings.Join(u, ", "))
}
if g := sec.Access.Sshd.AllowGroups; len(g) > 0 {
add("sshd-allowgroups", "sshd AllowGroups is set (%s); the Salt/Ansible users must be in one of them", strings.Join(g, ", "))
}
if sec.Access.Sshd.AllowUsers == nil && sec.Access.Sshd.Source != nil {
add("sshd-allowusers-unknown", "sshd AllowUsers could not be read (%s only); check it by hand", *sec.Access.Sshd.Source)
}
if m := sec.Software.SaltMinion; m.Installed && m.ID != nil && *m.ID != name {
add("minion-id", "salt-minion id %q differs from the inventory name %q", *m.ID, name)
}
if sl := host.SyslogHostname(); sl != "" && !strings.EqualFold(sec.Identity.Hostname, sl) {
add("hostname", "hostname %q differs from syslog_hostname %q in the inventory", sec.Identity.Hostname, sl)
}
return out
}
func candidates(sec probe.Sections, unreadable []probe.Unreadable, salted map[string]bool) []Finding {
var out []Finding
add := func(id, format string, args ...any) { out = append(out, Finding{id, fmt.Sprintf(format, args...)}) }
for _, c := range sec.Candidates {
if salted[c.Path] {
continue
}
sum := "sha256 unknown"
if c.SHA256 != nil {
sum = "sha256 " + *c.SHA256
}
note := ""
if c.Note != "" {
note = " (" + c.Note + ")"
}
add("script", "%s %s:%s %s %s, run by %s%s", c.Path, c.Owner, c.Group, c.Mode, sum, c.Unit, note)
}
for _, sv := range sec.Services {
if sv.HubManaged || salted["/etc/systemd/system/"+sv.Name] {
continue
}
add("unit", "hand-made %s %s (%s/%s)", sv.Kind, sv.Name, sv.Enabled, sv.Active)
}
for _, line := range publicPorts(sec) {
add("public-port", "%s", line)
}
sshd := sec.Access.Sshd
if sshd.PasswordAuthentication == "yes" {
add("sshd-password-login", "sshd PasswordAuthentication is yes")
}
if sshd.PermitRootLogin == "yes" {
add("sshd-root-login", "sshd PermitRootLogin is yes")
}
switch f := sec.Access.Fail2ban; {
case !f.Installed:
add("fail2ban", "fail2ban is not installed")
case !f.Active:
add("fail2ban", "fail2ban is installed but not active")
}
if !sec.Access.UFW.Active && !sec.Access.NFT.Active {
add("firewall", "no active host firewall (ufw and nftables are inactive)")
}
for _, c := range sec.Containers {
if c.Privileged {
add("privileged-container", "container %s runs privileged", c.Name)
}
}
for _, u := range unreadable {
add("unreadable", "%s: %s (%s)", u.Section, u.Item, u.Reason)
}
return out
}
func groupHints(host *inventory.Host, sec probe.Sections) []GroupHint {
has := map[string]bool{}
for _, g := range host.Groups {
has[g] = true
}
var out []GroupHint
add := func(name, reason string) { out = append(out, GroupHint{name, reason, has[name]}) }
add("managed_admin", "every adopted host")
if pm := sec.Software.PackageManager; pm != nil {
switch *pm {
case "apt-get":
add("apt", "package manager apt-get")
case "dnf", "yum":
add("yum", "package manager "+*pm)
}
}
for _, sv := range sec.Services {
if !sv.HubManaged && strings.HasPrefix(sv.Name, "forgejo-runner") {
add("ci", "forgejo-runner unit present")
break
}
}
for _, c := range sec.Containers {
if strings.Contains(c.Image, "forgejo/forgejo") {
add("protected_services", "runs Forgejo ("+c.Image+"); protected service node")
break
}
}
return out
}
func composePillar(sec probe.Sections) ([]pillar.ComposeProject, []string) {
byProject := map[string][]probe.Container{}
allNonRoot := true
for _, c := range sec.Containers {
if c.Project == "" {
continue // not a compose container (for example a CI job container)
}
byProject[c.Project] = append(byProject[c.Project], c)
if isRoot(c.User) {
allNonRoot = false
}
}
names := make([]string, 0, len(byProject))
for n := range byProject {
names = append(names, n)
}
sort.Strings(names)
var projects []pillar.ComposeProject
for _, n := range names {
svcSet := map[string]bool{}
portSet := map[int]bool{}
for _, c := range byProject[n] {
if c.Service != "" {
svcSet[c.Service] = true
}
for _, pt := range c.Ports {
if !loopback(pt.HostIP) {
portSet[pt.HostPort] = true
}
}
}
services := make([]string, 0, len(svcSet))
for sv := range svcSet {
services = append(services, sv)
}
ports := make([]int, 0, len(portSet))
for pt := range portSet {
ports = append(ports, pt)
}
sort.Ints(ports)
proj := pillar.ComposeProject{Name: n, Services: pillar.OrderServices(n, services), ForbidRoot: allNonRoot}
if len(ports) > MaxAllowedPortsList {
proj.PortsNote = fmt.Sprintf("%d distinct published ports (open lab); add one only if a port rule is wanted", len(ports))
} else {
proj.AllowedPorts = ports // empty (never nil) when nothing is published
if proj.AllowedPorts == nil {
proj.AllowedPorts = []int{}
}
}
projects = append(projects, proj)
}
var nopasswd []string
if sec.Access.SudoNopasswd && sec.Access.User != "" {
nopasswd = []string{sec.Access.User}
}
return projects, nopasswd
}
// isRoot: an empty user is the image default, usually root.
func isRoot(user string) bool {
u, _, _ := strings.Cut(user, ":")
return u == "" || u == "0" || u == "root"
}
func loopback(ip string) bool {
a, err := netip.ParseAddr(ip)
return err == nil && a.IsLoopback()
}
func contains(v []string, s string) bool {
for _, x := range v {
if x == s {
return true
}
}
return false
}
// publicPorts lists listening sockets that are not loopback and not bound to a tailscale0 address, collapsing
// IPv4/IPv6 twins and consecutive ports of one process into ranges.
func publicPorts(sec probe.Sections) []string {
ts := map[string]bool{}
for _, a := range sec.Identity.Tailscale0 {
ts[a] = true
}
type key struct {
proto, process string
}
groups := map[key]map[int]bool{}
for _, l := range sec.Listening {
if loopback(l.Address) || ts[l.Address] {
continue
}
proc := ""
if l.Process != nil {
proc = *l.Process
}
k := key{l.Proto, proc}
if groups[k] == nil {
groups[k] = map[int]bool{}
}
groups[k][l.Port] = true
}
var lines []string
for k, set := range groups {
ports := make([]int, 0, len(set))
for p := range set {
ports = append(ports, p)
}
sort.Ints(ports)
for _, r := range ranges(ports) {
proc := k.process
if proc == "" {
proc = "process unknown"
}
lines = append(lines, fmt.Sprintf("public %s port %s (%s)", k.proto, r, proc))
}
}
sort.Strings(lines)
return lines
}
func ranges(ports []int) []string {
var out []string
for i := 0; i < len(ports); {
j := i
for j+1 < len(ports) && ports[j+1] == ports[j]+1 {
j++
}
if j > i {
out = append(out, fmt.Sprintf("%d-%d", ports[i], ports[j]))
} else {
out = append(out, strconv.Itoa(ports[i]))
}
i = j + 1
}
return out
}
// DefaultManagedPaths is the built-in list of absolute paths a Security Hub Salt rollout installs. It is a default:
// `managed_paths_file` in hub.json replaces it with your own list.
var DefaultManagedPaths = []string{
"/etc/apt/apt.conf.d/20auto-upgrade",
"/etc/apt/apt.conf.d/52security-hub-unattended-upgrade",
"/etc/apt/apt.conf.d/99security-hub-monthly-reboot",
"/etc/dnf/automatic.conf",
"/etc/forgejo-runner",
"/etc/forgejo-runner/config.yml",
"/etc/forgejo-runner/credential",
"/etc/rsyslog.d/30-security-forwarding.conf",
"/etc/sanoid/sanoid.conf",
"/etc/security-hub",
"/etc/security-hub/ci-probe.json",
"/etc/security-hub/ctf-watch.json",
"/etc/security-hub/forgejo-update-status.json",
"/etc/security-hub/monthly-reboot.json",
"/etc/systemd/system/forgejo-backup.service",
"/etc/systemd/system/forgejo-backup.timer",
"/etc/systemd/system/forgejo-runner.service",
"/etc/systemd/system/forgejo-update.service",
"/etc/systemd/system/forgejo-update.timer",
"/etc/systemd/system/security-hub-ci-probe.service",
"/etc/systemd/system/security-hub-ci-probe.timer",
"/etc/systemd/system/security-hub-ctf-watch.service",
"/etc/systemd/system/security-hub-ctf-watch.service.d/auto-restart.conf",
"/etc/systemd/system/security-hub-ctf-watch.timer",
"/etc/systemd/system/security-hub-monthly-reboot.service",
"/etc/systemd/system/security-hub-monthly-reboot.timer",
"/etc/yum/yum-cron.conf",
"/usr/local/bin/forgejo-runner",
"/usr/local/libexec/security-hub-ci-probe",
"/usr/local/libexec/security-hub-ctf-restart",
"/usr/local/libexec/security-hub-ctf-watch",
}
// DefaultSaltManagedPaths returns DefaultManagedPaths as a set.
func DefaultSaltManagedPaths() map[string]bool {
out := make(map[string]bool, len(DefaultManagedPaths))
for _, p := range DefaultManagedPaths {
out[p] = true
}
return out
}
// SaltManagedPaths returns the paths Salt already installs: the built-in default when file is empty, otherwise the
// paths listed in file (one absolute path per line; blank lines and `#` comments are ignored; any other line, or a
// file without paths, is an error so a typo cannot silently empty the set).
func SaltManagedPaths(file string) (map[string]bool, error) {
if file == "" {
return DefaultSaltManagedPaths(), nil
}
raw, err := os.ReadFile(file)
if err != nil {
return nil, fmt.Errorf("managed_paths_file unreadable: %s", file)
}
out := map[string]bool{}
for i, line := range strings.Split(string(raw), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
if !managedPathRe.MatchString(line) {
return nil, fmt.Errorf("%s:%d: not an absolute path: %q", file, i+1, line)
}
out[line] = true
}
if len(out) == 0 {
return nil, fmt.Errorf("managed_paths_file %s lists no paths", file)
}
return out, nil
}
var managedPathRe = regexp.MustCompile(`^/[^\s{}'"]+$`)
// Render prints the suggestion as text.
func Render(s *Suggestion) string {
var b strings.Builder
fmt.Fprintf(&b, "host %s: inventory %s@%s:%d", s.Host, orDash(s.Inventory.User), s.Inventory.Address, s.Inventory.Port)
if len(s.Inventory.Groups) > 0 {
fmt.Fprintf(&b, " groups [%s]", strings.Join(s.Inventory.Groups, ", "))
}
b.WriteString("\n\nGROUPS (suggested)\n")
for _, g := range s.Groups {
mark := "add"
if g.Present {
mark = "ok "
}
fmt.Fprintf(&b, " %s %s: %s\n", mark, g.Name, g.Reason)
}
b.WriteString("\nPILLAR (review, then paste)\n")
for _, line := range strings.Split(strings.TrimRight(s.Pillar, "\n"), "\n") {
b.WriteString(" " + line + "\n")
}
fmt.Fprintf(&b, "\nBLOCKERS (%d)\n", len(s.Blockers))
for _, f := range s.Blockers {
fmt.Fprintf(&b, " [%s] %s\n", f.ID, f.Message)
}
fmt.Fprintf(&b, "\nCANDIDATES (%d)\n", len(s.Candidates))
for _, f := range s.Candidates {
fmt.Fprintf(&b, " [%s] %s\n", f.ID, f.Message)
}
return b.String()
}
func orDash(s string) string {
if s == "" {
return "-"
}
return s
}