Mohammad Abd El-Fattah Mohammad
مهندس أمن سيبراني وذكاء اصطناعي
متاح لفرص العمل والدراسة

Repositories

AI Attack Vector Brainstormer Risk Assessor

بقلم Mohammad Abd El-Fattah Mohammad · آخر تحديث 2025-06-01 · 9 دقيقة قراءة

AI Attack Vector Brainstormer & Risk Assessor 🛡️

Executive Summary

The AI Attack Vector Brainstormer & Risk Assessor is a Python-based application designed to leverage the Google Gemini API for offensive security conceptualization. It serves two primary functions: first, to brainstorm a diverse range of potential attack vectors against a user-defined target system or application; and second, to provide an automated, AI-driven risk assessment for each identified vector. This assessment is delivered in a structured JSON format, evaluating aspects such as potential impact, likelihood, and plausibility. This project demonstrates the practical application of Large Language Models (LLMs) for both generative and evaluative tasks within the cybersecurity domain, emphasizing structured output as explored in AI evaluation-focused lessons. The tool is provided as a single script, optimized for Google Colaboratory (Colab) or local Python environments.

Important Disclaimer: This initiative is conceived strictly for educational and research purposes. Any application of this tool or the methodologies it demonstrates must be confined to legally authorized environments and undertaken only with explicit, documented permission. The utilization of these techniques for any unauthorized activities constitutes a violation of legal and ethical standards. The developers disclaim all liability and bear no responsibility for any illicit use or resultant damage attributable to this program.

📚 Educational Aims

This project is structured to facilitate user comprehension and practical application of LLMs, focusing on:

  • Generative AI for Idea Generation: Utilizing an LLM to brainstorm diverse and creative attack vectors relevant to a given target profile.
  • Evaluative AI for Risk Assessment: Employing an LLM to perform a qualitative risk assessment on generated ideas, simulating an expert security analyst's judgment.
  • Structured Output from LLMs: Implementing techniques to obtain consistent, machine-readable (JSON) output from an LLM, based on a predefined schema, for evaluation results. This directly applies concepts from lessons on structured data capabilities of models like Gemini.
  • Prompt Engineering for Complex Tasks: Designing and iteratively refining effective prompts for both the brainstorming phase (to encourage breadth) and the evaluation phase (to ensure adherence to assessment criteria and strict structured output).
  • Understanding AI in Cybersecurity: Exploring the potential and limitations of AI as an assistive tool in penetration testing and vulnerability assessment workflows.

✨ Core Functionalities

  1. Attack Vector Brainstorming Module:
    • Input: A textual description of the target system, application, or organization.
    • AI Task: Generates a list of distinct, potential attack vectors tailored to the provided target description.
    • Output: A Python list of strings, where each string describes a conceptual attack vector.
  1. Automated Risk Assessment Module (Structured Output):
    • Input: A single attack vector (from the brainstorming phase) and the original target context.
    • AI Task: Evaluates the provided attack vector based on predefined criteria (impact, likelihood, plausibility, assessor confidence) and suggests a mitigation category.
    • Output: A structured Python dictionary (derived from JSON) conforming to the AttackVectorEvaluation schema, including fields such as estimated_impact: ImpactLevel, estimated_likelihood: LikelihoodLevel, plausibility: PlausibilityRating, brief_justification: str, etc.

🛠️ System Setup and Installation Procedures

This project is furnished as a singular, fully functional Python script, engineered for execution within Google Colaboratory or a standard local Python environment. The script contains all necessary logic, including interactions with the Gemini API.

Prerequisites

  • Python version 3.7 or higher. (Note: typing_extensions is used for TypedDict for compatibility with Python < 3.12; Colab environments are generally suitable).
  • Authorized access to the Gemini API, including a valid API Key.
  • The google-generativeai and typing_extensions Python libraries.

1. Code Acquisition

  • Google Colaboratory Users: The source code from this repository (the .py file or its content) can be directly incorporated into a Colaboratory notebook. This is the complete script with API calls.
  • Local Environment Users: The Python script (e.g., ai_attack_vector_assessor.py from this repository) should be downloaded. This file contains the full application logic.

