#!/bin/bash
# Automated HTTPS decryption for Nuke telemetry
# Tries mitmproxy method, provides instructions for frida fallback

OUTPUT_DIR="$HOME/Documents/obsidian-vault/2-projects/Nuke-monitoring/dump/decrypted"
mkdir -p "$OUTPUT_DIR"
TIMESTAMP=$(date +%Y-%m-%d_%H-%M-%S)

echo "═══════════════════════════════════════════════════════"
echo "  Nuke HTTPS Traffic Decryption Tool"
echo "═══════════════════════════════════════════════════════"
echo ""
echo "This tool will attempt to decrypt HTTPS traffic from Nuke"
echo "using SSL/TLS interception (mitmproxy method)."
echo ""
echo "LEGAL NOTE: This intercepts YOUR traffic from YOUR software"
echo "on YOUR computer. This is legal and ethical for privacy research."
echo ""

# Check if mitmproxy is installed
if ! command -v mitmproxy &> /dev/null; then
    echo "ERROR: mitmproxy is not installed."
    echo ""
    echo "Install with:"
    echo "  sudo pacman -S mitmproxy"
    echo ""
    exit 1
fi

# Check if Nuke is running (it shouldn't be yet)
if pgrep -f Nuke > /dev/null 2>&1; then
    echo "WARNING: Nuke is currently running."
    echo "For best results, close Nuke before starting interception."
    echo ""
    read -p "Continue anyway? (y/n): " continue_anyway
    if [ "$continue_anyway" != "y" ]; then
        echo "Aborted."
        exit 0
    fi
fi

echo ""
echo "═══════════════════════════════════════════════════════"
echo "  Step 1: Setup mitmproxy certificate"
echo "═══════════════════════════════════════════════════════"
echo ""

# Generate mitmproxy certificate if not exists
if [ ! -f "$HOME/.mitmproxy/mitmproxy-ca-cert.pem" ]; then
    echo "Generating mitmproxy certificate..."
    mitmproxy --version > /dev/null 2>&1
    sleep 2
    if [ ! -f "$HOME/.mitmproxy/mitmproxy-ca-cert.pem" ]; then
        echo "Running mitmproxy briefly to generate certificate..."
        timeout 3 mitmproxy 2>/dev/null || true
    fi
fi

# Install certificate to system trust store
if [ -f "$HOME/.mitmproxy/mitmproxy-ca-cert.pem" ]; then
    echo "Installing mitmproxy certificate to system trust store..."
    sudo cp "$HOME/.mitmproxy/mitmproxy-ca-cert.pem" /etc/ca-certificates/trust-source/anchors/mitmproxy.crt 2>/dev/null || true
    sudo trust extract-compat 2>/dev/null || true
    sudo update-ca-trust 2>/dev/null || true
    echo "✓ Certificate installed"
else
    echo "WARNING: Could not generate mitmproxy certificate."
    echo "Interception may not work properly."
fi

echo ""
echo "═══════════════════════════════════════════════════════"
echo "  Step 2: Start mitmproxy web interface"
echo "═══════════════════════════════════════════════════════"
echo ""

MITM_LOG="$OUTPUT_DIR/nuke_traffic_$TIMESTAMP.mitm"

echo "Starting mitmweb on http://127.0.0.1:8081"
echo "Log file: $MITM_LOG"
echo ""

# Start mitmweb in background
mitmweb --mode transparent --showhost --set block_global=false -w "$MITM_LOG" > "$OUTPUT_DIR/mitmproxy_$TIMESTAMP.log" 2>&1 &
MITMPROXY_PID=$!

echo "mitmproxy PID: $MITMPROXY_PID"
sleep 3

# Check if mitmproxy started successfully
if ! kill -0 $MITMPROXY_PID 2>/dev/null; then
    echo "ERROR: mitmproxy failed to start."
    echo "Check log: $OUTPUT_DIR/mitmproxy_$TIMESTAMP.log"
    exit 1
fi

echo "✓ mitmproxy started successfully"
echo ""

echo "═══════════════════════════════════════════════════════"
echo "  Step 3: Setup iptables traffic redirection"
echo "═══════════════════════════════════════════════════════"
echo ""

# Save current iptables rules for restoration
sudo iptables-save > "$OUTPUT_DIR/iptables_backup_$TIMESTAMP.rules"

echo "Redirecting Foundry traffic through mitmproxy..."

# Redirect Honeycomb traffic
sudo iptables -t nat -A OUTPUT -p tcp -d 52.205.16.9 --dport 443 -j REDIRECT --to-port 8080

# Redirect learn.foundry.com
sudo iptables -t nat -A OUTPUT -p tcp -d 52.50.232.31 --dport 443 -j REDIRECT --to-port 8080
sudo iptables -t nat -A OUTPUT -p tcp -d 52.50.232.31 --dport 80 -j REDIRECT --to-port 8080

