Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
284 lines
6.9 KiB
Go
284 lines
6.9 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
|
)
|
|
|
|
const (
|
|
geoCountries = 250
|
|
geoRegions = 64
|
|
geoCities = 200
|
|
geoIPs = 50
|
|
geoTTL = 5 * time.Second
|
|
geoCacheMax = 256
|
|
)
|
|
|
|
var ccRe = regexp.MustCompile(`^[A-Z]{2}$`)
|
|
|
|
type geoCache struct {
|
|
mu sync.Mutex
|
|
at map[string]time.Time
|
|
v map[string]any
|
|
}
|
|
|
|
type regionOut struct {
|
|
Name string `json:"name"`
|
|
Events uint64 `json:"events"`
|
|
IPs int `json:"ips"`
|
|
Cats map[string]int `json:"cats"`
|
|
}
|
|
|
|
type cityOut struct {
|
|
Name string `json:"name"`
|
|
Region string `json:"region"`
|
|
Lat *float64 `json:"lat,omitempty"`
|
|
Lon *float64 `json:"lon,omitempty"`
|
|
Events uint64 `json:"events"`
|
|
IPs int `json:"ips"`
|
|
}
|
|
|
|
type geoIPOut struct {
|
|
IP string `json:"ip"`
|
|
Score float64 `json:"score"`
|
|
Level string `json:"level"`
|
|
City string `json:"city"`
|
|
Reg string `json:"region"`
|
|
ASN uint32 `json:"asn"`
|
|
ASOrg string `json:"as_org"`
|
|
Last int64 `json:"last"`
|
|
}
|
|
|
|
type countryOut struct {
|
|
CC string `json:"cc"`
|
|
Events uint64 `json:"events"`
|
|
IPs int `json:"ips"`
|
|
Hostile int `json:"hostile"`
|
|
Suspicious int `json:"suspicious"`
|
|
Cats map[string]int `json:"cats"`
|
|
}
|
|
|
|
type agg struct {
|
|
events uint64
|
|
ips int
|
|
hostile, suspic int
|
|
cats map[string]int
|
|
}
|
|
|
|
func (a *agg) add(x store.IPSummary, ev uint64, cats map[string]int) {
|
|
if a.cats == nil {
|
|
a.cats = map[string]int{}
|
|
}
|
|
a.events += ev
|
|
a.ips++
|
|
switch x.Level {
|
|
case core.LevelHostile:
|
|
a.hostile++
|
|
case core.LevelSuspicious:
|
|
a.suspic++
|
|
}
|
|
for k, v := range cats {
|
|
a.cats[k] += v
|
|
}
|
|
}
|
|
|
|
// attackerEvents sums the malicious category counts of an IP row.
|
|
func attackerEvents(x store.IPSummary) (uint64, map[string]int) {
|
|
var n uint64
|
|
cats := map[string]int{}
|
|
for _, c := range core.Categories {
|
|
if !c.IsMalicious() {
|
|
continue
|
|
}
|
|
if v := x.Counts[string(c)]; v > 0 {
|
|
n += uint64(v)
|
|
cats[string(c)] = int(v)
|
|
}
|
|
}
|
|
return n, cats
|
|
}
|
|
|
|
// geoAPI serves GET /api/v1/geo (see the package documentation of the routes).
|
|
func (s *Server) geoAPI(w http.ResponseWriter, r *http.Request) {
|
|
q := r.URL.Query()
|
|
rng, ok := s.rangeOf(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
rg := rng.Key()
|
|
host := q.Get("host")
|
|
if host == "" {
|
|
host = "all"
|
|
}
|
|
if _, ok := s.parseHosts(host); !ok {
|
|
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
|
|
return
|
|
}
|
|
cc, region := q.Get("cc"), q.Get("region")
|
|
if cc != "" && !ccRe.MatchString(cc) {
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid cc"})
|
|
return
|
|
}
|
|
if region != "" && (cc == "" || len(region) > 80) {
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid region"})
|
|
return
|
|
}
|
|
key := strings.Join([]string{rg, host, cc, region}, "\x00")
|
|
s.geo.mu.Lock()
|
|
defer s.geo.mu.Unlock()
|
|
if v, ok := s.geo.v[key]; ok && time.Since(s.geo.at[key]) < geoTTL {
|
|
writeJSON(w, 200, v)
|
|
return
|
|
}
|
|
if s.geo.v == nil || len(s.geo.v) >= geoCacheMax {
|
|
s.geo.v, s.geo.at = map[string]any{}, map[string]time.Time{}
|
|
}
|
|
var out any
|
|
if cc == "" {
|
|
out = s.geoWorld(r.Context(), rng, host)
|
|
} else {
|
|
out = s.geoCountry(r.Context(), rng, host, cc, region)
|
|
}
|
|
s.geo.v[key], s.geo.at[key] = out, time.Now()
|
|
writeJSON(w, 200, out)
|
|
}
|
|
|
|
// geoOf resolves the geography of a row: the local databases first, the data
|
|
// the row already carries (a peer's) as the fallback for country and city.
|
|
func (s *Server) geoOf(x store.IPSummary) core.GeoInfo {
|
|
g := s.opt.Store.GeoOf(x.IP)
|
|
if g.CC == "" && ccRe.MatchString(x.CC) {
|
|
g.CC, g.Country, g.City = x.CC, x.Country, x.City
|
|
}
|
|
return g
|
|
}
|
|
|
|
func (s *Server) geoWorld(ctx context.Context, rg store.Range, host string) map[string]any {
|
|
by := map[string]*agg{}
|
|
for _, x := range s.allIPs(ctx, rg, host) {
|
|
ev, cats := attackerEvents(x)
|
|
if ev == 0 {
|
|
continue
|
|
}
|
|
g := s.geoOf(x)
|
|
if g.CC == "" {
|
|
continue
|
|
}
|
|
a := by[g.CC]
|
|
if a == nil {
|
|
a = &agg{}
|
|
by[g.CC] = a
|
|
}
|
|
a.add(x, ev, cats)
|
|
}
|
|
list := make([]countryOut, 0, len(by))
|
|
for cc, a := range by {
|
|
list = append(list, countryOut{cc, a.events, a.ips, a.hostile, a.suspic, a.cats})
|
|
}
|
|
sort.Slice(list, func(i, j int) bool {
|
|
if list[i].Events != list[j].Events {
|
|
return list[i].Events > list[j].Events
|
|
}
|
|
return list[i].CC < list[j].CC
|
|
})
|
|
if len(list) > geoCountries {
|
|
list = list[:geoCountries]
|
|
}
|
|
return map[string]any{"range": rg.Name, "window": rg.Info(s.opt.Now().Unix()), "host": host, "countries": list}
|
|
}
|
|
|
|
func (s *Server) geoCountry(ctx context.Context, rg store.Range, host, cc, region string) map[string]any {
|
|
total := &agg{}
|
|
regs := map[string]*agg{}
|
|
type ck struct{ name, region string }
|
|
cities := map[ck]*cityOut{}
|
|
var rows []geoIPOut
|
|
for _, x := range s.allIPs(ctx, rg, host) {
|
|
ev, cats := attackerEvents(x)
|
|
if ev == 0 {
|
|
continue
|
|
}
|
|
g := s.geoOf(x)
|
|
if g.CC != cc {
|
|
continue
|
|
}
|
|
ra := regs[g.Region]
|
|
if ra == nil {
|
|
ra = &agg{}
|
|
regs[g.Region] = ra
|
|
}
|
|
ra.add(x, ev, cats)
|
|
if region != "" && g.Region != region {
|
|
continue
|
|
}
|
|
total.add(x, ev, cats)
|
|
c := cities[ck{g.City, g.Region}]
|
|
if c == nil {
|
|
c = &cityOut{Name: g.City, Region: g.Region}
|
|
if (g.Lat != 0 || g.Lon != 0) && g.Lat >= -90 && g.Lat <= 90 && g.Lon >= -180 && g.Lon <= 180 {
|
|
lat, lon := g.Lat, g.Lon
|
|
c.Lat, c.Lon = &lat, &lon
|
|
}
|
|
cities[ck{g.City, g.Region}] = c
|
|
}
|
|
c.Events += ev
|
|
c.IPs++
|
|
s.opt.Store.Enrich(&x)
|
|
rows = append(rows, geoIPOut{IP: x.IP, Score: x.Score, Level: string(x.Level), City: g.City, Reg: g.Region,
|
|
ASN: g.ASN, ASOrg: g.ASOrg, Last: x.Last})
|
|
}
|
|
if total.cats == nil {
|
|
total.cats = map[string]int{}
|
|
}
|
|
rl := make([]regionOut, 0, len(regs))
|
|
for name, a := range regs {
|
|
rl = append(rl, regionOut{name, a.events, a.ips, a.cats})
|
|
}
|
|
sort.Slice(rl, func(i, j int) bool {
|
|
if rl[i].Events != rl[j].Events {
|
|
return rl[i].Events > rl[j].Events
|
|
}
|
|
return rl[i].Name < rl[j].Name
|
|
})
|
|
if len(rl) > geoRegions {
|
|
rl = rl[:geoRegions]
|
|
}
|
|
cl := make([]cityOut, 0, len(cities))
|
|
for _, c := range cities {
|
|
cl = append(cl, *c)
|
|
}
|
|
sort.Slice(cl, func(i, j int) bool {
|
|
if cl[i].Events != cl[j].Events {
|
|
return cl[i].Events > cl[j].Events
|
|
}
|
|
return cl[i].Name < cl[j].Name
|
|
})
|
|
if len(cl) > geoCities {
|
|
cl = cl[:geoCities]
|
|
}
|
|
sort.Slice(rows, func(i, j int) bool {
|
|
if rows[i].Score != rows[j].Score {
|
|
return rows[i].Score > rows[j].Score
|
|
}
|
|
return rows[i].IP < rows[j].IP
|
|
})
|
|
if len(rows) > geoIPs {
|
|
rows = rows[:geoIPs]
|
|
}
|
|
out := map[string]any{"range": rg.Name, "window": rg.Info(s.opt.Now().Unix()), "host": host, "cc": cc, "events": total.events, "ips": total.ips,
|
|
"hostile": total.hostile, "suspicious": total.suspic, "cats": total.cats,
|
|
"regions": rl, "cities": cl, "top_ips": rows}
|
|
if region != "" {
|
|
out["region"] = region
|
|
}
|
|
return out
|
|
}
|