#!/bin/bash # check-cwe134.sh - Static analysis for CWE-134 format string vulnerabilities # # This script detects potentially unsafe usage of format string functions # where user-controlled data may be passed without "%s" wrapper. # # Usage: ./check-cwe134.sh [directory] set -e DIR="${1:-src}" echo "=== CWE-134 Format String Vulnerability Check ===" echo "Scanning: $DIR" echo "" # Functions that accept format strings FORMAT_FUNCS="cons_show|cons_debug|cons_show_error|log_info|log_error|log_warning|log_debug|win_println|win_print" ERRORS=0 echo "Checking for unsafe format string usage..." echo "" # Pattern 1: function call with single variable argument (no format string) # Example: cons_show(variable); - BAD # Example: cons_show("%s", variable); - OK # Matches: func(identifier) or func(identifier->member) or func(identifier[index]) RESULTS=$(grep -rn --include="*.c" -P "($FORMAT_FUNCS)\s*\(\s*[a-zA-Z_][a-zA-Z0-9_]*(\s*->\s*\w+|\s*\[\s*\w+\s*\])?\s*\)\s*;" "$DIR" 2>/dev/null || true) # Filter out function definitions, declarations, and safe api_* wrappers RESULTS=$(echo "$RESULTS" | grep -v "const char\|void \|^[^:]*:[0-9]*:[a-z_]*(\|api_cons_show\|api_log_" || true) if [ -n "$RESULTS" ]; then echo "❌ POTENTIAL CWE-134 VULNERABILITIES FOUND:" echo "" echo "$RESULTS" echo "" ERRORS=$(echo "$RESULTS" | wc -l) else echo "✅ No obvious CWE-134 issues found." fi # Additional check: GString->str passed directly (not as %s argument) echo "" echo "Checking for GString->str passed to format functions..." GSTRING_RESULTS=$(grep -rn --include="*.c" -P "($FORMAT_FUNCS)\s*\([^)]*->str\s*\)" "$DIR" 2>/dev/null | grep -v '"%s"' || true) if [ -n "$GSTRING_RESULTS" ]; then echo "⚠️ GString->str passed without \"%s\" (review manually):" echo "" echo "$GSTRING_RESULTS" echo "" fi echo "" echo "=== Summary ===" echo "Critical issues: $ERRORS" if [ "$ERRORS" -gt 0 ]; then echo "" echo "Fix by adding \"%s\" format specifier:" echo " BAD: cons_show(variable);" echo " GOOD: cons_show(\"%s\", variable);" exit 1 fi exit 0