# Redirect any other foundry.com domains (by name - requires DNS)
# Note: This might not work for direct IP connections
echo "✓ iptables rules applied"
echo ""

echo "═══════════════════════════════════════════════════════"
echo "  Step 4: Launch Nuke and capture traffic"
echo "═══════════════════════════════════════════════════════"
echo ""
echo "INSTRUCTIONS:"
echo ""
echo "1. Open your browser to: http://127.0.0.1:8081"
echo "   (mitmproxy web interface)"
echo ""
echo "2. Launch Nuke now and use it normally"
echo ""
echo "3. Watch the mitmproxy interface for captured requests"
echo "   Look for requests to:"
echo "   - api.honeycomb.io"
echo "   - learn.foundry.com"
echo "   - sentry.foundry.com"
echo ""
echo "4. Click on any request to see:"
echo "   - Full HTTP headers"
echo "   - Complete request/response body (JSON)"
echo "   - Timing information"
echo ""
echo "5. When done capturing, return to this terminal and press Enter"
echo ""
echo "═══════════════════════════════════════════════════════"

read -p "Press Enter after you're done capturing traffic..."

echo ""
echo "═══════════════════════════════════════════════════════"
echo "  Step 5: Cleanup"
echo "═══════════════════════════════════════════════════════"
echo ""

echo "Stopping mitmproxy..."
kill $MITMPROXY_PID 2>/dev/null
wait $MITMPROXY_PID 2>/dev/null

echo "Restoring iptables rules..."
sudo iptables -t nat -F OUTPUT 2>/dev/null

echo "✓ Cleanup complete"
echo ""

echo "═══════════════════════════════════════════════════════"
echo "  Results"
echo "═══════════════════════════════════════════════════════"
echo ""

if [ -f "$MITM_LOG" ]; then
    CAPTURE_SIZE=$(du -h "$MITM_LOG" | cut -f1)
    echo "Capture saved to: $MITM_LOG"
    echo "Capture size: $CAPTURE_SIZE"
    echo ""
    echo "To replay and analyze:"
    echo "  mitmproxy -r $MITM_LOG"
    echo ""
    echo "To export to JSON:"
    echo "  mitmdump -r $MITM_LOG -w $OUTPUT_DIR/nuke_traffic_$TIMESTAMP.json"
    echo ""
    echo "To view in web interface again:"
    echo "  mitmweb -r $MITM_LOG"
    echo ""
else
    echo "WARNING: No capture file created."
    echo "This could mean:"
    echo "  1. No traffic was captured (Nuke didn't connect)"
    echo "  2. Nuke rejected the mitmproxy certificate (certificate pinning)"
    echo "  3. Traffic went around the proxy"
    echo ""
    echo "TROUBLESHOOTING:"
    echo ""
    echo "If Nuke showed SSL/certificate errors:"
    echo "  → Nuke likely uses certificate pinning"
    echo "  → Try Method 3 (frida) instead"
    echo "  → See INTERCEPTING-HTTPS.md for instructions"
    echo ""
    echo "If no errors but no traffic captured:"
    echo "  → Check that Foundry IPs are correct"
    echo "  → Try capturing during Nuke startup"
    echo "  → Monitor /tmp/mitmproxy_*.log for errors"
fi

echo ""
echo "═══════════════════════════════════════════════════════"
echo "  Next Steps"
echo "═══════════════════════════════════════════════════════"
echo ""

if [ -f "$MITM_LOG" ] && [ -s "$MITM_LOG" ]; then
    echo "✓ SUCCESS! Traffic was captured and decrypted."
    echo ""
    echo "Review the capture to find:"
    echo "  - Email domain transmission"
    echo "  - Geographic location data"
    echo "  - System information collected"
    echo "  - Usage profiling details"
    echo "  - Any sensitive data (file paths, project names)"
    echo ""
    echo "Document findings in:"
    echo "  $OUTPUT_DIR/analysis_$TIMESTAMP.txt"
    echo ""
    echo "Update the master document:"
    echo "  Foudry-Nuke-Monitoring.md"
else
    echo "✗ No traffic captured."
    echo ""
    echo "OPTION 1: Try again with different approach"
    echo "  ./decrypt_nuke_traffic.sh"
    echo ""
    echo "OPTION 2: Use frida method (more reliable)"
    echo "  See: INTERCEPTING-HTTPS.md - Method 3"
    echo ""
    echo "OPTION 3: Check if telemetry is already blocked"
    echo "  cat /etc/hosts | grep foundry"
fi

echo ""
echo "For detailed instructions and alternative methods:"
echo "  See: INTERCEPTING-HTTPS.md"
echo ""
