Files
urutau/internal/intel/session.go
T
Lucas RayanandClaude Opus 5.5 b7462c14fa
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 27s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux, race detector) (push) Successful in 58s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 5s
feat: 1.2.0 attack intelligence, replay, 30-day history and new interface
Intelligence: attack families mapped to MITRE ATT&CK, network type from
ASN/rDNS without external APIs, request cadence, sessions with
recon/probe/exploit/access/banned stages, campaigns across IPs, verdict
with reasons, recommended actions, exposure detection (2xx with a body
on sensitive paths), STIX 2.1 export, FCrDNS for search engine bots,
optional Tor exit list.

Data: 30-day retention, twelve ranges plus custom from/to, an on-disk
event log (daily files, hourly gzip members, size cap, corruption and
disk-full tolerant), /events, /period, /metrics with stable per-hour
metrics, an extended /ip/{ip}, and peer /period merged on the hub.

Interface: layout system with fixed card sizes, range picker in the
URL, IP analysis page, Replay page, Geography down to state and city
(Natural Earth admin-1), Live page redesigned with stable metrics and a
reusable attack map. Demo data and documentation screenshots.

Security: bounded and deadline-limited period computations, linear
campaign clustering, singleflight caches, sanitized peer studies, event
query budgets, gzip bomb guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 21:45:59 -03:00

287 lines
7.0 KiB
Go

