package app import ( "bytes" "errors" "time" "encoding/json" "fmt" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" "io" "os" "path/filepath" ) // Check is one doctor finding. type Check struct { Name string `json:"name"` Status string `json:"status"` // ok, warn, fail, off Detail string `json:"detail"` } // Doctor inspects the configuration and the environment. It returns false when // something that prevents correct operation fails. func Doctor(c Config, w io.Writer, asJSON bool) bool { var checks []Check add := func(name, status, detail string) { checks = append(checks, Check{name, status, detail}) } token, terr := Secret("URUTAU_TOKEN") if terr != nil { add("config", "fail", terr.Error()) } else if err := c.Validate(token); err != nil { add("config", "fail", err.Error()) } else { add("config", "ok", "token and bind are valid") } for _, s := range []struct{ name, path string }{{"traefik", c.TraefikLog}, {"ssh", c.AuthLog}, {"fail2ban", c.Fail2banLog}} { if s.path == "" { add("source "+s.name, "off", "disabled") continue } f, err := os.Open(s.path) if err != nil { add("source "+s.name, "warn", err.Error()) continue } fi, _ := f.Stat() f.Close() add("source "+s.name, "ok", fmt.Sprintf("%s readable (%d bytes)", s.path, fi.Size())) if s.name == "traefik" { if bad, n := sampleMalformed(s.path); n >= winMin && bad*5 > n { add("source traefik format", "warn", fmt.Sprintf("degraded: %d of the last %d lines are malformed: %s", bad, n, degradedMsg)) } } } if err := os.MkdirAll(c.DataDir, 0o700); err != nil { add("data-dir", "fail", err.Error()) } else if f, err := os.CreateTemp(c.DataDir, ".doctor-*"); err != nil { add("data-dir", "fail", err.Error()) } else { f.Close() os.Remove(f.Name()) add("data-dir", "ok", fmt.Sprintf("%s writable", filepath.Clean(c.DataDir))) } doctorEnforce(c, add) geoInfo := doctorGeo(c, add) stateInfo := doctorState(c, add) ok := true for _, ch := range checks { if ch.Status == "fail" { ok = false } } if asJSON { enc := json.NewEncoder(w) enc.SetIndent("", " ") enc.Encode(map[string]any{"version": Version, "name": c.Name, "ok": ok, "checks": checks, "geo": geoInfo, "state": stateInfo}) return ok } fmt.Fprintf(w, "urutau %s (%s)\n", Version, c.Name) for _, ch := range checks { fmt.Fprintf(w, " %-4s %-16s %s\n", ch.Status, ch.Name, ch.Detail) } return ok } // doctorGeo reports the state of the geo databases. func doctorGeo(c Config, add func(name, status, detail string)) map[string]any { info := map[string]any{"dir": c.GeoDir, "attribution": Attribution, "update_every": c.GeoUpdate.String()} g, err := geo.Open(c.GeoDir) if err != nil { add("geo", "warn", err.Error()) info["error"] = err.Error() return info } defer g.Close() st := g.Status() info["city"], info["asn"] = st.City, st.ASN if st.LastError != "" { info["last_error"] = st.LastError } if !st.LastUpdate.IsZero() { info["last_update"] = st.LastUpdate.Format(time.RFC3339) } switch { case st.City.Loaded && st.ASN.Loaded: add("geo", "ok", fmt.Sprintf("city build %s, asn build %s", st.City.Build.Format("2006-01-02"), st.ASN.Build.Format("2006-01-02"))) default: add("geo", "warn", "databases not loaded yet; they are downloaded at start unless --geo-update is 0"+lastErr(st.LastError)) } return info } func lastErr(e string) string { if e == "" { return "" } return " (last error: " + e + ")" } // doctorState reads the snapshot and reports what it holds, traffic included. func doctorState(c Config, add func(name, status, detail string)) map[string]any { path := SnapshotPath(c.DataDir) info := map[string]any{"path": path} fi, err := os.Stat(path) if err != nil { info["exists"] = false add("state", "ok", "no snapshot yet (fresh start)") return info } info["exists"], info["bytes"] = true, fi.Size() st := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList()}) if _, err := st.Load(path); err != nil { info["error"] = err.Error() add("state", "warn", "snapshot unreadable, it will be set aside at start: "+err.Error()) return info } tr := st.TrafficSummary("7d", "all") info["ips"], info["traffic_domains"], info["traffic_requests_7d"] = st.IPCount(), len(tr.Domains), tr.Requests add("state", "ok", fmt.Sprintf("%d IPs, %d domains, %d requests in 7 days", st.IPCount(), len(tr.Domains), tr.Requests)) return info } // sampleMalformed parses up to the last winSize lines of a Traefik log and // counts the malformed ones. func sampleMalformed(path string) (bad, n int) { f, err := os.Open(path) if err != nil { return 0, 0 } defer f.Close() const tailBytes = 512 << 10 off := int64(0) if fi, err := f.Stat(); err == nil && fi.Size() > tailBytes { off = fi.Size() - tailBytes } if _, err := f.Seek(off, io.SeekStart); err != nil { return 0, 0 } b, err := io.ReadAll(io.LimitReader(f, tailBytes)) if err != nil { return 0, 0 } lines := bytes.Split(b, []byte("\n")) if off > 0 && len(lines) > 0 { lines = lines[1:] // first line is cut } if len(lines) > 0 && len(lines[len(lines)-1]) == 0 { lines = lines[:len(lines)-1] } if len(lines) > winSize { lines = lines[len(lines)-winSize:] } for _, l := range lines { if len(bytes.TrimSpace(l)) == 0 { continue } n++ if _, err := core.ParseTraefik(l); err != nil && !errors.Is(err, core.ErrIgnored) { bad++ } } return bad, n }