-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathserver.py
More file actions
633 lines (532 loc) · 19.4 KB
/
server.py
File metadata and controls
633 lines (532 loc) · 19.4 KB
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
#!/usr/bin/env python3
"""
Gitleaks MCP Server
A Model Context Protocol server that provides secrets detection
capabilities using Gitleaks.
Tools:
- gitleaks_scan_repo: Scan a git repository for secrets
- gitleaks_scan_dir: Scan a directory for secrets
- gitleaks_detect: Quick scan provided content for secrets
- get_scan_results: Retrieve previous scan results
- list_active_scans: Show running scans
"""
import asyncio
import json
import logging
import os
import tempfile
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import (
Resource,
TextContent,
Tool,
)
from pydantic import BaseModel, Field
from pydantic_settings import BaseSettings
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger("gitleaks-mcp")
class Settings(BaseSettings):
"""Server configuration from environment variables."""
output_dir: str = Field(default="/app/output", alias="GITLEAKS_OUTPUT_DIR")
default_timeout: int = Field(default=300, alias="GITLEAKS_TIMEOUT")
max_concurrent_scans: int = Field(default=2, alias="GITLEAKS_MAX_CONCURRENT")
class Config:
env_prefix = "GITLEAKS_"
settings = Settings()
class SecretFinding(BaseModel):
"""Model for a single secret finding."""
rule_id: str
description: str | None = None
secret: str | None = None
file: str | None = None
line: int | None = None
start_column: int | None = None
end_column: int | None = None
commit: str | None = None
author: str | None = None
email: str | None = None
date: str | None = None
message: str | None = None
fingerprint: str | None = None
tags: list[str] = []
class ScanResult(BaseModel):
"""Model for scan results."""
scan_id: str
target: str
scan_type: str
started_at: datetime
completed_at: datetime | None = None
status: str = "running"
findings: list[SecretFinding] = []
stats: dict[str, Any] = {}
error: str | None = None
raw_output: str | None = None
# In-memory storage for scan results
scan_results: dict[str, ScanResult] = {}
active_scans: set[str] = set()
def parse_gitleaks_json(output: str) -> list[SecretFinding]:
"""Parse gitleaks JSON output into findings."""
findings = []
try:
data = json.loads(output)
if isinstance(data, list):
for item in data:
finding = SecretFinding(
rule_id=item.get("RuleID", "unknown"),
description=item.get("Description"),
secret=mask_secret(item.get("Secret", "")),
file=item.get("File"),
line=item.get("StartLine"),
start_column=item.get("StartColumn"),
end_column=item.get("EndColumn"),
commit=item.get("Commit"),
author=item.get("Author"),
email=item.get("Email"),
date=item.get("Date"),
message=item.get("Message"),
fingerprint=item.get("Fingerprint"),
tags=item.get("Tags", []),
)
findings.append(finding)
except json.JSONDecodeError:
logger.warning("Failed to parse gitleaks JSON output")
return findings
def mask_secret(secret: str, visible_chars: int = 4) -> str:
"""Mask a secret, showing only first few characters."""
if not secret or len(secret) <= visible_chars:
return "****"
return secret[:visible_chars] + "*" * (len(secret) - visible_chars)
async def run_gitleaks_scan(
target: str,
scan_type: str = "dir",
timeout: int | None = None,
no_git: bool = False,
) -> ScanResult:
"""Execute a gitleaks scan asynchronously."""
scan_id = str(uuid.uuid4())[:8]
output_file = Path(settings.output_dir) / f"scan_{scan_id}.json"
result = ScanResult(
scan_id=scan_id,
target=target,
scan_type=scan_type,
started_at=datetime.now(),
)
scan_results[scan_id] = result
active_scans.add(scan_id)
# Build gitleaks command
cmd = [
"gitleaks",
"detect",
"--source", target,
"--report-format", "json",
"--report-path", str(output_file),
"--exit-code", "0", # Don't fail on findings
]
if no_git:
cmd.append("--no-git")
logger.info(f"Starting gitleaks {scan_type} scan {scan_id} for target: {target}")
logger.debug(f"Command: {' '.join(cmd)}")
try:
process = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await asyncio.wait_for(
process.communicate(),
timeout=float(timeout or settings.default_timeout),
)
result.completed_at = datetime.now()
# Read output file if exists
if output_file.exists():
output_content = output_file.read_text()
result.raw_output = output_content
result.findings = parse_gitleaks_json(output_content)
else:
# No findings
result.findings = []
# Generate stats
rules_triggered = {}
for finding in result.findings:
rule = finding.rule_id
rules_triggered[rule] = rules_triggered.get(rule, 0) + 1
files_with_secrets = set(f.file for f in result.findings if f.file)
result.stats = {
"total_findings": len(result.findings),
"unique_rules_triggered": len(rules_triggered),
"files_with_secrets": len(files_with_secrets),
"rules_breakdown": rules_triggered,
}
result.status = "completed"
logger.info(f"Scan {scan_id} completed: {len(result.findings)} findings")
if stderr:
stderr_text = stderr.decode()
if "error" in stderr_text.lower():
logger.warning(f"Scan {scan_id} warnings: {stderr_text}")
except asyncio.TimeoutError:
result.status = "timeout"
result.error = f"Scan timed out after {timeout or settings.default_timeout} seconds"
result.completed_at = datetime.now()
logger.error(f"Scan {scan_id} timed out")
except Exception as e:
result.status = "error"
result.error = str(e)
result.completed_at = datetime.now()
logger.exception(f"Scan {scan_id} error: {e}")
finally:
active_scans.discard(scan_id)
scan_results[scan_id] = result
return result
async def scan_content(content: str, timeout: int | None = None) -> ScanResult:
"""Scan provided content for secrets."""
scan_id = str(uuid.uuid4())[:8]
result = ScanResult(
scan_id=scan_id,
target="<content>",
scan_type="content",
started_at=datetime.now(),
)
scan_results[scan_id] = result
active_scans.add(scan_id)
# Write content to temp file
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
f.write(content)
temp_path = f.name
output_file = Path(settings.output_dir) / f"scan_{scan_id}.json"
try:
cmd = [
"gitleaks",
"detect",
"--source", temp_path,
"--report-format", "json",
"--report-path", str(output_file),
"--exit-code", "0",
"--no-git",
]
process = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
await asyncio.wait_for(
process.communicate(),
timeout=float(timeout or settings.default_timeout),
)
result.completed_at = datetime.now()
if output_file.exists():
output_content = output_file.read_text()
result.raw_output = output_content
result.findings = parse_gitleaks_json(output_content)
rules_triggered = {}
for finding in result.findings:
rule = finding.rule_id
rules_triggered[rule] = rules_triggered.get(rule, 0) + 1
result.stats = {
"total_findings": len(result.findings),
"rules_breakdown": rules_triggered,
}
result.status = "completed"
except asyncio.TimeoutError:
result.status = "timeout"
result.error = f"Scan timed out"
result.completed_at = datetime.now()
except Exception as e:
result.status = "error"
result.error = str(e)
result.completed_at = datetime.now()
finally:
active_scans.discard(scan_id)
scan_results[scan_id] = result
# Clean up temp file
Path(temp_path).unlink(missing_ok=True)
return result
def format_scan_summary(result: ScanResult) -> dict[str, Any]:
"""Format scan result for response."""
findings_summary = []
for finding in result.findings[:50]: # Limit to 50 findings
findings_summary.append({
"rule_id": finding.rule_id,
"description": finding.description,
"secret": finding.secret,
"file": finding.file,
"line": finding.line,
"commit": finding.commit[:8] if finding.commit else None,
"author": finding.author,
})
return {
"scan_id": result.scan_id,
"target": result.target,
"scan_type": result.scan_type,
"status": result.status,
"stats": result.stats,
"findings": findings_summary,
"error": result.error,
}
# Create MCP server
app = Server("gitleaks-mcp")
@app.list_tools()
async def list_tools() -> list[Tool]:
"""List available tools."""
return [
Tool(
name="gitleaks_scan_repo",
description="Scan a git repository for secrets and credentials. "
"Analyzes commit history for leaked API keys, passwords, tokens, etc.",
inputSchema={
"type": "object",
"properties": {
"repo_path": {
"type": "string",
"description": "Path to the git repository to scan",
},
"timeout": {
"type": "integer",
"description": "Scan timeout in seconds",
"default": 300,
},
},
"required": ["repo_path"],
},
),
Tool(
name="gitleaks_scan_dir",
description="Scan a directory for secrets without git history analysis. "
"Useful for scanning non-git directories or specific folders.",
inputSchema={
"type": "object",
"properties": {
"dir_path": {
"type": "string",
"description": "Directory path to scan",
},
"timeout": {
"type": "integer",
"description": "Scan timeout in seconds",
"default": 300,
},
},
"required": ["dir_path"],
},
),
Tool(
name="gitleaks_detect",
description="Quick scan provided content (text/code) for secrets. "
"Useful for checking config files, environment variables, etc.",
inputSchema={
"type": "object",
"properties": {
"content": {
"type": "string",
"description": "Text content to scan for secrets",
},
"timeout": {
"type": "integer",
"description": "Scan timeout in seconds",
"default": 60,
},
},
"required": ["content"],
},
),
Tool(
name="get_scan_results",
description="Retrieve results from a previous scan by scan ID.",
inputSchema={
"type": "object",
"properties": {
"scan_id": {
"type": "string",
"description": "Scan ID returned from a previous scan",
},
"include_raw": {
"type": "boolean",
"description": "Include raw gitleaks JSON output",
"default": False,
},
},
"required": ["scan_id"],
},
),
Tool(
name="list_active_scans",
description="List currently running scans.",
inputSchema={
"type": "object",
"properties": {},
},
),
]
@app.call_tool()
async def call_tool(name: str, arguments: dict[str, Any]) -> list[TextContent]:
"""Handle tool calls."""
try:
if name == "gitleaks_scan_repo":
if len(active_scans) >= settings.max_concurrent_scans:
return [
TextContent(
type="text",
text=f"Maximum concurrent scans ({settings.max_concurrent_scans}) reached.",
)
]
repo_path = arguments["repo_path"]
if not Path(repo_path).exists():
return [
TextContent(type="text", text=f"Repository not found: {repo_path}")
]
if not (Path(repo_path) / ".git").exists():
return [
TextContent(
type="text",
text=f"Not a git repository: {repo_path}. Use gitleaks_scan_dir for non-git directories.",
)
]
result = await run_gitleaks_scan(
target=repo_path,
scan_type="repo",
timeout=arguments.get("timeout"),
no_git=False,
)
return [
TextContent(
type="text",
text=json.dumps(format_scan_summary(result), indent=2),
)
]
elif name == "gitleaks_scan_dir":
if len(active_scans) >= settings.max_concurrent_scans:
return [
TextContent(
type="text",
text=f"Maximum concurrent scans ({settings.max_concurrent_scans}) reached.",
)
]
dir_path = arguments["dir_path"]
if not Path(dir_path).exists():
return [
TextContent(type="text", text=f"Directory not found: {dir_path}")
]
result = await run_gitleaks_scan(
target=dir_path,
scan_type="dir",
timeout=arguments.get("timeout"),
no_git=True,
)
return [
TextContent(
type="text",
text=json.dumps(format_scan_summary(result), indent=2),
)
]
elif name == "gitleaks_detect":
if len(active_scans) >= settings.max_concurrent_scans:
return [
TextContent(
type="text",
text=f"Maximum concurrent scans ({settings.max_concurrent_scans}) reached.",
)
]
content = arguments["content"]
if not content.strip():
return [
TextContent(type="text", text="Content cannot be empty")
]
result = await scan_content(
content=content,
timeout=arguments.get("timeout", 60),
)
return [
TextContent(
type="text",
text=json.dumps(format_scan_summary(result), indent=2),
)
]
elif name == "get_scan_results":
scan_id = arguments["scan_id"]
result = scan_results.get(scan_id)
if result:
output = format_scan_summary(result)
if arguments.get("include_raw") and result.raw_output:
output["raw_output"] = result.raw_output[:10000]
return [
TextContent(
type="text",
text=json.dumps(output, indent=2),
)
]
else:
return [
TextContent(type="text", text=f"Scan '{scan_id}' not found")
]
elif name == "list_active_scans":
active = [
{
"scan_id": scan_id,
"target": scan_results[scan_id].target,
"scan_type": scan_results[scan_id].scan_type,
"started_at": scan_results[scan_id].started_at.isoformat(),
}
for scan_id in active_scans
if scan_id in scan_results
]
return [
TextContent(
type="text",
text=json.dumps(
{
"active_scans": active,
"count": len(active),
"max_concurrent": settings.max_concurrent_scans,
},
indent=2,
),
)
]
else:
return [TextContent(type="text", text=f"Unknown tool: {name}")]
except Exception as e:
logger.exception(f"Error executing tool {name}: {e}")
return [TextContent(type="text", text=f"Error: {str(e)}")]
@app.list_resources()
async def list_resources() -> list[Resource]:
"""List available resources."""
resources = []
for scan_id, result in scan_results.items():
if result.status == "completed":
finding_count = len(result.findings)
resources.append(
Resource(
uri=f"gitleaks://results/{scan_id}",
name=f"Scan Results: {result.target} ({finding_count} secrets)",
description=f"{result.scan_type} scan completed at {result.completed_at}",
mimeType="application/json",
)
)
return resources
@app.read_resource()
async def read_resource(uri: str) -> str:
"""Read a resource."""
if uri.startswith("gitleaks://results/"):
scan_id = uri.replace("gitleaks://results/", "")
result = scan_results.get(scan_id)
if result:
return json.dumps(format_scan_summary(result), indent=2)
return json.dumps({"error": "Resource not found"})
async def main():
"""Run the MCP server."""
logger.info("Starting Gitleaks MCP Server")
logger.info(f"Output directory: {settings.output_dir}")
# Ensure output directory exists
Path(settings.output_dir).mkdir(parents=True, exist_ok=True)
async with stdio_server() as (read_stream, write_stream):
await app.run(read_stream, write_stream, app.create_initialization_options())
if __name__ == "__main__":
asyncio.run(main())