package server import ( "bytes" _ "embed" "encoding/base64" "fmt" "html/template" "net/http" "regexp" "sort" "strings" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" ) // This file renders GET /api/v1/report?format=html: one self-contained A4 document // (inline CSS, SVG charts, logo as data URI, no JavaScript). Every dynamic string // goes through html/template; SVG is built here from escaped text and numbers. // enforceView is the second-firewall data of the report (nil: engine not running). type enforceView struct { Mode string Share bool Coverage enforce.Coverage Counts enforce.Counts Recent []enforce.Recent } // egressView is the outbound-traffic data of the report (nil: analysis not running). type egressView struct { Source egress.SourceInfo Report egress.Report Suppressed int // findings hidden by tickets } // reportInput is everything the renderer needs. To wire another source, fill a // field here in reportExtras; the renderer skips sections whose pointer is nil. type reportInput struct { Out reportOut Lang string Traffic store.TrafficData Classes [store.NumCls]uint32 HasHealth bool Enforce *enforceView Egress *egressView Peers bool // other hosts included: health and egress cover only this server } // reportLogo is the repository logo.png (1254 px) scaled to 800 px WebP, sharp // on the cover even when printed. Regenerate it from ./logo.png when the logo changes. // //go:embed report_logo.webp var reportLogo []byte var logoURI = "data:image/webp;base64," + base64.StdEncoding.EncodeToString(reportLogo) // logoDataURI returns the report logo as a data URI. func logoDataURI() template.URL { return template.URL(logoURI) } // ---- view model ------------------------------------------------------------- type kpiV struct{ Label, Value, Delta, Cls string } type rowV struct{ Cells []string } type tableV struct { Head []string Rows []rowV Num map[int]bool // right-aligned columns NoWrap map[int]bool None string } type chartV struct { Title string SVG template.HTML Legend []legendV Empty bool } type legendV struct{ Label, Value, Color string } type recV struct{ Level, Label, Text string } type secV struct{ ID, Title string } type viewV struct { Lang, Title, RunHead, RunFoot, Kicker, CoverTitle, CoverSub string Logo template.URL Motif template.HTML Servers, Period, Generated string LPeriod, LServers, LGen, LConf, LToc string CoverNums []kpiV TOC []secV KPIs []kpiV VerdictCls, VerdictTitle string Verdict []string Recs []recV Trunc string Timeline chartV Fams, Techs chartV IPs, Camps, Escs tableV Expo tableV Countries, ASNs chartV HealthLead string HealthNotes []string Classes, Status chartV VisLead string VisKPIs []kpiV Pages, Browsers, Devices, Refs chartV Defense tableV HasEnf bool EnfLead string EnfNotes []string EnfKPIs []kpiV EnfRecent tableV HasEgress bool XLead string XNotes []string XWl, XFind tableV XChart, XDst chartV NoEnf, NoEgress, None, PeersNote, MethodP1, MethodP2, MethodP3 string TThreats, TGeo, THealth, TVis, TDef, TEnf, TEgress, TRecs, TMethod, TSum string TIPs, TCamps, TEscs, TExpo, TTimeline, TFams, TTechs, TCountries, TASNs string TEnfRecent, TXFind, TXWl, TXChart, TXDst, TClasses, TStatus string ShowPeers bool } var rptCCRe = regexp.MustCompile(`^[A-Za-z]{2}$`) type renderer struct { lang int code string } func newRenderer(lang string) *renderer { if strings.HasPrefix(strings.ToLower(lang), "en") { return &renderer{1, "en"} } return &renderer{0, "pt-BR"} } func (r *renderer) t(key string, args ...any) string { v, ok := reportText[key] if !ok { return key } s := v[r.lang] if len(args) > 0 { return fmt.Sprintf(s, args...) } return s } // num formats integers with the thousands separator of the language. func (r *renderer) num(n float64) string { neg := n < 0 if neg { n = -n } s := fmt.Sprintf("%.0f", n) sep := "." if r.lang == 1 { sep = "," } var out []byte for i := range s { if i > 0 && (len(s)-i)%3 == 0 { out = append(out, sep...) } out = append(out, s[i]) } if neg { return "-" + string(out) } return string(out) } func (r *renderer) dec(v float64, d int) string { s := fmt.Sprintf("%.*f", d, v) if r.lang == 0 { s = strings.Replace(s, ".", ",", 1) } return s } func (r *renderer) pct(v float64) string { return r.dec(v, 1) + "%" } func (r *renderer) dur(sec float64) string { s := int64(sec + 0.5) switch { case s < 60: return fmt.Sprintf("%ds", s) case s < 3600: return fmt.Sprintf("%dmin", s/60) case s < 86400: return fmt.Sprintf("%dh%02d", s/3600, s%3600/60) } return fmt.Sprintf("%dd", s/86400) } func (r *renderer) date(ts int64) string { if r.lang == 1 { return time.Unix(ts, 0).UTC().Format("2006-01-02 15:04 UTC") } return time.Unix(ts, 0).UTC().Format("02/01/2006 15:04 UTC") } func (r *renderer) day(ts int64) string { if r.lang == 1 { return time.Unix(ts, 0).UTC().Format("2006-01-02") } return time.Unix(ts, 0).UTC().Format("02/01/2006") } func (r *renderer) yn(b bool) string { if b { return r.t("yes") } return r.t("no") } func (r *renderer) tr(prefix, k string) string { if v, ok := reportText[prefix+k]; ok { return v[r.lang] } return k } func ccOf(cc, name string) string { switch { case rptCCRe.MatchString(cc) && name != "": return strings.ToUpper(cc) + " · " + name case rptCCRe.MatchString(cc): return strings.ToUpper(cc) case name != "": return name } return "-" } func (r *renderer) counts(c []store.Count, label func(store.Count) string, n int) []chartItem { var out []chartItem for i, x := range c { if i >= n { break } out = append(out, chartItem{label(x), float64(x.N)}) } return out } func (r *renderer) barChart(title string, items []chartItem, color string) chartV { if len(items) == 0 { return chartV{Title: title, Empty: true} } return chartV{Title: title, SVG: template.HTML(svgBars(items, color, func(v float64) string { return r.num(v) }, title))} } func (r *renderer) donutChart(title string, items []chartItem) chartV { var total float64 for _, it := range items { total += it.N } if total <= 0 { return chartV{Title: title, Empty: true} } c := chartV{Title: title, SVG: template.HTML(svgDonut(items, title))} for i, it := range items { c.Legend = append(c.Legend, legendV{it.Label, r.num(it.N) + " · " + r.pct(it.N/total*100), reportPalette[i%len(reportPalette)]}) } return c } func delta(r *renderer, v float64, ok bool, prev float64) string { if !ok { return "" } a := "▲" if v < 0 { a = "▼" } if v > -0.5 && v < 0.5 { a = "=" } if v < 0 { v = -v } return fmt.Sprintf("%s %s%% · %s", a, r.num(v+0.0001), r.t("k.before", r.num(prev))) } // build turns the data into the view model (all the report decisions live here). func (r *renderer) build(in reportInput, genTS int64) viewV { o, s := in.Out, in.Out.Summary v := viewV{Lang: r.code, Logo: logoDataURI()} v.Title, v.RunHead, v.RunFoot = r.t("doc.title"), r.t("run.head"), r.t("run.foot") v.Kicker, v.CoverTitle, v.CoverSub = r.t("cover.kicker"), r.t("cover.title"), r.t("cover.sub") v.LPeriod, v.LServers, v.LGen, v.LConf, v.LToc = r.t("cover.period"), r.t("cover.servers"), r.t("cover.gen"), r.t("cover.conf"), r.t("toc") v.None, v.NoEnf, v.NoEgress, v.PeersNote = r.t("none"), r.t("noenf"), r.t("noegress"), r.t("peers.note") v.MethodP1, v.MethodP2, v.MethodP3 = r.t("m.p1"), r.t("m.p2"), r.t("m.p3") v.TSum, v.TThreats, v.TGeo, v.THealth, v.TVis = r.t("s.sum"), r.t("s.threats"), r.t("s.geo"), r.t("s.health"), r.t("s.visitors") v.TDef, v.TEnf, v.TEgress, v.TRecs, v.TMethod = r.t("s.defense"), r.t("s.enforce"), r.t("s.egress"), r.t("s.recs"), r.t("s.method") v.TIPs, v.TCamps, v.TEscs, v.TExpo, v.TTimeline = r.t("t.ips"), r.t("t.camp"), r.t("t.esc"), r.t("t.expo"), r.t("c.timeline") v.TFams, v.TTechs, v.TCountries, v.TASNs = r.t("c.families"), r.t("c.techs"), r.t("c.countries"), r.t("c.asns") v.TEnfRecent, v.TXFind, v.TXWl, v.TXChart, v.TXDst = r.t("t.enf"), r.t("t.find"), r.t("t.wl"), r.t("c.egress"), r.t("c.dst") v.TClasses, v.TStatus = r.t("c.classes"), r.t("c.status") v.ShowPeers = in.Peers servers := r.t("cover.all") if len(o.Hosts) > 0 { servers = strings.Join(o.Hosts, ", ") } v.Servers = servers v.Period = r.day(o.Range.From) + " – " + r.day(o.Range.To) v.Generated = r.date(genTS) cover := 0.0 if s.HostileIPs > 0 { cover = o.Defense.BanCoverage } v.CoverNums = []kpiV{ {Label: r.t("k.attacks"), Value: r.num(float64(s.Attacks))}, {Label: r.t("k.hostile"), Value: r.num(float64(s.HostileIPs))}, {Label: r.t("k.bans"), Value: r.num(float64(s.Bans))}, {Label: r.t("k.coverage"), Value: r.dec(cover, 0) + "%"}, } // signals for verdict and recommendations expo := o.Exposures.Total var xHigh int if in.Egress != nil { for _, f := range in.Egress.Report.Findings { if f.Severity == "high" || f.Severity == "critical" { xHigh++ } } } level := "good" switch { case expo > 0 || xHigh > 0: level = "bad" case len(o.Escalations) > 0 || (s.HostileIPs > 0 && cover < 80): level = "warn" } v.VerdictCls = level v.VerdictTitle = r.t("verdict." + level) // verdict paragraph, lay language var vd []string if s.Attacks == 0 { vd = append(vd, r.t("v.none")) } else { vd = append(vd, r.t("v.intro", servers, r.num(float64(s.Attacks)), r.num(float64(s.UniqueIPs)), r.num(float64(s.HostileIPs)), r.num(float64(s.Bans)))) if dp, ok := s.DeltaPct["attacks"]; s.HasPrev && ok { switch { case dp > -5 && dp < 5: vd = append(vd, r.t("v.flat")) case dp > 0: vd = append(vd, r.t("v.up", r.num(dp))) default: vd = append(vd, r.t("v.down", r.num(-dp))) } } else { vd = append(vd, r.t("v.noprev")) } if len(o.Families) > 0 && len(o.Countries) > 0 { vd = append(vd, r.t("v.top", o.Families[0].Key, o.Countries[0].Key)) } if s.HostileIPs > 0 { vd = append(vd, r.t("v.cover", r.dec(cover, 0))) } if o.Defense.MTTBN > 0 { vd = append(vd, r.t("v.mttb", r.dur(o.Defense.MTTBMedianS))) } } if expo > 0 { vd = append(vd, r.t("v.expo", r.num(float64(expo)))) } else if s.Attacks > 0 { vd = append(vd, r.t("v.expo0")) } if len(o.Escalations) > 0 { vd = append(vd, r.t("v.esc", r.num(float64(len(o.Escalations))))) } if xHigh > 0 { vd = append(vd, r.t("v.egress", r.num(float64(xHigh)))) } v.Verdict = vd if o.Truncated { v.Trunc = r.t("trunc") } // KPIs dl := func(k string, cur, prev uint64) string { d, ok := s.DeltaPct[k] return delta(r, d, s.HasPrev && ok, float64(prev)) } kc := func(warn bool) string { if warn { return "warn" } return "" } v.KPIs = []kpiV{ {r.t("k.requests"), r.num(float64(s.Requests)), dl("requests", s.Requests, s.Prev.Requests), ""}, {r.t("k.attacks"), r.num(float64(s.Attacks)), dl("attacks", s.Attacks, s.Prev.Attacks), kc(s.Attacks > 0)}, {r.t("k.hostile"), r.num(float64(s.HostileIPs)), dl("hostile_ips", uint64(s.HostileIPs), uint64(s.Prev.HostileIPs)), kc(s.HostileIPs > 0)}, {r.t("k.bans"), r.num(float64(s.Bans)), dl("bans", uint64(s.Bans), uint64(s.Prev.Bans)), ""}, {r.t("k.visitors"), r.num(float64(s.Visitors)), dl("visitors", s.Visitors, s.Prev.Visitors), ""}, {r.t("k.coverage"), r.dec(cover, 0) + "%", "", kc(s.HostileIPs > 0 && cover < 80)}, } // threats vals := o.Timeline.Values v.Timeline = chartV{Title: v.TTimeline, SVG: template.HTML(svgArea(vals, o.Timeline.Start, o.Timeline.Step, r.num, v.TTimeline))} if len(vals) == 0 { v.Timeline = chartV{Title: v.TTimeline, Empty: true} } v.Motif = template.HTML(svgMotif(vals)) v.Fams = r.donutChart(v.TFams, r.counts(o.Families, func(c store.Count) string { return c.Key }, 6)) v.Techs = r.barChart(v.TTechs, r.counts(o.Techniques, func(c store.Count) string { if c.Label != "" { return c.Key + " " + c.Label } return c.Key }, 8), "#c2410c") v.IPs = tableV{Head: []string{r.t("col.ip"), r.t("col.level"), r.t("col.score"), r.t("col.country"), r.t("col.net"), r.t("col.events"), r.t("col.banned")}, Num: map[int]bool{2: true, 5: true}, NoWrap: map[int]bool{0: true}} for _, x := range o.TopIPs { v.IPs.Rows = append(v.IPs.Rows, rowV{[]string{x.IP, r.tr("lvl.", x.Level), r.dec(x.Score, 1), ccOf(x.CC, x.Country), dash(x.ASOrg), r.num(float64(x.Events)), r.yn(x.Banned)}}) } v.Camps = tableV{Head: []string{r.t("col.camp"), r.t("col.ips"), r.t("col.active"), r.t("col.techs")}, Num: map[int]bool{1: true}} for _, c := range o.Campaigns { v.Camps.Rows = append(v.Camps.Rows, rowV{[]string{c.ID, r.num(float64(c.IPsN)), r.day(c.First.Unix()) + " – " + r.day(c.Last.Unix()), strings.Join(firstN(c.Techs, 4), ", ")}}) } v.Escs = tableV{Head: []string{r.t("col.ip"), r.t("col.stage"), r.t("col.host")}} for _, e := range o.Escalations { v.Escs.Rows = append(v.Escs.Rows, rowV{[]string{e.IP, r.tr("stage.", e.Stage), dash(e.Host)}}) } v.Expo = tableV{Head: []string{r.t("col.when"), r.t("col.ip"), r.t("col.host"), r.t("col.path"), r.t("col.status"), r.t("col.fam")}, Num: map[int]bool{4: true}, NoWrap: map[int]bool{0: true, 1: true}} for _, e := range o.Exposures.Items { host := e.Domain if host == "" { host = e.Host } v.Expo.Rows = append(v.Expo.Rows, rowV{[]string{r.date(e.T), e.IP, dash(host), clip(e.Path, 56), fmt.Sprint(e.Status), dash(e.Fam)}}) } // geography v.Countries = r.barChart(v.TCountries, r.counts(o.Countries, func(c store.Count) string { return c.Key }, 10), "#087f68") v.ASNs = r.barChart(v.TASNs, r.counts(o.ASNs, func(c store.Count) string { if c.Label != "" { return c.Key + " " + c.Label } return c.Key }, 10), "#087f68") // health: thwarted attacks are not application errors c := in.Classes if in.HasHealth { good := float64(c[store.ClsAttack] + c[store.ClsBlocked] + c[store.ClsBot]) bad := float64(c[store.ClsApp] + c[store.ClsProxy]) v.HealthLead = r.t("h.lead") if good > 0 { v.HealthNotes = append(v.HealthNotes, r.t("h.good", r.num(good))) } if bad > 0 { v.HealthNotes = append(v.HealthNotes, r.t("h.app", r.num(bad))) } var items []chartItem for i, n := range store.ClsNames { items = append(items, chartItem{r.tr("cls.", n), float64(c[i])}) } sort.SliceStable(items, func(a, b int) bool { return items[a].N > items[b].N }) v.Classes = r.donutChart(v.TClasses, items) if in.Traffic.P95 > 0 { v.HealthNotes = append(v.HealthNotes, r.t("h.p95", r.num(in.Traffic.P50), r.num(in.Traffic.P95))) } } else { v.HealthLead = r.t("h.nodata") v.Classes = chartV{Title: v.TClasses, Empty: true} } st := in.Traffic.Status v.Status = r.donutChart(v.TStatus, []chartItem{{r.t("st.2xx"), float64(st[0])}, {r.t("st.3xx"), float64(st[1])}, {r.t("st.4xx"), float64(st[2])}, {r.t("st.5xx"), float64(st[3])}}) // visitors tr := in.Traffic v.VisLead = r.t("vis.lead") v.VisKPIs = []kpiV{{Label: r.t("k.visitors"), Value: r.num(float64(tr.Visitors))}, {Label: r.t("k.pages"), Value: r.num(float64(tr.Pages))}, {Label: r.t("k.nonhuman"), Value: r.num(float64(tr.NonHuman))}} lab := func(c store.Count) string { return dash(c.Key) } v.Pages = r.barChart(r.t("c.pages"), r.counts(tr.TopPages, lab, 8), "#f97316") v.Browsers = r.donutChart(r.t("c.browsers"), r.counts(tr.Browsers, lab, 6)) v.Devices = r.donutChart(r.t("c.devices"), r.counts(tr.Devices, lab, 5)) v.Refs = r.barChart(r.t("c.refs"), r.counts(tr.Referrers, lab, 6), "#4b6b61") // defence d := o.Defense nodata := d.MTTBN == 0 mt := func(x float64) string { if nodata { return "-" } return r.dur(x) } v.Defense = tableV{Head: []string{r.t("col.metric"), r.t("col.value"), r.t("col.meaning")}, Num: map[int]bool{1: true}, Rows: []rowV{ {[]string{r.t("d.cover"), r.pct(d.BanCoverage), r.t("d.cover.m")}}, {[]string{r.t("d.mttb"), mt(d.MTTBMedianS), r.t("d.mttb.m")}}, {[]string{r.t("d.mttbp90"), mt(d.MTTBP90S), ""}}, {[]string{r.t("d.mttbn"), r.num(float64(d.MTTBN)), ""}}, {[]string{r.t("d.block"), r.pct(d.BlocklistCover), r.t("d.block.m")}}, {[]string{r.t("d.expo"), r.pct(d.ExposureRate), r.t("d.expo.m")}}, {[]string{r.t("d.refused"), r.pct(d.ExploitsRefused), r.t("d.refused.m")}}, }} // second firewall if e := in.Enforce; e != nil && e.Mode != enforce.ModeOff { v.HasEnf = true v.EnfLead = r.t("e.lead") v.EnfNotes = append(v.EnfNotes, r.t("e.mode")+": "+r.t("e.mode."+e.Mode)) cv := e.Coverage if cv.AttackIPs > 0 { v.EnfNotes = append(v.EnfNotes, r.t("e.cov", r.num(float64(cv.BlockedByFirewall+cv.BlockedByUrutau)), r.num(float64(cv.AttackIPs)), r.num(float64(cv.BlockedByFirewall)), r.num(float64(cv.BlockedByUrutau)))) } if cv.WouldBlock > 0 { v.EnfNotes = append(v.EnfNotes, r.t("e.would", r.num(float64(cv.WouldBlock)))) } if cv.Unblocked > 0 { v.EnfNotes = append(v.EnfNotes, r.t("e.unb", r.num(float64(cv.Unblocked)))) } v.EnfKPIs = []kpiV{{Label: r.t("e.decided"), Value: r.num(float64(e.Counts.Decided))}, {Label: r.t("e.written"), Value: r.num(float64(e.Counts.Written))}, {Label: r.t("e.already"), Value: r.num(float64(e.Counts.AlreadyBlocked))}, {Label: r.t("e.werr"), Value: r.num(float64(e.Counts.WriteErrors)), Cls: kc(e.Counts.WriteErrors > 0)}} v.EnfRecent = tableV{Head: []string{r.t("col.when"), r.t("col.ip"), r.t("col.reason"), r.t("col.action"), r.t("col.country")}, NoWrap: map[int]bool{0: true, 1: true}} for i, x := range e.Recent { if i >= 10 { break } v.EnfRecent.Rows = append(v.EnfRecent.Rows, rowV{[]string{r.date(x.T), x.IP, dash(x.Reason), dash(x.Action), ccOf(x.CC, "")}}) } } // egress if x := in.Egress; x != nil && x.Source.State != "disabled" && x.Source.State != "" { v.HasEgress = true v.XLead = r.t("x.lead") rep := x.Report if len(rep.Findings) == 0 { v.XNotes = append(v.XNotes, r.t("x.nof")) } else { v.XNotes = append(v.XNotes, r.t("x.sev", r.num(float64(len(rep.Findings))), r.num(float64(xHigh)))) } if x.Suppressed > 0 { v.XNotes = append(v.XNotes, r.t("x.supp", r.num(float64(x.Suppressed)))) } v.XNotes = append(v.XNotes, r.t("x.src", x.Source.State)) v.XWl = tableV{Head: []string{r.t("col.wl"), r.t("col.role"), r.t("col.conns"), r.t("col.dst")}, Num: map[int]bool{2: true, 3: true}} var items []chartItem for i, w := range rep.Workloads { if i < 12 { v.XWl.Rows = append(v.XWl.Rows, rowV{[]string{w.Name, dash(w.Role), r.num(float64(w.Conns)), r.num(float64(w.Dsts))}}) } if i < 8 { items = append(items, chartItem{w.Name, float64(w.Conns)}) } } v.XChart = r.barChart(v.TXChart, items, "#087f68") var dst []chartItem for i, d := range rep.TopDst { if i >= 8 { break } dst = append(dst, chartItem{d.IP + " " + d.CC, float64(d.Conns)}) } v.XDst = r.barChart(v.TXDst, dst, "#c2410c") v.XFind = tableV{Head: []string{r.t("col.sev"), r.t("col.kind"), r.t("col.wl"), r.t("col.dst"), r.t("col.detail")}} for i, f := range rep.Findings { if i >= 10 { break } v.XFind.Rows = append(v.XFind.Rows, rowV{[]string{r.tr("sev.", f.Severity), dash(f.Kind), f.Workload, fmt.Sprintf("%s:%d/%s", f.Dst, f.DPort, f.Proto), clip(f.Detail, 80)}}) } } for _, tb := range []*tableV{&v.IPs, &v.Camps, &v.Escs, &v.Expo, &v.Defense, &v.EnfRecent, &v.XWl, &v.XFind} { tb.None = v.None } v.Expo.None = r.t("v.expo0") v.Recs = r.recommend(in, cover, xHigh) v.TOC = []secV{{"sum", v.TSum}, {"threats", v.TThreats}, {"geo", v.TGeo}, {"health", v.THealth}, {"vis", v.TVis}, {"def", v.TDef}} if v.HasEnf { v.TOC = append(v.TOC, secV{"enf", v.TEnf}) } if v.HasEgress { v.TOC = append(v.TOC, secV{"egress", v.TEgress}) } v.TOC = append(v.TOC, secV{"method", v.TMethod}) return v } func dash(s string) string { if s == "" { return "-" } return s } func firstN(s []string, n int) []string { if len(s) > n { return s[:n] } return s } // recommend turns the figures into actions with plain rules, most urgent first. func (r *renderer) recommend(in reportInput, cover float64, xHigh int) []recV { o, s := in.Out, in.Out.Summary var rs []recV add := func(l, k string, a ...any) { rs = append(rs, recV{l, r.t("rec." + l), r.t(k, a...)}) } enfOn := in.Enforce != nil && in.Enforce.Mode == enforce.ModeOn if o.Exposures.Total > 0 { add("bad", "r.expo", r.num(float64(o.Exposures.Total))) } if xHigh > 0 { add("bad", "r.egress", r.num(float64(xHigh))) } if len(o.Escalations) > 0 { add("warn", "r.esc", r.num(float64(len(o.Escalations)))) } switch { case in.Enforce == nil || in.Enforce.Mode == enforce.ModeOff: if s.Attacks > 0 && (s.HostileIPs > 0 && cover < 90) { add("warn", "r.enforce", r.num(float64(maxInt(s.HostileIPs-s.Bans, 1)))) } case in.Enforce.Mode == enforce.ModeObserve: add("warn", "r.observe") case enfOn && in.Enforce.Coverage.Unblocked > 0: add("warn", "r.unblocked", r.num(float64(in.Enforce.Coverage.Unblocked))) } if s.HostileIPs > 0 && cover < 50 { add("warn", "r.cover", r.dec(cover, 0)) } if o.Defense.MTTBN > 0 && o.Defense.MTTBMedianS > 600 { add("warn", "r.mttb", r.dur(o.Defense.MTTBMedianS)) } if len(o.Campaigns) > 0 { add("info", "r.camp", r.num(float64(len(o.Campaigns)))) } if in.HasHealth { if n := in.Classes[store.ClsApp] + in.Classes[store.ClsProxy]; n > 0 { add("warn", "r.app", r.num(float64(n))) } } if dp, ok := s.DeltaPct["attacks"]; s.HasPrev && ok && dp >= 50 && s.Attacks >= 20 { add("info", "r.up", r.num(dp)) } if in.Egress == nil || in.Egress.Source.State == "disabled" { add("info", "r.noegress") } if len(rs) == 0 { add("ok", "r.ok") } return rs } func maxInt(a, b int) int { if a > b { return a } return b } var reportTpl = template.Must(template.New("report").Parse(reportTemplate)) // renderReportHTML renders the document; the error is a template failure. func renderReportHTML(in reportInput, now int64) ([]byte, error) { r := newRenderer(in.Lang) var buf bytes.Buffer if err := reportTpl.Execute(&buf, r.build(in, now)); err != nil { return nil, err } return buf.Bytes(), nil } var fileSafe = regexp.MustCompile(`[^A-Za-z0-9._-]+`) // reportExtras gathers what the JSON report does not carry: service health // classes, traffic study, second firewall and outbound analysis. func (s *Server) reportExtras(r *http.Request, rc *reportCtx) reportInput { in := reportInput{Out: rc.out, Lang: r.URL.Query().Get("lang")} self := s.opt.Store.Name() in.Traffic = s.trafficOf(r, rc.rg, rc.host) in.Peers = rc.host != self && s.opt.Hub != nil if rc.host == "all" || rc.host == self { for _, v := range s.opt.Store.Services(rc.from, rc.to, "", "") { in.HasHealth = true for i := range in.Classes { in.Classes[i] += v.Tot.Cls[i] } } if e := enforceEngine.Load(); e != nil { rep := e.Report(rc.from) in.Enforce = &enforceView{Mode: e.Mode(), Share: e.Share(), Coverage: rep.Coverage, Counts: rep.Counts, Recent: rep.Recent} } if e := egressEngine.Load(); e != nil { rep := e.Report(rc.from, rc.to) sup := s.annotateFindings(&rep, false) // tickets marked false positive/benign leave the report in.Egress = &egressView{Source: e.Info(), Report: rep, Suppressed: sup} } } return in } func (s *Server) writeReportHTML(w http.ResponseWriter, r *http.Request, rc *reportCtx) { now := s.opt.Now().Unix() body, err := renderReportHTML(s.reportExtras(r, rc), now) if err != nil { http.Error(w, "report failed", http.StatusInternalServerError) return } name := fileSafe.ReplaceAllString(rc.host, "-") if rc.host == "all" && len(rc.out.Hosts) == 1 { name = fileSafe.ReplaceAllString(rc.out.Hosts[0], "-") } if name == "" { name = "all" } w.Header().Set("Content-Type", "text/html; charset=utf-8") // the document is self-contained: inline CSS and data: images only, no script w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'self'") w.Header().Set("X-Frame-Options", "SAMEORIGIN") // previewed in an iframe by the Reports page only disp := "attachment" if r.URL.Query().Get("inline") == "1" { disp = "inline" } w.Header().Set("Content-Disposition", fmt.Sprintf(`%s; filename="urutau-relatorio-%s-%s.html"`, disp, name, time.Unix(now, 0).UTC().Format("2006-01-02"))) w.Header().Set("Cache-Control", "no-store") _, _ = w.Write(body) }