1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
| from typing import Any, Dict, Optional, List import uuid import asyncio import subprocess import os import re from enum import Enum from mcp.server.fastmcp import FastMCP
mcp = FastMCP("sqlmap")
tasks: Dict[str, Dict[str, Any]] = {} SQLMAP_PATH = "D:\\tools\\sqlmap\\sqlmap.py"
class ScanStatus(Enum): QUEUED = "queued" RUNNING = "running" COMPLETED = "completed" FAILED = "failed"
async def run_sqlmap_scan(task_id: str, target_url: str, options: Dict[str, Any]) -> None: """异步执行sqlmap扫描并实时捕获输出""" try: if task_id not in tasks: return
cmd = [ "python", SQLMAP_PATH, "-u", target_url, "--batch" ]
if options: for key, value in options.items(): if isinstance(value, bool) and value: cmd.append(f"--{key}") elif isinstance(value, (int, float)): cmd.append(f"--{key}={value}") elif isinstance(value, str): cmd.append(f"--{key}={value}")
tasks[task_id]["status"] = ScanStatus.RUNNING.value tasks[task_id]["command"] = " ".join(cmd) tasks[task_id]["output"] = "" tasks[task_id]["critical_lines"] = [] tasks[task_id]["vulnerabilities"] = []
process = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE )
while True: stdout_line = await process.stdout.readline() if stdout_line: line = stdout_line.decode('utf-8', errors='ignore').rstrip() tasks[task_id]["output"] += line + "\n"
if "[CRITICAL]" in line: tasks[task_id]["critical_lines"].append(line)
if "is vulnerable" in line and "parameter" in line: parts = line.split() if len(parts) > 3: param = parts[1].strip("'") vuln_type = " ".join(parts[3:]) tasks[task_id]["vulnerabilities"].append({ "parameter": param, "type": vuln_type })
stderr_line = await process.stderr.readline() if stderr_line: line = stderr_line.decode('utf-8', errors='ignore').rstrip() tasks[task_id]["output"] += "[ERROR] " + line + "\n" if "errors" not in tasks[task_id]: tasks[task_id]["errors"] = [] tasks[task_id]["errors"].append(line)
if process.stdout.at_eof() and process.stderr.at_eof(): break
return_code = await process.wait()
if return_code == 0: tasks[task_id]["status"] = ScanStatus.COMPLETED.value parse_scan_results_from_output(task_id) else: tasks[task_id]["status"] = ScanStatus.FAILED.value
tasks[task_id]["return_code"] = return_code tasks[task_id]["end_time"] = asyncio.get_event_loop().time()
except Exception as e: if task_id in tasks: tasks[task_id].update({ "status": ScanStatus.FAILED.value, "error": str(e), "end_time": asyncio.get_event_loop().time() })
def parse_scan_results_from_output(task_id: str) -> None: """改进的sqlmap输出解析器,处理各种格式""" try: if "output" not in tasks[task_id]: return
output = tasks[task_id]["output"] results = []
injection_points = re.findall( r"Parameter: (.+?) \(.+?\)\n((?:\s+Type: .+?\n\s+Title: .+?\n\s+Payload: .+?\n)+)", output, re.DOTALL )
for param, vuln_block in injection_points: vulns = re.findall( r"\s+Type: (.+?)\n\s+Title: (.+?)\n\s+Payload: (.+?)\n", vuln_block, re.DOTALL ) for vuln in vulns: vuln_type, title, payload = vuln results.append({ "parameter": param, "type": vuln_type.strip(), "title": title.strip(), "payload": payload.strip() })
if not results: alt_points = re.findall( r"(\w+) parameter '(.+?)' (is vulnerable.+)", output ) for method, param, details in alt_points: results.append({ "parameter": param, "type": f"{method} - {details}" })
db_info = re.search( r"back-end DBMS: (.+?)\n", output ) if db_info: results.append({ "type": "DBMS", "info": db_info.group(1).strip() })
if "critical_lines" in tasks[task_id]: for line in tasks[task_id]["critical_lines"]: if "is vulnerable" in line: results.append({ "type": "CRITICAL", "info": line.replace("[CRITICAL] ", "") })
if "vulnerabilities" in tasks[task_id]: for vuln in tasks[task_id]["vulnerabilities"]: if not any(r.get("parameter") == vuln["parameter"] for r in results): results.append(vuln)
if results: tasks[task_id]["results"] = results
except Exception as e: if task_id in tasks: tasks[task_id]["parse_error"] = str(e)
@mcp.tool() async def start_scan(target_url: str, options: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: """启动一个新的SQLMap扫描任务
Args: target_url: 要扫描的URL options: 额外的sqlmap选项 (例如 {"level": 3, "risk": 2}) """ task_id = str(uuid.uuid4())
try: tasks[task_id] = { "status": ScanStatus.QUEUED.value, "target_url": target_url, "options": options or {}, "start_time": asyncio.get_event_loop().time(), "output": "", "results": None }
asyncio.create_task(run_sqlmap_scan(task_id, target_url, options or {}))
return { "task_id": task_id, "message": f"已开始扫描 {target_url}", "status_url": f"/scan/status/{task_id}" }
except Exception as e: return { "task_id": task_id, "error": f"无法启动扫描: {str(e)}", "status": ScanStatus.FAILED.value }
@mcp.tool() async def get_scan_status(task_id: str) -> Dict[str, Any]: """获取扫描任务的状态
Args: task_id: 扫描任务的ID """ if task_id not in tasks: return {"error": "无效的任务ID"}
task = tasks[task_id] status = { "task_id": task_id, "status": task["status"], "target_url": task["target_url"], }
current_time = asyncio.get_event_loop().time() if "start_time" in task: elapsed = current_time - task["start_time"] status["elapsed_time"] = f"{elapsed:.2f}s"
if "results" in task and task["results"]: status["results"] = task["results"]
if task["status"] == ScanStatus.RUNNING.value and "output" in task: lines = task["output"].splitlines() status["partial_output"] = "\n".join(lines[-20:])
if task["status"] == ScanStatus.COMPLETED.value: if "output" in task: summary = re.search( r"sqlmap identified the following injection point\(s\):(.+?)\n\n", task["output"], re.DOTALL ) if summary: status["summary"] = summary.group(1).strip() else: status["summary"] = "未发现漏洞" if not task.get("results") else "发现漏洞"
if task["status"] == ScanStatus.FAILED.value: if "error" in task: status["error"] = task["error"] elif "errors" in task and task["errors"]: status["error"] = task["errors"][-1] elif "output" in task: error_match = re.search(r"\[ERROR\] (.+)", task["output"]) if error_match: status["error"] = error_match.group(1)
if "command" in task: status["command"] = task["command"]
return status
@mcp.tool() async def list_scans(include_completed: bool = True) -> Dict[str, Any]: """列出所有扫描任务
Args: include_completed: 是否包含已完成的任务 """ active_tasks = [] completed_tasks = []
for task_id, task in tasks.items(): task_info = { "task_id": task_id, "status": task["status"], "target_url": task["target_url"], "start_time": task.get("start_time", 0) }
if task["status"] in [ScanStatus.QUEUED.value, ScanStatus.RUNNING.value]: active_tasks.append(task_info) elif include_completed and task["status"] in [ScanStatus.COMPLETED.value, ScanStatus.FAILED.value]: task_info["end_time"] = task.get("end_time", 0) completed_tasks.append(task_info)
return { "active_tasks": active_tasks, "completed_tasks": completed_tasks }
if __name__ == "__main__": mcp.run(transport='stdio')
|