feat: record own and trusted web traffic in its own classes instead of dropping it
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4143bf599e
commit
3511a7141c
18 files changed
+434
-17
No files matched your search
@@ -62,13 +62,13 @@ func TestMonitoringTrustedAndForged(t *testing.T) {
|
||||
t.Fatalf("feed %+v", rec)
|
||||
}
|
||||
|
||||
// trusted origins are dropped entirely, even for exploits and with other UAs
|
||||
// trusted origins are only counted (see TestOwnTrafficIsCountedNeverAnalysed), even for exploits
|
||||
h(line("136.248.78.83", "GET", "/?x=../../etc/passwd", "curl/8", 200))
|
||||
h(line("2001:db8:1::5", "GET", "/.env", "curl/8", 404))
|
||||
h(line("127.0.0.1", "GET", "/.env", "curl/8", 404))
|
||||
for _, a := range []string{"136.248.78.83", "2001:db8:1::5", "127.0.0.1"} {
|
||||
if _, ok := st.IP(a); ok {
|
||||
t.Fatalf("%s must be dropped", a)
|
||||
t.Fatalf("%s must not become an IP record", a)
|
||||
}
|
||||
}
|
||||
// a non-matching UA from an external IP is a normal request
|
||||
@@ -374,3 +374,100 @@ func TestLocationFlagIsValidated(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnTrafficIsCountedNeverAnalysed(t *testing.T) {
|
||||
r, st := runner(t, nil)
|
||||
h := r.handle(&source{name: "traefik", parse: traefikParse})
|
||||
h(line("198.51.100.4", "GET", "/", "Mozilla/5.0 (X11; Linux x86_64) Firefox/120.0", 200)) // external: counted as usual
|
||||
before := st.Summary("1h")
|
||||
// trusted (--trusted), including an attack-looking request, and a private address (--ignore default)
|
||||
h(line("136.248.78.83", "GET", "/.env", "curl/8", 404))
|
||||
h(line("136.248.78.83", "GET", "/api/x?token=secret", "curl/8", 200))
|
||||
h(line("2001:db8:1::5", "POST", "/login", "curl/8", 401))
|
||||
h(line("172.18.0.1", "GET", "/", "Mozilla/5.0 (X11; Linux x86_64) Firefox/120.0", 200))
|
||||
h(line("127.0.0.1", "GET", "/", "x", 502))
|
||||
after := st.Summary("2h") // another range: the summary of "1h" is cached for 2 s
|
||||
if after.Totals.Trusted != 3 || after.Totals.Internal != 2 {
|
||||
t.Fatalf("own counts: %+v", after.Totals)
|
||||
}
|
||||
if after.Totals.Requests != before.Totals.Requests || after.Totals.Malicious != before.Totals.Malicious ||
|
||||
after.Totals.RequestsAll != before.Totals.Requests+5 {
|
||||
t.Fatalf("totals: before %+v after %+v", before.Totals, after.Totals)
|
||||
}
|
||||
if after.Totals.Counts["trusted"] != 3 || after.Totals.Counts["internal"] != 2 {
|
||||
t.Fatalf("counts: %v", after.Totals.Counts)
|
||||
}
|
||||
if after.Totals.UniqueIPs != before.Totals.UniqueIPs || after.Totals.HostileIPs != 0 || after.Totals.SuspiciousIPs != 0 {
|
||||
t.Fatalf("own traffic must not create IPs: %+v", after.Totals)
|
||||
}
|
||||
for _, a := range []string{"136.248.78.83", "2001:db8:1::5", "172.18.0.1", "127.0.0.1"} {
|
||||
if _, ok := st.IP(a); ok {
|
||||
t.Fatalf("%s must not have an IP record", a)
|
||||
}
|
||||
}
|
||||
if len(st.Recent(10)) != len(before.Recent) || len(after.IPs) != len(before.IPs) || len(after.TopPaths) != len(before.TopPaths) {
|
||||
t.Fatal("own traffic must not reach the feed, the IP table or the attack tops")
|
||||
}
|
||||
if tr := after; tr.Totals.Monitoring != 0 {
|
||||
t.Fatalf("monitoring: %+v", tr.Totals)
|
||||
}
|
||||
if v := st.TrafficFor(store.ParseRange("1h"), "all"); v.Requests != 1 || v.Visitors != 0 {
|
||||
t.Fatalf("web analytics must not count own traffic (one external request, no visitor without an enricher): %+v", v)
|
||||
}
|
||||
o := after.Own
|
||||
if o.Status[0] != 2 || o.Status[2] != 2 || o.Status[3] != 1 {
|
||||
t.Fatalf("status classes: %v", o.Status)
|
||||
}
|
||||
var sum uint32
|
||||
for _, c := range []string{"trusted", "internal"} {
|
||||
for _, v := range o.Series[c] {
|
||||
sum += v
|
||||
}
|
||||
}
|
||||
if sum != 5 {
|
||||
t.Fatalf("series sum %d", sum)
|
||||
}
|
||||
got := map[string]string{}
|
||||
for _, c := range o.Origins {
|
||||
got[c.Key] = c.Label
|
||||
}
|
||||
if got["136.248.78.83"] != "trusted" || got["172.18.0.1"] != "internal" || got["2001:db8:1::/64"] != "trusted" {
|
||||
t.Fatalf("origins: %+v", o.Origins)
|
||||
}
|
||||
for _, p := range o.Paths {
|
||||
if strings.Contains(p.Key, "secret") {
|
||||
t.Fatalf("query strings must not be kept: %+v", o.Paths)
|
||||
}
|
||||
}
|
||||
// a snapshot keeps the own traffic
|
||||
dir := t.TempDir()
|
||||
if err := st.Save(SnapshotPath(dir), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st2 := store.New(store.Config{Name: "t", Version: "t"})
|
||||
if _, err := st2.Load(SnapshotPath(dir)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s2 := st2.Summary("3h"); s2.Totals.Trusted != 3 || s2.Totals.Internal != 2 {
|
||||
t.Fatalf("after reload: %+v", s2.Totals)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnTrafficThroughFeed(t *testing.T) {
|
||||
// the probe sends every line; the hub runner (remote mode) classifies it
|
||||
c := Config{Ignore: DefaultIgnore, Trusted: "10.9.9.9", Retention: 168 * time.Hour, Name: "n"}
|
||||
st := store.New(store.Config{Name: "n", Version: "t"})
|
||||
r, err := NewRemoteRunner(c, st, slog.New(slog.NewTextHandler(io.Discard, nil)), t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !r.Feed("traefik", line("10.9.9.9", "GET", "/", "x", 200), store.Offset{Inode: 1, Offset: 10}) ||
|
||||
!r.Feed("traefik", line("203.0.113.9", "GET", "/", "x", 200), store.Offset{Inode: 1, Offset: 20}) ||
|
||||
!r.Feed("traefik", line("192.168.1.2", "GET", "/", "x", 200), store.Offset{Inode: 1, Offset: 30}) {
|
||||
t.Fatal("feed refused")
|
||||
}
|
||||
s := st.Summary("1h")
|
||||
if s.Totals.Trusted != 1 || s.Totals.Internal != 1 || s.Totals.Requests != 1 || s.Totals.RequestsAll != 3 {
|
||||
t.Fatalf("totals: %+v", s.Totals)
|
||||
}
|
||||
}
|
||||
+16
-1
@@ -105,7 +105,8 @@ func (s *source) status() store.SourceStatus {
|
||||
// Runner owns the log sources of one instance.
|
||||
type Runner struct {
|
||||
St *store.Store
|
||||
Ignore []netip.Prefix
|
||||
Ignore []netip.Prefix // --ignore and --trusted: their web requests are counted as own traffic only
|
||||
Trusted []netip.Prefix // --trusted: the class "trusted"; the rest of Ignore is "internal"
|
||||
Monitor *regexp.Regexp
|
||||
MonitorFrom []netip.Prefix // when set, monitors are only believed from these networks
|
||||
Enr core.Enricher // optional geo and User-Agent resolver
|
||||
@@ -132,6 +133,9 @@ func NewRunner(c Config, st *store.Store, log *slog.Logger) (*Runner, error) {
|
||||
return nil, err
|
||||
}
|
||||
r := &Runner{St: st, Ignore: ign, DataDir: c.DataDir, Log: log}
|
||||
if r.Trusted, err = core.ParseCIDRs(c.Trusted); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if r.MonitorFrom, err = core.ParseCIDRs(c.MonitorFrom); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -377,6 +381,17 @@ func (r *Runner) handle(s *source) func([]byte) {
|
||||
}
|
||||
s.win.add(false)
|
||||
if core.Ignored(r.Ignore, ev.IP) {
|
||||
// own and trusted origins are counted, never analysed
|
||||
if ev.Source == "traefik" {
|
||||
if _, err := netip.ParseAddr(ev.IP); err == nil {
|
||||
class := store.OwnInternal
|
||||
if core.Ignored(r.Trusted, ev.IP) {
|
||||
class = store.OwnTrusted
|
||||
}
|
||||
s.lastEvent.Store(time.Now().Unix())
|
||||
r.St.Own(ev, class)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if r.monitorTraffic(&ev) {
|
||||
|
||||
@@ -1579,6 +1579,31 @@
|
||||
var CLIENT_COLORS = { desktop: '--viz-1', mobile: '--viz-6', tablet: '--viz-5', bot: '--viz-3', tool: '--viz-7', unknown: '--viz-8', misc: '--viz-2' };
|
||||
var CLIENT_ORDER = ['desktop', 'mobile', 'tablet', 'bot', 'tool', 'unknown', 'misc'];
|
||||
var STATUS_TOKENS = ['--ok', '--info', '--warn', '--danger'];
|
||||
// Own infrastructure and trusted origins: counted apart, never analysed (s.own, s.totals.trusted/internal)
|
||||
function renderOwnTraffic(box, s) {
|
||||
var o = s.own || {}, T = s.totals || {}, tr = o.trusted || 0, inn = o.internal || 0, tot = tr + inn;
|
||||
ready(box); clear(box.body);
|
||||
if (!tot) { box.body.appendChild(empty(t('own.none'), t('own.noneBody'))); return; }
|
||||
var kp = h('div', 'kpi-row');
|
||||
kp.appendChild(stat(t('own.trusted'), nf(tr), t('own.sub.trusted'), 'neutral'));
|
||||
kp.appendChild(stat(t('own.internal'), nf(inn), t('own.sub.internal'), 'neutral'));
|
||||
kp.appendChild(stat(t('own.all'), nf(T.requests_all || (T.requests || 0) + tot), t('own.sub.all', { n: nf(T.requests || 0), o: nf(tot) }), 'neutral'));
|
||||
box.body.appendChild(kp);
|
||||
var ser = o.series || {};
|
||||
box.body.appendChild(charts.stackedArea([{ key: 'trusted', label: t('own.trusted'), values: ser.trusted || [] }, { key: 'internal', label: t('own.internal'), values: ser.internal || [] }], o.step, { start: o.start, colors: ['--viz-5', '--viz-8'], title: t('own.title') }));
|
||||
var cls = ['2xx', '3xx', '4xx', '5xx'];
|
||||
box.body.appendChild(charts.bars(cls.map(function (k, i) { return { key: k, label: t('traffic.status.' + k), value: (o.status || [])[i] || 0, color: STATUS_TOKENS[i] }; }), { title: t('traffic.status') }));
|
||||
var rows = o.origins || [], tb = el('table', { class: 'tbl' });
|
||||
tb.appendChild(h('thead', null, h('tr', null, h('th', null, t('own.col.origin')), h('th', null, t('own.col.class')), h('th', 'num', t('own.col.requests')))));
|
||||
var body = el('tbody');
|
||||
rows.forEach(function (r) { body.appendChild(h('tr', null, h('td', 'mono', r.key), h('td', null, t('own.' + pick(['trusted', 'internal'], r.label, 'internal'))), h('td', 'num', nf(r.n)))); });
|
||||
tb.appendChild(body);
|
||||
box.body.appendChild(h('h3', null, t('own.origins'))); box.body.appendChild(tb);
|
||||
var two = h('div', 'grid-12');
|
||||
var dm = h('div', 'span-6', h('h3', null, t('own.domains')), bars(o.domains || [], { mono: true }));
|
||||
var ph = h('div', 'span-6', h('h3', null, t('own.paths')), bars(o.paths || [], { mono: true }));
|
||||
two.appendChild(dm); two.appendChild(ph); box.body.appendChild(two);
|
||||
}
|
||||
var pTraffic = corePage({
|
||||
id: 'traffic', icon: ICONS.traffic, titleKey: 'nav.traffic', domain: true,
|
||||
build: function (root) {
|
||||
@@ -1594,19 +1619,22 @@
|
||||
v.browsers = panel({ title: t('traffic.browsers'), hint: t('traffic.browsers.hint'), loading: true });
|
||||
v.oses = panel({ title: t('traffic.oses'), hint: t('traffic.oses.hint'), loading: true });
|
||||
v.status = panel({ title: t('traffic.status'), hint: t('traffic.status.hint'), loading: true, help: 'term.status_class' });
|
||||
v.own = panel({ title: t('own.title'), hint: t('own.hint'), loading: true });
|
||||
v.privacy = sp(12, h('p', 'note', t('traffic.privacy')));
|
||||
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(12, v.timeline)); g.appendChild(sp(12, v.map));
|
||||
g.appendChild(sp(4, v.client)); g.appendChild(sp(4, v.browsers)); g.appendChild(sp(4, v.oses));
|
||||
g.appendChild(sp(6, v.status)); g.appendChild(sp(6, v.bots));
|
||||
['pages', 'refs', 'cities'].forEach(function (k) { g.appendChild(sp(4, v[k])); });
|
||||
g.appendChild(sp(12, v.own));
|
||||
g.appendChild(v.privacy);
|
||||
root.appendChild(g);
|
||||
return v;
|
||||
},
|
||||
load: function (c) { return api('/api/v1/traffic', Object.assign({ host: c.host, domain: c.domain }, c.from !== null && c.from !== undefined ? { from: c.from, to: c.to } : { range: c.range })); },
|
||||
render: function (v, d) {
|
||||
render: function (v, d, c) {
|
||||
v.data = d;
|
||||
setDomains(d.domains || []);
|
||||
getSummary(c).then(function (s) { renderOwnTraffic(v.own, s); }, function () { ready(v.own); clear(v.own.body); v.own.body.appendChild(empty(t('own.none'), '')); });
|
||||
var hasData = d.requests > 0;
|
||||
clear(v.lead); v.lead.classList.remove('skeleton', 'lead-skel');
|
||||
v.lead.appendChild(hasData
|
||||
|
||||
@@ -321,6 +321,22 @@ window.URUTAU_I18N = {
|
||||
'traffic.browsers': 'Browsers',
|
||||
'traffic.oses': 'Operating systems',
|
||||
'traffic.status': 'Status codes',
|
||||
'own.title': 'Own infrastructure and trusted origins',
|
||||
'own.hint': 'Requests from --trusted origins and private networks. They are counted here and nowhere else: they never score an IP, enter threats, maps, visitors or the blocklist.',
|
||||
'own.none': 'No requests from own or trusted origins',
|
||||
'own.noneBody': 'Nothing came from --trusted or --ignore addresses in this range.',
|
||||
'own.trusted': 'Trusted origins',
|
||||
'own.internal': 'Internal networks',
|
||||
'own.all': 'All requests',
|
||||
'own.sub.trusted': 'addresses of --trusted',
|
||||
'own.sub.internal': 'private and --ignore ranges',
|
||||
'own.sub.all': '{n} external + {o} own',
|
||||
'own.origins': 'By origin',
|
||||
'own.domains': 'By domain',
|
||||
'own.paths': 'Top paths',
|
||||
'own.col.origin': 'Origin',
|
||||
'own.col.class': 'Class',
|
||||
'own.col.requests': 'Requests',
|
||||
'traffic.privacy': 'Visitors are counted with a daily rotating hash kept in memory only. No visitor IP is stored.',
|
||||
'traffic.sub.visitors': 'distinct, hash per day',
|
||||
'traffic.sub.requests': 'incl. assets and bots',
|
||||
@@ -857,6 +873,22 @@ window.URUTAU_I18N = {
|
||||
'traffic.browsers': 'Navegadores',
|
||||
'traffic.oses': 'Sistemas operacionais',
|
||||
'traffic.status': 'Códigos de status',
|
||||
'own.title': 'Infraestrutura própria e origens confiáveis',
|
||||
'own.hint': 'Requisições de origens --trusted e de redes privadas. Elas são contadas aqui e em mais nenhum lugar: nunca pontuam um IP, nem entram em ameaças, mapas, visitantes ou na lista de bloqueio.',
|
||||
'own.none': 'Nenhuma requisição de origens próprias ou confiáveis',
|
||||
'own.noneBody': 'Nada veio de endereços --trusted ou --ignore neste período.',
|
||||
'own.trusted': 'Origens confiáveis',
|
||||
'own.internal': 'Redes internas',
|
||||
'own.all': 'Todas as requisições',
|
||||
'own.sub.trusted': 'endereços de --trusted',
|
||||
'own.sub.internal': 'faixas privadas e --ignore',
|
||||
'own.sub.all': '{n} externas + {o} próprias',
|
||||
'own.origins': 'Por origem',
|
||||
'own.domains': 'Por domínio',
|
||||
'own.paths': 'Caminhos mais pedidos',
|
||||
'own.col.origin': 'Origem',
|
||||
'own.col.class': 'Classe',
|
||||
'own.col.requests': 'Requisições',
|
||||
'traffic.privacy': 'Visitantes são contados com um hash que muda todo dia e fica só na memória. Nenhum IP de visitante é guardado.',
|
||||
'traffic.sub.visitors': 'distintos, hash diário',
|
||||
'traffic.sub.requests': 'inclui recursos e bots',
|
||||
|
||||
@@ -128,7 +128,7 @@ func (e *PeerExport) SanitizeRange(rg Range) error {
|
||||
cats[string(c)] = true
|
||||
}
|
||||
for k := range s.Totals.Counts {
|
||||
if !cats[k] {
|
||||
if !cats[k] && k != OwnTrusted && k != OwnInternal {
|
||||
delete(s.Totals.Counts, k)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,6 +124,9 @@ func Merge(host string, parts []Summary) Summary {
|
||||
out.Totals.Malicious += p.Totals.Malicious
|
||||
out.Totals.ActiveBans += p.Totals.ActiveBans
|
||||
out.Totals.Monitoring += p.Totals.Monitoring
|
||||
out.Totals.Trusted += p.Totals.Trusted
|
||||
out.Totals.Internal += p.Totals.Internal
|
||||
out.Totals.RequestsAll += p.Totals.RequestsAll
|
||||
for k, v := range p.Totals.Counts {
|
||||
out.Totals.Counts[k] += v
|
||||
}
|
||||
@@ -148,6 +151,7 @@ func Merge(host string, parts []Summary) Summary {
|
||||
ctry = append(ctry, p.Countries)
|
||||
recent = append(recent, p.Recent...)
|
||||
}
|
||||
out.Own = mergeOwn(parts, out.Timeline)
|
||||
out.IPs = MergeIPs(ipLists...)
|
||||
// Peers only ship their top IPs, so the merged list can undercount; never
|
||||
// report less than the largest single instance, and exact for one part.
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
// Own traffic: web requests whose client is an own or trusted origin (--trusted
|
||||
// and the --ignore ranges, private networks by default). They are counted in
|
||||
// aggregates only, apart from every attack and visitor aggregate: they never
|
||||
// create an IP record, score, session, campaign, technique, family, ban
|
||||
// evidence or page view, and they leave no event record. The classes are the
|
||||
// two names below.
|
||||
const (
|
||||
OwnTrusted = "trusted" // an address of --trusted (URUTAU_TRUSTED)
|
||||
OwnInternal = "internal" // an address of an --ignore range (private networks by default)
|
||||
)
|
||||
|
||||
const (
|
||||
ownCap = 64 // distinct origins, domains and paths kept per hour and class-agnostic
|
||||
ownPath = 120
|
||||
)
|
||||
|
||||
// ownHour is the own traffic of one hour. Class index: 0 trusted, 1 internal.
|
||||
type ownHour struct {
|
||||
N [2]uint32
|
||||
S [2][4]uint32 // 2xx 3xx 4xx 5xx
|
||||
Origins, Domains, Paths map[string]uint32
|
||||
}
|
||||
|
||||
func ownIdx(class string) int {
|
||||
if class == OwnInternal {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Own counts one web request of an own or trusted origin (class OwnTrusted or
|
||||
// OwnInternal). Only the Traefik source is recorded.
|
||||
func (s *Store) Own(ev core.Event, class string) {
|
||||
now := s.now()
|
||||
if ev.Time.Before(now.Add(-s.cfg.Retention)) || ev.IP == "" {
|
||||
return
|
||||
}
|
||||
ts := ev.Time.Unix()
|
||||
if max := now.Unix() + 300; ts > max {
|
||||
ts = max
|
||||
}
|
||||
ci := ownIdx(class)
|
||||
m, h := ts/60, ts/3600
|
||||
i := int(m % slots)
|
||||
path := ev.Path
|
||||
if j := strings.IndexAny(path, "?#"); j >= 0 {
|
||||
path = path[:j]
|
||||
}
|
||||
if len(path) > ownPath {
|
||||
path = path[:ownPath]
|
||||
}
|
||||
origin := class[:1] + "|" + KeyOf(ev.IP)
|
||||
s.mu.Lock()
|
||||
if s.ownSt[i] != m {
|
||||
s.ownSt[i], s.ownN[i] = m, [2]uint32{}
|
||||
}
|
||||
s.ownN[i][ci]++
|
||||
hs := &s.hours[int(h%hourSlots)]
|
||||
if hs.Hour != h {
|
||||
*hs = hourSlot{Hour: h}
|
||||
}
|
||||
if hs.Own == nil {
|
||||
hs.Own = &ownHour{}
|
||||
}
|
||||
o := hs.Own
|
||||
o.N[ci]++
|
||||
if k := ev.Status/100 - 2; k >= 0 && k < 4 {
|
||||
o.S[ci][k]++
|
||||
}
|
||||
bumpCap(&o.Origins, origin, ownCap)
|
||||
bumpCap(&o.Domains, normDomain(ev.Domain), ownCap)
|
||||
bumpCap(&o.Paths, path, ownCap)
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// OwnTraffic is the own and trusted traffic of a window. It is not part of
|
||||
// totals.requests: RequestsAll in the totals adds it.
|
||||
type OwnTraffic struct {
|
||||
Trusted uint64 `json:"trusted"`
|
||||
Internal uint64 `json:"internal"`
|
||||
Status [4]uint64 `json:"status"` // 2xx 3xx 4xx 5xx
|
||||
Start int64 `json:"start"`
|
||||
Step int64 `json:"step"`
|
||||
Series map[string][]uint32 `json:"series"` // "trusted" and "internal"
|
||||
Origins []Count `json:"origins"` // Key: address (an IPv6 /64 as a prefix), Label: class
|
||||
Domains []Count `json:"domains"`
|
||||
Paths []Count `json:"paths"`
|
||||
}
|
||||
|
||||
// ownLocked adds the own traffic of the grid to the totals and, when o is not
|
||||
// nil, to the breakdown. The caller holds s.mu.
|
||||
func (s *Store) ownLocked(g grid, to int64, tot *Totals) OwnTraffic {
|
||||
o := OwnTraffic{Start: g.Start, Step: g.Step, Series: map[string][]uint32{
|
||||
OwnTrusted: make([]uint32, g.N), OwnInternal: make([]uint32, g.N)}}
|
||||
if g.minute() {
|
||||
for m := g.Start / 60; m <= to/60; m++ {
|
||||
i := int(m % slots)
|
||||
if s.ownSt[i] != m {
|
||||
continue
|
||||
}
|
||||
if b := int((m*60 - g.Start) / g.Step); b >= 0 && b < g.N {
|
||||
o.Series[OwnTrusted][b] += s.ownN[i][0]
|
||||
o.Series[OwnInternal][b] += s.ownN[i][1]
|
||||
}
|
||||
}
|
||||
}
|
||||
origins, doms, paths := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}
|
||||
for h := g.Start / 3600; h <= to/3600; h++ {
|
||||
hs := &s.hours[int(h%hourSlots)]
|
||||
if hs.Hour != h || hs.Own == nil {
|
||||
continue
|
||||
}
|
||||
oh := hs.Own
|
||||
o.Trusted += uint64(oh.N[0])
|
||||
o.Internal += uint64(oh.N[1])
|
||||
for c := range oh.S {
|
||||
for k, v := range oh.S[c] {
|
||||
o.Status[k] += uint64(v)
|
||||
}
|
||||
}
|
||||
if !g.minute() {
|
||||
if b := int(h - g.Start/3600); b >= 0 && b < g.N {
|
||||
o.Series[OwnTrusted][b] += oh.N[0]
|
||||
o.Series[OwnInternal][b] += oh.N[1]
|
||||
}
|
||||
}
|
||||
for _, p := range [...]struct{ from, to map[string]uint32 }{{oh.Origins, origins}, {oh.Domains, doms}, {oh.Paths, paths}} {
|
||||
for k, v := range p.from {
|
||||
p.to[k] += v
|
||||
}
|
||||
}
|
||||
}
|
||||
tot.Trusted, tot.Internal = o.Trusted, o.Internal
|
||||
tot.RequestsAll = tot.Requests + o.Trusted + o.Internal
|
||||
if o.Trusted > 0 {
|
||||
tot.Counts[OwnTrusted] = o.Trusted
|
||||
}
|
||||
if o.Internal > 0 {
|
||||
tot.Counts[OwnInternal] = o.Internal
|
||||
}
|
||||
o.Origins = ownOrigins(topN(origins, 40))
|
||||
o.Domains, o.Paths = topN(doms, 20), topN(paths, 20)
|
||||
return o
|
||||
}
|
||||
|
||||
// ownOrigins splits the stored "<class>|<address>" keys into key and label.
|
||||
func ownOrigins(in []Count) []Count {
|
||||
for i, c := range in {
|
||||
if len(c.Key) > 2 && c.Key[1] == '|' {
|
||||
if c.Key[0] == 't' {
|
||||
in[i].Label = OwnTrusted
|
||||
} else {
|
||||
in[i].Label = OwnInternal
|
||||
}
|
||||
in[i].Key = c.Key[2:]
|
||||
}
|
||||
}
|
||||
return in
|
||||
}
|
||||
|
||||
// mergeOwn adds the own traffic of several hosts. Series are aligned by
|
||||
// timestamp like the attack timeline.
|
||||
func mergeOwn(parts []Summary, grid Timeline) OwnTraffic {
|
||||
n := 0
|
||||
for _, c := range grid.Cats {
|
||||
n = len(grid.Series[c])
|
||||
break
|
||||
}
|
||||
out := OwnTraffic{Start: grid.Start, Step: grid.Step, Series: map[string][]uint32{
|
||||
OwnTrusted: make([]uint32, n), OwnInternal: make([]uint32, n)}}
|
||||
var origins, doms, paths [][]Count
|
||||
for _, p := range parts {
|
||||
o := p.Own
|
||||
out.Trusted += o.Trusted
|
||||
out.Internal += o.Internal
|
||||
for k, v := range o.Status {
|
||||
out.Status[k] += v
|
||||
}
|
||||
if o.Step == out.Step && o.Step > 0 {
|
||||
shift := (o.Start - out.Start) / out.Step
|
||||
for _, c := range []string{OwnTrusted, OwnInternal} {
|
||||
for i, v := range o.Series[c] {
|
||||
if j := int64(i) + shift; j >= 0 && j < int64(n) {
|
||||
out.Series[c][j] += v
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
origins = append(origins, o.Origins)
|
||||
doms = append(doms, o.Domains)
|
||||
paths = append(paths, o.Paths)
|
||||
}
|
||||
out.Origins = mergeOwnOrigins(40, origins)
|
||||
out.Domains, out.Paths = mergeCounts(20, doms...), mergeCounts(20, paths...)
|
||||
return out
|
||||
}
|
||||
|
||||
func mergeOwnOrigins(n int, lists [][]Count) []Count {
|
||||
m, lab := map[string]uint32{}, map[string]string{}
|
||||
for _, l := range lists {
|
||||
for _, c := range l {
|
||||
k := c.Label + "|" + c.Key
|
||||
m[k] += c.N
|
||||
lab[k] = c.Label
|
||||
}
|
||||
}
|
||||
out := topN(m, n)
|
||||
for i := range out {
|
||||
out[i].Label = lab[out[i].Key]
|
||||
out[i].Key = out[i].Key[len(out[i].Label)+1:]
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -28,6 +28,8 @@ type snapshot struct {
|
||||
Hours [hourSlots]hourSlot
|
||||
MonSt [slots]int64
|
||||
MonN [slots]uint32
|
||||
OwnSt [slots]int64 // own traffic minute buckets (optional: older snapshots lack it)
|
||||
OwnN [slots][2]uint32
|
||||
Dom map[string]*domData
|
||||
GDays [anDays]gDay
|
||||
Svc map[string]*svcData // service health (optional: older snapshots lack it)
|
||||
@@ -73,7 +75,7 @@ func (s *Store) Save(path string, offsets map[string]Offset) error {
|
||||
}
|
||||
bw := bufio.NewWriterSize(f, 256*1024)
|
||||
s.mu.RLock()
|
||||
snap := snapshot{V: snapshotVersion, Saved: s.now().Unix(), Stamps: s.stamps, Counts: s.counts, Hours: s.hours, MonSt: s.monSt, MonN: s.monN, Dom: s.tr.dom, GDays: s.tr.gdays, Svc: s.sv.m,
|
||||
snap := snapshot{V: snapshotVersion, Saved: s.now().Unix(), Stamps: s.stamps, Counts: s.counts, Hours: s.hours, MonSt: s.monSt, MonN: s.monN, OwnSt: s.ownSt, OwnN: s.ownN, Dom: s.tr.dom, GDays: s.tr.gdays, Svc: s.sv.m,
|
||||
IPs: s.ips, Recent: s.recent, Rhead: s.rhead, Offsets: offsets, IDSeq: s.ids.Load()}
|
||||
err = gob.NewEncoder(bw).Encode(&snap)
|
||||
s.mu.RUnlock()
|
||||
@@ -124,6 +126,7 @@ func (s *Store) Load(path string) (map[string]Offset, error) {
|
||||
s.mu.Lock()
|
||||
s.stamps, s.counts, s.hours = snap.Stamps, snap.Counts, snap.Hours
|
||||
s.monSt, s.monN = snap.MonSt, snap.MonN
|
||||
s.ownSt, s.ownN = snap.OwnSt, snap.OwnN
|
||||
s.tr.dom, s.tr.gdays = snap.Dom, snap.GDays
|
||||
s.sv.m = snap.Svc
|
||||
for _, d := range s.tr.dom {
|
||||
|
||||
@@ -135,6 +135,7 @@ type hourSlot struct {
|
||||
Paths, Domains, UAs, Users, Countries map[string]uint32
|
||||
C [core.NumCats]uint32 // events per category in the hour
|
||||
Mon uint32 // monitoring requests in the hour
|
||||
Own *ownHour // own and trusted traffic (see own.go), nil when none
|
||||
}
|
||||
|
||||
// FeedEvent is one entry of the live feed.
|
||||
@@ -261,6 +262,8 @@ type Store struct {
|
||||
hours [hourSlots]hourSlot
|
||||
monSt [slots]int64
|
||||
monN [slots]uint32
|
||||
ownSt [slots]int64
|
||||
ownN [slots][2]uint32
|
||||
tr trafficState
|
||||
sv svcState
|
||||
allow []string
|
||||
|
||||
@@ -32,6 +32,10 @@ type Totals struct {
|
||||
ActiveBans int `json:"active_bans"`
|
||||
Monitoring uint64 `json:"monitoring"`
|
||||
Counts map[string]uint64 `json:"counts"`
|
||||
// Own and trusted traffic (see own.go) is NOT in Requests; RequestsAll adds it.
|
||||
Trusted uint64 `json:"trusted"`
|
||||
Internal uint64 `json:"internal"`
|
||||
RequestsAll uint64 `json:"requests_all"`
|
||||
}
|
||||
|
||||
// IPSummary describes one IP. Samples, UAs and Domains are only filled in the
|
||||
@@ -98,6 +102,7 @@ type Summary struct {
|
||||
Generated int64 `json:"generated"`
|
||||
Hosts []HostInfo `json:"hosts"`
|
||||
Totals Totals `json:"totals"`
|
||||
Own OwnTraffic `json:"own"` // own and trusted origins, apart from every attack number
|
||||
Timeline Timeline `json:"timeline"`
|
||||
Rates Rates `json:"rates"`
|
||||
IPs []IPSummary `json:"ips"`
|
||||
@@ -428,6 +433,7 @@ func (s *Store) buildSummary(rg Range) Summary {
|
||||
tot.Monitoring += uint64(hs.Mon)
|
||||
}
|
||||
}
|
||||
own := s.ownLocked(g, to, &tot)
|
||||
paths, doms, uas, users, ctry := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}
|
||||
firstHour, lastHour := start/3600, to/3600
|
||||
for i := range s.hours {
|
||||
@@ -522,7 +528,7 @@ func (s *Store) buildSummary(rg Range) Summary {
|
||||
Hosts: []HostInfo{{Name: s.cfg.Name, Self: true, Online: true, Version: s.cfg.Version, LastSeen: nowU,
|
||||
Requests: tot.Requests, Malicious: tot.Malicious, HostileIPs: tot.HostileIPs, ActiveBans: tot.ActiveBans,
|
||||
Live: true, Location: s.Location()}},
|
||||
Totals: tot, Timeline: tl, Rates: rates, IPs: ips,
|
||||
Totals: tot, Own: own, Timeline: tl, Rates: rates, IPs: ips,
|
||||
TopPaths: topN(paths, topKeep), TopDomains: topN(doms, topKeep), TopUAs: topUAs, TopUsers: topN(users, topKeep), Countries: topN(ctry, 120),
|
||||
Recent: recent, Sources: srcs, Attribution: s.attrib,
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user