securegit 0.7.1

Zero-trust git replacement with 12 built-in security scanners, universal undo, durable backups, and a 37-tool MCP server
Documentation
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
# SecureGit Plugin Development Guide

## Overview

SecureGit's plugin architecture allows you to integrate any security scanning tool into the SecureGit ecosystem. Plugins can be written in any language and can wrap existing security tools, enabling the security community to leverage decades of battle-tested scanners.

## Plugin Types

### 1. Built-in Rust Plugins
- Compiled directly into the SecureGit binary
- Highest performance, zero startup overhead
- Implement the `SecurityPlugin` trait
- Examples: secrets, patterns, entropy, binary detection

### 2. External Executable Plugins
- Standalone scripts or binaries
- Language-agnostic (Bash, Python, Go, Node.js, etc.)
- Communicate via JSON on stdin/stdout
- Located in `~/.config/securegit/plugins/`

### 3. Dynamic Library Plugins (Native)
- Compiled shared libraries (.so/.dll/.dylib)
- Any language with C FFI support
- Loaded at runtime via `libloading`
- High performance with dynamic loading

### 4. WebAssembly Plugins (Future)
- Sandboxed, portable execution
- Compile from Rust, Go, C++, AssemblyScript
- Cross-platform compatibility
- Security isolation

## Plugin Interface

### Input Format

Plugins receive scan context as JSON via stdin or as command arguments:

```json
{
  "file_path": "/path/to/file.py",
  "scan_phase": "post_extract",
  "content_base64": "IyEvdXNyL2Jpbi9lbnYgcHl0aG9u...",
  "metadata": {
    "size": 1024,
    "mime_type": "text/x-python"
  }
}
```

### Output Format

Plugins must return findings as JSON on stdout:

```json
{
  "plugin_name": "bandit",
  "version": "1.0.0",
  "findings": [
    {
      "id": "B201",
      "title": "flask_debug_true",
      "description": "A Flask app is run with debug=True, which exposes the debugger",
      "severity": "high",
      "confidence": "high",
      "file_path": "/path/to/file.py",
      "line_start": 42,
      "line_end": 42,
      "evidence": "app.run(debug=True)",
      "remediation": "Set debug=False in production",
      "references": [
        "https://flask.palletsprojects.com/en/2.0.x/security/"
      ],
      "cwe_ids": [489]
    }
  ],
  "scanned_files": 1,
  "duration_ms": 123
}
```

### Severity Levels

- `critical` - Immediate security threat (exposed credentials, RCE vulnerabilities)
- `high` - Serious security issue (injection flaws, weak crypto)
- `medium` - Moderate risk (missing security headers, outdated dependencies)
- `low` - Minor concern (code quality issues with security implications)
- `info` - Informational finding

## Creating a Plugin

### Example 1: Bash Script Plugin

Wrap any command-line security tool:

```bash
#!/bin/bash
# ~/.config/securegit/plugins/gitleaks

# Plugin metadata (optional, for discovery)
# NAME: gitleaks
# VERSION: 1.0.0
# DESCRIPTION: Detect hardcoded secrets using gitleaks
# REQUIRES: gitleaks

set -euo pipefail

FILE_PATH="$1"

# Check if gitleaks is installed
if ! command -v gitleaks &> /dev/null; then
    echo '{"error": "gitleaks not found in PATH"}' >&2
    exit 1
fi

# Run gitleaks and convert output to SecureGit format
gitleaks detect --no-git -f "$FILE_PATH" --report-format json 2>/dev/null | \
jq -c '{
  plugin_name: "gitleaks",
  version: "1.0.0",
  findings: [.[] | {
    id: .RuleID,
    title: ("Secret detected: " + .Description),
    description: .Description,
    severity: "critical",
    confidence: "high",
    file_path: .File,
    line_start: .StartLine,
    line_end: .EndLine,
    evidence: .Secret[0:50]
  }],
  scanned_files: 1
}'
```

Make it executable:
```bash
chmod +x ~/.config/securegit/plugins/gitleaks
```

### Example 2: Python Plugin

Integrate Python security tools:

