diff --git a/internal/egress/egress_test.go b/internal/egress/egress_test.go index 6f27938..e6ae578 100644 --- a/internal/egress/egress_test.go +++ b/internal/egress/egress_test.go @@ -681,3 +681,22 @@ func TestBeaconMetadataAndKnownCDN(t *testing.T) { t.Fatalf("surbl: %+v", f) } } + +func TestEngineDst(t *testing.T) { + e := newEng(t, Config{Workloads: "ciberlab=10.0.5.0/24:scanner"}) + for i := 0; i < 70; i++ { // more destinations than the top-50 + e.IngestEvent(mk(t0.Add(time.Duration(i)*time.Second), "10.0.3.5", fmt.Sprintf("198.18.0.%d", i+1), "tcp", 80)) + } + e.IngestEvent(mk(t0.Add(time.Hour), "10.0.3.5", "198.18.0.70", "tcp", 443)) + from, to := t0.Unix()-60, t0.Unix()+7200 + d, _, ok := e.Dst(from, to, ip("198.18.0.70")) + if !ok || d.Conns != 2 || d.IP != "198.18.0.70" || len(d.Workloads) != 1 || len(d.Ports) != 2 || d.Ports[0] != 80 { + t.Fatalf("dst: %+v ok=%v", d, ok) + } + if _, _, ok := e.Dst(from, to, ip("203.0.113.9")); ok { + t.Fatal("unknown dst found") + } + if _, _, ok := e.Dst(from-10*86400, from-9*86400, ip("198.18.0.70")); ok { + t.Fatal("dst found outside the window") + } +} diff --git a/internal/egress/report.go b/internal/egress/report.go index a7f1558..0e804e8 100644 --- a/internal/egress/report.go +++ b/internal/egress/report.go @@ -454,3 +454,46 @@ func EmptyReport() Report { return Report{Workloads: []WorkloadOut{}, TopDst: []DstOut{}, Findings: []Finding{}, ByCountry: []CountryOut{}, Scanner: ScannerOut{Bursts: []BurstOut{}}, Timeline: Timeline{Step: 3600, Series: map[string][]uint32{}}} } + +// Dst looks one destination up in the dst table (not limited to the top 50): +// its connections in [from, to] and the findings that target it. ok is false +// when the window holds neither. +func (e *Engine) Dst(from, to int64, ip netip.Addr) (DstOut, []Finding, bool) { + e.mu.Lock() + defer e.mu.Unlock() + if to <= from { + to = from + 1 + } + fs := []Finding{} + for _, f := range e.findings { + if f.Last >= from && f.First <= to && f.Dst == ip.String() { + c := *f + c.Samples = append([]int64(nil), f.Samples...) + fs = append(fs, c) + } + } + sort.Slice(fs, func(i, j int) bool { + if fs[i].Last != fs[j].Last { + return fs[i].Last > fs[j].Last + } + return fs[i].ID < fs[j].ID + }) + out := DstOut{IP: ip.String(), Workloads: []string{}, Ports: []uint16{}} + if el, ok := e.dsts.m[ip]; ok { // read-only: no LRU promotion + ds := el.Value.(*lent[netip.Addr, *dstStat]).v + d0, d1 := int32(from/86400), int32(to/86400) + for _, d := range ds.days { + if d.day >= d0 && d.day <= d1 { + out.Conns += uint64(d.n) + } + } + out.CC, out.ASN, out.Org = ds.cc, ds.asn, ds.og + out.Workloads = append(out.Workloads, ds.wls...) + out.Ports = append(out.Ports, ds.ports...) + sort.Slice(out.Ports, func(a, b int) bool { return out.Ports[a] < out.Ports[b] }) + } + if out.Conns == 0 && len(fs) == 0 { + return DstOut{}, nil, false + } + return out, fs, true +} diff --git a/internal/server/api_egress_ip.go b/internal/server/api_egress_ip.go new file mode 100644 index 0000000..5dbebe4 --- /dev/null +++ b/internal/server/api_egress_ip.go @@ -0,0 +1,149 @@ +package server + +import ( + "encoding/json" + "net/http" + "net/netip" + "sort" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents" +) + +func init() { + registerUserRoute("GET /api/v1/ip/{ip}/egress", func(s *Server) http.HandlerFunc { return s.ipEgressAPI }) +} + +type ipEgressHost struct { + Host string `json:"host"` + Conns uint64 `json:"conns"` + CC string `json:"cc"` + ASN string `json:"asn"` + Org string `json:"org"` + Workloads []string `json:"workloads"` + Ports []uint16 `json:"ports"` +} + +type ipEgressInc struct { + ID string `json:"id"` + Host string `json:"host"` + Title string `json:"title"` + Status string `json:"status"` + Severity string `json:"severity"` + Kind string `json:"kind"` + Workload string `json:"workload"` + Last int64 `json:"last_seen"` +} + +// ipEgressAPI: GET /api/v1/ip/{ip}/egress. What the node(s) did towards this +// address (egress connections, findings, incidents) and when it was last seen +// as an inbound source. +func (s *Server) ipEgressAPI(w http.ResponseWriter, r *http.Request) { + ip, err := netip.ParseAddr(r.PathValue("ip")) + if err != nil || ip.Zone() != "" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip"}) + return + } + ip = ip.Unmap() + rg, ok := s.rangeOf(w, r) + if !ok { + return + } + host := r.URL.Query().Get("host") + if len(host) > 253 { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad host"}) + return + } + local, peers, only, ok := s.studyHosts(w, host) + if !ok { + return + } + from, to := rg.Bounds(s.opt.Store.Now().Unix()) + self := s.opt.Store.Name() + out := struct { + IP string `json:"ip"` + Egress []ipEgressHost `json:"egress"` + Findings []egress.Finding `json:"findings"` + Incidents []ipEgressInc `json:"incidents"` + LastSeenInbound int64 `json:"last_seen_inbound"` + }{IP: ip.String(), Egress: []ipEgressHost{}, Findings: []egress.Finding{}, Incidents: []ipEgressInc{}} + + add := func(h string, d egress.DstOut, fs []egress.Finding) { + if d.Conns > 0 || len(d.Workloads) > 0 { + out.Egress = append(out.Egress, ipEgressHost{Host: h, Conns: d.Conns, CC: d.CC, ASN: d.ASN, Org: d.Org, + Workloads: append([]string{}, d.Workloads...), Ports: append([]uint16{}, d.Ports...)}) + } + for _, f := range fs { + f.Host = h + out.Findings = append(out.Findings, f) + } + } + if eng := egressEngine.Load(); local && eng != nil { + if d, fs, ok := eng.Dst(from, to, ip); ok { + add(self, d, fs) + } + } + if peers && s.opt.Hub != nil { + raws := s.opt.Hub.EgressFor(r.Context(), from, to, only) + names := make([]string, 0, len(raws)) + for n := range raws { + names = append(names, n) + } + sort.Strings(names) + for _, n := range names { + var pr egress.Report + if json.Unmarshal(raws[n], &pr) != nil { + continue + } + pr.Sanitize(n) + var fs []egress.Finding + for _, f := range pr.Findings { + if f.Dst == ip.String() { + fs = append(fs, f) + } + } + var d egress.DstOut + for _, x := range pr.TopDst { // peers only report their top destinations + if x.IP == ip.String() { + d = x + } + } + add(n, d, fs) + } + } + sort.Slice(out.Findings, func(i, j int) bool { return out.Findings[i].Last > out.Findings[j].Last }) + if len(out.Findings) > 200 { + out.Findings = out.Findings[:200] + } + + for _, h := range s.incHosts() { + if (host != "" && host != "all" && host != h) || len(out.Incidents) >= 100 { + continue + } + st := s.incStore(h) + if st == nil { + continue + } + for _, t := range st.All(incidents.Query{Q: ip.String()}) { + if t.Dst != ip.String() { + continue + } + out.Incidents = append(out.Incidents, ipEgressInc{ID: h + "/" + t.ID, Host: h, Title: t.Title, Status: t.Status, + Severity: t.Severity, Kind: t.Kind, Workload: t.Workload, Last: t.LastSeen}) + } + } + sort.Slice(out.Incidents, func(i, j int) bool { return out.Incidents[i].Last > out.Incidents[j].Last }) + + key := ip.String() + if d, ok := s.opt.Store.IP(key); ok { + out.LastSeenInbound = d.Last + } + if s.opt.Hub != nil { + for _, d := range s.opt.Hub.IPDetail(key) { + if d.Last > out.LastSeenInbound { + out.LastSeenInbound = d.Last + } + } + } + writeJSON(w, 200, out) +} diff --git a/internal/server/api_egress_test.go b/internal/server/api_egress_test.go index c884323..92735fa 100644 --- a/internal/server/api_egress_test.go +++ b/internal/server/api_egress_test.go @@ -1,7 +1,9 @@ package server import ( + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents" "net/netip" + "path/filepath" "strconv" "testing" "time" @@ -68,3 +70,42 @@ func TestEgressAPI(t *testing.T) { t.Fatalf("peer token must not open the user route") } } + +func TestIPEgressAPI(t *testing.T) { + st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour}) + inc, err := incidents.Open(filepath.Join(t.TempDir(), "incidents.json"), nil) + if err != nil { + t.Fatal(err) + } + h := New(Options{Token: userTok, Version: "t", Store: st, Incidents: inc}) + auth := map[string]string{"Authorization": "Bearer " + userTok} + e, err := egress.New(egress.Config{Workloads: "ciberlab=10.0.5.0/24:scanner"}) + if err != nil { + t.Fatal(err) + } + SetEgress(e) + defer SetEgress(nil) + now := time.Now() + e.IngestEvent(egress.Event{Time: now.Add(-time.Hour), Src: netip.MustParseAddr("10.0.5.2"), Dst: netip.MustParseAddr("203.0.113.7"), Proto: "tcp", DPort: 6667, In: "br-1"}) + inc.Sync([]incidents.Finding{{Host: "oracle", Kind: "beacon", Severity: "high", Workload: "ciberlab", Dst: "203.0.113.7", Proto: "tcp", DPort: 6667, First: now.Add(-time.Hour).Unix(), Last: now.Unix(), Count: 9}}) + + d := getJSON(t, h, "/api/v1/ip/203.0.113.7/egress?range=24h", auth) + eg := d["egress"].([]any) + if len(eg) != 1 || eg[0].(map[string]any)["host"] != "oracle" || eg[0].(map[string]any)["conns"].(float64) != 1 { + t.Fatalf("egress: %v", d) + } + ics := d["incidents"].([]any) + if len(ics) != 1 || ics[0].(map[string]any)["id"] != "oracle/INC-1" { + t.Fatalf("incidents: %v", d["incidents"]) + } + if d["last_seen_inbound"].(float64) != 0 { + t.Fatalf("inbound: %v", d) + } + d = getJSON(t, h, "/api/v1/ip/203.0.113.99/egress?range=24h", auth) + if len(d["egress"].([]any)) != 0 || len(d["incidents"].([]any)) != 0 || len(d["findings"].([]any)) != 0 { + t.Fatalf("empty: %v", d) + } + if w := do(h, "GET", "/api/v1/ip/nope/egress", cloneHdr(auth), nil); w.Code != 400 { + t.Fatalf("bad ip: %d", w.Code) + } +} diff --git a/internal/server/web/ip.js b/internal/server/web/ip.js index 0c62fc4..a9888b5 100644 --- a/internal/server/web/ip.js +++ b/internal/server/web/ip.js @@ -29,8 +29,21 @@ 'ip.loading': 'Loading the analysis.', 'ip.invalid': 'This is not a valid IP address.', 'ip.error': 'Could not load this IP.', - 'ip.notfound': 'No activity from this IP in the selected period.', - 'ip.notfound.hint': 'Pick a longer period above, or the IP was never seen.', + 'ip.never': 'This IP was never seen by Urutau (neither as a source nor as an egress destination).', + 'ip.dst.title': 'Egress destination', + 'ip.dst.lead': 'Our workloads connected to this address; it never attacked us.', + 'ip.dst.hint': 'Outbound connections from this installation to the IP, not inbound attacks.', + 'ip.dst.host': 'Host', + 'ip.dst.workloads': 'Workloads', + 'ip.dst.ports': 'Ports', + 'ip.dst.conns': 'Connections', + 'ip.dst.net': 'Network', + 'ip.dst.findings': 'Findings', + 'ip.dst.incidents': 'Linked incidents', + 'ip.dst.nofind': 'No finding in this period.', + 'ip.dst.last': 'Last: {when}', + 'ip.dst.inb.after': 'Last seen as an attacker (inbound) on {when}, outside the selected period.', + 'ip.dst.inb.btn': 'Show the last 30 days', 'ip.retry': 'Try again', 'ip.lead.hostile': 'Hostile: {events} {range}', 'ip.lead.suspicious': 'Suspicious: {events} {range}', @@ -354,8 +367,21 @@ 'ip.loading': 'Carregando a análise.', 'ip.invalid': 'Este não é um endereço IP válido.', 'ip.error': 'Não foi possível carregar este IP.', - 'ip.notfound': 'Nenhuma atividade deste IP no período selecionado.', - 'ip.notfound.hint': 'Escolha um período maior acima, ou o IP nunca foi visto.', + 'ip.never': 'Este IP nunca foi visto pelo Urutau (nem como origem nem como destino de saída).', + 'ip.dst.title': 'Destino de saída', + 'ip.dst.lead': 'Nossas cargas de trabalho conectaram a este endereço; ele nunca nos atacou.', + 'ip.dst.hint': 'Conexões de saída desta instalação para o IP, não ataques de entrada.', + 'ip.dst.host': 'Host', + 'ip.dst.workloads': 'Cargas de trabalho', + 'ip.dst.ports': 'Portas', + 'ip.dst.conns': 'Conexões', + 'ip.dst.net': 'Rede', + 'ip.dst.findings': 'Achados', + 'ip.dst.incidents': 'Incidentes ligados', + 'ip.dst.nofind': 'Nenhum achado neste período.', + 'ip.dst.last': 'Último: {when}', + 'ip.dst.inb.after': 'Visto pela última vez como atacante (entrada) em {when}, fora do período selecionado.', + 'ip.dst.inb.btn': 'Mostrar os últimos 30 dias', 'ip.retry': 'Tentar de novo', 'ip.lead.hostile': 'Hostil: {events} {range}', 'ip.lead.suspicious': 'Suspeito: {events} {range}', @@ -1988,7 +2014,7 @@ h('div', 'ipx-skel-b'), h('div', 'ipx-skel-b short'), h('div', 'ipx-skel-b')); } function errorNode(s, key, withRetry) { - var box = h('div', 'ipx-card state-error ipx-state', h('p', 'ipx-empty-t', t(key)), key === 'ip.notfound' ? h('p', 'ipx-empty-h', t('ip.notfound.hint')) : null); + var box = h('div', 'ipx-card state-error ipx-state', h('p', 'ipx-empty-t', t(key))); if (withRetry) { var b = h('button', 'ipx-btn', { type: 'button' }, t('ip.retry')); b.addEventListener('click', function () { load(s); }); @@ -2029,6 +2055,72 @@ watchScrollFade(s, toc); } + // ---------------------------------------------------------------- egress destination (no inbound data) + function dstBadge(sev) { return h('span', 'ipx-chip', str(sev)); } + function egressNode(s, d) { + var eg = arr(d.egress).filter(isObj), fs = arr(d.findings).filter(isObj), ics = arr(d.incidents).filter(isObj); + var c = card('ip.dst.title', 'ip.dst.hint', 12); + c.body.appendChild(h('p', 'ipx-lead', t('ip.dst.lead'))); + if (eg.length) { + var tb = h('tbody'); + eg.forEach(function (x) { + var cc = str(x.cc).toUpperCase(), net = [x.asn ? str(x.asn) : '', clip(x.org, 60)].filter(Boolean).join(' '); + tb.appendChild(h('tr', null, + h('td', null, str(x.host)), + h('td', null, arr(x.workloads).join(', ') || '-'), + h('td', 'ipx-mono', arr(x.ports).join(', ') || '-'), + h('td', 'ipx-num', N(num(x.conns))), + h('td', null, (cc && fmt.flag ? fmt.flag(cc) + ' ' : '') + (cc && fmt.country ? fmt.country(cc) : cc) + (net ? ' · ' + net : '')))); + }); + c.body.appendChild(h('div', 'ipx-tbl-w', h('table', 'ipx-tbl ipx-ctbl', h('thead', null, h('tr', null, + h('th', null, t('ip.dst.host')), h('th', null, t('ip.dst.workloads')), h('th', null, t('ip.dst.ports')), h('th', null, t('ip.dst.conns')), h('th', null, t('ip.dst.net')))), tb))); + } + c.body.appendChild(sub('ip.dst.findings')); + if (!fs.length) c.body.appendChild(h('p', 'ipx-muted', t('ip.dst.nofind'))); + else { + var fb = h('tbody'); + fs.forEach(function (f) { + fb.appendChild(h('tr', null, h('td', null, str(f.host)), h('td', null, str(f.kind)), h('td', null, dstBadge(f.severity)), h('td', null, str(f.workload)), + h('td', 'ipx-mono', (str(f.proto) + '/' + num(f.dport))), h('td', null, clip(f.detail, 120)), h('td', null, dt(num(f.last))))); + }); + c.body.appendChild(h('div', 'ipx-tbl-w', h('table', 'ipx-tbl ipx-ctbl', fb))); + } + if (ics.length) { + c.body.appendChild(sub('ip.dst.incidents')); + var ul = h('ul', 'ipx-list'); + ics.forEach(function (i) { + var id = str(i.id), parts = id.split('/'); + var href = '#/incidents/' + encodeURIComponent(parts[0]) + '/' + encodeURIComponent(parts.slice(1).join('/')); + ul.appendChild(h('li', null, h('a', null, { href: href }, id), ' ', dstBadge(i.severity), ' ', h('span', 'ipx-muted', str(i.status) + ' · ' + clip(i.title, 100)))); + }); + c.body.appendChild(ul); + } + return c.node; + } + function loadEgress(s, my) { + var p = Object.assign({}, rParams(s.ctx)); + if (s.ctx && s.ctx.host && s.ctx.host !== 'all') p.host = s.ctx.host; + U.api('/api/v1/ip/' + encodeURIComponent(s.ip) + '/egress', p).then(function (d) { + if (!s.alive || my !== s.seq) return; + if (!isObj(d)) throw new Error('bad payload'); + var has1 = arr(d.egress).length || arr(d.findings).length || arr(d.incidents).length, last = num(d.last_seen_inbound); + if (has1) { showState(s, egressNode(s, d)); return; } + if (last) { + var box = h('div', 'ipx-card ipx-state', h('p', 'ipx-empty-t', t('ip.dst.inb.after', { when: dt(last) }))); + var b = h('button', 'ipx-btn', { type: 'button' }, t('ip.dst.inb.btn')); + b.addEventListener('click', function () { location.hash = '#/ip/' + encodeURIComponent(s.ip) + '?r=30d'; }); + box.appendChild(b); + showState(s, box); + return; + } + showState(s, errorNode(s, 'ip.never', false)); + }).catch(function (e) { + if (!s.alive || my !== s.seq) return; + if (e && e.message === 'unauthorized') return; + showState(s, errorNode(s, 'ip.error', true)); + }); + } + function load(s) { var my = ++s.seq; s.ip = ipFromCtx(s.ctx); @@ -2048,7 +2140,8 @@ if (!s.alive || my !== s.seq) return; if (e && e.message === 'unauthorized') return; s.data = null; - showState(s, errorNode(s, e && e.status === 404 ? 'ip.notfound' : 'ip.error', !(e && e.status === 404))); + if (e && e.status === 404) { loadEgress(s, my); return; } + showState(s, errorNode(s, e && e.status === 404 ? 'ip.never' : 'ip.error', !(e && e.status === 404))); }); }