Buckets:

download
raw
5.66 kB
"""
Tool Execution Routes
"""
import asyncio
import logging
from typing import Any, Optional
from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from api.schemas import ToolExecuteRequest, ToolExecuteResponse
from api.security_logging import sanitize_for_log
router = APIRouter(prefix="/tools", tags=["Tools"])
security = HTTPBearer()
logger = logging.getLogger(__name__)
# Import verify_token from auth module
try:
from .auth import optional_auth, verify_token
except ImportError:
from api.auth_simple import verify_token as legacy_verify_token
async def verify_token(
credentials: HTTPAuthorizationCredentials = Depends(security),
):
user = legacy_verify_token(credentials.credentials)
if not user:
raise HTTPException(status_code=401, detail="Invalid token")
return user
async def optional_auth(
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
):
if not credentials:
return None
return legacy_verify_token(credentials.credentials)
# Tool registry
TOOL_REGISTRY = {
"nmap": {
"name": "nmap",
"category": "network",
"description": "Network port scanner",
"safe": True,
},
"sqlmap": {
"name": "sqlmap",
"category": "web",
"description": "SQL injection scanner",
"safe": False,
},
"nikto": {
"name": "nikto",
"category": "web",
"description": "Web vulnerability scanner",
"safe": True,
},
"gobuster": {
"name": "gobuster",
"category": "web",
"description": "Directory/file brute forcer",
"safe": True,
},
"subfinder": {
"name": "subfinder",
"category": "recon",
"description": "Subdomain discovery tool",
"safe": True,
},
"httpx": {
"name": "httpx",
"category": "web",
"description": "Fast HTTP prober",
"safe": True,
},
"nuclei": {
"name": "nuclei",
"category": "web",
"description": "Vulnerability scanner",
"safe": True,
},
}
def get_tool_category(tool_name: str) -> str:
"""Get the category of a tool"""
tool = TOOL_REGISTRY.get(tool_name.lower())
return tool["category"] if tool else "unknown"
async def execute_nmap(target: str, options: dict) -> dict:
"""Execute nmap scan"""
await asyncio.sleep(2) # Simulate execution
return {
"tool": "nmap",
"target": target,
"open_ports": [80, 443, 8080],
"status": "completed",
}
async def execute_sqlmap(target: str, options: dict) -> dict:
"""Execute sqlmap scan"""
await asyncio.sleep(3)
return {
"tool": "sqlmap",
"target": target,
"vulnerabilities": [],
"status": "completed",
}
async def execute_nikto(target: str, options: dict) -> dict:
"""Execute nikto scan"""
await asyncio.sleep(2)
return {
"tool": "nikto",
"target": target,
"findings": [],
"status": "completed",
}
@router.post("/execute", response_model=ToolExecuteResponse)
async def execute_tool(request: ToolExecuteRequest, user: Any = Depends(verify_token)):
"""Execute a security tool"""
tool_name = request.tool.lower()
if tool_name not in TOOL_REGISTRY:
raise HTTPException(status_code=400, detail=f"Unknown tool: {request.tool}")
# Check if tool requires elevated permissions
tool_info = TOOL_REGISTRY[tool_name]
if not tool_info.get("safe", True):
# Log potentially dangerous tool execution
logger.warning(f"Executing potentially dangerous tool: {sanitize_for_log(tool_name)}")
try:
# Execute the tool
if tool_name == "nmap":
result = await execute_nmap(request.target, request.options or {})
elif tool_name == "sqlmap":
result = await execute_sqlmap(request.target, request.options or {})
elif tool_name == "nikto":
result = await execute_nikto(request.target, request.options or {})
else:
# Generic execution for other tools
await asyncio.sleep(1)
result = {
"tool": tool_name,
"target": request.target,
"status": "completed",
"message": "Tool execution completed",
}
return {
"tool": request.tool,
"target": request.target,
"status": "completed",
"output": result,
"execution_time": 1.0,
}
except Exception as e:
logger.error(f"Tool execution failed: {sanitize_for_log(str(e))}")
raise HTTPException(status_code=500, detail=f"Tool execution failed: {str(e)}")
@router.get("/")
async def list_tools(user: Optional[dict] = Depends(optional_auth)):
"""List available tools with their categories"""
tools = []
for tool_id, tool_info in TOOL_REGISTRY.items():
tools.append(
{
"id": tool_id,
"name": tool_info["name"],
"category": tool_info["category"],
"description": tool_info["description"],
"safe": tool_info.get("safe", True),
}
)
# Group by category
categories = {}
for tool in tools:
cat = tool["category"]
if cat not in categories:
categories[cat] = []
categories[cat].append(tool)
return {"tools": tools, "categories": categories, "total": len(tools)}

Xet Storage Details

Size:
5.66 kB
·
Xet hash:
95204f9a21ed6e2be4d5c2d3e30e4c7dea23296cdf12e7cda80a620b2b6db685

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.