package intel import ( "context" "crypto/sha256" "encoding/hex" "regexp" "sort" "strconv" "strings" "sync" "sync/atomic" "time" ) // Signature fingerprints what a session asked for. Paths holds the five most // frequent normalised paths (sorted); Tool is the tool label or User-Agent. // ASN, CC and NetType are optional metadata of the session's IP, used only to // summarise campaigns. type Signature struct { Paths []string `json:"paths"` Tool string `json:"tool"` ASN uint32 `json:"asn,omitempty"` CC string `json:"cc,omitempty"` NetType string `json:"net_type,omitempty"` } // Campaign is a set of sessions from several IPs doing the same thing. type Campaign struct { ID string `json:"id"` SignatureID string `json:"signature_id"` First time.Time `json:"first"` Last time.Time `json:"last"` IPsN int `json:"ips_n"` IPs []string `json:"ips"` ASNs []uint32 `json:"asns"` CCs []string `json:"ccs"` NetTypes map[string]int `json:"net_types"` Signature Signature `json:"signature"` Techs []string `json:"techs"` SessionsN int `json:"sessions_n"` } // Campaign thresholds. const ( MinCampaignIPs = 3 MinJaccard = 0.6 DefaultCampaign = 6 * time.Hour maxCampaignIPs = 50 maxNormLen = 512 maxSigSessions = 50000 ) var ( uuidRe = regexp.MustCompile(`[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`) hexRe = regexp.MustCompile(`[0-9a-f]{8,}`) digRe = regexp.MustCompile(`[0-9]+`) ) // NormPath normalises a path for signatures: query dropped, lowercase, uuids // and long hex runs become {id}, digit runs become {n}. func NormPath(p string) string { if v, ok := normMemo.Load(p); ok { return v.(string) } n := normPath(p) if normMemoN.Add(1) > normMemoMax { // bounded: paths come from attackers normMemo.Clear() normMemoN.Store(1) } normMemo.Store(p, n) return n } // Paths repeat heavily in a study and the three regular expressions are the // costliest step of a signature, so results are memoised. const normMemoMax = 50000 var ( normMemo sync.Map normMemoN atomic.Int64 ) func normPath(p string) string { if i := strings.IndexAny(p, "?#"); i >= 0 { p = p[:i] } if len(p) > maxNormLen { p = p[:maxNormLen] } p = strings.ToLower(p) p = uuidRe.ReplaceAllString(p, "{id}") p = hexRe.ReplaceAllString(p, "{id}") return digRe.ReplaceAllString(p, "{n}") } // SignatureFrom builds the signature of a set of raw paths and a tool label. func SignatureFrom(paths []string, tool string) Signature { cnt := map[string]int{} for _, p := range paths { if p == "" { continue } cnt[NormPath(p)]++ } type kv struct { k string n int } list := make([]kv, 0, len(cnt)) for k, n := range cnt { list = append(list, kv{k, n}) } sort.Slice(list, func(i, j int) bool { if list[i].n != list[j].n { return list[i].n > list[j].n } return list[i].k < list[j].k }) if len(list) > 5 { list = list[:5] } sig := Signature{Tool: strings.ToLower(strings.TrimSpace(tool)), Paths: make([]string, 0, len(list))} for _, e := range list { sig.Paths = append(sig.Paths, e.k) } sort.Strings(sig.Paths) return sig } // Key is the canonical text of the signature (paths and tool only). func (s Signature) Key() string { return strings.Join(s.Paths, "\n") + "\x00" + s.Tool } // SignatureID is "c-" plus 8 hex chars of the sha256 of the signature key. It // is shared by every recurrence of the same signature. func (s Signature) SignatureID() string { h := sha256.Sum256([]byte(s.Key())) return "c-" + hex.EncodeToString(h[:4]) } // ID is an alias of SignatureID kept for callers that group recurring // campaigns; Campaign.ID itself is unique per campaign. func (s Signature) ID() string { return s.SignatureID() } func campaignID(sig Signature, first time.Time, window time.Duration, n int) string { k := sig.Key() + "\x00" + strconv.FormatInt(first.Truncate(window).Unix(), 10) if n > 0 { k += "\x00" + strconv.Itoa(n) } h := sha256.Sum256([]byte(k)) return "c-" + hex.EncodeToString(h[:4]) } // Jaccard is |a∩b| / |a∪b| over two string sets (0 when both are empty). // Lists of up to 8 items (every signature) are compared without allocating. func Jaccard(a, b []string) float64 { if len(a) == 0 && len(b) == 0 { return 0 } if len(a) > 8 || len(b) > 8 { return jaccardMap(a, b) } ua, ub, inter := 0, 0, 0 for i, x := range a { if indexOf(a[:i], x) < 0 { ua++ if indexOf(b, x) >= 0 { inter++ } } } for i, y := range b { if indexOf(b[:i], y) < 0 { ub++ } } return float64(inter) / float64(ua+ub-inter) } func indexOf(l []string, x string) int { for i, y := range l { if y == x { return i } } return -1 } func jaccardMap(a, b []string) float64 { set := make(map[string]bool, len(a)) for _, x := range a { set[x] = true } union := len(set) inter := 0 seen := map[string]bool{} for _, x := range b { if seen[x] { continue } seen[x] = true if set[x] { inter++ } else { union++ } } return float64(inter) / float64(union) } type cluster struct { sig Signature idx []int first time.Time last time.Time stamp int } func pruneBucket(b []*cluster, now time.Time, window time.Duration) []*cluster { w := 0 for _, c := range b { if now.Sub(c.last) <= window { b[w] = c w++ } } clear(b[w:]) return b[:w] } // maxCandidates bounds how many clusters one session is compared against. const maxCandidates = 512 // Campaigns groups sessions of different IPs that share a tool and similar // paths (Jaccard >= 0.6) and start within window of one another (default 6 h). // sigs is keyed by Session.ID. Only groups with at least 3 distinct IPs are // returned, ordered by first time. The CampaignID of the member sessions in // the sessions slice is set in place. func Campaigns(sessions []Session, sigs map[string]Signature, window time.Duration) []Campaign { return CampaignsCtx(context.Background(), sessions, sigs, window) } // CampaignsCtx is Campaigns with a cancellable context: when ctx is done the // clustering stops and the campaigns found so far are returned. // // Clusters are indexed by tool and path (a match needs at least 60% of the // session's paths, so only the rarest few path buckets are scanned) and // expire once older than the window, so the cost stays near linear. func CampaignsCtx(ctx context.Context, sessions []Session, sigs map[string]Signature, window time.Duration) []Campaign { if window <= 0 { window = DefaultCampaign } order := make([]int, 0, len(sessions)) for i, s := range sessions { if sg, ok := sigs[s.ID]; ok && len(sg.Paths) > 0 { order = append(order, i) } } if len(order) > maxSigSessions { order = order[:maxSigSessions] } sort.SliceStable(order, func(a, b int) bool { sa, sb := sessions[order[a]], sessions[order[b]] if !sa.Start.Equal(sb.Start) { return sa.Start.Before(sb.Start) } return sa.ID < sb.ID }) var cl []*cluster buckets := map[string][]*cluster{} stamp := 0 for n, i := range order { if n&255 == 0 && ctx.Err() != nil { break } s, sg := sessions[i], sigs[sessions[i].ID] stamp++ keys := make([]string, 0, len(sg.Paths)) for j, p := range sg.Paths { if indexOf(sg.Paths[:j], p) < 0 { keys = append(keys, sg.Tool+"\x00"+p) } } sort.Slice(keys, func(x, y int) bool { return len(buckets[keys[x]]) < len(buckets[keys[y]]) }) need := (3*len(keys) + 4) / 5 scan := len(keys) - need + 1 var best *cluster bestJ := 0.0 checked := 0 scanLoop: for _, k := range keys[:scan] { buckets[k] = pruneBucket(buckets[k], s.Start, window) for _, c := range buckets[k] { if c.stamp == stamp { continue } c.stamp = stamp if checked++; checked > maxCandidates { break scanLoop } if j := Jaccard(sg.Paths, c.sig.Paths); j >= MinJaccard && j > bestJ { best, bestJ = c, j } } } if best == nil { c := &cluster{sig: sg, idx: []int{i}, first: s.Start, last: s.End} cl = append(cl, c) for _, k := range keys { b := buckets[k] if n := len(b); n >= 64 && n&(n-1) == 0 { // amortised cleanup b = pruneBucket(b, s.Start, window) } buckets[k] = append(b, c) } continue } best.idx = append(best.idx, i) if s.End.After(best.last) { best.last = s.End } } var out []Campaign usedIDs := map[string]bool{} for _, c := range cl { ips := map[string]bool{} for _, i := range c.idx { ips[sessions[i].IP] = true } if len(ips) < MinCampaignIPs { continue } id := campaignID(c.sig, c.first, window, 0) for n := 1; usedIDs[id]; n++ { id = campaignID(c.sig, c.first, window, n) } usedIDs[id] = true camp := Campaign{ ID: id, SignatureID: c.sig.SignatureID(), First: c.first, Last: c.last, IPsN: len(ips), IPs: sortedKeys(ips, maxCampaignIPs), NetTypes: map[string]int{}, Signature: Signature{Paths: c.sig.Paths, Tool: c.sig.Tool}, SessionsN: len(c.idx), } asns, ccs, techs := map[uint32]bool{}, map[string]bool{}, map[string]bool{} seenIP := map[string]bool{} for _, i := range c.idx { s, sg := &sessions[i], sigs[sessions[i].ID] s.CampaignID = camp.ID for _, t := range s.Techs { techs[t] = true } if seenIP[s.IP] { continue } seenIP[s.IP] = true if sg.ASN != 0 { asns[sg.ASN] = true } if sg.CC != "" { ccs[sg.CC] = true } if sg.NetType != "" { camp.NetTypes[sg.NetType]++ } } for a := range asns { camp.ASNs = append(camp.ASNs, a) } sort.Slice(camp.ASNs, func(i, j int) bool { return camp.ASNs[i] < camp.ASNs[j] }) camp.CCs = sortedKeys(ccs, 0) camp.Techs = sortedKeys(techs, 0) out = append(out, camp) } sort.Slice(out, func(i, j int) bool { if !out[i].First.Equal(out[j].First) { return out[i].First.Before(out[j].First) } return out[i].ID < out[j].ID }) return out }