### Install Project Dependencies Source: https://github.com/banno-0720/vulnerability-scanner/blob/main/README.md This command installs all the necessary Python packages listed in the requirements.txt file, enabling the project's functionality. It's crucial for setting up the environment correctly. ```bash pip install -r requirements.txt ``` -------------------------------- ### Run Vulnerability Scanner Server Source: https://github.com/banno-0720/vulnerability-scanner/blob/main/README.md Starts the local server for the vulnerability scanner. This is optional as a hosted version is available. The server will be accessible at http://localhost:7860 with MCP endpoints at /gradio_api/mcp/. ```bash python server.py ``` -------------------------------- ### Run Vulnerability Scanner Locally (Bash) Source: https://github.com/banno-0720/vulnerability-scanner/blob/main/README.md This snippet shows the commands to run the vulnerability scanner client and server locally. It requires two terminal windows, one for starting the server and another for starting the client. ```bash # Terminal 1: Start the server python server.py # Terminal 2: Start the client python client.py ``` -------------------------------- ### Clone Repository using Git Source: https://github.com/banno-0720/vulnerability-scanner/blob/main/README.md This command clones the vulnerability scanner's source code from the GitHub repository to your local machine, serving as the initial setup step for the project. ```bash git clone https://github.com/banno-0720/vulnerability-scanner.git cd vulnerability-scanner ``` -------------------------------- ### Launch MCP Server with CVE Integration (Python) Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Starts the GitHub MCP server with integrated CVE knowledge base and NVD integration. Provides a Gradio web interface with tabbed access to all MCP tools. Requires GitHub token for authentication and Gradio for the web UI. ```python from server import GitHubMCPServer import gradio as gr import os # Set up environment os.environ['GITHUB_TOKEN'] = 'ghp_your_github_token_here' # Initialize server github_server = GitHubMCPServer() ``` -------------------------------- ### Get GitHub Repository Information using Python Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Retrieves metadata for a GitHub repository including name, description, language, stars, and creation date. Requires a GitHub token set as an environment variable. Returns success status and repository details or an error message. ```python from server import GitHubMCPServer import os # Initialize server with GitHub token os.environ['GITHUB_TOKEN'] = 'ghp_your_github_token_here' server = GitHubMCPServer() # Get repository information repo_info = server.get_repository_info(owner="octocat", repo="Hello-World") if repo_info["success"]: print(f"Repository: {repo_info['full_name']}") print(f"Description: {repo_info['description']}") print(f"Language: {repo_info['primary_language']}") print(f"Stars: {repo_info['stars']}") print(f"Default Branch: {repo_info['default_branch']}") print(f"Created: {repo_info['created_date']}") else: print(f"Error: {repo_info['error']}") # Expected output: # Repository: octocat/Hello-World # Description: My first repository on GitHub! # Language: JavaScript # Stars: 2145 # Default Branch: main # Created: 2011-01-26 ``` -------------------------------- ### Remediation for SQL Injection in Python Source: https://github.com/banno-0720/vulnerability-scanner/blob/main/VISUAL_WORKFLOW.md This code example demonstrates how to fix SQL injection vulnerabilities in Python by switching from string concatenation to parameterized queries. It shows the vulnerable code and the recommended secure alternative. ```python query = "SELECT * FROM users WHERE name='" + username + "'" # Remediation: query = "SELECT * FROM users WHERE name=?" cursor.execute(query, (username,)) ``` -------------------------------- ### Get Repository Information Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Retrieves comprehensive metadata about a GitHub repository including language, size, stars, forks, and creation date. This function uses the GitHub API with authentication to access both public and private repositories. ```APIDOC ## GET /repositories/{owner}/{repo} ### Description Retrieves comprehensive metadata about a GitHub repository including language, size, stars, forks, and creation date. ### Method GET ### Endpoint `/repositories/{owner}/{repo}` ### Parameters #### Path Parameters - **owner** (string) - Required - The owner of the repository. - **repo** (string) - Required - The name of the repository. #### Query Parameters None #### Request Body None ### Request Example ```python from server import GitHubMCPServer import os os.environ['GITHUB_TOKEN'] = 'ghp_your_github_token_here' server = GitHubMCPServer() repo_info = server.get_repository_info(owner="octocat", repo="Hello-World") if repo_info["success"]: print(f"Repository: {repo_info['full_name']}") print(f"Description: {repo_info['description']}") print(f"Language: {repo_info['primary_language']}") print(f"Stars: {repo_info['stars']}") print(f"Default Branch: {repo_info['default_branch']}") print(f"Created: {repo_info['created_date']}") else: print(f"Error: {repo_info['error']}") ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **full_name** (string) - The full name of the repository. - **description** (string) - The description of the repository. - **primary_language** (string) - The primary programming language of the repository. - **stars** (integer) - The number of stars the repository has. - **default_branch** (string) - The default branch of the repository. - **created_date** (string) - The creation date of the repository. #### Response Example ```json { "success": true, "full_name": "octocat/Hello-World", "description": "My first repository on GitHub!", "primary_language": "JavaScript", "stars": 2145, "default_branch": "main", "created_date": "2011-01-26" } ``` ``` -------------------------------- ### Get File Content Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Fetches and decodes the content of a specific file from a GitHub repository. The function handles base64-encoded content from GitHub API and returns plain text with error handling for binary files. ```APIDOC ## GET /repositories/{owner}/{repo}/files/{path} ### Description Fetches and decodes the content of a specific file from a GitHub repository. ### Method GET ### Endpoint `/repositories/{owner}/{repo}/files/{path}` ### Parameters #### Path Parameters - **owner** (string) - Required - The owner of the repository. - **repo** (string) - Required - The name of the repository. - **path** (string) - Required - The path to the file within the repository. #### Query Parameters None #### Request Body None ### Request Example ```python from server import GitHubMCPServer import os os.environ['GITHUB_TOKEN'] = 'ghp_your_github_token_here' server = GitHubMCPServer() content = server.get_file_content(owner="octocat", repo="Hello-World", path="README.md") if not content.startswith("ERROR:"): print("File Content:") print(content[:500]) # Print first 500 characters else: print(content) ``` ### Response #### Success Response (200) - **content** (string) - The content of the file. Returns an error message prefixed with "ERROR:" if the file cannot be retrieved or is binary. #### Response Example ``` File Content: # Hello-World This is a repository for testing purposes. It was created by the "octocat" user. ... ``` ``` -------------------------------- ### Run Vulnerability Scanner Client Source: https://github.com/banno-0720/vulnerability-scanner/blob/main/README.md Launches the vulnerability scanner client application. After running this command, the web interface can be accessed at http://localhost:7860. ```bash python client.py ``` -------------------------------- ### MCP Client Connection and Agent Usage (Python) Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt This Python code demonstrates how to establish a connection to a GitHub MCP server using the `smolagents` library. It retrieves available tools from the server, creates an AI agent configured with these tools and an inference model, and then runs a task using the agent. It also includes error handling for connection failures. ```Python from smolagents import MCPClient, CodeAgent, InferenceClientModel # Connect to MCP server (hosted or local) mcp_client = MCPClient({ "url": "https://himanshugoyal2004-github-mcp-server.hf.space/gradio_api/mcp/", "timeout": 120 }) # Get available tools from server github_tools = mcp_client.get_tools() print(f"Available tools: {[tool.name for tool in github_tools]}") # Output: ['get_repository_info', 'get_file_content', 'scan_repository', # 'search_cve_database', 'simple_cve_search', 'get_nvd_cve_details'] # Create AI agent with MCP tools hf_token = "hf_your_token_here" model = InferenceClientModel(token=hf_token) agent = CodeAgent(tools=github_tools, model=model, max_steps=10) # Use agent with MCP tools result = agent.run(""" Get information about repository 'octocat/Hello-World' and search for SQL injection CVEs """ ) print(result) # Clean up connection mcp_client.disconnect() # Error handling try: mcp_client = MCPClient({"url": "invalid-url", "timeout": 30}) except Exception as e: print(f"Connection failed: {e}") ``` -------------------------------- ### Launch Vulnerability Scanner Client (Python) Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt This Python script launches a Gradio chat interface for an AI-powered vulnerability scanner. It allows users to input GitHub file URLs and receive security analysis reports. The interface is customizable with a theme and requires a Hugging Face API key for the AI model. ```Python import gradio as gr from client import analyze_vulnerabilities_multiagent with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo: gr.Markdown("## 🛡️ Enhanced GitHub Vulnerability Scanner") with gr.Row(): with gr.Column(scale=1): gr.Markdown("### 🔑 API Configuration") hf_token_box = gr.Textbox( label="🤗 Hugging Face API Key", placeholder="Enter your Hugging Face API key", type="password", info="Get your key: https://huggingface.co/settings/tokens" ) chatbot = gr.ChatInterface( fn=lambda msg, hist, hf_token: analyze_vulnerabilities_multiagent(msg, hist, hf_token), additional_inputs=[hf_token_box], type="messages", examples=[ ["https://github.com/ayushmittal62/vunreability_scanner_testing/blob/master/python/database.py", ""], ["https://github.com/banno-0720/documentation-agent/blob/main/code.py", ""] ] ) if __name__ == "__main__": demo.launch(server_port=7861, share=False) # Client available at http://localhost:7861 # Accepts GitHub file URLs for vulnerability analysis ``` -------------------------------- ### Search CVE Database using Python Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Searches the CVE knowledge base using the BM25 retrieval algorithm to find relevant vulnerability patterns. This function is intended to return top CVE matches with descriptions for use in code analysis context. It requires initialization of the GitHubMCPServer with a GitHub token. ```python from server import GitHubMCPServer import os os.environ['GITHUB_TOKEN'] = 'ghp_your_github_token_here' server = GitHubMCPServer() ``` -------------------------------- ### Search CVE Database Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Searches the CVE knowledge base using BM25 retrieval algorithm to find relevant vulnerability patterns. Returns top 3 CVE matches with descriptions for code analysis context. ```APIDOC ## GET /cve/search ### Description Searches the CVE knowledge base using BM25 retrieval algorithm to find relevant vulnerability patterns. ### Method GET ### Endpoint `/cve/search` ### Parameters #### Path Parameters None #### Query Parameters - **query** (string) - Required - The search query string, typically a snippet of code or a description of a vulnerability. #### Request Body None ### Request Example ```python from server import GitHubMCPServer import os os.environ['GITHUB_TOKEN'] = 'ghp_your_github_token_here' server = GitHubMCPServer() # Example: Searching for vulnerabilities related to 'pickle deserialization' cve_matches = server.search_cve_database(query="pickle deserialization") if cve_matches: print("Top CVE Matches:") for match in cve_matches: print(f"- CVE ID: {match['cve_id']}, Description: {match['description']}") else: print("No CVE matches found.") ``` ### Response #### Success Response (200) - **cve_matches** (array of objects) - A list of top CVE matches. Each object contains: - **cve_id** (string) - The CVE identifier (e.g., "CVE-2023-XXXXX"). - **description** (string) - A brief description of the vulnerability. - **cvss_score** (float) - The CVSS score of the vulnerability. - **cwe_id** (string) - The CWE identifier. #### Response Example ```json { "cve_matches": [ { "cve_id": "CVE-2023-12345", "description": "Insecure deserialization vulnerability in the 'pickle' module could allow remote code execution.", "cvss_score": 7.5, "cwe_id": "CWE-502" }, { "cve_id": "CVE-2022-67890", "description": "Improper handling of pickled data may lead to denial of service or arbitrary code execution.", "cvss_score": 6.8, "cwe_id": "CWE-502" } ] } ``` ``` -------------------------------- ### GitHub Repository Analysis with AI Agent Source: https://github.com/banno-0720/vulnerability-scanner/blob/main/VISUAL_WORKFLOW.md This snippet demonstrates the AI agent's process of gathering repository information by calling the 'get_repository_info' tool. It takes the repository owner and name as input and returns repository details like name, language, stars, and description. ```Python agent.call("get_repository_info", owner="user", repo="repo") # Returns: {"name": "repo", "language": "Python", "stars": 42, "description": "A test repository"} ``` -------------------------------- ### Create Tabbed Interface for GitHub Tools (Python) Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt This snippet demonstrates how to create a tabbed interface for different GitHub-related tools using Gradio. It defines two interfaces: one for retrieving repository information and another for smart CVE analysis. The interface is launched with MCP (Multi-Agent Collaboration Platform) support. ```Python import gradio as gr # Assuming github_server is defined elsewhere and has the required functions # class MockGithubServer: # def get_repository_info(self, owner, repo): # return f"Info for {owner}/{repo}" # def search_and_fetch_cve_details(self, query, max_fetches): # return f"CVE analysis for {query} with max {max_fetches} fetches" # github_server = MockGithubServer() demo = gr.TabbedInterface( [ gr.Interface( fn=github_server.get_repository_info, inputs=[ gr.Textbox(label="Repository Owner", placeholder="octocat"), gr.Textbox(label="Repository Name", placeholder="Hello-World") ], outputs=gr.Textbox(label="Repository Information", lines=15), title="Get Repository Information", api_name="get_repository_info" ), gr.Interface( fn=github_server.search_and_fetch_cve_details, inputs=[ gr.Textbox(label="Vulnerability Query", value="SQL injection"), gr.Slider(minimum=1, maximum=10, value=5, step=1, label="Max NVD Fetches") ], outputs=gr.Textbox(label="Comprehensive CVE Analysis", lines=40), title="🔬 Smart CVE Analysis (RAG + NVD)", api_name="search_and_fetch_cve_details" ) ], ["Repository Info", "Smart CVE Analysis"], title="🐙 GitHub MCP Server" ) if __name__ == "__main__": demo.launch(mcp_server=True, server_port=7860, share=False) # Server available at http://localhost:7860 # MCP endpoints at /gradio_api/mcp/ ``` -------------------------------- ### Scan GitHub Repository for Code Files using Python Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Recursively scans a GitHub repository to find code files with specified extensions (e.g., '.py', '.js', '.php'). Returns a list of up to 50 file paths. Useful for batch vulnerability analysis. Requires a GitHub token. Also demonstrates filtering for specific languages like Python. ```python from server import GitHubMCPServer import os os.environ['GITHUB_TOKEN'] = 'ghp_your_github_token_here' server = GitHubMCPServer() # Scan repository for Python, JavaScript, and PHP files file_list = server.scan_repository( owner="ayushmittal62", repo="vunreability_scanner_testing", extensions=".py,.js,.php,.sql" ) print(f"Found {len(file_list)} files:") for file_path in file_list: if not file_path.startswith("ERROR:"): print(f" - {file_path}") else: print(f"Error: {file_path}") # Analyze only Python files python_files = server.scan_repository( owner="myorg", repo="myproject", extensions=".py" ) # Fetch content for each Python file for py_file in python_files[:5]: # Process first 5 files content = server.get_file_content("myorg", "myproject", py_file) if "import pickle" in content: print(f"⚠️ Insecure deserialization in: {py_file}") ``` -------------------------------- ### Hugging Face CLI Login Source: https://github.com/banno-0720/vulnerability-scanner/blob/main/README.md This command authenticates your local environment with the Hugging Face CLI, which is necessary for accessing private datasets or models, such as the CVE dataset used in this project. ```bash huggingface-cli login ``` -------------------------------- ### Scan Repository for Code Files Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Recursively scans a GitHub repository to identify code files with specific extensions. Returns a list of file paths up to 50 files, useful for batch vulnerability analysis. ```APIDOC ## GET /repositories/{owner}/{repo}/scan ### Description Recursively scans a GitHub repository to identify code files with specific extensions. ### Method GET ### Endpoint `/repositories/{owner}/{repo}/scan` ### Parameters #### Path Parameters - **owner** (string) - Required - The owner of the repository. - **repo** (string) - Required - The name of the repository. #### Query Parameters - **extensions** (string) - Optional - A comma-separated list of file extensions to scan for (e.g., ".py,.js,.php,.sql"). Defaults to scanning common code file types if not provided. #### Request Body None ### Request Example ```python from server import GitHubMCPServer import os os.environ['GITHUB_TOKEN'] = 'ghp_your_github_token_here' server = GitHubMCPServer() file_list = server.scan_repository(owner="ayushmittal62", repo="vunreability_scanner_testing", extensions=".py,.js,.php,.sql") print(f"Found {len(file_list)} files:") for file_path in file_list: if not file_path.startswith("ERROR:"): print(f" - {file_path}") else: print(f"Error: {file_path}") ``` ### Response #### Success Response (200) - **file_paths** (array of strings) - A list of file paths within the repository that match the specified extensions. Returns an error message prefixed with "ERROR:" if the scan fails. #### Response Example ```json { "file_paths": [ "src/main.py", "tests/test_utils.js", "scripts/deploy.php" ] } ``` ``` -------------------------------- ### Visit Webpage Tool (Python) Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Custom tool for AI agents to fetch and convert web pages to Markdown format. Used to scrape CVE details from external vulnerability databases with proper error handling, including rate limiting and exceptions. ```python from client import visit_webpage # Visit CVE details webpage cve_url = "https://www.cvedetails.com/cve/CVE-2023-12345/" markdown_content = visit_webpage(url=cve_url) if not markdown_content.startswith("Error"): print("CVE Details:") print(markdown_content[:1000]) # Print first 1000 characters else: print(f"Failed to fetch: {markdown_content}") # Visit NVD page for CVE nvd_url = "https://nvd.nist.gov/vuln/detail/CVE-2023-12345" nvd_content = visit_webpage(url=nvd_url) # Handle rate limiting and errors try: content = visit_webpage(url="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-12345") if "Error fetching" in content: print("Failed to fetch CVE data - check URL or rate limit") elif len(content) > 5000: print("Content truncated due to length") print(content[-100:]) # Last 100 chars show truncation message except Exception as e: print(f"Exception: {e}") # Use with agent workflow security_page = visit_webpage("https://example.com/security-advisory") # Content is cleaned and formatted for AI processing ``` -------------------------------- ### Multi-Agent Vulnerability Analysis (Python) Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Complete vulnerability analysis workflow using AI agents with MCP tools for GitHub access and CVE research. Generates comprehensive security reports with CVE references and remediation advice. Handles file URLs and repository URLs, and provides error feedback for invalid inputs. ```python from client import analyze_vulnerabilities_multiagent # Analyze a vulnerable Python file message = "https://github.com/ayushmittal62/vunreability_scanner_testing/blob/master/python/database.py" hf_token = "hf_your_huggingface_token_here" history = [] # Chat history for context report = analyze_vulnerabilities_multiagent( message=message, history=history, hf_token=hf_token ) print(report) # Expected report structure: # 🛡️ Security Analysis Report # # ## 🔍 File Overview # - **Path**: python/database.py # - **Repository**: ayushmittal62/vunreability_scanner_testing # # ## 🚨 Vulnerabilities Found # 1. **SQL Injection** (Line 23) # - Code: `cursor.execute(f"SELECT * FROM users WHERE id={user_id}")` # - Risk: CRITICAL # # ## 📊 CVE Research # **Top Related CVE**: CVE-2023-12345 # **CVSS Score**: 9.8 (CRITICAL) # **Attack Vector**: Network # # ## 🛠️ Remediation # - Use parameterized queries # - Implement input validation # Analyze SQL file sql_message = "https://github.com/ayushmittal62/vunreability_scanner_testing/blob/master/database/schema.sql" sql_report = analyze_vulnerabilities_multiagent(sql_message, [], hf_token) # Handle errors invalid_url = "https://github.com/user/repo" # Repository URL without file error_response = analyze_vulnerabilities_multiagent(invalid_url, [], hf_token) if "❌" in error_response: print("Error in analysis:", error_response) ``` -------------------------------- ### Fetch GitHub File Content using Python Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Fetches the content of a specified file from a GitHub repository. Handles base64 encoding from the GitHub API and returns plain text. Includes error handling for binary files and a check for dangerous functions like 'exec()' or 'eval()'. Requires a GitHub token. ```python from server import GitHubMCPServer import os os.environ['GITHUB_TOKEN'] = 'ghp_your_github_token_here' server = GitHubMCPServer() # Get file content from repository content = server.get_file_content( owner="octocat", repo="Hello-World", path="README.md" ) if not content.startswith("ERROR:"): print("File Content:") print(content[:500]) # Print first 500 characters else: print(content) # Example with vulnerable Python file vulnerable_content = server.get_file_content( owner="ayushmittal62", repo="vunreability_scanner_testing", path="python/database.py" ) # Check for security issues in the content if "exec(" in vulnerable_content or "eval(" in vulnerable_content: print("⚠️ Warning: Dangerous functions detected") ``` -------------------------------- ### Scanning Repository Files with AI Agent Source: https://github.com/banno-0720/vulnerability-scanner/blob/main/VISUAL_WORKFLOW.md This snippet illustrates the AI agent's capability to scan a repository for specific file types. The 'scan_repository' tool is used with the owner, repository name, and file extension as parameters, returning a list of file paths matching the criteria. ```Python agent.call("scan_repository", owner="user", repo="repo", file_extension=".py") # Returns: ["main.py", "database.py", "utils.py", "config.py"] ``` -------------------------------- ### Simple CVE Search for Multi-Agent Workflows Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Provides a lightweight CVE search function optimized for multi-agent systems, returning concise results that are easily parsable. It allows specifying the number of results and extracting CVE IDs programmatically. ```python from server import GitHubMCPServer import os import re os.environ['GITHUB_TOKEN'] = 'ghp_your_github_token_here' server = GitHubMCPServer() # Simple search for SQL injection (default 3 results) simple_results = server.simple_cve_search(query="SQL injection", k=3) print(simple_results) # Extract CVE IDs programmatically cve_pattern = r'CVE-\d{4}-\d+' cve_ids = re.findall(cve_pattern, simple_results) print(f"Found CVE IDs: {cve_ids}") # Use in multi-agent workflow search_results = server.simple_cve_search(query="XSS JavaScript", k=5) # Agent can parse the string result directly for cve_id in re.findall(cve_pattern, search_results): print(f"Processing: {cve_id}") ``` -------------------------------- ### Search CVE Database and Parse IDs Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Searches the CVE knowledge base for specific vulnerabilities and extracts CVE IDs from the results using regular expressions. Designed for initial vulnerability discovery and subsequent detailed analysis. ```python sql_results = server.search_cve_database(query="SQL injection") print(sql_results) import re cve_pattern = r'CVE-\d{4}-\d{4,7}' cve_ids = re.findall(cve_pattern, sql_results) print(f"\nFound CVE IDs: {cve_ids}") xss_results = server.search_cve_database(query="cross-site scripting XSS") print(xss_results) cmd_results = server.search_cve_database(query="command injection exec") print(cmd_results) ``` -------------------------------- ### Analyze Python Code for Command Injection Source: https://github.com/banno-0720/vulnerability-scanner/blob/main/VISUAL_WORKFLOW.md This snippet demonstrates the process of retrieving Python file content and analyzing it for command injection vulnerabilities. It involves using placeholder functions for file retrieval and vulnerability searching, suitable for integration into a larger security analysis tool. ```python get_file_content("user", "repo", "utils.py") Analyzes for command injection search_and_fetch_cve_details("command injection", 3) ``` -------------------------------- ### CVE Data Fetching using Search and NVD API Source: https://github.com/banno-0720/vulnerability-scanner/blob/main/VISUAL_WORKFLOW.md This function simulates fetching CVE details for a given vulnerability type. It first searches a CVE database using BM25, then parses CVE IDs using regex, and finally retrieves detailed information from the NVD API for each identified CVE, including CVSS scores and attack vectors. Rate limiting is applied between NVD API calls. ```python # This is a conceptual representation of the search_and_fetch_cve_details function. # Actual implementation would involve database queries, regex, and HTTP requests. def search_and_fetch_cve_details(vulnerability_type, max_results): # Sub-Step 1: Search CVE Database (RAG) # BM25Retriever searches 10,000+ CVE records # Returns top 10 matches for "SQL injection" # Result includes: CVE IDs, CWE codes, CVSS scores cve_search_results = bm25_search(vulnerability_type, 10) # Sub-Step 2: Parse CVE IDs # Regex: CVE-\d{4}-\d{4,7} # Extracts: CVE-2019-16515, CVE-2020-12345, etc. # Removes duplicates # Takes top 5 cve_ids = parse_cve_ids(cve_search_results, max_results) # Sub-Step 3: Fetch NVD Details (Loop for each CVE) all_cve_details = [] for cve_id in cve_ids: # GET NVD API with cveId parameter nvd_data = get_nvd_data(cve_id) # Parse JSON response # Extract CVSS v3 score, attack vector, CWE codes # Format with NVD URL formatted_details = format_nvd_details(cve_id, nvd_data) all_cve_details.append(formatted_details) # Wait 6 seconds (rate limiting) time.sleep(6) # Sub-Step 4: Combine Results return combine_results(all_cve_details) ``` -------------------------------- ### Fetch NVD CVE Details with Rate Limiting Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Retrieves detailed vulnerability information from the National Vulnerability Database (NVD) for a given CVE ID. Includes rate limiting with delays to comply with NVD API usage policies and handles non-existent CVEs. ```python from server import GitHubMCPServer import os import time os.environ['GITHUB_TOKEN'] = 'ghp_your_github_token_here' server = GitHubMCPServer() # Get detailed information about a specific CVE cve_details = server.get_nvd_cve_details(cve_id="CVE-2019-16515") print(cve_details) # Handle errors gracefully invalid_cve = server.get_nvd_cve_details(cve_id="CVE-9999-9999") if "⚠️ CVE not found" in invalid_cve: print("CVE does not exist in NVD database") # Get multiple CVE details with rate limiting cve_list = ["CVE-2023-1234", "CVE-2023-5678", "CVE-2023-9012"] for cve_id in cve_list: details = server.get_nvd_cve_details(cve_id) print(f"\n{details}\n") time.sleep(6) # NVD recommends 6 second delay between requests ``` -------------------------------- ### Enable Debug Mode (Bash) Source: https://github.com/banno-0720/vulnerability-scanner/blob/main/README.md This command enables debug output for the vulnerability scanner client. It involves setting the DEBUG environment variable to 'true' before executing the client script. ```bash DEBUG=true python client.py ``` -------------------------------- ### Comprehensive CVE Analysis (RAG + NVD) Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Performs a combined vulnerability analysis by first searching a CVE knowledge base and then fetching detailed NVD information for a specified number of top results. This provides both a broad overview and deep insights into vulnerabilities. ```python from server import GitHubMCPServer import os os.environ['GITHUB_TOKEN'] = 'ghp_your_github_token_here' server = GitHubMCPServer() # Comprehensive analysis of SQL injection vulnerabilities comprehensive_analysis = server.search_and_fetch_cve_details( query="SQL injection PHP MySQL", max_nvd_fetches=3 ) print(comprehensive_analysis) # Analyze command injection vulnerabilities cmd_injection_analysis = server.search_and_fetch_cve_details( query="command injection Python os.system", max_nvd_fetches=5 ) # Analyze XSS vulnerabilities in JavaScript xss_analysis = server.search_and_fetch_cve_details( query="cross-site scripting JavaScript innerHTML", max_nvd_fetches=3 ) ``` -------------------------------- ### Parse GitHub URL (Python) Source: https://context7.com/banno-0720/vulnerability-scanner/llms.txt Utility function to extract owner, repository name, and file path from GitHub URLs. Supports both repository URLs and file blob URLs. Handles invalid URL formats gracefully by returning None for owner. ```python from client import parse_github_url # Parse repository URL owner, repo, file_path = parse_github_url("https://github.com/octocat/Hello-World") print(f"Owner: {owner}, Repo: {repo}, File: {file_path}") # Output: Owner: octocat, Repo: Hello-World, File: None # Parse file URL owner, repo, file_path = parse_github_url( "https://github.com/ayushmittal62/vunreability_scanner_testing/blob/master/python/database.py" ) print(f"Owner: {owner}, Repo: {repo}, File: {file_path}") # Output: Owner: ayushmittal62, Repo: vunreability_scanner_testing, File: python/database.py # Handle invalid URLs owner, repo, file_path = parse_github_url("https://invalid-url.com/test") if owner is None: print("Invalid GitHub URL") # Validate URL before analysis url = "https://github.com/user/project/blob/main/src/app.py" owner, repo, file_path = parse_github_url(url) if owner and repo and file_path: print(f"Valid file URL for analysis: {file_path}") elif owner and repo: print("Repository URL - need specific file URL") else: print("Invalid URL format") ``` -------------------------------- ### Check Python Code for Hardcoded Secrets Source: https://github.com/banno-0720/vulnerability-scanner/blob/main/VISUAL_WORKFLOW.md This snippet illustrates the function of checking Python files for hardcoded secrets. It includes a placeholder function for retrieving file content and implies a subsequent analysis step to identify sensitive information within the code. ```python get_file_content("user", "repo", "config.py") Checks for hardcoded secrets ``` -------------------------------- ### Python Database Interaction with SQL Injection Vulnerability Source: https://github.com/banno-0720/vulnerability-scanner/blob/main/VISUAL_WORKFLOW.md This Python code snippet demonstrates connecting to an SQLite database and fetching user data. It is vulnerable to SQL injection due to direct string concatenation in the SQL query and lack of input validation for the username parameter. ```python import sqlite3 def get_user(username): conn = sqlite3.connect('db.sqlite') query = "SELECT * FROM users WHERE name='" + username + "'" cursor = conn.execute(query) # ⚠️ VULNERABLE! return cursor.fetchone() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.