2. Dependency Installation

The script includes !pip install -U -q google-generativeai typing_extensions at the beginning, suitable for Colab.
For local environments, ensure these are installed:

pip install google-generativeai typing_extensions

3. API Key Configuration

The script (ai_attack_vector_assessor.py or the Colaboratory notebook) is designed to load the Gemini API key. The configure_api_key() function within the script manages this process by checking the following sources in order:

  1. Google Colaboratory Secrets (Preferred for Colaboratory):
    • Navigate to the "Key" icon (🔑) in the left sidebar of the Colaboratory notebook.
    • Select "Add new secret".
    • Specify GOOGLE_API_KEY as the Name.
    • Input the actual Gemini API key as the Value.
    • Ensure the "Notebook access" toggle is activated for this secret.
  2. Environment Variables (Preferred for Local Execution):
    • Define an environment variable named GOOGLE_API_KEY and assign it the value of your API key. ``bash # Example for Linux/macOS export GOOGLE_API_KEY="YOUR_API_KEY_HERE" # Example for Windows (Command Prompt) set GOOGLE_API_KEY=YOUR_API_KEY_HERE ``

The script will utilize the first successfully located key to initialize the Gemini client.

🚀 Script Execution

  • Google Colaboratory: Subsequent to integrating the complete code into a notebook and configuring the API key secret, execute the cell(s) containing the script.
  • Local Environment: If the script has been saved as ai_attack_vector_assessor.py, it can be executed from the terminal using: ``bash python ai_attack_vector_assessor.py ``

Adhere to the interactive prompts displayed in the console. You will be asked to describe the target system, after which the AI will brainstorm attack vectors and then evaluate each one, printing the structured assessment.

Illustrative In-Application Usage:

  1. The user is prompted: 📝 Describe the target system/application (or type 'quit' to exit):
  2. User inputs: An internal HR portal running on an old version of JBoss Application Server (version 4.x). It's only accessible from the corporate LAN. The portal handles employee PII and salary information. Standard endpoint protection is on user workstations.
  3. The AI first brainstorms vectors (example): `` 🧠 Brainstorming attack vectors for: An internal HR portal running on an old version of JBoss Application Server (version 4.x). It's only... 💡 Found 7 potential attack vectors. `` (Example vectors: "Exploit known JBoss 4.x vulnerabilities for remote code execution.", "Lateral movement from compromised workstation...", "Phishing for credentials targeting HR employees...")
  4. For each vector, the AI then provides a structured evaluation. The script includes a DEBUG print of the raw JSON from the AI, followed by the parsed output: `` ⚖️ Evaluating vector: Exploit known JBoss 4.x vulnerabilities for remote code execution. DEBUG: Raw text from AI for evaluation: {"vector_description": "Exploit known JBoss 4.x vulnerabilities for remote code execution.", "estimated_impact": "CRITICAL", "estimated_likelihood": "HIGH", "plausibility": "VERY_PLAUSIBLE", "evaluator_confidence_in_assessment": "HIGH", "brief_justification": "JBoss 4.x is end-of-life with many known, unpatched vulnerabilities allowing for remote code execution and access to sensitive data.", "suggested_mitigation_category": "Application Upgrade and Patching"} DEBUG: Successfully parsed JSON: {'vector_description': 'Exploit known JBoss 4.x vulnerabilities for remote code execution.', 'estimated_impact': 'CRITICAL', 'estimated_likelihood': 'HIGH', 'plausibility': 'VERY_PLAUSIBLE', 'evaluator_confidence_in_assessment': 'HIGH', 'brief_justification': 'JBoss 4.x is end-of-life with many known, unpatched vulnerabilities allowing for remote code execution and access to sensitive data.', 'suggested_mitigation_category': 'Application Upgrade and Patching'} Impact: CRITICAL Likelihood: HIGH Plausibility: VERY_PLAUSIBLE Assessor Confidence: HIGH Justification: JBoss 4.x is end-of-life with many known, unpatched vulnerabilities allowing for remote code execution and access to sensitive data. Mitigation Category: Application Upgrade and Patching `` (This process repeats for all brainstormed vectors, demonstrating successful structured data extraction and nuanced, non-default assessments.)

