Revolutionizing Risk Assessment: How to Automate CVSS Scoring with Local LLMs and Python + Video

Listen to this Post

Featured Image

Introduction:

In the ever-evolving landscape of cybersecurity, risk assessment remains a cornerstone of proactive defense. Traditional methods of calculating CVSS scores and populating risk matrices are manual, time‑consuming, and prone to human error. By combining local Large Language Models (LLMs) like Qwen with Python’s CVSS library, security professionals can automate the extraction of CVSS vectors from vulnerability descriptions and generate consistent, real‑time risk ratings. This approach not only accelerates the assessment process but also integrates seamlessly into modern GRC workflows, enabling teams to focus on mitigation rather than data entry.

Learning Objectives:

  • Understand the structure of CVSS v3 vectors and how they map to risk scores.
  • Set up and interact with a local LLM (Qwen) for automated risk analysis.
  • Automate CVSS scoring using Python’s `cvss` library.
  • Build a dynamic risk matrix dashboard to visualize and manage vulnerabilities.
  • Explore advanced techniques like fine‑tuning and threat intelligence integration.

You Should Know:

1. Building a Local AI-Powered Risk Assessment Engine

The first step toward automation is deploying a local LLM that can interpret natural language vulnerability descriptions and output a corresponding CVSS vector. Using Ollama, we can run Qwen (a powerful open‑source model) entirely on‑premises, ensuring data privacy and low latency.