```python
#!/usr/bin/env python3
# ~/.config/securegit/plugins/bandit

import json
import sys
import subprocess
from pathlib import Path

def scan_file(file_path):
    """Run Bandit security scanner on a Python file."""

    # Run bandit
    result = subprocess.run(
        ['bandit', '-f', 'json', file_path],
        capture_output=True,
        text=True
    )

    if result.returncode not in [0, 1]:
        return {"error": f"Bandit failed: {result.stderr}"}

    bandit_output = json.loads(result.stdout)

    # Convert to SecureGit format
    findings = []
    for issue in bandit_output.get('results', []):
        findings.append({
            "id": issue['test_id'],
            "title": issue['test_name'],
            "description": issue['issue_text'],
            "severity": issue['issue_severity'].lower(),
            "confidence": issue['issue_confidence'].lower(),
            "file_path": issue['filename'],
            "line_start": issue['line_number'],
            "evidence": issue['code'],
            "cwe_ids": [issue.get('cwe', {}).get('id')] if 'cwe' in issue else []
        })

    return {
        "plugin_name": "bandit",
        "version": "1.0.0",
        "findings": findings,
        "scanned_files": 1
    }

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(json.dumps({"error": "No file path provided"}), file=sys.stderr)
        sys.exit(1)

    file_path = sys.argv[1]

    # Only scan Python files
    if not file_path.endswith('.py'):
        print(json.dumps({
            "plugin_name": "bandit",
            "findings": [],
            "scanned_files": 0
        }))
        sys.exit(0)

    result = scan_file(file_path)
    print(json.dumps(result))
```

### Example 3: Go Plugin

High-performance compiled plugin:

```go
// ~/.config/securegit/plugins/gosec.go
package main

import (
    "encoding/json"
    "fmt"
    "os"
    "os/exec"
    "strings"
)

type Finding struct {
    ID          string   `json:"id"`
    Title       string   `json:"title"`
    Description string   `json:"description"`
    Severity    string   `json:"severity"`
    FilePath    string   `json:"file_path"`
    LineStart   int      `json:"line_start"`
    Evidence    string   `json:"evidence"`
}

type PluginResult struct {
    PluginName   string    `json:"plugin_name"`
    Version      string    `json:"version"`
    Findings     []Finding `json:"findings"`
    ScannedFiles int       `json:"scanned_files"`
}

func scanFile(filePath string) (*PluginResult, error) {
    // Run gosec
    cmd := exec.Command("gosec", "-fmt", "json", filePath)
    output, err := cmd.Output()
    if err != nil && len(output) == 0 {
        return nil, fmt.Errorf("gosec failed: %v", err)
    }

    // Parse gosec output
    var gosecResult map[string]interface{}
    if err := json.Unmarshal(output, &gosecResult); err != nil {
        return nil, err
    }

    // Convert to SecureGit format
    findings := []Finding{}
    if issues, ok := gosecResult["Issues"].([]interface{}); ok {
        for _, issue := range issues {
            i := issue.(map[string]interface{})
            findings = append(findings, Finding{
                ID:          i["rule_id"].(string),
                Title:       i["details"].(string),
                Severity:    strings.ToLower(i["severity"].(string)),
                FilePath:    i["file"].(string),
                LineStart:   int(i["line"].(float64)),
                Evidence:    i["code"].(string),
            })
        }
    }

    return &PluginResult{
        PluginName:   "gosec",
        Version:      "1.0.0",
        Findings:     findings,
        ScannedFiles: 1,
    }, nil
}

func main() {
    if len(os.Args) < 2 {
        fmt.Fprintln(os.Stderr, `{"error": "No file path provided"}`)
        os.Exit(1)
    }

    result, err := scanFile(os.Args[1])
    if err != nil {
        fmt.Fprintf(os.Stderr, `{"error": "%s"}`, err)
        os.Exit(1)
    }

    output, _ := json.Marshal(result)
    fmt.Println(string(output))
}
```

Compile:
```bash
go build -o ~/.config/securegit/plugins/gosec gosec.go
```

## Wrapping Existing Tools

### ClamAV Malware Scanner

```bash
#!/bin/bash
# ~/.config/securegit/plugins/clamav

FILE="$1"

clamscan --no-summary "$FILE" 2>&1 | \
awk -v file="$FILE" '
BEGIN { findings = "" }
/FOUND/ {
    if (findings != "") findings = findings ","
    findings = findings sprintf("{\"id\":\"CLAMAV_MALWARE\",\"title\":\"Malware detected\",\"severity\":\"critical\",\"file_path\":\"%s\",\"evidence\":\"%s\"}", file, $0)
}
END {
    printf "{\"plugin_name\":\"clamav\",\"findings\":[%s]}\n", findings
}'
```

### YARA Rules

```bash
#!/bin/bash
# ~/.config/securegit/plugins/yara-rules

FILE="$1"
RULES_DIR="$HOME/.config/securegit/yara-rules"

if [ ! -d "$RULES_DIR" ]; then
    echo '{"error": "YARA rules not found. Run: git clone https://github.com/Yara-Rules/rules ~/.config/securegit/yara-rules"}' >&2
    exit 1
fi

yara -r "$RULES_DIR" "$FILE" 2>/dev/null | \
awk -v file="$FILE" '{
    printf "{\"plugin_name\":\"yara\",\"findings\":[{\"id\":\"%s\",\"title\":\"YARA rule matched: %s\",\"severity\":\"high\",\"file_path\":\"%s\"}]}\n", $1, $1, file
}'
```

