File size: 11,916 Bytes
4f21d95
 
 
 
 
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
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
#!/usr/bin/env python3
"""
MCP server for Bandit - a tool for finding common security issues in Python code
"""

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

def bandit_scan(
    code_input: str,
    scan_type: str = "code",
    severity_level: str = "low",
    confidence_level: str = "low",
    output_format: str = "json"
) -> Dict:
    """
    Analyzes Python code for security issues using Bandit.
    
    Args:
        code_input (str): Python code for analysis or path to file/directory
        scan_type (str): Scan type - 'code' for direct code or 'path' for file/directory
        severity_level (str): Minimum severity level - 'low', 'medium', 'high'
        confidence_level (str): Minimum confidence level - 'low', 'medium', 'high'
        output_format (str): Output format - 'json', 'txt', 'xml'
    
    Returns:
        Dict: Security analysis results
    """
    try:
        # Create temporary file or use existing path
        if scan_type == "code":
            # Create temporary file with code
            with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as tmp_file:
                tmp_file.write(code_input)
                target_path = tmp_file.name
        else:
            # Use existing path
            target_path = code_input
            if not os.path.exists(target_path):
                return {
                    "error": f"Path not found: {target_path}",
                    "success": False
                }
        
        # Build bandit command
        cmd = ["bandit"]
        
        # Add severity level flags
        if severity_level == "medium":
            cmd.append("-ll")
        elif severity_level == "high":
            cmd.append("-lll")
        
        # Add confidence level flags
        if confidence_level == "medium":
            cmd.append("-ii")
        elif confidence_level == "high":
            cmd.append("-iii")
        
        # Add output format
        if output_format == "json":
            cmd.extend(["-f", "json"])
        elif output_format == "xml":
            cmd.extend(["-f", "xml"])
        
        # Add recursive scanning for directories
        if scan_type == "path" and os.path.isdir(target_path):
            cmd.append("-r")
        
        # Add scan target path
        cmd.append(target_path)
        
        # Execute command
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        # Remove temporary file if created
        if scan_type == "code":
            try:
                os.unlink(target_path)
            except:
                pass
        
        # Process result
        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 Bandit: {str(e)}"
        }

def bandit_baseline(
    target_path: str,
    baseline_file: str
) -> Dict:
    """
    Creates baseline file for Bandit or compares with existing baseline.
    
    Args:
        target_path (str): Path to code for analysis
        baseline_file (str): Path to baseline file
    
    Returns:
        Dict: Result of baseline creation or comparison
    """
    try:
        if not os.path.exists(target_path):
            return {
                "error": f"Path not found: {target_path}",
                "success": False
            }
        
        # If baseline file doesn't exist, create it
        if not os.path.exists(baseline_file):
            cmd = ["bandit", "-r", target_path, "-f", "json", "-o", baseline_file]
            result = subprocess.run(cmd, capture_output=True, text=True)
            
            return {
                "success": True,
                "action": "created",
                "message": f"Baseline file created: {baseline_file}",
                "return_code": result.returncode,
                "stderr": result.stderr
            }
        else:
            # Compare with existing baseline
            cmd = ["bandit", "-r", target_path, "-b", baseline_file, "-f", "json"]
            result = subprocess.run(cmd, capture_output=True, text=True)
            
            try:
                output_data = json.loads(result.stdout) if result.stdout else {}
                return {
                    "success": True,
                    "action": "compared",
                    "results": output_data,
                    "return_code": result.returncode,
                    "stderr": result.stderr
                }
            except json.JSONDecodeError:
                return {
                    "success": False,
                    "error": "JSON parsing error when comparing with baseline",
                    "stdout": result.stdout,
                    "stderr": result.stderr
                }
                
    except Exception as e:
        return {
            "success": False,
            "error": f"Error working with baseline: {str(e)}"
        }

