SamJoshua commited on
Commit
51b23af
·
verified ·
1 Parent(s): dadadb4

Add CVE explainer Gradio app

Browse files
Files changed (4) hide show
  1. README.md +18 -6
  2. __pycache__/app.cpython-312.pyc +0 -0
  3. app.py +356 -0
  4. requirements.txt +1 -0
README.md CHANGED
@@ -1,13 +1,25 @@
1
  ---
2
- title: Cve Explainer
3
- emoji: 🌖
4
- colorFrom: gray
5
- colorTo: gray
6
  sdk: gradio
7
  sdk_version: 6.31.0
8
- python_version: '3.12'
9
  app_file: app.py
 
 
10
  pinned: false
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: CVE Explainer
3
+ emoji: 🛡️
4
+ colorFrom: red
5
+ colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 6.31.0
 
8
  app_file: app.py
9
+ short_description: Plain-English CVE summaries, risk & remediation
10
+ python_version: "3.12"
11
  pinned: false
12
  ---
13
 
14
+ # CVE Explainer / Summarizer
15
+
16
+ Paste a **CVE ID** (e.g. `CVE-2024-3094`) or a raw vulnerability description to get:
17
+
18
+ - Plain-English summary
19
+ - Risk level (from CVSS when available)
20
+ - Remediation steps
21
+ - MITRE ATT&CK technique hints
22
+
23
+ Public metadata is loaded from the [CIRCL CVE API](https://cve.circl.lu/) (and NVD when reachable). Enable **Expand with AI** and set a Space secret `HF_TOKEN` (inference scope) for richer narratives via Hugging Face Inference Providers.
24
+
25
+ ⚠️ For triage and awareness — always confirm impact against vendor advisories and your environment.
__pycache__/app.cpython-312.pyc ADDED
Binary file (21.7 kB). View file
 
app.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CVE Explainer / Summarizer.
2
+
3
+ Enter a CVE ID (e.g. CVE-2024-3094) or paste a raw vulnerability description.
4
+ Fetches public CVE metadata (CIRCL / NVD-style JSON) and produces a plain-English
5
+ summary, risk level, remediation steps and suggested MITRE ATT&CK techniques.
6
+ Uses Hugging Face Inference Providers when a hub token is available; otherwise a
7
+ structured fallback built from CVSS/CWE fields.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import re
15
+ from typing import Any
16
+
17
+ import gradio as gr
18
+ import requests
19
+
20
+ CVE_RE = re.compile(r"CVE-\d{4}-\d{4,7}", re.I)
21
+ CIRCL = "https://cve.circl.lu/api/cve/{cve_id}"
22
+ NVD = "https://services.nvd.nist.gov/rest/json/cvds/2.0?cveId={cve_id}"
23
+
24
+ LLM = os.environ.get("CVE_LLM", "Qwen/Qwen2.5-7B-Instruct")
25
+ PROVIDER = os.environ.get("CVE_INFERENCE_PROVIDER", "featherless-ai")
26
+
27
+
28
+ def _token() -> str | None:
29
+ return os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
30
+
31
+
32
+ def parse_cve_id(text: str) -> str | None:
33
+ m = CVE_RE.search(text.strip())
34
+ return m.group(0).upper() if m else None
35
+
36
+
37
+ def fetch_circl(cve_id: str) -> dict[str, Any]:
38
+ r = requests.get(CIRCL.format(cve_id=cve_id), timeout=30)
39
+ r.raise_for_status()
40
+ return r.json()
41
+
42
+
43
+ def fetch_nvd(cve_id: str) -> dict[str, Any] | None:
44
+ try:
45
+ r = requests.get(NVD.format(cve_id=cve_id), timeout=45, headers={"Accept": "application/json"})
46
+ if r.status_code != 200:
47
+ return None
48
+ data = r.json()
49
+ if not data.get("vulnerabilities"):
50
+ return None
51
+ return data["vulnerabilities"][0]["cve"]
52
+ except Exception:
53
+ return None
54
+
55
+
56
+ def cvss_from_record(rec: dict[str, Any]) -> tuple[float | None, str, dict[str, Any]]:
57
+ """Return (score, severity_label, metric_dict)."""
58
+ best_score, best_sev, best = None, "UNKNOWN", {}
59
+ containers = rec.get("containers") or {}
60
+ for block in (containers.get("cna"), *(containers.get("adp") or [])):
61
+ if not block:
62
+ continue
63
+ for m in block.get("metrics") or []:
64
+ for key in ("cvssV3_1", "cvssV3_0", "cvssV4_0"):
65
+ if key in m:
66
+ d = m[key]
67
+ sc = float(d.get("baseScore", 0))
68
+ sev = str(d.get("baseSeverity", "UNKNOWN"))
69
+ if best_score is None or sc > best_score:
70
+ best_score, best_sev, best = sc, sev, d
71
+ return best_score, best_sev, best
72
+
73
+
74
+ def descriptions_from_record(rec: dict[str, Any]) -> list[str]:
75
+ out: list[str] = []
76
+ cna = (rec.get("containers") or {}).get("cna") or {}
77
+ for d in cna.get("descriptions") or []:
78
+ if d.get("lang", "en") == "en" and d.get("value"):
79
+ out.append(d["value"])
80
+ nvd = rec.get("_nvd") or {}
81
+ for d in nvd.get("descriptions") or []:
82
+ if d.get("lang") == "en" and d.get("value"):
83
+ out.append(d["value"])
84
+ return out
85
+
86
+
87
+ def cwes_from_record(rec: dict[str, Any]) -> list[str]:
88
+ ids: list[str] = []
89
+ cna = (rec.get("containers") or {}).get("cna") or {}
90
+ for p in cna.get("problemTypes") or []:
91
+ for d in p.get("descriptions") or []:
92
+ if d.get("cweId"):
93
+ ids.append(d["cweId"])
94
+ elif d.get("description"):
95
+ ids.append(d["description"])
96
+ nvd = rec.get("_nvd") or {}
97
+ for w in nvd.get("weaknesses") or []:
98
+ for d in w.get("description") or []:
99
+ if d.get("value", "").startswith("CWE-"):
100
+ ids.append(d["value"])
101
+ return list(dict.fromkeys(ids))
102
+
103
+
104
+ def references_from_record(rec: dict[str, Any]) -> list[str]:
105
+ refs: list[str] = []
106
+ cna = (rec.get("containers") or {}).get("cna") or {}
107
+ for ref in cna.get("references") or []:
108
+ u = ref.get("url")
109
+ if u:
110
+ refs.append(u)
111
+ nvd = rec.get("_nvd") or {}
112
+ for ref in nvd.get("references") or []:
113
+ u = ref.get("url")
114
+ if u:
115
+ refs.append(u)
116
+ return list(dict.fromkeys(refs))[:12]
117
+
118
+
119
+ def risk_band(score: float | None, severity: str) -> str:
120
+ if score is not None:
121
+ if score >= 9.0:
122
+ return "Critical"
123
+ if score >= 7.0:
124
+ return "High"
125
+ if score >= 4.0:
126
+ return "Medium"
127
+ return "Low"
128
+ sev = severity.upper()
129
+ if "CRIT" in sev:
130
+ return "Critical"
131
+ if "HIGH" in sev:
132
+ return "High"
133
+ if "MED" in sev:
134
+ return "Medium"
135
+ if "LOW" in sev:
136
+ return "Low"
137
+ return "Unknown"
138
+
139
+
140
+ def cwe_mitre_hints(cwes: list[str], description: str) -> list[str]:
141
+ text = " ".join(cwes) + " " + description.lower()
142
+ hints: list[tuple[str, str]] = [
143
+ (r"remote code execution|\brce\b|arbitrary code", "T1190 – Exploit Public-Facing Application"),
144
+ (r"privilege escalation|elevation of privilege", "T1068 – Exploitation for Privilege Escalation"),
145
+ (r"sql injection", "T1190 – Exploit Public-Facing Application (SQLi)"),
146
+ (r"cross[- ]site scripting|\bxss\b", "T1189 – Drive-by Compromise (XSS delivery)"),
147
+ (r"phishing|social engineering", "T1566 – Phishing"),
148
+ (r"credential|password|authentication bypass", "T1078 – Valid Accounts"),
149
+ (r"lateral movement", "T1021 – Remote Services"),
150
+ (r"command injection|shell", "T1059 – Command and Scripting Interpreter"),
151
+ (r"backdoor|supply chain|malicious code", "T1195 – Supply Chain Compromise"),
152
+ (r"denial of service|\bdos\b", "T1499 – Endpoint Denial of Service"),
153
+ (r"memory corruption|buffer overflow|use after free", "T1203 – Exploitation for Client Execution"),
154
+ ]
155
+ found = []
156
+ for pat, tid in hints:
157
+ if re.search(pat, text, re.I):
158
+ found.append(tid)
159
+ return list(dict.fromkeys(found))[:6]
160
+
161
+
162
+ def build_context(cve_id: str | None, raw: str, rec: dict[str, Any] | None) -> dict[str, Any]:
163
+ if rec:
164
+ score, sev, metrics = cvss_from_record(rec)
165
+ descs = descriptions_from_record(rec)
166
+ desc = descs[0] if descs else raw or "(no description in feed)"
167
+ cwes = cwes_from_record(rec)
168
+ refs = references_from_record(rec)
169
+ title = ((rec.get("containers") or {}).get("cna") or {}).get("title") or cve_id
170
+ published = (rec.get("cveMetadata") or {}).get("datePublished", "")
171
+ else:
172
+ score, sev, metrics, cwes, refs, title, published = None, "UNKNOWN", {}, [], [], cve_id or "Custom text", ""
173
+ desc = raw.strip()
174
+ band = risk_band(score, sev)
175
+ mitre = cwe_mitre_hints(cwes, desc)
176
+ return {
177
+ "cve_id": cve_id or "N/A",
178
+ "title": title,
179
+ "published": published,
180
+ "description": desc,
181
+ "cvss_score": score,
182
+ "cvss_severity": sev,
183
+ "cvss_vector": metrics.get("vectorString"),
184
+ "risk_band": band,
185
+ "cwes": cwes,
186
+ "references": refs,
187
+ "mitre_hints": mitre,
188
+ "attack_vector": metrics.get("attackVector"),
189
+ "attack_complexity": metrics.get("attackComplexity"),
190
+ "privileges_required": metrics.get("privilegesRequired"),
191
+ "user_interaction": metrics.get("userInteraction"),
192
+ }
193
+
194
+
195
+ def llm_explain(ctx: dict[str, Any]) -> str | None:
196
+ token = _token()
197
+ if not token:
198
+ return None
199
+ try:
200
+ from huggingface_hub import InferenceClient
201
+ except ImportError:
202
+ return None
203
+ prompt = f"""You are a senior vulnerability analyst writing for IT and security teams.
204
+
205
+ CVE: {ctx['cve_id']}
206
+ Title: {ctx['title']}
207
+ CVSS: {ctx['cvss_score']} ({ctx['cvss_severity']}) — overall risk band: {ctx['risk_band']}
208
+ CWEs: {', '.join(ctx['cwes']) or 'none listed'}
209
+ Official description:
210
+ {ctx['description'][:3500]}
211
+
212
+ Write a concise report with these sections (use markdown headings):
213
+ ## Plain-English summary
214
+ (2-4 sentences, no jargon)
215
+ ## Risk level
216
+ (why it is {ctx['risk_band']}; mention exploitability if known)
217
+ ## Remediation steps
218
+ (numbered, practical: patch, config, detection, workarounds)
219
+ ## MITRE ATT&CK mapping
220
+ (list 2-5 relevant technique IDs like T1190 with one-line justification each; include these hints if relevant: {', '.join(ctx['mitre_hints']) or 'infer from description'})
221
+
222
+ Be accurate. If something is unknown, say so. Do not invent CVE details not present above."""
223
+ client = InferenceClient(token=token, provider=PROVIDER)
224
+ try:
225
+ out = client.chat_completion(
226
+ model=LLM,
227
+ messages=[{"role": "user", "content": prompt}],
228
+ max_tokens=900,
229
+ temperature=0.2,
230
+ )
231
+ return out.choices[0].message.content
232
+ except Exception:
233
+ try:
234
+ out = client.chat_completion(
235
+ model=LLM,
236
+ messages=[{"role": "user", "content": prompt}],
237
+ max_tokens=900,
238
+ temperature=0.2,
239
+ )
240
+ return out.choices[0].message.content
241
+ except Exception:
242
+ return None
243
+
244
+
245
+ def fallback_report(ctx: dict[str, Any]) -> str:
246
+ lines = [
247
+ f"## Plain-English summary\n{ctx['description'][:1200]}",
248
+ f"\n## Risk level\n**{ctx['risk_band']}**",
249
+ ]
250
+ if ctx["cvss_score"] is not None:
251
+ lines.append(f"- CVSS base score: **{ctx['cvss_score']}** ({ctx['cvss_severity']})")
252
+ if ctx.get("cvss_vector"):
253
+ lines.append(f"- Vector: `{ctx['cvss_vector']}`")
254
+ if ctx.get("attack_vector"):
255
+ lines.append(f"- Attack vector: {ctx['attack_vector']} · Complexity: {ctx.get('attack_complexity')} · Privileges: {ctx.get('privileges_required')} · User interaction: {ctx.get('user_interaction')}")
256
+ lines.append("\n## Remediation steps")
257
+ steps = [
258
+ "1. Confirm affected products/versions in your environment against vendor advisories.",
259
+ "2. Apply the vendor patch or upgrade to a fixed release as soon as possible.",
260
+ "3. If no patch exists, implement compensating controls (WAF rules, disable vulnerable feature, network segmentation).",
261
+ "4. Hunt for exploitation indicators in logs (unexpected child processes, suspicious outbound connections, auth anomalies).",
262
+ "5. Document exceptions and track residual risk until fully remediated.",
263
+ ]
264
+ if "supply chain" in ctx["description"].lower() or "backdoor" in ctx["description"].lower():
265
+ steps.insert(2, "2b. For supply-chain issues: rebuild from trusted sources, rotate secrets, verify package signatures and SBOMs.")
266
+ lines.extend(steps)
267
+ lines.append("\n## MITRE ATT&CK mapping (heuristic)")
268
+ if ctx["mitre_hints"]:
269
+ lines.extend(f"- {h}" for h in ctx["mitre_hints"])
270
+ else:
271
+ lines.append("- No strong keyword match — review the description with your CTI team.")
272
+ if ctx["cwes"]:
273
+ lines.append(f"\n**CWE references:** {', '.join(ctx['cwes'])}")
274
+ if ctx["references"]:
275
+ lines.append("\n**References:**")
276
+ lines.extend(f"- {u}" for u in ctx["references"][:6])
277
+ lines.append("\n<sub>Generated from public CVE metadata (no LLM). Add `HF_TOKEN` Space secret for AI-expanded remediation.</sub>")
278
+ return "\n".join(lines)
279
+
280
+
281
+ def explain(cve_input: str, raw_description: str, use_llm: bool):
282
+ cve_input = (cve_input or "").strip()
283
+ raw_description = (raw_description or "").strip()
284
+ cve_id = parse_cve_id(cve_input) or parse_cve_id(raw_description)
285
+ if not cve_id and not raw_description and not cve_input:
286
+ raise gr.Error("Enter a CVE ID (e.g. CVE-2024-3094) and/or paste a description.")
287
+
288
+ rec: dict[str, Any] | None = None
289
+ meta_line = ""
290
+ if cve_id:
291
+ try:
292
+ rec = fetch_circl(cve_id)
293
+ nvd = fetch_nvd(cve_id)
294
+ if nvd:
295
+ rec["_nvd"] = nvd
296
+ meta_line = f"Loaded **{cve_id}** from public CVE feeds."
297
+ except requests.HTTPError as e:
298
+ if e.response is not None and e.response.status_code == 404:
299
+ raise gr.Error(f"{cve_id} was not found in the CIRCL feed.")
300
+ raise gr.Error(f"Could not fetch {cve_id}: {e}") from e
301
+ except requests.RequestException as e:
302
+ raise gr.Error(f"Network error fetching {cve_id}: {e}") from e
303
+ elif cve_input and not raw_description:
304
+ raw_description = cve_input
305
+
306
+ ctx = build_context(cve_id, raw_description or cve_input, rec)
307
+ report = None
308
+ if use_llm:
309
+ report = llm_explain(ctx)
310
+ if not report:
311
+ report = fallback_report(ctx)
312
+ if use_llm and not _token():
313
+ meta_line += " (LLM disabled: set Space secret `HF_TOKEN` with inference scope.)"
314
+ elif use_llm:
315
+ meta_line += " (LLM call failed — showing structured fallback.)"
316
+
317
+ header = f"# {ctx['cve_id']}: {ctx['title']}\n"
318
+ if ctx["published"]:
319
+ header += f"*Published: {ctx['published'][:10]}*\n\n"
320
+ header += meta_line + "\n\n"
321
+ risk_md = f"**{ctx['risk_band']}**" + (f" (CVSS {ctx['cvss_score']})" if ctx["cvss_score"] is not None else "")
322
+ json_out = json.dumps({k: v for k, v in ctx.items() if k != "description" or len(str(v)) < 500}, indent=2)
323
+ return risk_md, header + report, json_out
324
+
325
+
326
+ EXAMPLES = [
327
+ ["CVE-2024-3094", "", True],
328
+ ["CVE-2021-44228", "", True],
329
+ ["", "A buffer overflow in the XYZ VPN client allows remote attackers to execute arbitrary code via a crafted UDP packet. CVSS 9.8.", False],
330
+ ]
331
+
332
+ with gr.Blocks(title="CVE Explainer") as demo:
333
+ with gr.Column(elem_id="col"):
334
+ gr.Markdown(
335
+ "# 🛡️ CVE Explainer / Summarizer\n"
336
+ "Enter a **CVE ID** or paste a **raw vulnerability description** → plain-English summary, "
337
+ "**risk level**, **remediation steps**, and **MITRE ATT&CK** mapping.\n\n"
338
+ "Data: [CIRCL CVE API](https://cve.circl.lu/) (+ NVD when available). "
339
+ f"Optional AI summary via Inference Providers (`{LLM}`)."
340
+ )
341
+ with gr.Row():
342
+ with gr.Column():
343
+ cve = gr.Textbox(label="CVE ID", placeholder="CVE-2024-3094")
344
+ raw = gr.Textbox(label="Or paste description / advisory text", lines=6, placeholder="Optional if CVE ID is set…")
345
+ use_llm = gr.Checkbox(value=True, label="Expand with AI (requires HF_TOKEN secret on the Space)")
346
+ btn = gr.Button("Explain", variant="primary")
347
+ with gr.Column():
348
+ risk = gr.Textbox(label="Risk level", interactive=False)
349
+ out = gr.Markdown(label="Report")
350
+ meta = gr.Code(label="Structured metadata (JSON)", language="json")
351
+ gr.Examples(EXAMPLES, inputs=[cve, raw, use_llm], outputs=[risk, out, meta], fn=explain, cache_examples=False)
352
+ gr.Markdown("⚠️ Advisory only — validate patches and scope with vendor bulletins and your asset inventory.")
353
+ btn.click(explain, [cve, raw, use_llm], [risk, out, meta], api_name="explain")
354
+
355
+ if __name__ == "__main__":
356
+ demo.queue(max_size=16).launch(theme=gr.themes.Soft(), css="#col {max-width: 960px; margin: 0 auto;}")
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ requests