🐍 Architectural Overview

The application's logic is encapsulated within a single Python script (e.g., ai_attack_vector_assessor.py). Its principal components include:

  • configure_api_key(): Manages API key loading and Gemini client initialization.
  • ImpactLevel, LikelihoodLevel, PlausibilityRating (Enums): Define controlled vocabularies for consistent assessment categories.
  • AttackVectorEvaluation (TypedDict): Defines the Python class structure for the JSON output from the evaluation AI, ensuring type safety and clarity for the structured data.
  • brainstorm_attack_vectors(target_description): Interacts with the Gemini API to generate a list of potential attack vectors.
  • evaluate_attack_vector(vector_description, target_context): Interacts with the Gemini API, using a specific prompt and generation_config (with response_mime_type="application/json"), to assess a single attack vector and return a structured AttackVectorEvaluation object. This function includes logic to parse the JSON and handle potential inconsistencies in AI output.
  • main_loop(): Governs user interaction, calls the brainstorming and evaluation functions, and presents the results.

💡 Prompting Strategies & Structured Output Application

This project effectively demonstrates key concepts from AI evaluation and structured output:

  • Two-Phase AI Interaction: A generative phase (attack vector brainstorming) is followed by a distinct evaluative phase (risk assessment of each vector).
  • Reliable Structured Output for Evaluation: The evaluate_attack_vector function has been engineered through iterative prompt refinement to successfully request and parse JSON output from the Gemini API. Key aspects include:
    • Highly Explicit Prompts: The evaluation prompt strongly emphasizes the requirement for a single, complete JSON object as the entire response, detailing mandatory keys and strict adherence to specified enum string values.
    • JSON Schema in Prompt: While response_schema in generation_config is available, this project focuses on clearly defining the expected JSON structure directly within the prompt text, including example formats, which has proven effective with the gemini-1.5-flash-latest model.
    • Robust Parsing: The script includes logic to extract the JSON block even if minor extraneous text is present and handles potential ValueError exceptions during enum conversion by logging warnings and falling back to defaults if necessary (though current performance shows good adherence).
  • Iterative Refinement: The development process for this tool highlighted the importance of iterative prompt engineering. Initial prompts for structured JSON sometimes resulted in verbose or incomplete responses. Through successive refinements—making instructions more direct, emphasizing JSON-only output, and simplifying the example—consistent and accurate structured output was achieved.
  • Debug Logging: The inclusion of DEBUG print statements showing the raw JSON received from the AI and the result of json.loads() was crucial for diagnosing and resolving issues with the AI's adherence to the desired output format.

🤝 Contribution Guidelines

Contributions to this project are encouraged. Individuals with proposals for new functionalities, enhancements, or defect remediation are invited to:

  1. Fork the repository.
  2. Establish a new branch for development (git checkout -b feature/YourFeature).
  3. Implement the proposed modifications.
  4. Commit the changes with a descriptive message (git commit -m 'Implement YourFeature').
  5. Push the modifications to the branch (git push origin feature/YourFeature).
  6. Initiate a Pull Request for review.

Please ensure all submissions adhere to the ethical use disclaimer articulated for this project.

📄 Licensing

This project may be distributed under the terms of the MIT License. (A LICENSE file containing the MIT License text should be included in the repository if this license is adopted).

🙏 Acknowledgements

  • This project derives inspiration from, and serves as a practical exercise based upon, concepts presented in the 5-Day Gen AI Intensive Course with Google Learn Guide Unit 1 – “Prompt Engineering”. Specifically, it applies principles demonstrated in the following Kaggle codelabs and supplementary materials:
    • Evaluation and structured data: <https://www.kaggle.com/code/markishere/day-1-evaluation-and-structured-output>
    • Bonus whitepaper on Evaluating Large Language Models: <https://services.google.com/fh/files/blogs/neurips_evaluation.pdf>
  • The project utilizes the Google Gemini API.
  • Methodologies and concepts are informed by community resources, including the MITRE ATT&CK® framework for TTPs.

الملف في مستودعي: README.md