File size: 3,322 Bytes
209e79d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""Shared helpers for CyberData 2 builders."""
import ast, hashlib, math, os, re

HERE = os.path.dirname(os.path.abspath(__file__))
SALT = "cyberdata2-v1:"
SYSTEMS = [
    "You are a cybersecurity expert. Answer accurately and concisely. If you are not certain, say so instead of guessing.",
    "You are a senior security engineer. Give precise, practical answers grounded in established standards (CWE, CAPEC, MITRE ATT&CK, NVD).",
    "You are an expert in application security and threat detection. Be accurate; never invent identifiers or facts.",
]


def prio(s, salt=""):
    return int(hashlib.md5((SALT + salt + str(s)).encode()).hexdigest()[:12], 16)


def pick_system(rid):
    return SYSTEMS[prio(rid, "sys") % len(SYSTEMS)]


def xt(e):
    """Text of an XML element with single spaces (handles xhtml markup inside)."""
    return "" if e is None else " ".join(s.strip() for s in e.itertext() if s.strip())


def clean(t):
    t = re.sub(r"\(Citation: [^)]*\)", "", t or "")
    t = re.sub(r"\[([^\]]+)\]\((?:https?://)[^)]*\)", r"\1", t)          # markdown links -> text
    t = re.sub(r"<code>(.*?)</code>", r"`\1`", t)
    return re.sub(r"[ \t]+", " ", re.sub(r"\n{3,}", "\n\n", t)).strip()


def trunc(t, n):
    t = (t or "").strip()
    if len(t) <= n: return t
    cut = t[:n]
    k = max(cut.rfind(". "), cut.rfind("\n"))
    return (cut[: k + 1] if k > n * 0.5 else cut.rsplit(" ", 1)[0]).rstrip()


def first_line(t):
    return next((l.strip() for l in (t or "").splitlines() if l.strip()), "")[:200]


def parse_list(s):
    if isinstance(s, list): return s
    try: v = ast.literal_eval(s)
    except Exception: return []
    return [x for x in v if isinstance(x, str) and re.fullmatch(r"CWE-\d+", x)] if isinstance(v, list) else []


# ---- CVSS v3.1 base score (FIRST specification), used as a self-checking arithmetic task -----------------------------------------------------
W = {"AV": {"N": 0.85, "A": 0.62, "L": 0.55, "P": 0.2}, "AC": {"L": 0.77, "H": 0.44}, "UI": {"N": 0.85, "R": 0.62}, "CIA": {"H": 0.56, "L": 0.22, "N": 0.0}}
PR = {"U": {"N": 0.85, "L": 0.62, "H": 0.27}, "C": {"N": 0.85, "L": 0.68, "H": 0.5}}


def roundup(x):
    i = round(x * 100000)
    return i / 100000.0 if i % 10000 == 0 else (math.floor(i / 10000) + 1) / 10.0


def cvss31(vec):
    m = dict(p.split(":") for p in vec.split("/")[1:])
    s = m["S"]
    iss = 1 - (1 - W["CIA"][m["C"]]) * (1 - W["CIA"][m["I"]]) * (1 - W["CIA"][m["A"]])
    imp = 6.42 * iss if s == "U" else 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02) ** 15
    expl = 8.22 * W["AV"][m["AV"]] * W["AC"][m["AC"]] * PR[s][m["PR"]] * W["UI"][m["UI"]]
    if imp <= 0: score = 0.0
    elif s == "U": score = roundup(min(imp + expl, 10))
    else: score = roundup(min(1.08 * (imp + expl), 10))
    sev = "None" if score == 0 else "Low" if score < 4 else "Medium" if score < 7 else "High" if score < 9 else "Critical"
    return score, sev


assert cvss31("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H") == (9.8, "Critical")
assert cvss31("CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N") == (6.1, "Medium")
assert cvss31("CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H") == (7.8, "High")
assert cvss31("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H") == (10.0, "Critical")
assert cvss31("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:N") == (0.0, "None")