package intel
import (
"crypto/sha256"
"encoding/hex"
"sort"
"strconv"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
// Ev is one event (HTTP or SSH) fed to Sessions.
type Ev struct {
T time.Time
IP string
Host string
Domain string
Cat string
Fam string
Path string
User string
Jail string
Status int
Strong bool
Unban bool
}
// Session is a burst of activity of one IP separated from the next by a gap.
type Session struct {
ID string `json:"id"`
IP string `json:"ip"`
Start time.Time `json:"start"`
End time.Time `json:"end"`
DurS int64 `json:"dur_s"`
N int `json:"n"`
Cats map[string]int `json:"cats"`
Fams map[string]int `json:"fams"`
Techs []string `json:"techs"`
Hosts []string `json:"hosts"`
Domains []string `json:"domains"`
UsersN int `json:"users_n"`
PeakRPM int `json:"peak_rpm"`
Stage string `json:"stage"`
Success bool `json:"success"`
BannedAt *time.Time `json:"banned_at,omitempty"`
CampaignID string `json:"campaign_id,omitempty"`
}
// Step is one link of an escalation chain.
type Step struct {
Stage string `json:"stage"`
T time.Time `json:"t"`
Evidence string `json:"evidence"`
}
// Stages, in increasing severity.
const (
StageRecon = "recon"
StageProbe = "probe"
StageExploit = "exploit"
StageAccess = "access"
StageBanned = "banned"
)
// DefaultGap is the session gap used when Sessions gets a non-positive one.
const DefaultGap = 30 * time.Minute
const (
maxSessionEvents = 1_000_000
maxListed = 50
)
// StageRank orders stages (0 for none/unknown).
func StageRank(s string) int {
switch s {
case StageRecon:
return 1
case StageProbe:
return 2
case StageExploit:
return 3
case StageAccess:
return 4
case StageBanned:
return 5
}
return 0
}
var accessFams = map[string]bool{
FamEnvCreds: true, FamVCS: true, FamBackup: true, FamActuator: true,
FamPhpMyAdmin: true, FamAdminPanel: true,
}
func is2xx(s int) bool { return s >= 200 && s < 300 }
// stageOf gives the stage one event reaches. priorFail says the same IP had
// ssh-fail events before it.
func stageOf(e Ev, priorFail bool) (string, string) {
if e.Unban {
return "", ""
}
if is2xx(e.Status) && accessFams[e.Fam] && core.Category(e.Cat).IsHTTP() {
return StageAccess, e.Fam + " " + strconv.Itoa(e.Status) + " " + e.Path
}
switch core.Category(e.Cat) {
case core.NotFound:
return StageRecon, "notfound " + e.Path
case core.SSHProbe:
return StageRecon, "ssh-probe"
case core.Scanner:
return StageProbe, "scanner " + e.Path
case core.BruteForce:
return StageProbe, "bruteforce " + e.Path
case core.SSHFail:
return StageProbe, "ssh-fail " + e.User
case core.Exploit:
return StageExploit, "exploit " + e.Path
case core.SSHOK:
if priorFail {
return StageAccess, "ssh-ok after failures " + e.User
}
case core.Ban:
return StageBanned, "ban " + e.Jail
}
return "", ""
}
func shortHash(s string) string {
h := sha256.Sum256([]byte(s))
return hex.EncodeToString(h[:4])
}
func sortedKeys(m map[string]bool, limit int) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
if limit > 0 && len(out) > limit {
out = out[:limit]
}
return out
}
// Sessions groups events by IP and splits each IP's timeline wherever two
// consecutive events are more than gap apart (default 30 min). Output is
// ordered by start time, then IP. At most 1,000,000 events are considered.
func Sessions(events []Ev, gap time.Duration) []Session {
if gap <= 0 {
gap = DefaultGap
}
if len(events) > maxSessionEvents {
events = events[:maxSessionEvents]
}
byIP := map[string][]Ev{}
for _, e := range events {
byIP[e.IP] = append(byIP[e.IP], e)
}
var out []Session
for ip, evs := range byIP {
sort.SliceStable(evs, func(i, j int) bool { return evs[i].T.Before(evs[j].T) })
priorFail := false
start := 0
for i := 1; i <= len(evs); i++ {
if i < len(evs) && evs[i].T.Sub(evs[i-1].T) <= gap {
continue
}
s, pf := buildSession(ip, evs[start:i], priorFail)
priorFail = pf
out = append(out, s)
start = i
}
}
sort.Slice(out, func(i, j int) bool {
if !out[i].Start.Equal(out[j].Start) {
return out[i].Start.Before(out[j].Start)
}
return out[i].IP < out[j].IP
})
return out
}
func buildSession(ip string, evs []Ev, priorFail bool) (Session, bool) {
s := Session{
IP: ip, Start: evs[0].T, End: evs[len(evs)-1].T, N: len(evs),
Cats: map[string]int{}, Fams: map[string]int{},
}
s.ID = "s-" + shortHash(ip+"|"+strconv.FormatInt(s.Start.UnixNano(), 10))
s.DurS = int64(s.End.Sub(s.Start).Seconds())
hosts, doms, techs := map[string]bool{}, map[string]bool{}, map[string]bool{}
users := map[string]int{}
best := 0
failsBefore := priorFail
times := make([]time.Time, 0, len(evs))
for _, e := range evs {
s.Cats[e.Cat]++
if e.Fam != "" {
s.Fams[e.Fam]++
}
if e.Host != "" {
hosts[e.Host] = true
}
if e.Domain != "" {
doms[e.Domain] = true
}
if e.User != "" && (e.Cat == string(core.SSHFail) || e.Cat == string(core.SSHOK)) {
users[e.User]++
}
if st, _ := stageOf(e, failsBefore); StageRank(st) > best {
best = StageRank(st)
s.Stage = st
}
if st, _ := stageOf(e, failsBefore); st == StageAccess {
s.Success = true
}
if e.Cat == string(core.Ban) && !e.Unban && s.BannedAt == nil {
t := e.T
s.BannedAt = &t
}
if e.Cat == string(core.SSHFail) {
failsBefore = true
}
times = append(times, e.T)
}
maxPer := 0
for _, c := range users {
if c > maxPer {
maxPer = c
}
}
s.UsersN = len(users)
fails := priorFail
for _, e := range evs {
ctx := TechCtx{Path: e.Path, Users: len(users), MaxPerUser: maxPer, PriorFails: fails}
for _, t := range Techniques(e.Cat, e.Fam, ctx) {
techs[t] = true
}
if e.Cat == string(core.SSHFail) {
fails = true
}
}
s.Techs = sortedKeys(techs, 0)
s.Hosts = sortedKeys(hosts, maxListed)
s.Domains = sortedKeys(doms, maxListed)
s.PeakRPM = CadenceFrom(times).BurstMax60
return s, failsBefore
}
// Escalation lists, in time order, each event of s that raised the session to
// a stage not yet reached, with the evidence behind it.
func Escalation(s Session, events []Ev) []Step {
var evs []Ev
fails := false
for _, e := range events {
if e.IP != s.IP {
continue
}
if e.T.Before(s.Start) {
fails = fails || e.Cat == string(core.SSHFail)
} else if !e.T.After(s.End) {
evs = append(evs, e)
}
}
sort.SliceStable(evs, func(i, j int) bool { return evs[i].T.Before(evs[j].T) })
var steps []Step
best := 0
for _, e := range evs {
if st, ev := stageOf(e, fails); StageRank(st) > best {
best = StageRank(st)
steps = append(steps, Step{Stage: st, T: e.T, Evidence: clipStr(ev, 200)})
}
if e.Cat == string(core.SSHFail) {
fails = true
}
}
return steps
}
func clipStr(s string, n int) string {
if len(s) > n {
return s[:n]
}
return s
}