diff --git a/docs/img/egress-dark-pt.png b/docs/img/egress-dark-pt.png index 8551628..6d14d26 100644 Binary files a/docs/img/egress-dark-pt.png and b/docs/img/egress-dark-pt.png differ diff --git a/docs/img/egress-dark.png b/docs/img/egress-dark.png index 0e0ce67..e8a8f3a 100644 Binary files a/docs/img/egress-dark.png and b/docs/img/egress-dark.png differ diff --git a/docs/img/egress-light.png b/docs/img/egress-light.png index ec68f79..624e108 100644 Binary files a/docs/img/egress-light.png and b/docs/img/egress-light.png differ diff --git a/docs/img/egress-mobile.png b/docs/img/egress-mobile.png index eeee652..e97d892 100644 Binary files a/docs/img/egress-mobile.png and b/docs/img/egress-mobile.png differ diff --git a/internal/egress/egress_test.go b/internal/egress/egress_test.go index bc641c8..ff4b628 100644 --- a/internal/egress/egress_test.go +++ b/internal/egress/egress_test.go @@ -173,6 +173,14 @@ func TestBeaconPositive(t *testing.T) { if hi == nil || hi.Severity != "high" { t.Fatalf("attacker beacon: %+v", hi) } + if n := len(got.Samples); n < 40 || n > MaxSamples || got.Samples[n-1] != got.Last { + t.Fatalf("samples: %d %v", n, got.Samples) + } + for i := 1; i < len(got.Samples); i++ { + if got.Samples[i] <= got.Samples[i-1] { + t.Fatalf("samples not increasing: %v", got.Samples) + } + } } func TestBeaconNegatives(t *testing.T) { @@ -420,6 +428,34 @@ func TestReportMergeSanitize(t *testing.T) { } } +func TestReportByCountry(t *testing.T) { + geo := func(s string) (string, string, string) { + if s == "203.0.113.1" || s == "203.0.113.2" { + return "DE", "AS1", "x" + } + return "US", "AS2", "y" + } + e := newEng(t, Config{Geo: geo}) + e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.1", "tcp", 443)) + e.IngestEvent(mk(t0, "10.0.3.5", "203.0.113.2", "tcp", 443)) + e.IngestEvent(mk(t0.Add(time.Minute), "10.0.3.5", "203.0.113.2", "tcp", 443)) + e.IngestEvent(mk(t0, "10.0.3.5", "198.51.100.1", "tcp", 443)) + r := e.Report(t0.Unix()-3600, t0.Unix()+3600) + if len(r.ByCountry) != 2 || r.ByCountry[0].CC != "DE" || r.ByCountry[0].Conns != 3 || r.ByCountry[0].Dsts != 2 || r.ByCountry[1].Conns != 1 { + t.Fatalf("by_country: %+v", r.ByCountry) + } + peer := e.Report(t0.Unix()-3600, t0.Unix()+3600) + peer.ByCountry = append(peer.ByCountry, make([]CountryOut, 400)...) + peer.Sanitize("p") + if len(peer.ByCountry) > maxCountries { + t.Fatalf("sanitize: %d", len(peer.ByCountry)) + } + r.Merge(peer, "p") + if r.ByCountry[0].CC != "DE" || r.ByCountry[0].Conns != 6 { + t.Fatalf("merge: %+v", r.ByCountry[:2]) + } +} + func TestNameMatchExactAndPrefix(t *testing.T) { e := newEng(t, Config{Workloads: "a=name:web:default;b=name:api*:default;c=name:pay:default"}) e.SetContainers(map[netip.Addr]string{ip("172.18.0.1"): "web-1700000000000", ip("172.18.0.2"): "webshell-1700000000000", diff --git a/internal/egress/engine.go b/internal/egress/engine.go index f635df9..dff688a 100644 --- a/internal/egress/engine.go +++ b/internal/egress/engine.go @@ -744,7 +744,14 @@ func suspiciousPort(port uint16, role string) (sev, why string) { func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairState, ds *dstStat) { if p.flagged { - e.addFinding("beacon", "", ws.name, ev.Dst.String(), dport, ev.Proto, p.last, p.interval, p.cv, "", 1) + if f := e.addFinding("beacon", "", ws.name, ev.Dst.String(), dport, ev.Proto, p.last, p.interval, p.cv, "", 1); f != nil { + if n := len(f.Samples); n == 0 || f.Samples[n-1] != p.last { + if n >= MaxSamples { + f.Samples = append(f.Samples[:0], f.Samples[1:]...) + } + f.Samples = append(f.Samples, p.last) + } + } return } ntp := ev.Proto == "udp" && dport == 123 @@ -806,6 +813,10 @@ func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairSta f := e.addFinding("beacon", sev, ws.name, ev.Dst.String(), dport, ev.Proto, p.last, med, jit, why, 0) if f != nil { f.Count, f.First = int(p.total), p.first + f.Samples = make([]int64, 0, MaxSamples) + for i := 0; i < p.n; i++ { + f.Samples = append(f.Samples, int64(p.ts[i])) + } } } diff --git a/internal/egress/report.go b/internal/egress/report.go index cb168eb..ed6d8e3 100644 --- a/internal/egress/report.go +++ b/internal/egress/report.go @@ -22,6 +22,18 @@ type Finding struct { Last int64 `json:"last"` Detail string `json:"detail"` Host string `json:"host,omitempty"` + // Samples are the unix times of the last connections (beacons only, at most MaxSamples). + Samples []int64 `json:"samples,omitempty"` +} + +// MaxSamples bounds Finding.Samples. +const MaxSamples = 64 + +// CountryOut sums the destinations of one country. +type CountryOut struct { + CC string `json:"cc"` + Conns uint64 `json:"conns"` + Dsts int `json:"dsts"` } // WorkloadOut summarises a workload over the window. @@ -79,6 +91,7 @@ type Report struct { TopDst []DstOut `json:"top_dst"` Findings []Finding `json:"findings"` Scanner ScannerOut `json:"scanner"` + ByCountry []CountryOut `json:"by_country"` } func (bs *burstState) out(wl string, end int64) BurstOut { @@ -133,14 +146,16 @@ func (e *Engine) Report(from, to int64) Report { startH = endH - (HourBuckets - 1) } nb := int(endH-startH) + 1 - r := Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{}, + r := Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{}, ByCountry: []CountryOut{}, Timeline: Timeline{Start: startH * 3600, Step: 3600, Series: map[string][]uint32{}}, Scanner: ScannerOut{Bursts: []BurstOut{}}} fc := map[string]int{} for _, f := range e.findings { if f.Last >= from && f.First <= to { - r.Findings = append(r.Findings, *f) + c := *f + c.Samples = append([]int64(nil), f.Samples...) + r.Findings = append(r.Findings, c) fc[f.Workload]++ } } @@ -212,6 +227,20 @@ func (e *Engine) Report(from, to int64) Report { } return all[i].ds.ip.Compare(all[j].ds.ip) < 0 }) + bc := map[string]*CountryOut{} + for _, a := range all { + c := bc[a.ds.cc] + if c == nil { + c = &CountryOut{CC: a.ds.cc} + bc[a.ds.cc] = c + } + c.Conns += a.n + c.Dsts++ + } + for _, c := range bc { + r.ByCountry = append(r.ByCountry, *c) + } + sortCountries(r.ByCountry) for i := 0; i < len(all) && i < 50; i++ { ds := all[i].ds ports := append([]uint16(nil), ds.ports...) @@ -237,8 +266,18 @@ const ( maxPeerWorkloads = 256 maxPeerFindings = MaxFindings maxStr = 200 + maxCountries = 300 ) +func sortCountries(cs []CountryOut) { + sort.Slice(cs, func(i, j int) bool { + if cs[i].Conns != cs[j].Conns { + return cs[i].Conns > cs[j].Conns + } + return cs[i].CC < cs[j].CC + }) +} + func clip(s string) string { if len(s) > maxStr { return s[:maxStr] @@ -268,6 +307,15 @@ func (r *Report) Sanitize(host string) { f := &r.Findings[i] f.ID, f.Kind, f.Severity = host+":"+clip(f.ID), clip(f.Kind), clip(f.Severity) f.Workload, f.Dst, f.Proto, f.Detail, f.Host = clip(f.Workload), clip(f.Dst), clip(f.Proto), clip(f.Detail), host + if len(f.Samples) > MaxSamples { + f.Samples = f.Samples[len(f.Samples)-MaxSamples:] + } + } + if len(r.ByCountry) > maxCountries { + r.ByCountry = r.ByCountry[:maxCountries] + } + for i := range r.ByCountry { + r.ByCountry[i].CC = clip(r.ByCountry[i].CC) } for i := range r.TopDst { d := &r.TopDst[i] @@ -312,6 +360,22 @@ func (r *Report) Merge(o Report, host string) { r.Findings = append(r.Findings, o.Findings...) r.Scanner.Bursts = append(r.Scanner.Bursts, o.Scanner.Bursts...) r.TopDst = append(r.TopDst, o.TopDst...) + if len(o.ByCountry) > 0 { + idx := map[string]int{} + for i, c := range r.ByCountry { + idx[c.CC] = i + } + for _, c := range o.ByCountry { + if i, ok := idx[c.CC]; ok { + r.ByCountry[i].Conns += c.Conns + r.ByCountry[i].Dsts += c.Dsts // a destination reached by two hosts counts twice + continue + } + idx[c.CC] = len(r.ByCountry) + r.ByCountry = append(r.ByCountry, c) + } + sortCountries(r.ByCountry) + } sort.SliceStable(r.TopDst, func(i, j int) bool { return r.TopDst[i].Conns > r.TopDst[j].Conns }) if len(r.TopDst) > 50 { r.TopDst = r.TopDst[:50] @@ -366,6 +430,6 @@ func (r *Report) Stamp(host string) { // EmptyReport is a well-formed report without data. func EmptyReport() Report { - return Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{}, Scanner: ScannerOut{Bursts: []BurstOut{}}, + return Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{}, ByCountry: []CountryOut{}, Scanner: ScannerOut{Bursts: []BurstOut{}}, Timeline: Timeline{Step: 3600, Series: map[string][]uint32{}}} } diff --git a/internal/server/web/egress.css b/internal/server/web/egress.css index 9b1820f..a78a482 100644 --- a/internal/server/web/egress.css +++ b/internal/server/web/egress.css @@ -1,30 +1,155 @@ /* Egress page */ .eg-page { display: grid; gap: var(--grid-gap, 16px); min-width: 0; } -.eg-page .panel, .eg-kpis .card-metric { min-width: 0; } -.eg-wl-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 240px), 1fr)); gap: 12px; } -.eg-wl { min-width: 0; } -.eg-wl-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 8px; margin-bottom: 8px; } -.eg-wl-head .badge { white-space: normal; } -.eg-wl-name { margin: 0; font-size: 1rem; overflow-wrap: anywhere; } -.eg-wl-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin: 0; } -.eg-wl-stats div { min-width: 0; } -.eg-wl-stats dd { margin: 0; font-size: 1.125rem; font-weight: 600; } -.eg-wl-stats dt { color: var(--ink-muted); font-size: .75rem; overflow-wrap: anywhere; } -.eg-warn { color: var(--danger); font-weight: 600; } -.eg-findings { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; } -.eg-f { border: 1px solid var(--line); border-left-width: 4px; border-radius: 6px; padding: 10px 12px; min-width: 0; } -.eg-sev-high { border-left-color: var(--danger); } -.eg-sev-medium { border-left-color: var(--warn); } -.eg-sev-low { border-left-color: var(--info); } -.eg-f-top { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; } -.eg-f p { margin: 6px 0 0; overflow-wrap: anywhere; } -.eg-f-why { color: var(--ink-muted); } -.eg-f-detail { font-size: .8125rem; } -.eg-scroll { max-height: 440px; overflow: auto; } +.eg-page .panel, .eg-page .card-metric { min-width: 0; } + +/* verdict */ +.eg-verdict { --tn: var(--ok); --tn-soft: var(--ok-soft); display: flex; gap: 18px; align-items: flex-start; padding: 20px 22px; border: 1px solid color-mix(in srgb, var(--tn) 45%, var(--line)); border-radius: 14px; + background: linear-gradient(110deg, color-mix(in srgb, var(--tn-soft) 90%, transparent), var(--surface-panel) 70%); min-width: 0; } +.eg-verdict.tone-danger { --tn: var(--danger); --tn-soft: var(--danger-soft); } +.eg-verdict.tone-warn { --tn: var(--warn); --tn-soft: var(--warn-soft); } +.eg-verdict.tone-info { --tn: var(--info); --tn-soft: var(--info-soft); } +.eg-verdict.tone-neutral { --tn: var(--ink-faint); --tn-soft: var(--surface-raised); } +.eg-v-ico { flex: none; width: 52px; height: 52px; border-radius: 50%; display: grid; place-items: center; font-size: 1.6rem; font-weight: 800; color: var(--surface-base); background: var(--tn); + box-shadow: 0 0 0 7px color-mix(in srgb, var(--tn) 22%, transparent); } +.eg-v-txt { min-width: 0; display: grid; gap: 6px; } +.eg-v-txt h2 { margin: 0; font-size: 1.5rem; line-height: 1.2; color: var(--ink); } +.eg-v-txt > p { margin: 0; color: var(--ink-muted); overflow-wrap: anywhere; } +.eg-v-pills { display: flex; flex-wrap: wrap; gap: 6px; } +.eg-v-src { font-size: .8125rem; color: var(--ink-faint) !important; display: flex; align-items: center; gap: 6px; } +.eg-dot { width: 8px; height: 8px; border-radius: 50%; flex: none; display: inline-block; background: var(--warn); } +.eg-dot-ok { background: var(--ok); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ok) 25%, transparent); } + +/* KPIs */ +.eg-kpis { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: var(--grid-gap, 16px); } +@media (max-width: 900px) { .eg-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); } } + +/* evidence */ +.eg-evs { display: grid; gap: 14px; } +.eg-ev { --sv: var(--info); border: 1px solid var(--line); border-radius: 12px; background: var(--surface-raised); overflow: hidden; min-width: 0; position: relative; } +.eg-ev::before { content: ""; position: absolute; inset: 0 auto 0 0; width: 4px; background: var(--sv); } +.eg-sev-high { --sv: var(--danger); } +.eg-sev-medium { --sv: var(--warn); } +.eg-ev-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 10px; padding: 12px 16px 10px 20px; border-bottom: 1px solid var(--line); + background: linear-gradient(90deg, color-mix(in srgb, var(--sv) 14%, transparent), transparent 60%); } +.eg-ev-title { margin: 0; font-size: 1.0625rem; } +.eg-ev-body { padding: 14px 16px 16px 20px; display: grid; gap: 14px; min-width: 0; } +.eg-ev-top { display: flex; flex-wrap: wrap; gap: 14px 24px; align-items: center; justify-content: space-between; } +.eg-route { display: flex; align-items: center; gap: 12px; min-width: 0; flex-wrap: wrap; } +.eg-node { display: grid; gap: 2px; padding: 8px 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface-panel); min-width: 0; } +.eg-node-dst { border-color: color-mix(in srgb, var(--sv) 55%, var(--line)); } +.eg-node-k { font-size: .75rem; color: var(--ink-faint); text-transform: uppercase; letter-spacing: .04em; } +.eg-node-ip { font-weight: 600; overflow-wrap: anywhere; } +.eg-node-org { font-size: .8125rem; color: var(--ink-muted); overflow-wrap: anywhere; } +.eg-port { color: var(--ink-muted); } +.eg-arrow { width: 44px; height: 2px; background: linear-gradient(90deg, var(--line-strong), var(--sv)); position: relative; flex: none; } +.eg-arrow::after { content: ""; position: absolute; right: -2px; top: -4px; border: 5px solid transparent; border-left-color: var(--sv); border-right: 0; } +.eg-facts { display: flex; flex-wrap: wrap; gap: 8px; } +.eg-fact { display: grid; padding: 6px 12px; border-radius: 8px; background: var(--surface-panel); border: 1px solid var(--line); min-width: 0; } +.eg-fact strong { font-size: 1.05rem; } +.eg-fact > span { font-size: .75rem; color: var(--ink-faint); display: inline-flex; align-items: center; gap: 4px; } +.eg-ev-vizrow { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); gap: 16px; } +.eg-ev-viz { min-width: 0; display: grid; gap: 4px; } +.eg-ev-viz .hint { margin: 0; font-size: .75rem; } +.eg-ev-lab { margin: 0; font-size: .75rem; font-weight: 600; text-transform: uppercase; letter-spacing: .05em; color: var(--ink-faint); } +.eg-rhythm, .eg-hist, .eg-scan-tl { width: 100%; display: block; background: var(--surface-sunken); border-radius: 8px; } +.eg-rhythm { height: 52px; } +.eg-hist { height: 52px; } +.eg-scan-tl { height: 64px; } +.eg-axis { stroke: var(--line-strong); stroke-width: 1; vector-effect: non-scaling-stroke; } +.eg-tick { stroke: var(--sv); stroke-width: 2; vector-effect: non-scaling-stroke; stroke-linecap: round; } +.eg-bin { fill: color-mix(in srgb, var(--sv) 40%, transparent); } +.eg-bin.on { fill: var(--sv); } +.eg-ev-axis { display: flex; justify-content: space-between; gap: 8px; font-size: .75rem; color: var(--ink-faint); font-variant-numeric: tabular-nums; } +.eg-ev-axis strong { color: var(--ink); font-weight: 600; } +.eg-ev-detail { margin: 0; font-size: .8125rem; color: var(--ink-muted); padding: 6px 10px; background: var(--surface-sunken); border-radius: 6px; overflow-wrap: anywhere; } +.eg-ev-advice { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } +.eg-ev-advice > div { padding: 10px 12px; border-radius: 8px; background: var(--surface-panel); border: 1px solid var(--line); min-width: 0; } +.eg-ev-advice p { margin: 0; overflow-wrap: anywhere; } +.eg-ev-advice p + p { margin-top: 4px; color: var(--ink-muted); } +.eg-ev-todo { border-color: color-mix(in srgb, var(--accent) 40%, var(--line)) !important; } +.eg-ev-btn { justify-self: start; text-decoration: none; } +.eg-calm { display: flex; gap: 16px; align-items: center; padding: 22px; border-radius: 12px; border: 1px dashed color-mix(in srgb, var(--ok) 50%, var(--line)); background: color-mix(in srgb, var(--ok-soft) 50%, transparent); } +.eg-calm-ico { width: 44px; height: 44px; flex: none; border-radius: 50%; display: grid; place-items: center; background: var(--ok); color: var(--surface-base); font-weight: 800; font-size: 1.3rem; } +.eg-calm p { margin: 4px 0 0; color: var(--ink-muted); } + +/* map */ +.eg-mapwrap { display: grid; grid-template-columns: minmax(0, 1fr) 260px; gap: 16px; align-items: center; } +.eg-mapbox { border-radius: 10px; background: color-mix(in srgb, var(--surface-sunken) 70%, transparent); overflow: hidden; min-width: 0; } +.eg-map { width: 100%; height: auto; display: block; } +.eg-land { fill: var(--surface-raised); stroke: var(--line); stroke-width: .6; } +.eg-land.s1 { fill: color-mix(in srgb, var(--seq-2) 45%, var(--surface-raised)); } .eg-land.s2 { fill: color-mix(in srgb, var(--seq-2) 70%, var(--surface-raised)); } .eg-land.s3 { fill: var(--seq-2); } .eg-land.s4, .eg-land.s5 { fill: var(--seq-3); } +.eg-arc { fill: none; stroke: var(--accent); stroke-width: 2.2; opacity: .75; stroke-dasharray: 6 5; } +.eg-arc.warn { stroke: var(--warn); opacity: .95; } +.eg-arc.danger { stroke: var(--danger); opacity: 1; stroke-width: 3; } +.eg-dst { fill: color-mix(in srgb, var(--accent) 35%, transparent); stroke: var(--accent); stroke-width: 2; } +.eg-dst.warn { fill: color-mix(in srgb, var(--warn) 35%, transparent); stroke: var(--warn); } +.eg-dst.danger { fill: color-mix(in srgb, var(--danger) 35%, transparent); stroke: var(--danger); } +.eg-src { fill: var(--ok); stroke: var(--surface-base); stroke-width: 2; } +.eg-src-halo { fill: color-mix(in srgb, var(--ok) 25%, transparent); } +.eg-cc { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; } +.eg-cc li { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 8px; align-items: center; } +.eg-cc-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.eg-cc-n { font-variant-numeric: tabular-nums; color: var(--ink-muted); } +.eg-bar { grid-column: 1 / -1; display: block; height: 6px; border-radius: 3px; background: var(--surface-sunken); overflow: hidden; } +.eg-bar > span { display: block; height: 100%; border-radius: 3px; background: linear-gradient(90deg, var(--seq-2), var(--seq-4)); } + +/* tables */ .eg-table { width: 100%; border-collapse: collapse; font-size: .875rem; } -.eg-table th, .eg-table td { padding: 5px var(--s-3, 10px); border-bottom: 1px solid var(--line); text-align: left; overflow-wrap: anywhere; vertical-align: top; } -.eg-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); } +.eg-table th, .eg-table td { padding: 8px var(--s-3, 10px); border-bottom: 1px solid var(--line); text-align: left; vertical-align: middle; overflow-wrap: anywhere; } +.eg-table th { color: var(--ink-muted); font-weight: 500; font-size: .8125rem; } .eg-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; } -.eg-scanwarn { margin-bottom: 10px; } -@media (max-width: 600px) { .eg-kpis .span-4 { grid-column: 1 / -1; } } -@media (max-width: 700px) { .eg-table { min-width: 560px; } } +.eg-table tbody tr:hover { background: color-mix(in srgb, var(--accent) 6%, transparent); } +.eg-row-bad td:first-child { box-shadow: inset 3px 0 0 var(--danger); } +.eg-wl-name { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; } +.eg-wl-supp { flex-basis: 100%; font-size: .75rem; margin: 0; } +.eg-spark { width: 140px; color: var(--accent); } +.eg-spark .cm-spark { width: 130px; height: 24px; display: block; position: static; } +.eg-spark .cm-spark polyline { fill: none; stroke: currentColor; stroke-width: 1.5; vector-effect: non-scaling-stroke; } +.eg-ok { color: var(--ok); font-weight: 700; } +.eg-chips { display: inline-flex; flex-wrap: wrap; gap: 4px; } +.eg-chips .chip { margin: 0; } +.eg-chip-port { color: var(--accent); } +.eg-dst-ip { display: inline-flex; flex-wrap: wrap; align-items: center; gap: 6px; } +.eg-flag { font-size: 1.1rem; } +.eg-asn { color: var(--ink-faint); } +.eg-conns { min-width: 110px; } +.eg-conns .eg-bar { margin-top: 4px; } + +/* scanner */ +.eg-scan { display: grid; gap: 12px; } +.eg-scan-ok { margin: 0; display: flex; align-items: center; gap: 8px; color: var(--ink-muted); } +.eg-burst { fill: color-mix(in srgb, var(--info) 55%, transparent); stroke: var(--info); stroke-width: 1; vector-effect: non-scaling-stroke; } +.eg-burst.bad { fill: color-mix(in srgb, var(--danger) 60%, transparent); stroke: var(--danger); } +.eg-bursts { list-style: none; margin: 0; padding: 0; display: grid; } +.eg-bursts li { display: grid; grid-template-columns: 96px minmax(0, 260px) minmax(0, 1fr); gap: 6px 12px; align-items: center; padding: 8px 0; border-bottom: 1px solid var(--line); } +.eg-bursts li.bad { box-shadow: inset 3px 0 0 var(--danger); padding-left: 8px; } +.eg-b-when { color: var(--ink-faint); white-space: nowrap; } +.eg-b-chips { display: flex; flex-wrap: wrap; gap: 4px; min-width: 0; } +.eg-scanwarn { margin: 0; } + +@media (max-width: 1000px) { + .eg-mapwrap { grid-template-columns: 1fr; } + .eg-ev-vizrow, .eg-ev-advice { grid-template-columns: 1fr; } +} +@media (max-width: 700px) { + .eg-verdict { padding: 16px; gap: 12px; } + .eg-v-ico { width: 40px; height: 40px; font-size: 1.2rem; box-shadow: 0 0 0 5px color-mix(in srgb, var(--tn) 22%, transparent); } + .eg-v-txt h2 { font-size: 1.2rem; } + .eg-ev-body { padding: 12px 12px 14px 16px; } + .eg-ev-head { padding-left: 16px; } + .eg-arrow { transform: rotate(90deg); width: 20px; margin: 6px 0 6px 20px; } + .eg-route { flex-direction: column; align-items: stretch; gap: 4px; } + .eg-facts .eg-fact { flex: 1 1 40%; } + /* tables become stacked rows */ + .eg-table thead { display: none; } + .eg-table, .eg-table tbody, .eg-table tr, .eg-table td { display: block; width: 100%; } + .eg-table tr { padding: 10px 0; border-bottom: 1px solid var(--line); display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px 12px; } + .eg-table td { border: 0; padding: 0; text-align: left !important; } + .eg-table td.eg-c-name { grid-column: 1 / -1; } + .eg-table td[data-l]::before { content: attr(data-l); display: block; font-size: .6875rem; color: var(--ink-faint); text-transform: uppercase; letter-spacing: .04em; } + .eg-row-bad td:first-child { box-shadow: none; } + .eg-row-bad { box-shadow: inset 3px 0 0 var(--danger); padding-left: 10px !important; } + .eg-spark, .eg-conns { width: auto; min-width: 0; } + .eg-bursts li { grid-template-columns: 84px minmax(0, 1fr); } + .eg-b-chips { grid-column: 1 / -1; } +} diff --git a/internal/server/web/egress.js b/internal/server/web/egress.js index 290743b..249d51f 100644 --- a/internal/server/web/egress.js +++ b/internal/server/web/egress.js @@ -1,15 +1,19 @@ /* Urutau - EGRESS page: what the workloads of your servers talk to on the - internet (outbound traffic). Beacons, scans, odd ports, known-bad - destinations, DNS bypass, new countries, and the summarised scans of the - authorised scanner. Data: /api/v1/egress. Log data is hostile: dynamic text - goes through textContent only. */ + internet (outbound traffic). A verdict in plain words, evidence cards per + finding (beacon rhythm drawn from real connection times), a world map of + destinations, workload x hour activity, the workloads table, the authorised + scanner bursts on a time axis and the top destinations. + Data: /api/v1/egress (+ /api/v1/summary for the server locations). + Log data is hostile: dynamic text goes through textContent only. */ (function () { 'use strict'; var SEV = { high: 0, medium: 1, low: 2 }; + var SEV_NAME = ['high', 'medium', 'low']; var SEV_TONE = { high: 'danger', medium: 'warn', low: 'info' }; var KINDS = ['beacon', 'scan', 'port', 'bad_dst', 'dns_bypass', 'new_geo']; - var KIND_HELP = { beacon: 'term.beaconing', scan: 'term.fanout', port: 'term.stratum', bad_dst: 'term.c2', dns_bypass: 'term.dot', new_geo: 'term.new_geo' }; + var KIND_HELP = { beacon: 'term.beaconing', scan: 'term.fanout', port: 'term.stratum', bad_dst: 'term.eg_baddst', dns_bypass: 'term.dot', new_geo: 'term.new_geo' }; + var LAT_TOP = 84, LAT_SPAN = 142; function boot() { var U = window.Urutau; @@ -21,44 +25,34 @@ 'eg.retry': 'Try again', 'eg.disabled': 'Outbound traffic is not being watched', 'eg.disabled.sub': 'This page shows connections that leave your servers. To see them, add an outbound firewall rule on the server that logs new connections, and set the variable URUTAU_EGRESS so Urutau reads that log.', - 'eg.lead.none': 'No outbound connections {range}', - 'eg.lead.none.sub': 'Nothing left the watched workloads in this window.', - 'eg.lead.ok': '{n} outbound connections {range}, nothing suspicious', - 'eg.lead.ok.sub': 'No findings in this window. Authorised scans, if any, are summarised below.', - 'eg.lead.bad': '{f} findings in {n} outbound connections {range}', - 'eg.lead.bad.sub': '{h} high, {m} medium and {l} low severity. Start with the high ones.', - 'eg.src': 'Log source: {state} · {lines} lines read · {bad} unreadable', + 'eg.v.ok': 'No sign of a compromised server', + 'eg.v.ok.sub': '{n} outbound connections {range} from {w} workloads, all with normal behaviour.', + 'eg.v.none': 'No outbound connections {range}', + 'eg.v.none.sub': 'Nothing left the watched workloads in this window.', + 'eg.v.bad.1': '1 sign to investigate', + 'eg.v.bad.n': '{n} signs to investigate', + 'eg.v.bad.sub': 'Found among {c} outbound connections {range}. Start with the first card below.', + 'eg.src': 'Log {state} · {lines} lines read · {bad} unreadable', 'eg.src.following': 'being followed', 'eg.src.waiting': 'waiting for the file', 'eg.src.missing': 'file not found', - 'eg.src.error': 'error', + 'eg.src.error': 'with errors', 'eg.kpi.conns': 'Connections', 'eg.kpi.conns.sub': 'new outbound connections', 'eg.kpi.dsts': 'Destinations', - 'eg.kpi.dsts.sub': 'different addresses reached', + 'eg.kpi.dsts.sub': 'addresses in {c} countries', + 'eg.kpi.wl': 'Workloads', + 'eg.kpi.wl.sub': '{n} talking to the internet', 'eg.kpi.find': 'Findings', 'eg.kpi.find.sub': '{h} high · {m} medium · {l} low', - 'eg.workloads': 'Workloads', - 'eg.workloads.hint': 'Each workload is a program or container that makes outbound connections.', - 'eg.wl.conns': 'connections', - 'eg.wl.dsts': 'destinations', - 'eg.wl.ports': 'ports', - 'eg.wl.findings': 'findings', - 'eg.wl.suppressed': '{n} scan connections summarised', - 'eg.role.scanner': 'authorised scans summarised', - 'eg.role.app': 'application', - 'eg.role.proxy': 'proxy', - 'eg.role.database': 'database', - 'eg.role.system': 'system', - 'eg.timeline': 'Connections over time', - 'eg.timeline.hint': 'Stacked by workload.', - 'eg.findings': 'Findings', - 'eg.findings.hint': 'Sorted by severity. Each one explains what the pattern usually means.', - 'eg.findings.none': 'No findings in this window.', + 'eg.findings': 'Evidence', + 'eg.findings.hint': 'Each card is one suspicious pattern, most serious first, with what it means and what to do.', + 'eg.calm': 'All quiet', + 'eg.calm.sub': 'No workload is beaconing, scanning, mining or talking to known-bad addresses. Urutau keeps watching every new connection.', 'eg.sev.high': 'High', 'eg.sev.medium': 'Medium', 'eg.sev.low': 'Low', - 'eg.kind.beacon': 'Regular conversation', + 'eg.kind.beacon': 'Regular check-ins', 'eg.kind.scan': 'Mass connection attempts', 'eg.kind.port': 'Unusual port', 'eg.kind.bad_dst': 'Known-bad destination', @@ -70,35 +64,69 @@ 'eg.why.bad_dst': 'The destination is on a list of addresses known for malware or attacks. Nothing on your server should talk to it.', 'eg.why.dns_bypass': 'The workload asked for names directly from an outside DNS server instead of your resolver. Malware does this to hide what it looks up.', 'eg.why.new_geo': 'The workload connected to a country it had never reached before in this window. It may be harmless, but is worth a look.', - 'eg.f.to': 'To', - 'eg.f.count': '{n} connections', - 'eg.f.interval': 'every {s} s (variation {j}%)', - 'eg.f.first': 'first {t}', - 'eg.f.last': 'last {t}', + 'eg.do.beacon': 'Check whether the program is supposed to call this address (an update or monitoring agent). If not, isolate the container, look for unknown processes and rotate its credentials.', + 'eg.do.scan': 'Stop the workload, find which process opened the connections and rebuild it from a clean image.', + 'eg.do.port': 'Look for a crypto miner (high CPU use, unknown binaries) in the workload and rebuild it from a clean image.', + 'eg.do.bad_dst': 'Block the destination at the firewall and investigate the workload as compromised.', + 'eg.do.dns_bypass': 'Force DNS through your resolver at the firewall and check which process made the queries.', + 'eg.do.new_geo': 'Confirm that the service in that country is expected (a CDN or API). If not, treat it as a lead.', + 'eg.f.means': 'What it means', + 'eg.f.todo': 'What to do', + 'eg.f.conns': 'connections', + 'eg.f.every': 'interval', + 'eg.f.jitter': 'variation', + 'eg.f.when': 'first and last', 'eg.f.host': 'server {h}', + 'eg.f.from': 'workload', + 'eg.f.rhythm': 'Connection rhythm', + 'eg.f.rhythm.sub': 'Each tick is one connection. Evenly spaced ticks mean a machine, not a person.', + 'eg.f.hist': 'Time between connections', + 'eg.f.median': 'typical {s}', + 'eg.f.open': 'Investigate address', + 'eg.map': 'Where the traffic goes', + 'eg.map.hint': 'Lines go from your servers to the countries of the destinations; bigger circles, more connections. Red marks a country with a finding.', + 'eg.map.alt': 'World map of outbound destinations by country.', + 'eg.map.unknown': 'unknown', + 'eg.heat': 'Activity by hour', + 'eg.heat.hint': 'Connections per workload per hour. A lit row at night, or a perfectly even row, deserves a look.', + 'eg.wl': 'Workloads', + 'eg.wl.hint': 'Each workload is a program or container that opens connections to the internet.', + 'eg.wl.col.name': 'Workload', + 'eg.wl.col.conns': 'Connections', + 'eg.wl.col.dsts': 'Destinations', + 'eg.wl.col.ports': 'Ports', + 'eg.wl.col.trend': 'Last 24 h', + 'eg.wl.col.find': 'Findings', + 'eg.wl.supp': '{n} scan connections summarised · beaconing still watched', + 'eg.role.scanner': 'authorised scans summarised', + 'eg.role.default': 'application', + 'eg.role.app': 'application', + 'eg.role.proxy': 'proxy', + 'eg.role.resolver': 'DNS resolver', + 'eg.role.database': 'database', + 'eg.role.system': 'system', + 'eg.scan': 'Authorised scans', + 'eg.scan.hint': 'Bursts of your own scanner on a time axis (taller bar, more targets). They are summarised instead of raising findings, but if the scanner itself starts beaconing it is still flagged.', + 'eg.scan.none': 'No scan bursts in this window.', + 'eg.scan.warn': 'A scan reached {n} known-bad destinations: check that the scanner is not aiming at the wrong targets.', + 'eg.scan.ok': 'No scan touched a known-bad destination.', + 'eg.scan.targets': '{n} targets', + 'eg.scan.conns': '{n} connections', + 'eg.scan.bad': '{n} bad destinations', + 'eg.scan.more': '+{n} networks', 'eg.dst': 'Top destinations', - 'eg.dst.hint': 'Where the connections went.', + 'eg.dst.hint': 'The addresses that received the most connections. Click one to investigate it.', 'eg.dst.none': 'No destinations in this window.', 'eg.col.ip': 'Address', - 'eg.col.country': 'Country', - 'eg.col.asn': 'Network (ASN)', + 'eg.col.net': 'Network', 'eg.col.conns': 'Connections', 'eg.col.who': 'Workloads', 'eg.col.ports': 'Ports', - 'eg.scan': 'Authorised scans', - 'eg.scan.hint': 'Scans your own scanner runs on purpose. They are summarised here instead of raising findings.', - 'eg.scan.none': 'No scan bursts in this window.', - 'eg.scan.warn': 'A scan reached {n} known-bad destinations: check that the scanner is not aiming at the wrong targets.', - 'eg.scan.targets': '{n} targets', - 'eg.scan.nets': 'networks', - 'eg.scan.ports': 'ports', - 'eg.scan.conns': '{n} connections', - 'eg.scan.when': '{a} to {b}', - 'eg.col.who1': 'Workload', - 'eg.col.when': 'When', - 'eg.col.targets': 'Targets', - 'eg.col.nets': 'Networks', - 'eg.col.badhits': 'Bad destinations hit' + 'help.term.eg_baddst': 'An address that public threat lists mark as used by malware, botnets or attackers.', + 'help.term.eg_baddst.do': 'Nothing legitimate should talk to it: block it and investigate the workload.', + 'help.term.eg_asn': 'The ASN (autonomous system number) identifies the company or provider that owns the destination network, such as a cloud, an ISP or a VPN service.', + 'help.term.eg_jitter': 'How much the time between connections changes. Near 0% means the connections come like clockwork, which people never do.', + 'help.term.eg_port': 'A port is the numbered "door" a connection uses on the destination: 443 is secure web, 53 is DNS, 3333 is often a mining pool.' }, 'pt-BR': { 'eg.title': 'Tráfego de saída', @@ -106,44 +134,34 @@ 'eg.retry': 'Tentar de novo', 'eg.disabled': 'O tráfego de saída não está sendo monitorado', 'eg.disabled.sub': 'Esta página mostra as conexões que saem dos seus servidores. Para vê-las, crie no servidor uma regra de firewall de saída que registre as conexões novas e defina a variável URUTAU_EGRESS para o Urutau ler esse registro.', - 'eg.lead.none': 'Nenhuma conexão de saída {range}', - 'eg.lead.none.sub': 'Nada saiu dos workloads monitorados nesta janela.', - 'eg.lead.ok': '{n} conexões de saída {range}, nada suspeito', - 'eg.lead.ok.sub': 'Nenhum achado nesta janela. As varreduras autorizadas, se houver, aparecem resumidas abaixo.', - 'eg.lead.bad': '{f} achados em {n} conexões de saída {range}', - 'eg.lead.bad.sub': '{h} de gravidade alta, {m} média e {l} baixa. Comece pelos de gravidade alta.', - 'eg.src': 'Origem do registro: {state} · {lines} linhas lidas · {bad} ilegíveis', + 'eg.v.ok': 'Nenhum sinal de servidor comprometido', + 'eg.v.ok.sub': '{n} conexões de saída {range} vindas de {w} workloads, todas com comportamento normal.', + 'eg.v.none': 'Nenhuma conexão de saída {range}', + 'eg.v.none.sub': 'Nada saiu dos workloads monitorados nesta janela.', + 'eg.v.bad.1': '1 sinal a investigar', + 'eg.v.bad.n': '{n} sinais a investigar', + 'eg.v.bad.sub': 'Encontrados entre {c} conexões de saída {range}. Comece pelo primeiro cartão abaixo.', + 'eg.src': 'Registro {state} · {lines} linhas lidas · {bad} ilegíveis', 'eg.src.following': 'sendo acompanhado', 'eg.src.waiting': 'aguardando o arquivo', - 'eg.src.missing': 'arquivo não encontrado', - 'eg.src.error': 'erro', + 'eg.src.missing': 'não encontrado', + 'eg.src.error': 'com erros', 'eg.kpi.conns': 'Conexões', 'eg.kpi.conns.sub': 'novas conexões de saída', 'eg.kpi.dsts': 'Destinos', - 'eg.kpi.dsts.sub': 'endereços diferentes alcançados', + 'eg.kpi.dsts.sub': 'endereços em {c} países', + 'eg.kpi.wl': 'Workloads', + 'eg.kpi.wl.sub': '{n} falando com a internet', 'eg.kpi.find': 'Achados', 'eg.kpi.find.sub': '{h} altos · {m} médios · {l} baixos', - 'eg.workloads': 'Workloads', - 'eg.workloads.hint': 'Cada workload é um programa ou contêiner que faz conexões de saída.', - 'eg.wl.conns': 'conexões', - 'eg.wl.dsts': 'destinos', - 'eg.wl.ports': 'portas', - 'eg.wl.findings': 'achados', - 'eg.wl.suppressed': '{n} conexões de varredura resumidas', - 'eg.role.scanner': 'varreduras autorizadas resumidas', - 'eg.role.app': 'aplicação', - 'eg.role.proxy': 'proxy', - 'eg.role.database': 'banco de dados', - 'eg.role.system': 'sistema', - 'eg.timeline': 'Conexões ao longo do tempo', - 'eg.timeline.hint': 'Empilhadas por workload.', - 'eg.findings': 'Achados', - 'eg.findings.hint': 'Ordenados por gravidade. Cada um explica o que o padrão costuma significar.', - 'eg.findings.none': 'Nenhum achado nesta janela.', + 'eg.findings': 'Evidências', + 'eg.findings.hint': 'Cada cartão é um padrão suspeito, do mais grave ao menos grave, com o que significa e o que fazer.', + 'eg.calm': 'Tudo tranquilo', + 'eg.calm.sub': 'Nenhum workload está fazendo contatos regulares, varrendo, minerando ou falando com endereços sabidamente ruins. O Urutau continua vigiando cada conexão nova.', 'eg.sev.high': 'Alta', 'eg.sev.medium': 'Média', 'eg.sev.low': 'Baixa', - 'eg.kind.beacon': 'Conversa em intervalos regulares', + 'eg.kind.beacon': 'Contatos em intervalos regulares', 'eg.kind.scan': 'Tentativas de conexão em massa', 'eg.kind.port': 'Porta incomum', 'eg.kind.bad_dst': 'Destino sabidamente ruim', @@ -155,95 +173,339 @@ 'eg.why.bad_dst': 'O destino está numa lista de endereços conhecidos por malware ou ataques. Nada no seu servidor deveria falar com ele.', 'eg.why.dns_bypass': 'O workload consultou nomes direto num servidor DNS de fora, em vez do seu resolvedor. Malware faz isso para esconder o que procura.', 'eg.why.new_geo': 'O workload conectou a um país que ainda não tinha alcançado nesta janela. Pode ser inofensivo, mas vale olhar.', - 'eg.f.to': 'Para', - 'eg.f.count': '{n} conexões', - 'eg.f.interval': 'a cada {s} s (variação {j}%)', - 'eg.f.first': 'primeira {t}', - 'eg.f.last': 'última {t}', + 'eg.do.beacon': 'Confira se o programa deveria chamar este endereço (um agente de atualização ou monitoramento). Se não, isole o contêiner, procure processos desconhecidos e troque as credenciais dele.', + 'eg.do.scan': 'Pare o workload, descubra qual processo abriu as conexões e recrie-o a partir de uma imagem limpa.', + 'eg.do.port': 'Procure um minerador de criptomoeda (CPU alta, binários desconhecidos) no workload e recrie-o a partir de uma imagem limpa.', + 'eg.do.bad_dst': 'Bloqueie o destino no firewall e investigue o workload como comprometido.', + 'eg.do.dns_bypass': 'Obrigue o DNS a passar pelo seu resolvedor no firewall e veja qual processo fez as consultas.', + 'eg.do.new_geo': 'Confirme se o serviço naquele país é esperado (uma CDN ou API). Se não for, trate como pista.', + 'eg.f.means': 'O que significa', + 'eg.f.todo': 'O que fazer', + 'eg.f.conns': 'conexões', + 'eg.f.every': 'intervalo', + 'eg.f.jitter': 'variação', + 'eg.f.when': 'primeira e última', 'eg.f.host': 'servidor {h}', + 'eg.f.from': 'workload', + 'eg.f.rhythm': 'Ritmo das conexões', + 'eg.f.rhythm.sub': 'Cada traço é uma conexão. Traços igualmente espaçados indicam uma máquina, não uma pessoa.', + 'eg.f.hist': 'Tempo entre conexões', + 'eg.f.median': 'típico {s}', + 'eg.f.open': 'Investigar endereço', + 'eg.map': 'Para onde vai o tráfego', + 'eg.map.hint': 'As linhas saem dos seus servidores para os países dos destinos; círculos maiores, mais conexões. Vermelho marca um país com achado.', + 'eg.map.alt': 'Mapa-múndi dos destinos de saída por país.', + 'eg.map.unknown': 'desconhecido', + 'eg.heat': 'Atividade por hora', + 'eg.heat.hint': 'Conexões por workload em cada hora. Uma linha acesa de madrugada, ou perfeitamente uniforme, merece atenção.', + 'eg.wl': 'Workloads', + 'eg.wl.hint': 'Cada workload é um programa ou contêiner que abre conexões para a internet.', + 'eg.wl.col.name': 'Workload', + 'eg.wl.col.conns': 'Conexões', + 'eg.wl.col.dsts': 'Destinos', + 'eg.wl.col.ports': 'Portas', + 'eg.wl.col.trend': 'Últimas 24 h', + 'eg.wl.col.find': 'Achados', + 'eg.wl.supp': '{n} conexões de varredura resumidas · contatos regulares continuam vigiados', + 'eg.role.scanner': 'varreduras autorizadas resumidas', + 'eg.role.default': 'aplicação', + 'eg.role.app': 'aplicação', + 'eg.role.proxy': 'proxy', + 'eg.role.resolver': 'resolvedor DNS', + 'eg.role.database': 'banco de dados', + 'eg.role.system': 'sistema', + 'eg.scan': 'Varreduras autorizadas', + 'eg.scan.hint': 'Rajadas do seu próprio scanner num eixo de tempo (barra mais alta, mais alvos). Ficam resumidas em vez de gerar achados, mas se o próprio scanner passar a fazer contatos regulares isso ainda é apontado.', + 'eg.scan.none': 'Nenhuma rajada de varredura nesta janela.', + 'eg.scan.warn': 'Uma varredura atingiu {n} destinos sabidamente ruins: confira se o scanner não está mirando os alvos errados.', + 'eg.scan.ok': 'Nenhuma varredura tocou um destino sabidamente ruim.', + 'eg.scan.targets': '{n} alvos', + 'eg.scan.conns': '{n} conexões', + 'eg.scan.bad': '{n} destinos ruins', + 'eg.scan.more': '+{n} redes', 'eg.dst': 'Principais destinos', - 'eg.dst.hint': 'Para onde foram as conexões.', + 'eg.dst.hint': 'Os endereços que mais receberam conexões. Clique em um para investigá-lo.', 'eg.dst.none': 'Nenhum destino nesta janela.', 'eg.col.ip': 'Endereço', - 'eg.col.country': 'País', - 'eg.col.asn': 'Rede (ASN)', + 'eg.col.net': 'Rede', 'eg.col.conns': 'Conexões', 'eg.col.who': 'Workloads', 'eg.col.ports': 'Portas', - 'eg.scan': 'Varreduras autorizadas', - 'eg.scan.hint': 'Varreduras que o seu próprio scanner faz de propósito. Aparecem resumidas aqui em vez de gerar achados.', - 'eg.scan.none': 'Nenhuma rajada de varredura nesta janela.', - 'eg.scan.warn': 'Uma varredura atingiu {n} destinos sabidamente ruins: confira se o scanner não está mirando os alvos errados.', - 'eg.scan.targets': '{n} alvos', - 'eg.scan.nets': 'redes', - 'eg.scan.ports': 'portas', - 'eg.scan.conns': '{n} conexões', - 'eg.scan.when': '{a} a {b}', - 'eg.col.who1': 'Workload', - 'eg.col.when': 'Quando', - 'eg.col.targets': 'Alvos', - 'eg.col.nets': 'Redes', - 'eg.col.badhits': 'Destinos ruins atingidos' + 'help.term.eg_baddst': 'Um endereço que listas públicas de ameaças marcam como usado por malware, botnets ou atacantes.', + 'help.term.eg_baddst.do': 'Nada legítimo deveria falar com ele: bloqueie e investigue o workload.', + 'help.term.eg_asn': 'O ASN (número de sistema autônomo) identifica a empresa ou provedor dono da rede de destino, como uma nuvem, um provedor de internet ou um serviço de VPN.', + 'help.term.eg_jitter': 'Quanto o tempo entre as conexões muda. Perto de 0% quer dizer que as conexões chegam como um relógio, coisa que pessoas nunca fazem.', + 'help.term.eg_port': 'A porta é a "entrada" numerada que a conexão usa no destino: 443 é web segura, 53 é DNS, 3333 costuma ser um pool de mineração.' } }); var el = U.el, t = U.t, nf = U.fmt.num; - var root = null, seq = 0, alive = false, ctx = null, data = null, failed = false; + var root = null, seq = 0, alive = false, ctx = null, data = null, hosts = null; function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } - function tbl(cols, rows) { - var tb = el('tbody'); - rows.forEach(function (r) { tb.appendChild(el('tr', null, r.map(function (c, i) { return el('td', { class: cols[i].cls || '' }, c); }))); }); - return el('div', { class: 'eg-scroll' }, el('table', { class: 'eg-table' }, - el('thead', null, el('tr', null, cols.map(function (c) { return el('th', { class: c.cls || '' }, c.label); }))), tb)); - } - function ipLink(ip) { return el('a', { href: U.href('ip', [ip]), class: 'mono' }, ip); } - function when(ts) { return ts ? U.fmt.clock(ts) : '-'; } function help(node, key) { if (U.help) U.help(node, key); return node; } - function roleLabel(r) { var k = 'eg.role.' + r; return t(k) !== k ? t(k) : (r || '-'); } - function list(a) { return (a || []).join(', ') || '-'; } + function ipLink(ip) { return el('a', { href: U.href('ip', [ip]), class: 'mono eg-ip' }, ip); } + function roleLabel(r) { var k = 'eg.role.' + (r || 'default'); return t(k) !== k ? t(k) : r; } + function flag(cc) { return cc ? U.fmt.flag(cc) : '\u{1F310}'; } + function country(cc) { return cc ? U.fmt.country(cc) : t('eg.map.unknown'); } + function dur(s) { + s = Math.round(s || 0); + if (s < 120) return s + ' s'; + if (s < 7200) return Math.round(s / 6) / 10 + ' min'; + return Math.round(s / 360) / 10 + ' h'; + } + function sevOf(f) { return SEV[f.severity] !== undefined ? f.severity : 'low'; } + function chips(list, cls) { return el('span', { class: 'eg-chips' }, (list || []).map(function (x) { return el('span', { class: 'chip mono' + (cls ? ' ' + cls : '') }, String(x)); })); } + function tip(node, text) { var ti = el('title'); ti.textContent = text; node.appendChild(ti); return node; } - function workloadCard(w, multi) { - var scanner = w.role === 'scanner'; - var h = el('h3', { class: 'eg-wl-name' }, w.name); - var head = el('div', { class: 'eg-wl-head' }, h); - if (w.role) { - var b = U.ui.badge(roleLabel(w.role), scanner ? 'info' : 'neutral'); - head.appendChild(b); - if (scanner) help(head, 'term.authorized_scanner'); - } - var stats = el('dl', { class: 'eg-wl-stats' }); - [['conns', w.conns], ['dsts', w.dsts], ['ports', w.ports], ['findings', w.findings]].forEach(function (p) { - stats.appendChild(el('div', null, el('dd', { class: 'num' + (p[0] === 'findings' && p[1] ? ' eg-warn' : '') }, nf(p[1] || 0)), el('dt', null, t('eg.wl.' + p[0])))); - }); - var card = el('div', { class: 'card-metric eg-wl' }, head, stats); - if (w.suppressed_scan_conns) card.appendChild(el('p', { class: 'cm-sub' }, t('eg.wl.suppressed', { n: nf(w.suppressed_scan_conns) }))); - if (multi && w.host) card.appendChild(el('p', { class: 'cm-sub' }, t('eg.f.host', { h: w.host }))); - return card; + // ------------------------------------------------------------ verdict + KPIs + function verdict(d, st, range) { + var n = st.fnd.length, tone = !n ? (st.conns ? 'ok' : 'neutral') : st.sev.high ? 'danger' : st.sev.medium ? 'warn' : 'info'; + var title = !n ? (st.conns ? t('eg.v.ok') : t('eg.v.none', { range: range })) : n === 1 ? t('eg.v.bad.1') : t('eg.v.bad.n', { n: nf(n) }); + var sub = !n ? (st.conns ? t('eg.v.ok.sub', { n: nf(st.conns), range: range, w: nf(st.active) }) : t('eg.v.none.sub')) + : t('eg.v.bad.sub', { c: nf(st.conns), range: range }); + var src = d.source || {}, sk = 'eg.src.' + src.state; + var srcLine = el('p', { class: 'eg-v-src' }, el('span', { class: 'eg-dot eg-dot-' + (src.state === 'following' ? 'ok' : 'warn') }), + t('eg.src', { state: t(sk) !== sk ? t(sk) : (src.state || '-'), lines: nf(src.lines || 0), bad: nf(src.malformed || 0) })); + var pills = el('div', { class: 'eg-v-pills' }); + SEV_NAME.forEach(function (s) { if (st.sev[s]) pills.appendChild(U.ui.badge(st.sev[s] + ' ' + t('eg.sev.' + s).toLowerCase(), SEV_TONE[s])); }); + return el('section', { class: 'eg-verdict tone-' + tone }, + el('span', { class: 'eg-v-ico', 'aria-hidden': 'true' }, !n ? '✓' : '!'), + el('div', { class: 'eg-v-txt' }, el('h2', null, title), el('p', null, sub), pills.firstChild ? pills : null, srcLine)); } - function findingNode(f, multi) { - var kind = KINDS.indexOf(f.kind) >= 0 ? f.kind : null; - var sev = SEV[f.severity] !== undefined ? f.severity : 'low'; - var title = el('strong', { class: 'eg-f-title' }, kind ? t('eg.kind.' + kind) : String(f.kind || '-')); + function kpis(st) { + var kp = el('div', { class: 'eg-kpis' }); + kp.appendChild(U.ui.metric(t('eg.kpi.conns'), nf(st.conns), { sub: t('eg.kpi.conns.sub'), spark: st.total })); + kp.appendChild(U.ui.metric(t('eg.kpi.dsts'), nf(st.ndst), { sub: t('eg.kpi.dsts.sub', { c: nf(st.ncc) }) })); + kp.appendChild(U.ui.metric(t('eg.kpi.wl'), nf(st.wls.length), { sub: t('eg.kpi.wl.sub', { n: nf(st.active) }), help: 'term.workload' })); + kp.appendChild(U.ui.metric(t('eg.kpi.find'), nf(st.fnd.length), { sub: t('eg.kpi.find.sub', { h: st.sev.high, m: st.sev.medium, l: st.sev.low }), tone: st.sev.high ? 'danger' : st.fnd.length ? 'warn' : 'ok' })); + return kp; + } + + // ------------------------------------------------------------ evidence cards + function rhythm(samples) { + var a = samples[0], b = samples[samples.length - 1], span = Math.max(1, b - a), W = 600, H = 46; + var svg = el('svg', { viewBox: '0 0 ' + W + ' ' + H, preserveAspectRatio: 'none', class: 'eg-rhythm', role: 'img', 'aria-label': t('eg.f.rhythm') }); + svg.appendChild(el('line', { x1: 0, y1: H - 6, x2: W, y2: H - 6, class: 'eg-axis' })); + samples.forEach(function (s) { + var x = 4 + (s - a) / span * (W - 8); + svg.appendChild(tip(el('line', { x1: x, y1: 6, x2: x, y2: H - 6, class: 'eg-tick' }), U.fmt.clock(s))); + }); + return el('div', { class: 'eg-ev-viz' }, el('p', { class: 'eg-ev-lab' }, t('eg.f.rhythm')), svg, + el('div', { class: 'eg-ev-axis' }, el('span', null, U.fmt.clock(a)), el('span', null, U.fmt.clock(b))), + el('p', { class: 'hint' }, t('eg.f.rhythm.sub'))); + } + function histogram(samples, med) { + var iv = []; + for (var i = 1; i < samples.length; i++) iv.push(samples[i] - samples[i - 1]); + if (iv.length < 3) return null; + var c = med || iv.slice().sort(function (x, y) { return x - y; })[iv.length >> 1]; + var lo = Math.min(Math.min.apply(null, iv), c * 0.5), hi = Math.max(Math.max.apply(null, iv), c * 1.5); + var nb = 15, bw = (hi - lo) / nb || 1, bins = []; + for (i = 0; i < nb; i++) bins.push(0); + iv.forEach(function (v) { bins[Math.max(0, Math.min(nb - 1, Math.floor((v - lo) / bw)))]++; }); + var mx = Math.max.apply(null, bins), W = 300, H = 64; + var svg = el('svg', { viewBox: '0 0 ' + W + ' ' + H, preserveAspectRatio: 'none', class: 'eg-hist', role: 'img', 'aria-label': t('eg.f.hist') }); + svg.appendChild(el('line', { x1: 0, y1: H - 0.5, x2: W, y2: H - 0.5, class: 'eg-axis' })); + bins.forEach(function (n, k) { + var h = n ? Math.max(3, n / mx * (H - 4)) : 0, bx = k * W / nb, on = c >= lo + k * bw && c < lo + (k + 1) * bw; + svg.appendChild(tip(el('rect', { x: bx + 2, y: H - h, width: W / nb - 4, height: h, rx: 2, class: 'eg-bin' + (on ? ' on' : '') }), dur(lo + k * bw) + ' – ' + dur(lo + (k + 1) * bw) + ': ' + n)); + }); + return el('div', { class: 'eg-ev-viz' }, el('p', { class: 'eg-ev-lab' }, t('eg.f.hist')), svg, + el('div', { class: 'eg-ev-axis' }, el('span', null, dur(lo)), el('strong', null, t('eg.f.median', { s: dur(c) })), el('span', null, dur(hi)))); + } + + function evidence(f, st) { + var kind = KINDS.indexOf(f.kind) >= 0 ? f.kind : null, sev = sevOf(f), dst = st.dstBy[f.dst] || {}; + var title = el('h3', { class: 'eg-ev-title' }, kind ? t('eg.kind.' + kind) : String(f.kind || '-')); if (kind) help(title, KIND_HELP[kind]); - var top = el('div', { class: 'eg-f-top' }, U.ui.badge(t('eg.sev.' + sev), SEV_TONE[sev]), title); - var bits = []; - bits.push(el('span', { class: 'mono' }, f.workload || '-')); - bits.push(' → '); - if (f.dst) bits.push(ipLink(f.dst)); - if (f.dport) bits.push(el('span', { class: 'mono' }, ':' + f.dport + (f.proto ? '/' + f.proto : ''))); - var meta = []; - if (f.count) meta.push(t('eg.f.count', { n: nf(f.count) })); - if (f.interval_s) meta.push(t('eg.f.interval', { s: Math.round(f.interval_s * 10) / 10, j: Math.round((f.jitter || 0) * 100) })); - if (f.first) meta.push(t('eg.f.first', { t: when(f.first) })); - if (f.last) meta.push(t('eg.f.last', { t: when(f.last) })); - if (multi && f.host) meta.push(t('eg.f.host', { h: f.host })); - var li = el('li', { class: 'eg-f eg-sev-' + sev }, top, el('p', { class: 'eg-f-line' }, bits)); - if (kind) li.appendChild(el('p', { class: 'eg-f-why' }, t('eg.why.' + kind))); - if (f.detail) li.appendChild(el('p', { class: 'eg-f-detail mono' }, f.detail)); - if (meta.length) li.appendChild(el('p', { class: 'hint eg-f-meta' }, meta.join(' · '))); - return li; + var head = el('div', { class: 'eg-ev-head' }, U.ui.badge(t('eg.sev.' + sev), SEV_TONE[sev]), title); + if (st.multi && f.host) head.appendChild(el('span', { class: 'chip' }, t('eg.f.host', { h: f.host }))); + + var route = el('div', { class: 'eg-route' }, + el('span', { class: 'eg-node' }, el('span', { class: 'eg-node-k' }, t('eg.f.from')), el('strong', { class: 'mono' }, f.workload || '-')), + el('span', { class: 'eg-arrow', 'aria-hidden': 'true' }), + el('span', { class: 'eg-node eg-node-dst' }, el('span', { class: 'eg-node-k' }, flag(dst.cc) + ' ' + country(dst.cc)), + el('span', { class: 'eg-node-ip' }, f.dst ? ipLink(f.dst) : '-', f.dport ? el('span', { class: 'mono eg-port' }, ':' + f.dport + (f.proto ? '/' + f.proto : '')) : null), + dst.asn || dst.org ? el('span', { class: 'eg-node-org' }, (dst.asn || '') + (dst.org ? ' · ' + dst.org : '')) : null)); + + var facts = el('div', { class: 'eg-facts' }); + function fact(v, k, hk) { var lab = el('span', null, k); if (hk) help(lab, hk); facts.appendChild(el('span', { class: 'eg-fact' }, el('strong', { class: 'num' }, v), lab)); } + if (f.count) fact(nf(f.count), t('eg.f.conns')); + if (f.interval_s) { fact(dur(f.interval_s), t('eg.f.every')); fact(Math.round((f.jitter || 0) * 100) + '%', t('eg.f.jitter'), 'term.eg_jitter'); } + if (f.first) fact(U.fmt.clock(f.first) + ' → ' + U.fmt.clock(f.last || f.first), t('eg.f.when')); + + var body = el('div', { class: 'eg-ev-body' }, el('div', { class: 'eg-ev-top' }, route, facts)); + var samples = (f.samples || []).filter(function (x) { return typeof x === 'number' && isFinite(x); }).sort(function (x, y) { return x - y; }); + if (samples.length >= 3) body.appendChild(el('div', { class: 'eg-ev-vizrow' }, rhythm(samples), histogram(samples, f.interval_s))); + if (f.detail) body.appendChild(el('p', { class: 'eg-ev-detail mono' }, f.detail)); + if (kind) { + body.appendChild(el('div', { class: 'eg-ev-advice' }, + el('div', null, el('p', { class: 'eg-ev-lab' }, t('eg.f.means')), el('p', null, t('eg.why.' + kind))), + el('div', { class: 'eg-ev-todo' }, el('p', { class: 'eg-ev-lab' }, t('eg.f.todo')), el('p', null, t('eg.do.' + kind))))); + } + if (f.dst) body.appendChild(el('a', { class: 'btn eg-ev-btn', href: U.href('ip', [f.dst]) }, t('eg.f.open') + ' →')); + return el('article', { class: 'eg-ev eg-sev-' + sev }, head, body); + } + + // ------------------------------------------------------------ map + function worldMap(st) { + var world = U.world || window.URUTAU_WORLD; + if (!world || !world.paths) return null; + var W = world.w, Hh = world.h, cen = world.centroids || {}; + var svg = el('svg', { viewBox: '0 0 ' + W + ' ' + Math.round(Hh * 0.86), class: 'eg-map', role: 'img', 'aria-label': t('eg.map.alt') }); + var hit = {}, mx = st.cc.length ? st.cc[0].conns || 1 : 1; + st.cc.forEach(function (c) { if (c.cc) hit[c.cc] = c; }); + Object.keys(world.paths).forEach(function (k) { + var c = hit[k], lvl = c ? 1 + Math.min(4, Math.floor(c.conns / mx * 4.99)) : 0; + var p = el('path', { d: world.paths[k], class: 'eg-land' + (lvl ? ' s' + lvl : '') }); + if (c) tip(p, country(k) + ': ' + nf(c.conns)); + svg.appendChild(p); + }); + var srcs = (hosts || []).map(function (h) { return [(h.lon + 180) / 360 * W, (LAT_TOP - h.lat) / LAT_SPAN * Hh, h.name]; }); + var bad = {}; + st.fnd.forEach(function (f) { var d = st.dstBy[f.dst]; if (d && d.cc) bad[d.cc] = Math.min(bad[d.cc] === undefined ? 9 : bad[d.cc], SEV[sevOf(f)]); }); + var arcs = el('g'), dots = el('g'); + st.cc.forEach(function (c) { + var p = cen[c.cc]; if (!p) return; + var b = bad[c.cc], cls = b === 0 ? ' danger' : b === 1 ? ' warn' : ''; + srcs.forEach(function (s) { + var dx = p[0] - s[0], dy = p[1] - s[1], dist = Math.sqrt(dx * dx + dy * dy); + if (dist < 4) return; + var qx = (s[0] + p[0]) / 2, qy = (s[1] + p[1]) / 2 - dist * 0.25; + arcs.appendChild(el('path', { d: 'M' + s[0].toFixed(1) + ' ' + s[1].toFixed(1) + 'Q' + qx.toFixed(1) + ' ' + qy.toFixed(1) + ' ' + p[0] + ' ' + p[1], class: 'eg-arc' + cls })); + }); + dots.appendChild(tip(el('circle', { cx: p[0], cy: p[1], r: (7 + Math.sqrt(c.conns / mx) * 18).toFixed(1), class: 'eg-dst' + cls }), country(c.cc) + ': ' + nf(c.conns))); + }); + srcs.forEach(function (s) { + dots.appendChild(el('circle', { cx: s[0], cy: s[1], r: 16, class: 'eg-src-halo' })); + dots.appendChild(tip(el('circle', { cx: s[0], cy: s[1], r: 7, class: 'eg-src' }), s[2])); + }); + svg.appendChild(arcs); svg.appendChild(dots); + return svg; + } + function countryBars(st) { + var list = el('ol', { class: 'eg-cc' }), mx = st.cc.length ? st.cc[0].conns || 1 : 1; + st.cc.slice(0, 8).forEach(function (c) { + list.appendChild(el('li', null, el('span', { class: 'eg-cc-name' }, flag(c.cc) + ' ' + country(c.cc)), + el('span', { class: 'eg-cc-n num' }, nf(c.conns)), + el('span', { class: 'eg-bar' }, el('span', { style: { width: Math.max(2, c.conns / mx * 100) + '%' } })))); + }); + return list; + } + + // ------------------------------------------------------------ workloads + function seriesOf(st, w) { return st.ser[(w.host ? w.host + '/' : '') + w.name] || st.ser[w.name] || []; } + function workloadsTable(st) { + var tb = el('tbody'); + st.wls.forEach(function (w) { + var scanner = w.role === 'scanner', s = seriesOf(st, w).slice(-24); + var badge = U.ui.badge(roleLabel(w.role), scanner ? 'info' : 'neutral'); + var name = el('div', { class: 'eg-wl-name' }, el('strong', { class: 'mono' }, w.name), badge); + if (scanner) help(badge, 'term.authorized_scanner'); + if (st.multi && w.host) name.appendChild(el('span', { class: 'chip' }, w.host)); + if (scanner || w.suppressed_scan_conns) name.appendChild(el('span', { class: 'hint eg-wl-supp' }, t('eg.wl.supp', { n: nf(w.suppressed_scan_conns || 0) }))); + var sp = s.length > 1 && Math.max.apply(null, s) > 0 && U.charts && U.charts.sparkline ? U.charts.sparkline(s) : null; + tb.appendChild(el('tr', { class: w.findings ? 'eg-row-bad' : '' }, + el('td', { class: 'eg-c-name' }, name), + el('td', { class: 'num', 'data-l': t('eg.wl.col.conns') }, nf(w.conns || 0)), + el('td', { class: 'num', 'data-l': t('eg.wl.col.dsts') }, nf(w.dsts || 0)), + el('td', { class: 'num', 'data-l': t('eg.wl.col.ports') }, nf(w.ports || 0)), + el('td', { class: 'eg-spark', 'data-l': t('eg.wl.col.trend') }, sp || el('span', { class: 'hint' }, '–')), + el('td', { class: 'num', 'data-l': t('eg.wl.col.find') }, w.findings ? U.ui.badge(nf(w.findings), 'danger') : el('span', { class: 'eg-ok' }, '✓')))); + }); + var th = el('tr', null, [['name', ''], ['conns', 'num'], ['dsts', 'num'], ['ports', 'num'], ['trend', ''], ['find', 'num']].map(function (c) { return el('th', { class: c[1] }, t('eg.wl.col.' + c[0])); })); + help(th.children[3], 'term.eg_port'); + return el('table', { class: 'eg-table eg-wl-table' }, el('thead', null, th), tb); + } + + function heat(st) { + if (!U.charts || !U.charts.heatmap || !st.wls.length) return null; + var rows = [], labels = [], step = st.tl.step || 3600; + st.wls.forEach(function (w) { var s = seriesOf(st, w); if (s.length) { rows.push(s.slice(-24)); labels.push(w.name.length > 8 ? w.name.slice(0, 7) + '…' : w.name); } }); + if (!rows.length) return null; + var n = rows[0].length, start = (st.tl.start || 0) + (st.tlLen - n) * step, xl = []; + for (var i = 0; i < n; i++) xl.push(('0' + new Date((start + i * step) * 1000).getHours()).slice(-2) + 'h'); + return U.charts.heatmap(rows, xl, labels, { title: t('eg.heat') }); + } + + // ------------------------------------------------------------ scanner + function scans(st) { + var bursts = st.bursts.slice().sort(function (a, b) { return (a.start || 0) - (b.start || 0); }); + var box = el('div', { class: 'eg-scan' }), bad = 0; + bursts.forEach(function (b) { bad += b.bad_dst_hits || 0; }); + box.appendChild(bad ? el('div', { class: 'state-error eg-scanwarn' }, el('strong', null, t('eg.scan.warn', { n: nf(bad) }))) + : el('p', { class: 'eg-scan-ok' }, el('span', { class: 'eg-dot eg-dot-ok' }), t('eg.scan.ok'))); + var t0 = Infinity, t1 = -Infinity, mxT = 1; + bursts.forEach(function (b) { t0 = Math.min(t0, b.start); t1 = Math.max(t1, b.end || b.start); mxT = Math.max(mxT, b.targets || 0); }); + var span = Math.max(3600, t1 - t0), W = 1000, H = 60; + var svg = el('svg', { viewBox: '0 0 ' + W + ' ' + H, preserveAspectRatio: 'none', class: 'eg-scan-tl', role: 'img', 'aria-label': t('eg.scan') }); + svg.appendChild(el('line', { x1: 0, y1: H - 1, x2: W, y2: H - 1, class: 'eg-axis' })); + bursts.forEach(function (b) { + var x = (b.start - t0) / span * (W - 14) + 2, w = Math.max(10, ((b.end || b.start) - b.start) / span * W), h = 12 + (b.targets || 0) / mxT * (H - 16); + svg.appendChild(tip(el('rect', { x: x, y: H - 1 - h, width: w, height: h, rx: 2, class: 'eg-burst' + (b.bad_dst_hits ? ' bad' : '') }), U.fmt.clock(b.start) + ' · ' + t('eg.scan.targets', { n: nf(b.targets || 0) }))); + }); + box.appendChild(el('div', { class: 'eg-ev-viz' }, svg, el('div', { class: 'eg-ev-axis' }, el('span', null, U.fmt.clock(t0)), el('span', null, U.fmt.clock(t1))))); + var ul = el('ul', { class: 'eg-bursts' }); + bursts.slice().reverse().slice(0, 6).forEach(function (b) { + var nets = (b.nets || []).slice(0, 3), more = (b.nets || []).length - nets.length; + ul.appendChild(el('li', { class: b.bad_dst_hits ? 'bad' : '' }, + el('span', { class: 'eg-b-when mono' }, U.fmt.clock(b.start)), + el('span', { class: 'eg-b-main' }, el('strong', null, t('eg.scan.targets', { n: nf(b.targets || 0) })), + el('span', { class: 'hint' }, ' · ' + t('eg.scan.conns', { n: nf(b.conns || 0) }) + (st.multi && b.host ? ' · ' + b.host : '')), + b.bad_dst_hits ? U.ui.badge(t('eg.scan.bad', { n: nf(b.bad_dst_hits) }), 'danger') : null), + el('span', { class: 'eg-b-chips' }, chips(nets), more > 0 ? el('span', { class: 'hint' }, t('eg.scan.more', { n: more })) : null, chips(b.ports, 'eg-chip-port')))); + }); + box.appendChild(ul); + return box; + } + + // ------------------------------------------------------------ destinations + function destinations(st) { + var tb = el('tbody'), mx = st.dsts.length ? st.dsts[0].conns || 1 : 1; + st.dsts.slice(0, 15).forEach(function (x) { + var flagged = st.badDst[x.ip]; + tb.appendChild(el('tr', { class: flagged !== undefined ? 'eg-row-bad' : '' }, + el('td', { class: 'eg-c-name' }, el('span', { class: 'eg-dst-ip' }, el('span', { class: 'eg-flag', title: country(x.cc) }, flag(x.cc)), ipLink(x.ip), + flagged !== undefined ? U.ui.badge(t('eg.sev.' + flagged), SEV_TONE[flagged]) : null)), + el('td', { 'data-l': t('eg.col.net') }, el('span', { class: 'eg-org' }, el('span', { class: 'mono eg-asn' }, x.asn || ''), ' ', x.org || country(x.cc))), + el('td', { class: 'num eg-conns', 'data-l': t('eg.col.conns') }, nf(x.conns || 0), el('span', { class: 'eg-bar' }, el('span', { style: { width: Math.max(2, (x.conns || 0) / mx * 100) + '%' } }))), + el('td', { 'data-l': t('eg.col.ports') }, chips(x.ports, 'eg-chip-port')), + el('td', { 'data-l': t('eg.col.who') }, chips(x.workloads)))); + }); + var th = el('tr', null, [['ip', ''], ['net', ''], ['conns', 'num'], ['ports', ''], ['who', '']].map(function (c) { return el('th', { class: c[1] }, t('eg.col.' + c[0])); })); + help(th.children[1], 'term.eg_asn'); + return el('table', { class: 'eg-table eg-dst-table' }, el('thead', null, th), tb); + } + + // ------------------------------------------------------------ paint + function stats(d) { + var st = { wls: d.workloads || [], fnd: (d.findings || []).slice(), dsts: d.top_dst || [], bursts: (d.scanner && d.scanner.bursts) || [], tl: d.timeline || {} }; + st.fnd.sort(function (a, b) { return SEV[sevOf(a)] - SEV[sevOf(b)] || (b.last || 0) - (a.last || 0); }); + st.ser = st.tl.series || {}; + st.conns = 0; st.active = 0; st.sev = { high: 0, medium: 0, low: 0 }; + st.wls.forEach(function (w) { st.conns += w.conns || 0; if (w.conns) st.active++; }); + st.fnd.forEach(function (f) { st.sev[sevOf(f)]++; }); + var hs = {}; + st.wls.forEach(function (w) { if (w.host) hs[w.host] = 1; }); + st.multi = Object.keys(hs).length > 1; + st.dstBy = {}; st.dsts.forEach(function (x) { if (!st.dstBy[x.ip]) st.dstBy[x.ip] = x; }); + st.badDst = {}; st.fnd.forEach(function (f) { if (f.dst && st.badDst[f.dst] === undefined) st.badDst[f.dst] = sevOf(f); }); + st.tlLen = 0; var tot = []; + Object.keys(st.ser).forEach(function (k) { var v = st.ser[k] || []; st.tlLen = Math.max(st.tlLen, v.length); v.forEach(function (x, i) { tot[i] = (tot[i] || 0) + (x || 0); }); }); + for (var i = 0; i < st.tlLen; i++) tot[i] = tot[i] || 0; + st.total = tot.slice(-48); + st.cc = (d.by_country || []).slice(); + if (!st.cc.length) { + var m = {}; + st.dsts.forEach(function (x) { var c = m[x.cc] || (m[x.cc] = { cc: x.cc, conns: 0, dsts: 0 }); c.conns += x.conns || 0; c.dsts++; }); + st.cc = Object.keys(m).map(function (k) { return m[k]; }).sort(function (a, b) { return b.conns - a.conns; }); + } + st.ndst = 0; st.cc.forEach(function (c) { st.ndst += c.dsts || 0; }); + if (!st.ndst) st.ndst = st.dsts.length; + st.ncc = st.cc.filter(function (c) { return c.cc; }).length; + return st; } function paint() { @@ -251,74 +513,51 @@ clear(root); if (!data) { root.appendChild(el('div', { class: 'skeleton', style: { height: '8rem' } })); return; } if (!data.enabled) { root.appendChild(U.ui.empty(t('eg.disabled'), t('eg.disabled.sub'))); return; } - var d = data, range = U.rangeLabel({ inline: true }); - var wls = d.workloads || [], fnd = (d.findings || []).slice(); - fnd.sort(function (a, b) { var x = SEV[a.severity], y = SEV[b.severity]; x = x === undefined ? 3 : x; y = y === undefined ? 3 : y; return x - y || (b.count || 0) - (a.count || 0); }); - var conns = 0, nsev = { high: 0, medium: 0, low: 0 }; - wls.forEach(function (w) { conns += w.conns || 0; }); - fnd.forEach(function (f) { if (nsev[f.severity] !== undefined) nsev[f.severity]++; }); - var hosts = {}; - wls.forEach(function (w) { if (w.host) hosts[w.host] = 1; }); - fnd.forEach(function (f) { if (f.host) hosts[f.host] = 1; }); - var multi = Object.keys(hosts).length > 1; - var dsts = d.top_dst || []; - - if (!conns && !fnd.length) root.appendChild(U.ui.lead(t('eg.lead.none', { range: range }), t('eg.lead.none.sub'), 'neutral')); - else if (!fnd.length) root.appendChild(U.ui.lead(t('eg.lead.ok', { n: nf(conns), range: range }), t('eg.lead.ok.sub'), 'ok')); - else root.appendChild(U.ui.lead(t('eg.lead.bad', { f: nf(fnd.length), n: nf(conns), range: range }), t('eg.lead.bad.sub', { h: nsev.high, m: nsev.medium, l: nsev.low }), nsev.high ? 'danger' : 'ok')); - var src = d.source || {}; - var sk = 'eg.src.' + src.state; - root.appendChild(el('p', { class: 'hint' }, t('eg.src', { state: t(sk) !== sk ? t(sk) : (src.state || '-'), lines: nf(src.lines || 0), bad: nf(src.malformed || 0) }))); - - var kp = el('div', { class: 'grid-12 eg-kpis' }); - function k(node) { node.classList.add('span-4'); kp.appendChild(node); } - k(U.ui.metric(t('eg.kpi.conns'), nf(conns), { sub: t('eg.kpi.conns.sub') })); - k(U.ui.metric(t('eg.kpi.dsts'), nf(dsts.length), { sub: t('eg.kpi.dsts.sub') })); - k(U.ui.metric(t('eg.kpi.find'), nf(fnd.length), { sub: t('eg.kpi.find.sub', { h: nsev.high, m: nsev.medium, l: nsev.low }), tone: nsev.high ? 'danger' : fnd.length ? 'warn' : 'ok' })); - root.appendChild(kp); + var st = stats(data), range = U.rangeLabel({ inline: true }); + root.appendChild(verdict(data, st, range)); + root.appendChild(kpis(st)); var grid = el('div', { class: 'grid-12' }); - if (wls.length) { - var wp = U.ui.panel({ title: t('eg.workloads'), hint: t('eg.workloads.hint'), cls: 'span-12', help: 'term.workload' }); - var wg = el('div', { class: 'eg-wl-grid' }); - wls.forEach(function (w) { wg.appendChild(workloadCard(w, multi)); }); - wp.body.appendChild(wg); + var fp = U.ui.panel({ title: t('eg.findings'), hint: t('eg.findings.hint'), cls: 'span-12' }); + if (!st.fnd.length) { + fp.body.appendChild(el('div', { class: 'eg-calm' }, el('span', { class: 'eg-calm-ico', 'aria-hidden': 'true' }, '✓'), + el('div', null, el('strong', null, t('eg.calm')), el('p', null, t('eg.calm.sub'))))); + } else { + var list = el('div', { class: 'eg-evs' }); + st.fnd.slice(0, 20).forEach(function (f) { list.appendChild(evidence(f, st)); }); + fp.body.appendChild(list); + } + grid.appendChild(fp); + + if (st.cc.length) { + var mp = U.ui.panel({ title: t('eg.map'), hint: t('eg.map.hint'), cls: 'span-12', variant: 'map' }); + var m = worldMap(st); + mp.body.appendChild(el('div', { class: 'eg-mapwrap' }, m ? el('div', { class: 'eg-mapbox' }, m) : null, countryBars(st))); + grid.appendChild(mp); + } + + var hm = heat(st); + if (hm) { + var hp = U.ui.panel({ title: t('eg.heat'), hint: t('eg.heat.hint'), cls: 'span-12', variant: 'chart' }); + hp.body.appendChild(hm); + grid.appendChild(hp); + } + + if (st.wls.length) { + var wp = U.ui.panel({ title: t('eg.wl'), hint: t('eg.wl.hint'), cls: 'span-12', variant: 'list', help: 'term.workload' }); + wp.body.appendChild(workloadsTable(st)); grid.appendChild(wp); } - var tl = d.timeline || {}, ser = tl.series || {}, names = Object.keys(ser); - var tp = U.ui.panel({ title: t('eg.timeline'), hint: t('eg.timeline.hint'), cls: 'span-12', variant: 'chart' }); - if (U.charts && U.charts.stackedArea && names.length) tp.body.appendChild(U.charts.stackedArea(names.map(function (n) { return { key: n, label: n, values: ser[n] }; }), tl.step || 3600, { start: tl.start || 0, title: t('eg.timeline') })); - else tp.body.appendChild(U.ui.empty(t('eg.lead.none', { range: range }))); - grid.appendChild(tp); - - var fp = U.ui.panel({ title: t('eg.findings'), hint: t('eg.findings.hint'), cls: 'span-12' }); - if (!fnd.length) fp.body.appendChild(U.ui.empty(t('eg.findings.none'))); - else { var ul = el('ul', { class: 'eg-findings' }); fnd.forEach(function (f) { ul.appendChild(findingNode(f, multi)); }); fp.body.appendChild(ul); } - grid.appendChild(fp); + var sp = U.ui.panel({ title: t('eg.scan'), hint: t('eg.scan.hint'), cls: 'span-12', help: 'term.authorized_scanner' }); + if (!st.bursts.length) sp.body.appendChild(U.ui.empty(t('eg.scan.none'))); + else sp.body.appendChild(scans(st)); + grid.appendChild(sp); var dp = U.ui.panel({ title: t('eg.dst'), hint: t('eg.dst.hint'), cls: 'span-12', variant: 'list' }); - if (!dsts.length) dp.body.appendChild(U.ui.empty(t('eg.dst.none'))); - else dp.body.appendChild(tbl([{ label: t('eg.col.ip') }, { label: t('eg.col.country') }, { label: t('eg.col.asn') }, { label: t('eg.col.conns'), cls: 'num' }, { label: t('eg.col.who') }, { label: t('eg.col.ports') }], - dsts.map(function (x) { - return [ipLink(x.ip), (x.cc ? U.fmt.flag(x.cc) + ' ' + U.fmt.country(x.cc) : '-'), (x.asn || '') + (x.org ? ' ' + x.org : '') || '-', nf(x.conns || 0), list(x.workloads), list(x.ports)]; - }))); + if (!st.dsts.length) dp.body.appendChild(U.ui.empty(t('eg.dst.none'))); + else dp.body.appendChild(destinations(st)); grid.appendChild(dp); - - var bursts = (d.scanner && d.scanner.bursts) || []; - var sp = U.ui.panel({ title: t('eg.scan'), hint: t('eg.scan.hint'), cls: 'span-12', variant: 'list', help: 'term.authorized_scanner' }); - if (!bursts.length) sp.body.appendChild(U.ui.empty(t('eg.scan.none'))); - else { - var bad = 0; - bursts.forEach(function (b) { bad += b.bad_dst_hits || 0; }); - if (bad > 0) sp.body.appendChild(el('div', { class: 'state-error eg-scanwarn' }, el('strong', null, t('eg.scan.warn', { n: nf(bad) })))); - sp.body.appendChild(tbl([{ label: t('eg.col.who1') }, { label: t('eg.col.when') }, { label: t('eg.col.targets'), cls: 'num' }, { label: t('eg.col.nets') }, { label: t('eg.col.ports') }, { label: t('eg.col.conns'), cls: 'num' }, { label: t('eg.col.badhits'), cls: 'num' }], - bursts.map(function (b) { - return [b.workload || '-', t('eg.scan.when', { a: when(b.start), b: when(b.end) }), nf(b.targets || 0), list(b.nets), list(b.ports), nf(b.conns || 0), - el('span', { class: b.bad_dst_hits ? 'eg-warn' : '' }, nf(b.bad_dst_hits || 0))]; - }))); - } - grid.appendChild(sp); root.appendChild(grid); } @@ -326,6 +565,17 @@ var my = ++seq; var p = Object.assign({}, U.rangeParams()); if (ctx && ctx.host && ctx.host !== 'all') p.host = ctx.host; + if (!hosts) { + hosts = []; + U.api('/api/v1/summary', { range: '1h', host: 'all' }).then(function (s) { + if (!alive) return; + (Array.isArray(s && s.hosts) ? s.hosts : []).forEach(function (h) { + var l = h && h.location; + if (l && typeof l.lat === 'number' && typeof l.lon === 'number' && Math.abs(l.lat) <= 90 && Math.abs(l.lon) <= 180) hosts.push({ name: String(h.name || '').slice(0, 64), lat: l.lat, lon: l.lon }); + }); + if (data) paint(); + }).catch(function () { }); + } U.api('/api/v1/egress', p).then(function (d) { if (!alive || my !== seq) return; data = d; paint();