Step‑by‑step guide:

  • Install Ollama (Linux/macOS/Windows):
    curl -fsSL https://ollama.com/install.sh | sh
    
  • Pull the Qwen model (e.g., qwen2.5:7b):
    ollama pull qwen2.5:7b
    
  • Test the model with a simple prompt:
    ollama run qwen2.5:7b "Generate a CVSS v3.1 vector for a remote code execution vulnerability in a web application with no authentication required."
    
  • Create a Python script to interact with Ollama’s API and extract the vector:
    import requests
    import json</li>
    </ul>
    
    def get_cvss_vector(description):
    url = "http://localhost:11434/api/generate"
    payload = {
    "model": "qwen2.5:7b",
    "prompt": f"Given this vulnerability description, output only the CVSS v3.1 vector string (e.g., CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H): {description}",
    "stream": False
    }
    response = requests.post(url, json=payload)
    result = response.json()
    return result['response'].strip()
    

    This script sends the description to the local model and returns the CVSS vector, which can then be passed to the CVSS library for scoring.

    2. Automating CVSS Scoring with Python’s CVSS Library

    Once we have the vector, we need to compute the base, temporal, and environmental scores. The `cvss` library simplifies this and provides methods to derive severity ratings.

    Step‑by‑step guide:

    • Install the library:
      pip install cvss
      
    • Parse and calculate scores:
      from cvss import CVSS3</li>
      </ul>
      
      vector = get_cvss_vector("Arbitrary file upload in a PHP application leads to remote code execution.")
      c = CVSS3(vector)
      base_score = c.scores()[bash]  Base Score
      severity = c.severities()[bash]  e.g., 'HIGH'
      
      print(f"Vector: {vector}\nBase Score: {base_score}\nSeverity: {severity}")
      

      – Handle multiple vulnerabilities by iterating through a list of descriptions, storing results in a structured format (e.g., CSV or JSON) for further analysis.

      3. Creating a Dynamic Risk Matrix Dashboard

      A static spreadsheet is no longer sufficient. Using a lightweight web framework like Streamlit, we can build an interactive dashboard that displays vulnerabilities, their CVSS scores, and risk levels in real time.

      Step‑by‑step guide:

      • Install Streamlit:
        pip install streamlit pandas
        
      • Create a basic app (risk_dashboard.py):
        import streamlit as st
        import pandas as pd
        from cvss import CVSS3</li>
        </ul>
        
        st.title("Automated Risk Matrix")
        uploaded_file = st.file_uploader("Upload vulnerability descriptions (CSV with a 'description' column)")
        if uploaded_file:
        df = pd.read_csv(uploaded_file)
        vectors = []
        scores = []
        severities = []
        for desc in df['description']:
        vec = get_cvss_vector(desc)  reuse function from step 1
        c = CVSS3(vec)
        vectors.append(vec)
        scores.append(c.scores()[bash])
        severities.append(c.severities()[bash])
        df['vector'] = vectors
        df['base_score'] = scores
        df['severity'] = severities
        st.dataframe(df)
         Add a heatmap or risk matrix visualization
        st.bar_chart(df['base_score'])
        

        – Run the app:

        streamlit run risk_dashboard.py
        

        This dashboard can be extended with filters, export options, and integration with ticketing systems.

        4. Enhancing Accuracy with Fine‑Tuned Models

        Out‑of‑the‑box LLMs may occasionally hallucinate vectors. Fine‑tuning Qwen on a dataset of vulnerability descriptions paired with correct CVSS vectors drastically improves accuracy.

        Step‑by‑step guide:

        • Prepare a dataset (e.g., from NVD) with fields: description, vector.
        • Use the Hugging Face `transformers` library to fine‑tune Qwen. Example script structure:
          from transformers import AutoTokenizer, AutoModelForCausalLM, TrainingArguments, Trainer
          Load model and tokenizer
          Tokenize dataset with prompt template
          Train with appropriate hyperparameters
          
        • Export the fine‑tuned model and use it locally via Ollama or Hugging Face pipelines.
          This step requires GPU resources but yields a model specialized for your organization’s risk language.

        5. Integrating Threat Intelligence Feeds

        To keep the risk matrix current, automatically pull the latest CVEs from sources like the National Vulnerability Database (NVD) and feed them into your pipeline.

        Step‑by‑step guide:

        • Fetch recent CVEs using the NVD API:
          curl "https://services.nvd.nist.gov/rest/json/cves/2.0?startIndex=0&resultsPerPage=10"
          
        • Parse the JSON and extract descriptions.
        • Run the descriptions through your AI+CVSS pipeline and update the dashboard.
        • Schedule the script with cron (Linux) or Task Scheduler (Windows) to run daily.

        6. Security Considerations for AI in Risk Management

        Automating risk assessment introduces new attack surfaces. Protect your pipeline by:
        – Validating LLM outputs against known vector patterns using regex.
        – Implementing input sanitization to prevent prompt injection.
        – Running the AI model in a container with minimal privileges.
        – Encrypting communication between components, especially if using a remote API.

        7. Continuous Monitoring and Improvement

        Set up alerts for when new critical vulnerabilities are detected. Use the historical data to train your model further and refine the risk matrix over time.

        What Undercode Say:

        • Key Takeaway 1: Automating risk matrix generation with local LLMs and CVSS libraries slashes manual effort and enforces consistency across assessments. Teams can reallocate hours from data entry to strategic threat hunting.
        • Key Takeaway 2: The combination of open‑source models (like Qwen) and Python’s scientific stack democratizes advanced GRC automation, making it accessible even to smaller organizations with limited budgets.

        Analysis: The integration of AI into governance, risk, and compliance (GRC) processes is not just a trend—it is a necessity. As vulnerability volumes explode, manual methods collapse under their own weight. By leveraging local LLMs, organizations retain full control over sensitive data while benefiting from AI’s analytical power. However, practitioners must treat AI outputs as suggestions, not oracles; human validation remains critical. The future belongs to adaptive risk frameworks that learn from each assessment, continuously improving their accuracy and relevance.

        Prediction:

        Within the next three years, AI‑driven risk automation will become a standard component of enterprise GRC platforms. Fine‑tuned models tailored to specific industries and regulatory environments will enable real‑time risk posture updates, allowing organizations to pivot defenses before exploits are weaponized. The marriage of LLMs and CVSS will evolve into predictive risk analytics, where systems not only score current vulnerabilities but also forecast emerging threats based on global attack telemetry.

        ▶️ Related Video (82% Match):

        🎯Let’s Practice For Free:

        IT/Security Reporter URL:

        Reported By: Hernanrodriguez – Hackers Feeds
        Extra Hub: Undercode MoN
        Basic Verification: Pass ✅

        🔐JOIN OUR CYBER WORLD [ CVE News • HackMonitor • UndercodeNews ]

        💬 Whatsapp | 💬 Telegram

        📢 Follow UndercodeTesting & Stay Tuned:

        𝕏 formerly Twitter 🐦 | @ Threads | 🔗 Linkedin | 🦋BlueSky