CyberStrikeAI/internal/database/vulnerability_fingerprint.go

270 lines
7.9 KiB
Go

package database
import (
"crypto/sha256"
"database/sql"
"encoding/hex"
"net"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
)
var (
fingerprintNonAlnum = regexp.MustCompile(`[^\p{L}\p{N}]+`)
fingerprintCWE = regexp.MustCompile(`(?i)\bcwe-?\s*(\d+)\b`)
fingerprintUUID = regexp.MustCompile(`(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`)
fingerprintParam = regexp.MustCompile(`(?i)\b(?:param(?:eter)?|field)\s*(?:=|:|\s+)\s*["']?([a-zA-Z_][a-zA-Z0-9_.-]{0,63})`)
)
// DedupScope is the only set of findings a fingerprint may collapse.
// A project match never falls through to another project. Without a project,
// an assessment matches only that assessment and a chat matches only that conversation.
type DedupScope struct {
ProjectID string
AssessmentID string
ConversationID string
}
// VulnerabilityFingerprint is empty when any axis is ambiguous. Callers then
// create a normal record instead of risking a false merge.
// Axes: normalized class (CWE when present), asset IDs or host:port, and a
// path whose numeric IDs, UUIDs and query values have been removed plus the
// sorted parameter names.
func VulnerabilityFingerprint(vulnType, target, corpus string, assetIDs []string) string {
class := fingerprintClass(vulnType, corpus)
asset := fingerprintAsset(assetIDs, target, corpus)
endpoint := fingerprintEndpoint(target, corpus)
if class == "" || asset == "" || endpoint == "" {
return ""
}
sum := sha256.Sum256([]byte(class + "\x00" + asset + "\x00" + endpoint))
return "fp:" + hex.EncodeToString(sum[:16])
}
func fingerprintClass(vulnType, corpus string) string {
if match := fingerprintCWE.FindStringSubmatch(vulnType + "\n" + corpus); len(match) == 2 {
id := strings.TrimLeft(match[1], "0")
if id == "" {
id = "0"
}
return "cwe-" + id
}
token := strings.ToLower(strings.TrimSpace(vulnType))
token = fingerprintNonAlnum.ReplaceAllString(token, "_")
return strings.Trim(token, "_")
}
func fingerprintAsset(assetIDs []string, target, corpus string) string {
ids := make([]string, 0, len(assetIDs))
seen := map[string]bool{}
for _, id := range assetIDs {
id = strings.TrimSpace(id)
if id == "" || seen[id] {
continue
}
seen[id] = true
ids = append(ids, id)
}
if len(ids) > 0 {
sort.Strings(ids)
return "ids:" + strings.Join(ids, ",")
}
for _, raw := range []string{target, corpus} {
if host, port, ok := fingerprintHostPort(raw); ok {
if port > 0 {
return "host:" + host + ":" + strconv.Itoa(port)
}
return "host:" + host
}
}
return ""
}
func fingerprintHostPort(raw string) (string, int, bool) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", 0, false
}
if strings.Contains(raw, "://") {
for _, candidate := range fingerprintURLPattern.FindAllString(raw, 4) {
parsed, err := url.Parse(strings.TrimRight(candidate, ".,;:!)"))
if err != nil || parsed.Hostname() == "" {
continue
}
host := strings.ToLower(strings.TrimSuffix(parsed.Hostname(), "."))
if ip := net.ParseIP(host); ip != nil {
host = ip.String()
}
port := 0
if parsed.Port() != "" {
port, _ = strconv.Atoi(parsed.Port())
} else if parsed.Scheme == "https" {
port = 443
} else if parsed.Scheme == "http" {
port = 80
}
if port < 0 || port > 65535 {
port = 0
}
return host, port, true
}
}
host := raw
if cut := strings.IndexAny(host, "/?# \t"); cut >= 0 {
host = host[:cut]
}
if h, p, err := net.SplitHostPort(host); err == nil {
port, _ := strconv.Atoi(p)
if ip := net.ParseIP(h); ip != nil {
return ip.String(), port, true
}
return strings.ToLower(h), port, h != ""
}
if ip := net.ParseIP(host); ip != nil {
return ip.String(), 0, true
}
return "", 0, false
}
var fingerprintURLPattern = regexp.MustCompile(`(?i)\bhttps?://[^\s"'<>\]]+`)
func fingerprintEndpoint(target, corpus string) string {
path, params := "", []string{}
for _, raw := range []string{target, corpus} {
if path != "" {
break
}
for _, candidate := range fingerprintURLPattern.FindAllString(raw, 4) {
parsed, err := url.Parse(strings.TrimRight(candidate, ".,;:!)"))
if err != nil || parsed.Path == "" {
continue
}
path = normalizeFingerprintPath(parsed.Path)
params = append(params, queryNames(parsed.RawQuery)...)
if path != "" {
break
}
}
}
for _, match := range fingerprintParam.FindAllStringSubmatch(corpus, 4) {
if len(match) == 2 {
params = append(params, strings.ToLower(match[1]))
}
}
params = dedupeSorted(params)
if path == "" && len(params) == 0 {
return ""
}
if len(params) == 0 {
return "path:" + path
}
return "path:" + path + "|params:" + strings.Join(params, ",")
}
func normalizeFingerprintPath(path string) string {
path = strings.ToLower(strings.TrimSpace(path))
if path == "" || path == "/" {
return ""
}
path = fingerprintUUID.ReplaceAllString(path, "{id}")
parts := strings.Split(path, "/")
for i, part := range parts {
if part == "" || part == "{id}" {
continue
}
digits := true
for _, r := range part {
if r < '0' || r > '9' {
digits = false
break
}
}
if digits {
parts[i] = "{id}"
}
}
path = strings.Join(parts, "/")
for strings.Contains(path, "//") {
path = strings.ReplaceAll(path, "//", "/")
}
return strings.TrimRight(path, "/")
}
func queryNames(raw string) []string {
if strings.TrimSpace(raw) == "" {
return nil
}
var names []string
for _, pair := range strings.Split(raw, "&") {
name, _, _ := strings.Cut(pair, "=")
name = strings.ToLower(strings.TrimSpace(name))
if name != "" {
names = append(names, name)
}
}
return names
}
func dedupeSorted(in []string) []string {
if len(in) == 0 {
return nil
}
seen := map[string]bool{}
out := make([]string, 0, len(in))
for _, item := range in {
if item == "" || seen[item] {
continue
}
seen[item] = true
out = append(out, item)
}
sort.Strings(out)
return out
}
// DuplicateVulnerability is a non-dismissed finding with the same fingerprint
// inside one dedup scope. Readable is false when the caller may not see it.
type DuplicateVulnerability struct {
ID string
Readable bool
}
// FindVulnerabilityDuplicate looks up one active fingerprint hit in the scope.
// false_positive and ignored records do not block a new report.
func (db *DB) FindVulnerabilityDuplicate(scope DedupScope, fingerprint, userID, accessScope string) (*DuplicateVulnerability, error) {
fingerprint = strings.TrimSpace(fingerprint)
if db == nil || fingerprint == "" {
return nil, nil
}
var query string
var args []any
switch {
case strings.TrimSpace(scope.ProjectID) != "":
query = `SELECT id FROM vulnerabilities WHERE fingerprint=? AND project_id=? AND status NOT IN ('false_positive','ignored') AND manually_archived=0 ORDER BY created_at,id LIMIT 1`
args = []any{fingerprint, strings.TrimSpace(scope.ProjectID)}
case strings.TrimSpace(scope.AssessmentID) != "":
query = `SELECT v.id FROM vulnerabilities v JOIN vulnerability_assessment_sources s ON s.vulnerability_id=v.id
WHERE v.fingerprint=? AND s.assessment_id=? AND COALESCE(v.project_id,'')='' AND v.status NOT IN ('false_positive','ignored') AND v.manually_archived=0
ORDER BY v.created_at,v.id LIMIT 1`
args = []any{fingerprint, strings.TrimSpace(scope.AssessmentID)}
case strings.TrimSpace(scope.ConversationID) != "":
query = `SELECT id FROM vulnerabilities WHERE fingerprint=? AND conversation_id=? AND COALESCE(project_id,'')='' AND status NOT IN ('false_positive','ignored') AND manually_archived=0 ORDER BY created_at,id LIMIT 1`
args = []any{fingerprint, strings.TrimSpace(scope.ConversationID)}
default:
return nil, nil
}
var id string
err := db.QueryRow(query, args...).Scan(&id)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
readable := strings.TrimSpace(userID) == "" || accessScope == RBACScopeAll || db.UserCanAccessResource(userID, accessScope, "vulnerability", id)
return &DuplicateVulnerability{ID: id, Readable: readable}, nil
}