def bandit_profile_scan(
    target_path: str,
    profile_name: str = "ShellInjection"
) -> Dict:
    """
    Runs Bandit with a specific security profile.
    
    Args:
        target_path (str): Path to code for analysis
        profile_name (str): Profile name (e.g., 'ShellInjection')
    
    Returns:
        Dict: Analysis results using the profile
    """
    try:
        if not os.path.exists(target_path):
            return {
                "error": f"Path not found: {target_path}",
                "success": False
            }
        
        cmd = ["bandit", "-p", profile_name, "-f", "json"]
        
        if os.path.isdir(target_path):
            cmd.extend(["-r", target_path])
        else:
            cmd.append(target_path)
        
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        try:
            output_data = json.loads(result.stdout) if result.stdout else {}
            return {
                "success": True,
                "profile": profile_name,
                "results": output_data,
                "return_code": result.returncode,
                "stderr": result.stderr
            }
        except json.JSONDecodeError:
            return {
                "success": False,
                "error": "JSON parsing error",
                "stdout": result.stdout,
                "stderr": result.stderr
            }
            
    except Exception as e:
        return {
            "success": False,
            "error": f"Error executing profile scan: {str(e)}"
        }

# Create Gradio interfaces
with gr.Blocks(title="Bandit Security Scanner MCP") as demo:
    gr.Markdown("# 🔒 Bandit Security Scanner")
    gr.Markdown("Python code security analyzer 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 Python code or path to file/directory...",
                    label="Code or Path"
                )
                severity = gr.Dropdown(
                    choices=["low", "medium", "high"],
                    value="low",
                    label="Minimum Severity Level"
                )
                confidence = gr.Dropdown(
                    choices=["low", "medium", "high"],
                    value="low", 
                    label="Minimum Confidence Level"
                )
                output_format = gr.Dropdown(
                    choices=["json", "txt"],
                    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=bandit_scan,
            inputs=[code_input, scan_type, severity, confidence, output_format],
            outputs=scan_output
        )
    
    with gr.Tab("Baseline Management"):
        with gr.Row():
            with gr.Column():
                baseline_path = gr.Textbox(
                    label="Project Path",
                    placeholder="/path/to/your/project"
                )
                baseline_file = gr.Textbox(
                    label="Baseline File Path",
                    placeholder="/path/to/baseline.json"
                )
                baseline_btn = gr.Button("📋 Create/Compare Baseline", variant="secondary")
            
            with gr.Column():
                baseline_output = gr.JSON(label="Baseline Results")
        
        baseline_btn.click(
            fn=bandit_baseline,
            inputs=[baseline_path, baseline_file],
            outputs=baseline_output
        )
    
    with gr.Tab("Profile Scanning"):
        with gr.Row():
            with gr.Column():
                profile_path = gr.Textbox(
                    label="Project Path",
                    placeholder="/path/to/your/project"
                )
                profile_name = gr.Dropdown(
                    choices=["ShellInjection", "SqlInjection", "Crypto", "Subprocess"],
                    value="ShellInjection",
                    label="Security Profile"
                )
                profile_btn = gr.Button("🎯 Scan with Profile", variant="secondary")
            
            with gr.Column():
                profile_output = gr.JSON(label="Profile Scan Results")
        
        profile_btn.click(
            fn=bandit_profile_scan,
            inputs=[profile_path, profile_name],
            outputs=profile_output
        )
    
    with gr.Tab("Examples"):
        gr.Markdown("""
        ## 🚨 Vulnerable code examples for testing:
        
        ### 1. Using eval()
        ```python
        user_input = "print('hello')"
        eval(user_input)  # B307: Use of possibly insecure function
        ```
        
        ### 2. Hardcoded password
        ```python
        password = "secret123"  # B105: Possible hardcoded password
        ```
        
        ### 3. Insecure subprocess
        ```python
        import subprocess
        subprocess.call("ls -la", shell=True)  # B602: subprocess call with shell=True
        ```
        
        ### 4. Using pickle
        ```python
        import pickle
        data = pickle.loads(user_data)  # B301: Pickle usage
        ```
        """)

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