File size: 7,264 Bytes
4801adf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f21d95
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
MCP server for Semgrep - a tool for static analysis of code
"""

import gradio as gr
import subprocess
import json
import os
import tempfile
from typing import Dict, List, Optional
from pathlib import Path

def semgrep_scan(
    code_input: str,
    scan_type: str = "code",
    rules: str = "p/default",
    output_format: str = "json"
) -> Dict:
    """
    Сканирует код с помощью Semgrep.
    
    Args:
        code_input (str): Код для сканирования или путь к файлу/директории
        scan_type (str): Тип сканирования - 'code' для прямого кода или 'path' для файла/директории
        rules (str): Правила для сканирования (например, 'p/default' или путь к файлу правил)
        output_format (str): Формат вывода - 'json' или 'text'
    
    Returns:
        Dict: Результаты сканирования
    """
    try:
        # Создаем временный файл или используем существующий путь
        if scan_type == "code":
            # Создаем временный файл с кодом
            with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as tmp_file:
                tmp_file.write(code_input)
                target_path = tmp_file.name
        else:
            # Используем существующий путь
            target_path = code_input
            if not os.path.exists(target_path):
                return {
                    "error": f"Path not found: {target_path}",
                    "success": False
                }
        
        # Строим команду semgrep
        cmd = ["semgrep", "scan"]
        
        # Добавляем правила
        cmd.extend(["--config", rules])
        
        # Добавляем формат вывода
        if output_format == "json":
            cmd.extend(["--json"])
        
        # Добавляем путь для сканирования
        cmd.append(target_path)
        
        # Выполняем команду
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        # Удаляем временный файл, если он был создан
        if scan_type == "code":
            try:
                os.unlink(target_path)
            except:
                pass
        
        # Обрабатываем результат
        if output_format == "json":
            try:
                output_data = json.loads(result.stdout) if result.stdout else {}
                return {
                    "success": True,
                    "results": output_data,
                    "stderr": result.stderr,
                    "return_code": result.returncode
                }
            except json.JSONDecodeError:
                return {
                    "success": False,
                    "error": "JSON parsing error",
                    "stdout": result.stdout,
                    "stderr": result.stderr,
                    "return_code": result.returncode
                }
        else:
            return {
                "success": True,
                "output": result.stdout,
                "stderr": result.stderr,
                "return_code": result.returncode
            }
            
    except Exception as e:
        return {
            "success": False,
            "error": f"Error executing Semgrep: {str(e)}"
        }

def semgrep_list_rules() -> Dict:
    """
    Получает список доступных правил Semgrep.
    
    Returns:
        Dict: Список правил
    """
    try:
        cmd = ["semgrep", "list-rules"]
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode == 0:
            rules = []
            for line in result.stdout.split('\n'):
                if line.strip():
                    rules.append(line.strip())
            return {
                "success": True,
                "rules": rules
            }
        else:
            return {
                "success": False,
                "error": f"Error listing rules: {result.stderr}"
            }
            
    except Exception as e:
        return {
            "success": False,
            "error": f"Error executing Semgrep: {str(e)}"
        }

# Создаем Gradio интерфейс
with gr.Blocks(title="Semgrep MCP") as demo:
    gr.Markdown("# 🔍 Semgrep Scanner")
    gr.Markdown("Static analysis tool with MCP support")
    
    with gr.Tab("Basic Scanning"):
        with gr.Row():
            with gr.Column():
                scan_type = gr.Radio(
                    choices=["code", "path"],
                    value="code",
                    label="Scan Type"
                )
                code_input = gr.Textbox(
                    lines=10,
                    placeholder="Enter code or path to scan...",
                    label="Code or Path"
                )
                rules = gr.Textbox(
                    value="p/default",
                    label="Rules (e.g., p/default or path to rules file)"
                )
                output_format = gr.Dropdown(
                    choices=["json", "text"],
                    value="json",
                    label="Output Format"
                )
                scan_btn = gr.Button("🔍 Scan", variant="primary")
            
            with gr.Column():
                scan_output = gr.JSON(label="Scan Results")
        
        scan_btn.click(
            fn=semgrep_scan,
            inputs=[code_input, scan_type, rules, output_format],
            outputs=scan_output
        )
    
    with gr.Tab("Available Rules"):
        rules_btn = gr.Button("📋 List Rules", variant="secondary")
        rules_output = gr.JSON(label="Available Rules")
        
        rules_btn.click(
            fn=semgrep_list_rules,
            inputs=[],
            outputs=rules_output
        )
    
    with gr.Tab("Examples"):
        gr.Markdown("""
        ## 🚨 Examples of code to scan:
        
        ### 1. SQL Injection
        ```python
        def get_user(user_id):
            query = f"SELECT * FROM users WHERE id = {user_id}"
            return db.execute(query)
        ```
        
        ### 2. Command Injection
        ```python
        import subprocess
        def run_command(command):
            subprocess.call(f"ls {command}", shell=True)
        ```
        
        ### 3. Path Traversal
        ```python
        def read_file(filename):
            with open(f"/home/user/{filename}", "r") as f:
                return f.read()
        ```
        """)

if __name__ == "__main__":
    # Получаем настройки сервера из переменных окружения
    server_name = os.getenv("GRADIO_SERVER_NAME", "0.0.0.0")
    server_port = int(os.getenv("GRADIO_SERVER_PORT", "7865"))
    
    demo.launch(
        mcp_server=True,
        server_name=server_name,
        server_port=server_port,
        share=False
    )