### Trivy Container Scanner

```bash
#!/bin/bash
# ~/.config/securegit/plugins/trivy

FILE="$1"

# Only scan Dockerfiles and container-related files
if [[ ! "$FILE" =~ (Dockerfile|docker-compose\.ya?ml) ]]; then
    echo '{"plugin_name":"trivy","findings":[]}'
    exit 0
fi

trivy config "$FILE" --format json 2>/dev/null | \
jq '{
    plugin_name: "trivy",
    findings: [.Results[]?.Misconfigurations[]? | {
        id: .ID,
        title: .Title,
        description: .Description,
        severity: (.Severity | ascii_downcase),
        file_path: "'$FILE'",
        remediation: .Resolution
    }]
}'
```

## Plugin Installation

### Manual Installation

```bash
# Create plugin directory
mkdir -p ~/.config/securegit/plugins

# Copy plugin
cp my-scanner ~/.config/securegit/plugins/

# Make executable
chmod +x ~/.config/securegit/plugins/my-scanner

# Test plugin
echo '{}' | ~/.config/securegit/plugins/my-scanner test-file.py
```

### Plugin Configuration

Create `~/.config/securegit/config.toml`:

```toml
[plugins]
enabled = [
    "patterns",
    "secrets",
    "entropy",
    "binary",
    "gitleaks",
    "bandit",
    "gosec"
]

plugin_dir = "~/.config/securegit/plugins"

[plugins.gitleaks]
enabled = true
severity_threshold = "medium"

[plugins.yara]
enabled = true
rules_dir = "~/.config/securegit/yara-rules"
```

## Testing Your Plugin

### Unit Test

```bash
# Create test file with known issue
echo 'aws_key = "AKIAIOSFODNN7EXAMPLE"' > test.py

# Run plugin directly
~/.config/securegit/plugins/gitleaks test.py | jq .

# Expected output:
# {
#   "plugin_name": "gitleaks",
#   "findings": [
#     {
#       "id": "aws-access-key",
#       "severity": "critical",
#       ...
#     }
#   ]
# }
```

### Integration Test

```bash
# Run with SecureGit
securegit scan test.py --plugin gitleaks

# Should detect the hardcoded AWS key
```

## Best Practices

### Performance
- Exit quickly for irrelevant files (check file extension)
- Use streaming/incremental processing for large files
- Cache results when appropriate
- Set reasonable timeouts

### Error Handling
- Return errors via stderr in JSON format
- Use non-zero exit codes only for fatal errors
- Gracefully handle missing dependencies
- Provide clear error messages

### Output
- Always return valid JSON
- Redact or truncate sensitive evidence
- Include actionable remediation advice
- Provide relevant security references

### Security
- Validate all input paths (prevent path traversal)
- Don't execute user-provided code
- Limit resource consumption (CPU, memory, disk)
- Run with minimal required permissions

## Plugin Registry

### Submitting to Registry

1. Create plugin repository with structure:
```
my-plugin/
├── plugin.json         # Metadata
├── install.sh          # Installation script
├── scanner             # Plugin executable
└── README.md          # Documentation
```

2. `plugin.json` format:
```json
{
  "name": "my-scanner",
  "version": "1.0.0",
  "description": "Security scanner for X",
  "author": "Your Name",
  "license": "MIT",
  "homepage": "https://github.com/user/my-scanner",
  "requires": ["external-tool >= 2.0"],
  "platforms": ["linux", "darwin"],
  "tags": ["secrets", "static-analysis", "python"]
}
```

3. Submit PR to plugin registry repository

### Plugin Discovery

```bash
# Search registry
securegit plugin search yara

# View plugin info
securegit plugin info yara-rules

# Install from registry
securegit plugin install yara-rules

# Update plugins
securegit plugin update --all
```

## Community Plugins

Visit the plugin registry for community-maintained scanners:

https://github.com/armyknifelabs-tools/securegit-plugins

### Popular Categories
- Secret detection (gitleaks, trufflehog, detect-secrets)
- Language-specific SAST (bandit, gosec, brakeman)
- Container security (trivy, grype, hadolint)
- License compliance (licensee, scancode, fossology)
- Malware detection (clamav, yara)
- Infrastructure as Code (tfsec, checkov, terrascan)

## Support

- Documentation: https://github.com/armyknifelabs-tools/securegit
- Issues: https://github.com/armyknifelabs-tools/securegit/issues
- Plugin Registry: https://github.com/armyknifelabs-tools/securegit-plugins