diff --git a/.github/scan-config.yml b/.github/scan-config.yml new file mode 100644 index 0000000..822f703 --- /dev/null +++ b/.github/scan-config.yml @@ -0,0 +1,13 @@ +# CryptoGuard-Go Scan Configuration + +# Repositories to exclude from scanning +excluded_repos: + - golang/go # Go standard library - reference implementation, not for scanning + # Add more repositories to exclude here + # - owner/repo + +# Scan criteria +scan_settings: + max_repos: 10 + min_stars: 100 + min_forks: 50 diff --git a/.github/scripts/generate-report.sh b/.github/scripts/generate-report.sh new file mode 100755 index 0000000..c0dd99d --- /dev/null +++ b/.github/scripts/generate-report.sh @@ -0,0 +1,463 @@ +#!/bin/bash +set -e + +# CryptoGuard-Go Report Generator +# Generates a markdown report with tables from scan results + +echo "Generating vulnerability report..." + +# Create reports directory +mkdir -p reports + +# Start markdown report +REPORT_FILE="reports/summary.md" + +cat > "$REPORT_FILE" <
> "$REPORT_FILE" + echo "$(grep "Total repositories" scan-results/summary.txt)" >> "$REPORT_FILE" + echo "$(grep "Repositories with issues" scan-results/summary.txt)" >> "$REPORT_FILE" + echo "$(grep "Total issues found" scan-results/summary.txt)" >> "$REPORT_FILE" + echo "" >> "$REPORT_FILE" +fi + +# Add detailed results table +cat >> "$REPORT_FILE" <<'TABLE_HEADER' + +## Detailed Findings + +### Vulnerability Summary by Repository + +| Repository | Total Issues | Critical | High | Medium | Low | Status | +|------------|--------------|----------|------|--------|-----|--------| +TABLE_HEADER + +# Process each JSON result file +for json_file in scan-results/*.json; do + if [ -f "$json_file" ]; then + # Extract repository name from filename + filename=$(basename "$json_file" .json) + repo_name="${filename//-/\/}" + + # Count issues by severity using jq if available, otherwise use grep + if command -v jq &> /dev/null; then + total=$(jq '. | length' "$json_file" 2>/dev/null || echo "0") + critical=$(jq '[.[] | select(.severity == "CRITICAL")] | length' "$json_file" 2>/dev/null || echo "0") + high=$(jq '[.[] | select(.severity == "HIGH")] | length' "$json_file" 2>/dev/null || echo "0") + medium=$(jq '[.[] | select(.severity == "MEDIUM")] | length' "$json_file" 2>/dev/null || echo "0") + low=$(jq '[.[] | select(.severity == "LOW")] | length' "$json_file" 2>/dev/null || echo "0") + else + # Fallback to text file parsing + txt_file="${json_file%.json}.txt" + total=$(grep -c "Rule:" "$txt_file" 2>/dev/null || echo "0") + critical=$(grep -c "CRITICAL:" "$txt_file" 2>/dev/null || echo "0") + high=$(grep -c "HIGH:" "$txt_file" 2>/dev/null || echo "0") + medium=$(grep -c "MEDIUM:" "$txt_file" 2>/dev/null || echo "0") + low=$(grep -c "LOW:" "$txt_file" 2>/dev/null || echo "0") + fi + + # Determine status + if [ "$critical" -gt 0 ]; then + status="✗ Critical" + elif [ "$high" -gt 0 ]; then + status="✗ High" + elif [ "$total" -gt 0 ]; then + status="✗ Issues Found" + else + status="✓ Clean" + fi + + # Add row to table + echo "| $repo_name | $total | $critical | $high | $medium | $low | $status |" >> "$REPORT_FILE" + fi +done + +# Add issue breakdown section +cat >> "$REPORT_FILE" <<'BREAKDOWN_HEADER' + +## Issue Breakdown + +### Issues by Rule Type + +| Rule ID | Description | Severity | Count | CWE | +|---------|-------------|----------|-------|-----| +BREAKDOWN_HEADER + +# Create a temporary file to aggregate rule counts +TEMP_RULES=$(mktemp) + +# Process all text files to count issues by rule +for txt_file in scan-results/*.txt; do + if [ -f "$txt_file" ]; then + # Extract rule information + grep -A1 "Rule:" "$txt_file" | grep -v "^--$" >> "$TEMP_RULES" 2>/dev/null || true + fi +done + +# Count and display unique rules +if [ -s "$TEMP_RULES" ]; then + # Parse rules (simplified version) + echo "| CRYPTO001 | MD5 usage for security purposes | HIGH | - | CWE-328 |" >> "$REPORT_FILE" + echo "| CRYPTO002 | SHA1 usage for security purposes | HIGH | - | CWE-328 |" >> "$REPORT_FILE" + echo "| CRYPTO010 | Hardcoded cryptographic key | CRITICAL | - | CWE-321 |" >> "$REPORT_FILE" + echo "| CRYPTO020 | Static IV/nonce detected | CRITICAL | - | CWE-329 |" >> "$REPORT_FILE" + echo "| CRYPTO040 | Quantum-vulnerable algorithm | MEDIUM | - | CWE-327 |" >> "$REPORT_FILE" +fi + +rm -f "$TEMP_RULES" + +# Add recommendations section +cat >> "$REPORT_FILE" <<'RECOMMENDATIONS' + +## Recommendations + +### Critical Actions Required + +1. **Immediate Review**: All CRITICAL severity issues should be reviewed immediately +2. **Remediation Plan**: Create tickets for HIGH severity issues +3. **Security Best Practices**: + - Never hardcode cryptographic keys + - Use crypto/rand for IV/nonce generation + - Replace MD5/SHA1 with SHA-256 or stronger + - Consider post-quantum cryptography for long-term secrets + +### Next Steps + +- [ ] Review all CRITICAL findings +- [ ] Patch hardcoded keys immediately +- [ ] Update cryptographic algorithms +- [ ] Implement secure key management +- [ ] Run follow-up scan after remediation + +## Resources + +- [CryptoGuard-Go Documentation](https://github.com/ravisastryk/cryptoguard-go) +- [OWASP Cryptographic Storage Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html) +- [Go Crypto Best Practices](https://golang.org/pkg/crypto/) + +--- + +*Report generated by CryptoGuard-Go - Automated Cryptographic Vulnerability Scanner* +*For questions or issues, please visit: https://github.com/ravisastryk/cryptoguard-go/issues* +RECOMMENDATIONS + +echo "[OK] Summary report generated: $REPORT_FILE" + +# Generate detailed remediation guide +echo "" +echo "Generating detailed remediation guide..." + +REMEDIATION_FILE="reports/detailed-remediation.md" + +cat > "$REMEDIATION_FILE" <> "$REMEDIATION_FILE" +echo "## Repository-Specific Findings" >> "$REMEDIATION_FILE" +echo "" >> "$REMEDIATION_FILE" + +# Process each text result file for detailed findings +for txt_file in scan-results/*.txt; do + if [ -f "$txt_file" ]; then + filename=$(basename "$txt_file" .txt) + repo_name="${filename//-/\/}" + repo_anchor=$(echo "$filename" | tr '[:upper:]' '[:lower:]') + + # Count issues by severity + total=$(grep -c "Rule:" "$txt_file" 2>/dev/null || echo "0") + + if [ "$total" -gt 0 ]; then + # Add anchor for linking from README + echo "" >> "$REMEDIATION_FILE" + echo "" >> "$REMEDIATION_FILE" + echo "### Repository: $repo_name" >> "$REMEDIATION_FILE" + echo "" >> "$REMEDIATION_FILE" + echo "**Total Issues:** $total" >> "$REMEDIATION_FILE" + + # Count by severity (ensure single value) + critical=$(grep -c "CRITICAL:" "$txt_file" 2>/dev/null | head -1) + high=$(grep -c "HIGH:" "$txt_file" 2>/dev/null | head -1) + medium=$(grep -c "MEDIUM:" "$txt_file" 2>/dev/null | head -1) + low=$(grep -c "LOW:" "$txt_file" 2>/dev/null | head -1) + + # Default to 0 if empty + critical=${critical:-0} + high=${high:-0} + medium=${medium:-0} + low=${low:-0} + + echo "**Breakdown:** $critical Critical, $high High, $medium Medium, $low Low" >> "$REMEDIATION_FILE" + echo "" >> "$REMEDIATION_FILE" + + # Extract issues with code pointers (showing actual file:line) + echo "#### Code Locations:" >> "$REMEDIATION_FILE" + echo "" >> "$REMEDIATION_FILE" + echo "| Severity | Rule | File:Line | Description |" >> "$REMEDIATION_FILE" + echo "|----------|------|-----------|-------------|" >> "$REMEDIATION_FILE" + + # Parse each issue and format as table row + grep -A3 "Rule:" "$txt_file" 2>/dev/null | while IFS= read -r line; do + if [[ $line =~ ^(CRITICAL|HIGH|MEDIUM|LOW): ]]; then + severity=$(echo "$line" | cut -d: -f1) + message=$(echo "$line" | cut -d: -f2- | xargs) + # Read next 3 lines for Rule, File, Fix + read -r rule_line + read -r file_line + read -r fix_line + + rule=$(echo "$rule_line" | sed 's/.*Rule: \([^ ]*\).*/\1/') + file=$(echo "$file_line" | sed 's/.*File: //' | sed 's|.*/temp-scan-[^/]*/||') + + if [ "$file" != "-" ] && [ -n "$file" ]; then + # Clean up file path + clean_file=$(echo "$file" | sed 's|^/.*github.com/[^/]*/[^/]*/||') + echo "| $severity | $rule | \`$clean_file\` | $message |" >> "$REMEDIATION_FILE" + fi + fi + done | head -10 # Show top 10 issues per repo + + echo "" >> "$REMEDIATION_FILE" + echo "**Recommended Actions:**" >> "$REMEDIATION_FILE" + + # Add specific recommendations based on what we found + if [ "$critical" -gt 0 ] || [ "$high" -gt 0 ]; then + echo "1. Address HIGH/CRITICAL issues immediately" >> "$REMEDIATION_FILE" + fi + if grep -q "CRYPTO001" "$txt_file"; then + echo "2. Replace MD5 with SHA-256: \`find . -name \"*.go\" -exec sed -i 's/crypto\/md5/crypto\/sha256/g' {} \\;\`" >> "$REMEDIATION_FILE" + fi + if grep -q "CRYPTO002" "$txt_file"; then + echo "3. Replace SHA-1 with SHA-256: \`find . -name \"*.go\" -exec sed -i 's/crypto\/sha1/crypto\/sha256/g' {} \\;\`" >> "$REMEDIATION_FILE" + fi + if grep -q "CRYPTO040" "$txt_file"; then + echo "4. Consider post-quantum migration planning (informational)" >> "$REMEDIATION_FILE" + fi + + echo "" >> "$REMEDIATION_FILE" + echo "---" >> "$REMEDIATION_FILE" + echo "" >> "$REMEDIATION_FILE" + fi + fi +done + +# Add fix examples +cat >> "$REMEDIATION_FILE" <<'FIX_EXAMPLES' + +## Code Fix Examples + +### Fix: Replace MD5 with SHA-256 + +**Before:** +```go +import "crypto/md5" + +func GenerateHash(data []byte) string { + hash := md5.Sum(data) + return hex.EncodeToString(hash[:]) +} +``` + +**After:** +```go +import "crypto/sha256" + +func GenerateHash(data []byte) string { + hash := sha256.Sum256(data) + return hex.EncodeToString(hash[:]) +} +``` + +**Effort:** Low (1-2 hours) +**Priority:** IMMEDIATE + +--- + +### Fix: Replace SHA-1 with SHA-256 + +**Before:** +```go +import "crypto/sha1" + +h := sha1.New() +h.Write(data) +result := h.Sum(nil) +``` + +**After:** +```go +import "crypto/sha256" + +h := sha256.New() +h.Write(data) +result := h.Sum(nil) +``` + +**Effort:** Low (1-2 hours) +**Priority:** IMMEDIATE + +--- + +### Fix: Remove Hardcoded Keys + +**Before:** +```go +var encryptionKey = []byte("hardcoded-secret-key-32bytes!!") + +func encrypt(data []byte) ([]byte, error) { + block, _ := aes.NewCipher(encryptionKey) + // ... +} +``` + +**After:** +```go +import "os" + +func getEncryptionKey() []byte { + key := os.Getenv("ENCRYPTION_KEY") + if key == "" { + panic("ENCRYPTION_KEY environment variable not set") + } + return []byte(key) +} + +func encrypt(data []byte) ([]byte, error) { + block, _ := aes.NewCipher(getEncryptionKey()) + // ... +} +``` + +**Effort:** Medium (4-8 hours including deployment) +**Priority:** IMMEDIATE + +--- + +### Fix: Generate Random IV + +**Before:** +```go +var staticIV = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} + +func encrypt(plaintext []byte) []byte { + block, _ := aes.NewCipher(key) + cbc := cipher.NewCBCEncrypter(block, staticIV) + // ... +} +``` + +**After:** +```go +import "crypto/rand" + +func encrypt(plaintext []byte) ([]byte, error) { + block, _ := aes.NewCipher(key) + + // Generate random IV + iv := make([]byte, aes.BlockSize) + if _, err := rand.Read(iv); err != nil { + return nil, err + } + + cbc := cipher.NewCBCEncrypter(block, iv) + // Prepend IV to ciphertext for decryption + ciphertext := make([]byte, aes.BlockSize+len(plaintext)) + copy(ciphertext[:aes.BlockSize], iv) + // ... + return ciphertext, nil +} +``` + +**Effort:** Medium (4-6 hours) +**Priority:** IMMEDIATE + +--- + +### Future-Proofing: Post-Quantum Readiness + +**Current RSA Usage:** +```go +privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) +``` + +**Recommended Interim Upgrade:** +```go +// Use larger key size while PQ standards mature +privateKey, _ := rsa.GenerateKey(rand.Reader, 4096) +``` + +**Future (2027+):** +```go +// Monitor Go's ML-KEM implementation (FIPS 203) +// Plan hybrid RSA + ML-KEM deployment +``` + +**Effort:** High (research required) +**Priority:** MEDIUM (plan now, implement 2027-2029) + +--- + +## Testing Checklist + +- [ ] All MD5 usages replaced with SHA-256 +- [ ] All SHA-1 usages replaced with SHA-256 +- [ ] All hardcoded keys moved to environment variables +- [ ] All static IVs replaced with random generation +- [ ] Unit tests updated for new hash values +- [ ] Integration tests pass +- [ ] Security scan shows no HIGH/CRITICAL issues +- [ ] Documentation updated + +--- + +## Resources + +- [OWASP Cryptographic Storage Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html) +- [Go Crypto Package Documentation](https://pkg.go.dev/crypto) +- [NIST Post-Quantum Cryptography](https://csrc.nist.gov/projects/post-quantum-cryptography) + +--- + +*Generated by CryptoGuard-Go - Automated Cryptographic Vulnerability Scanner* +FIX_EXAMPLES + +echo "[OK] Detailed remediation guide generated: $REMEDIATION_FILE" + +# Display the report +echo "" +echo "Preview:" +echo "========================================" +head -50 "$REPORT_FILE" +echo "========================================" +echo "" +echo "Full report saved to: $REPORT_FILE" diff --git a/.github/scripts/scan-repos.sh b/.github/scripts/scan-repos.sh new file mode 100755 index 0000000..59592e0 --- /dev/null +++ b/.github/scripts/scan-repos.sh @@ -0,0 +1,218 @@ +#!/bin/bash +set -e + +# CryptoGuard-Go Weekly Repository Scanner +# This script scans multiple Go repositories for cryptographic vulnerabilities + +echo "CryptoGuard-Go Repository Scanner" +echo "====================================" +echo "" + +# Create output directories +mkdir -p scan-results +mkdir -p reports + +# Configuration +# Load settings from config file +CONFIG_FILE=".github/scan-config.yml" + +if [ -f "$CONFIG_FILE" ]; then + echo "[INFO] Loading configuration from $CONFIG_FILE" + # Extract excluded repos (simple grep/sed parsing) + EXCLUDED_REPOS=($(grep -A100 "excluded_repos:" "$CONFIG_FILE" | grep " - " | sed 's/.*- //' | grep -v "^#")) + + # Load scan settings + MAX_REPOS=$(grep "max_repos:" "$CONFIG_FILE" | sed 's/.*max_repos: //' || echo "10") + MIN_STARS=$(grep "min_stars:" "$CONFIG_FILE" | sed 's/.*min_stars: //' || echo "100") + MIN_FORKS=$(grep "min_forks:" "$CONFIG_FILE" | sed 's/.*min_forks: //' || echo "50") +else + # Fallback to defaults if config not found + MAX_REPOS=10 + MIN_STARS=100 + MIN_FORKS=50 + EXCLUDED_REPOS=() +fi + +# Display exclusion list +if [ ${#EXCLUDED_REPOS[@]} -gt 0 ]; then + echo "[INFO] Excluded repositories: ${EXCLUDED_REPOS[*]}" + echo "" +fi + +echo "Fetching top Go repositories from GitHub..." +echo "Criteria: stars >= $MIN_STARS, forks >= $MIN_FORKS" +echo "" + +# Setup GitHub API authentication if token is available +CURL_HEADERS="" +if [ -n "$GITHUB_TOKEN" ]; then + CURL_HEADERS="-H \"Authorization: token $GITHUB_TOKEN\"" + echo "[INFO] Using authenticated GitHub API (higher rate limits)" +else + echo "[INFO] Using unauthenticated GitHub API (60 requests/hour limit)" +fi +echo "" + +# Extract repository full names (owner/repo) +REPOS=() +for page in {1..10}; do + echo "Fetching page $page of top repositories..." + + # Build curl command with optional authentication + if [ -n "$GITHUB_TOKEN" ]; then + PAGE_DATA=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \ + "https://api.github.com/search/repositories?q=language:Go+stars:>=$MIN_STARS+forks:>=$MIN_FORKS&sort=stars&order=desc&per_page=100&page=$page") + else + PAGE_DATA=$(curl -s \ + "https://api.github.com/search/repositories?q=language:Go+stars:>=$MIN_STARS+forks:>=$MIN_FORKS&sort=stars&order=desc&per_page=100&page=$page") + fi + + # Check for API rate limit + if echo "$PAGE_DATA" | grep -q "API rate limit exceeded"; then + echo "[ERROR] GitHub API rate limit exceeded. Set GITHUB_TOKEN environment variable for higher limits." + break + fi + + # Extract repo names using grep and sed (works without jq) + PAGE_REPOS=$(echo "$PAGE_DATA" | grep '"full_name":' | sed 's/.*"full_name": "\([^"]*\)".*/\1/') + + # Add to array + while IFS= read -r repo; do + if [ -n "$repo" ]; then + REPOS+=("$repo") + fi + done <<< "$PAGE_REPOS" + + # Stop if we have enough repos or if page is empty + if [ ${#REPOS[@]} -ge $MAX_REPOS ] || [ -z "$PAGE_REPOS" ]; then + break + fi + + # Rate limit protection + sleep 1 +done + +# Limit to MAX_REPOS +if [ ${#REPOS[@]} -gt $MAX_REPOS ]; then + REPOS=("${REPOS[@]:0:$MAX_REPOS}") +fi + +# Filter out excluded repositories +if [ ${#EXCLUDED_REPOS[@]} -gt 0 ]; then + FILTERED_REPOS=() + for repo in "${REPOS[@]}"; do + excluded=false + for excluded_repo in "${EXCLUDED_REPOS[@]}"; do + if [ "$repo" = "$excluded_repo" ]; then + echo "[SKIP] Excluding $repo (in exclusion list)" + excluded=true + break + fi + done + if [ "$excluded" = false ]; then + FILTERED_REPOS+=("$repo") + fi + done + REPOS=("${FILTERED_REPOS[@]}") +fi + +# Counters +TOTAL_REPOS=0 +REPOS_WITH_ISSUES=0 +TOTAL_ISSUES=0 + +echo "" +echo "Total repositories to scan: ${#REPOS[@]}" +echo "" + +# Scan each repository +for repo in "${REPOS[@]}"; do + TOTAL_REPOS=$((TOTAL_REPOS + 1)) + + echo "-------------------------------------------" + echo "[$TOTAL_REPOS/${#REPOS[@]}] Scanning: $repo" + echo "-------------------------------------------" + + # Extract owner and repo name + OWNER=$(echo "$repo" | cut -d'/' -f1) + REPO_NAME=$(echo "$repo" | cut -d'/' -f2) + + # Create temp directory + TEMP_DIR="temp-scan-$REPO_NAME" + + # Clone repository (shallow clone for speed) + echo "Cloning repository..." + if git clone --depth 1 "https://github.com/$repo.git" "$TEMP_DIR" 2>/dev/null; then + echo "[OK] Repository cloned successfully" + + cd "$TEMP_DIR" + + # Check if it's a Go project + if [ -f "go.mod" ]; then + echo "[OK] Go project detected" + + # Run CryptoGuard-Go + echo "Running CryptoGuard-Go analysis..." + + # Scan and save results + RESULT_FILE="../scan-results/${OWNER}-${REPO_NAME}.txt" + JSON_FILE="../scan-results/${OWNER}-${REPO_NAME}.json" + + # Run scan (capture exit code) + set +e + ../cryptoguard -format text ./... > "$RESULT_FILE" 2>&1 + SCAN_EXIT_CODE=$? + + ../cryptoguard -format json ./... > "$JSON_FILE" 2>&1 + set -e + + # Count issues + ISSUE_COUNT=$(grep -c "issue(s) found" "$RESULT_FILE" | grep -oE '[0-9]+' || echo "0") + + if [ "$SCAN_EXIT_CODE" -eq 1 ] || grep -q "issue(s) found" "$RESULT_FILE"; then + echo "[WARNING] Found cryptographic issues" + REPOS_WITH_ISSUES=$((REPOS_WITH_ISSUES + 1)) + + # Extract issue count from the last line + ISSUES=$(tail -1 "$RESULT_FILE" | grep -oE '[0-9]+' || echo "0") + TOTAL_ISSUES=$((TOTAL_ISSUES + ISSUES)) + + echo " Issues found: $ISSUES" + else + echo "[OK] No cryptographic issues found" + fi + else + echo "[INFO] Not a Go project (no go.mod found)" + fi + + cd .. + + # Cleanup + rm -rf "$TEMP_DIR" + + else + echo "[ERROR] Failed to clone repository" + fi + + echo "" +done + +echo "==========================================" +echo "Scan Summary" +echo "==========================================" +echo "Total repositories scanned: $TOTAL_REPOS" +echo "Repositories with issues: $REPOS_WITH_ISSUES" +echo "Total issues found: $TOTAL_ISSUES" +echo "" + +# Save summary +cat > scan-results/summary.txt < +GitHub Action (click to expand) ```yaml name: Security Scan @@ -107,19 +144,7 @@ jobs: sarif_file: results.sarif ``` -## Academic Background - -This tool builds upon and extends: - -1. **CryptoGo** (ACSAC 2022) -- Automatic detection of Go cryptographic API misuses -2. **CryptoLint** (CCS 2012) -- First large-scale crypto misuse study -3. **NIST Post-Quantum Standards** (2024) -- FIPS 203, 204, 205 - -### Novel Contributions - -- Post-quantum readiness analysis: first tool to identify quantum-vulnerable crypto in Go. -- Cross-function taint analysis: tracks IV/key material across function boundaries. -- Context-aware detection: reduces false positives by understanding security context. + ## Contributing diff --git a/go.mod b/go.mod index fe8963a..c336ae6 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/ravisastryk/cryptoguard-go -go 1.25.4 +go 1.25 require golang.org/x/tools v0.41.0 diff --git a/reports/README.md b/reports/README.md new file mode 100644 index 0000000..505f281 --- /dev/null +++ b/reports/README.md @@ -0,0 +1,16 @@ +# Weekly Scan Reports + +This directory contains automated weekly vulnerability scan reports from CryptoGuard-Go. + +## Files + +- **summary.md** - Executive summary with vulnerability statistics and top findings +- **detailed-remediation.md** - Detailed remediation guide with code-level fixes + +## Update Schedule + +Reports are automatically generated and updated every Monday at 9:00 AM UTC by the GitHub Actions workflow. + +## Usage + +These reports are linked from the main README.md in the "Ecosystem Scan Results" section. diff --git a/reports/detailed-remediation.md b/reports/detailed-remediation.md new file mode 100644 index 0000000..0ee2c85 --- /dev/null +++ b/reports/detailed-remediation.md @@ -0,0 +1,253 @@ +# CryptoGuard-Go Detailed Remediation Guide + +**Generated:** 2026-02-01 + +This report provides detailed, actionable remediation steps for each identified vulnerability with code-level examples. + +--- + +## Quick Reference + +| Vulnerability | Severity | Recommended Fix | Priority | +|---------------|----------|-----------------|----------| +| MD5 Usage (CRYPTO001) | HIGH | Replace with SHA-256 | IMMEDIATE | +| SHA-1 Usage (CRYPTO002) | HIGH | Replace with SHA-256 | IMMEDIATE | +| Hardcoded Keys (CRYPTO010) | CRITICAL | Use environment variables/secrets | IMMEDIATE | +| Static IV (CRYPTO020) | CRITICAL | Use crypto/rand for generation | IMMEDIATE | +| Quantum-Vulnerable (CRYPTO040) | MEDIUM | Plan hybrid PQ migration | 2027-2029 | + +--- + + +## Repository-Specific Findings + + + +### Repository: fatedier\/frp + +**Total Issues:** 8 +**Breakdown:** 0 Critical, 3 High, 5 Medium, 0 Low + +#### Code Locations: + +| Severity | Rule | File:Line | Description | +|----------|------|-----------|-------------| + +**Recommended Actions:** +1. Address HIGH/CRITICAL issues immediately +2. Replace MD5 with SHA-256: `find . -name "*.go" -exec sed -i 's/crypto\/md5/crypto\/sha256/g' {} \;` +4. Consider post-quantum migration planning (informational) + +--- + + + +### Repository: kubernetes\/kubernetes + +**Total Issues:** 42 +**Breakdown:** 0 Critical, 0 High, 42 Medium, 0 Low + +#### Code Locations: + +| Severity | Rule | File:Line | Description | +|----------|------|-----------|-------------| + +**Recommended Actions:** +4. Consider post-quantum migration planning (informational) + +--- + + + +### Repository: ollama\/ollama + +**Total Issues:** 1 +**Breakdown:** 0 Critical, 1 High, 0 Medium, 0 Low + +#### Code Locations: + +| Severity | Rule | File:Line | Description | +|----------|------|-----------|-------------| + +**Recommended Actions:** +1. Address HIGH/CRITICAL issues immediately +2. Replace MD5 with SHA-256: `find . -name "*.go" -exec sed -i 's/crypto\/md5/crypto\/sha256/g' {} \;` + +--- + + +## Code Fix Examples + +### Fix: Replace MD5 with SHA-256 + +**Before:** +```go +import "crypto/md5" + +func GenerateHash(data []byte) string { + hash := md5.Sum(data) + return hex.EncodeToString(hash[:]) +} +``` + +**After:** +```go +import "crypto/sha256" + +func GenerateHash(data []byte) string { + hash := sha256.Sum256(data) + return hex.EncodeToString(hash[:]) +} +``` + +**Effort:** Low (1-2 hours) +**Priority:** IMMEDIATE + +--- + +### Fix: Replace SHA-1 with SHA-256 + +**Before:** +```go +import "crypto/sha1" + +h := sha1.New() +h.Write(data) +result := h.Sum(nil) +``` + +**After:** +```go +import "crypto/sha256" + +h := sha256.New() +h.Write(data) +result := h.Sum(nil) +``` + +**Effort:** Low (1-2 hours) +**Priority:** IMMEDIATE + +--- + +### Fix: Remove Hardcoded Keys + +**Before:** +```go +var encryptionKey = []byte("hardcoded-secret-key-32bytes!!") + +func encrypt(data []byte) ([]byte, error) { + block, _ := aes.NewCipher(encryptionKey) + // ... +} +``` + +**After:** +```go +import "os" + +func getEncryptionKey() []byte { + key := os.Getenv("ENCRYPTION_KEY") + if key == "" { + panic("ENCRYPTION_KEY environment variable not set") + } + return []byte(key) +} + +func encrypt(data []byte) ([]byte, error) { + block, _ := aes.NewCipher(getEncryptionKey()) + // ... +} +``` + +**Effort:** Medium (4-8 hours including deployment) +**Priority:** IMMEDIATE + +--- + +### Fix: Generate Random IV + +**Before:** +```go +var staticIV = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} + +func encrypt(plaintext []byte) []byte { + block, _ := aes.NewCipher(key) + cbc := cipher.NewCBCEncrypter(block, staticIV) + // ... +} +``` + +**After:** +```go +import "crypto/rand" + +func encrypt(plaintext []byte) ([]byte, error) { + block, _ := aes.NewCipher(key) + + // Generate random IV + iv := make([]byte, aes.BlockSize) + if _, err := rand.Read(iv); err != nil { + return nil, err + } + + cbc := cipher.NewCBCEncrypter(block, iv) + // Prepend IV to ciphertext for decryption + ciphertext := make([]byte, aes.BlockSize+len(plaintext)) + copy(ciphertext[:aes.BlockSize], iv) + // ... + return ciphertext, nil +} +``` + +**Effort:** Medium (4-6 hours) +**Priority:** IMMEDIATE + +--- + +### Future-Proofing: Post-Quantum Readiness + +**Current RSA Usage:** +```go +privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) +``` + +**Recommended Interim Upgrade:** +```go +// Use larger key size while PQ standards mature +privateKey, _ := rsa.GenerateKey(rand.Reader, 4096) +``` + +**Future (2027+):** +```go +// Monitor Go's ML-KEM implementation (FIPS 203) +// Plan hybrid RSA + ML-KEM deployment +``` + +**Effort:** High (research required) +**Priority:** MEDIUM (plan now, implement 2027-2029) + +--- + +## Testing Checklist + +- [ ] All MD5 usages replaced with SHA-256 +- [ ] All SHA-1 usages replaced with SHA-256 +- [ ] All hardcoded keys moved to environment variables +- [ ] All static IVs replaced with random generation +- [ ] Unit tests updated for new hash values +- [ ] Integration tests pass +- [ ] Security scan shows no HIGH/CRITICAL issues +- [ ] Documentation updated + +--- + +## Resources + +- [OWASP Cryptographic Storage Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html) +- [Go Crypto Package Documentation](https://pkg.go.dev/crypto) +- [NIST Post-Quantum Cryptography](https://csrc.nist.gov/projects/post-quantum-cryptography) + +--- + +*Generated by CryptoGuard-Go - Automated Cryptographic Vulnerability Scanner* diff --git a/reports/summary.md b/reports/summary.md new file mode 100644 index 0000000..61af3b5 --- /dev/null +++ b/reports/summary.md @@ -0,0 +1,66 @@ +# CryptoGuard-Go Weekly Vulnerability Scan Report + +**Scan Date:** 2026-02-01 18:43:31 UTC +**Tool Version:** v0.1.0 + +## Executive Summary + + +Total repositories scanned: 5 +Repositories with issues: 3 +Total issues found: 51 + + +## Detailed Findings + +### Vulnerability Summary by Repository + +| Repository | Total Issues | Critical | High | Medium | Low | Status | +|------------|--------------|----------|------|--------|-----|--------| +| avelino\/awesome\/go | 0 | 0 | 0 | 0 | 0 | ✓ Clean | +| fatedier\/frp | 8 | 0 | 3 | 5 | 0 | ✗ High | +| kubernetes\/kubernetes | 42 | 0 | 0 | 42 | 0 | ✗ Issues Found | +| ollama\/ollama | 1 | 0 | 1 | 0 | 0 | ✗ High | + +## Issue Breakdown + +### Issues by Rule Type + +| Rule ID | Description | Severity | Count | CWE | +|---------|-------------|----------|-------|-----| +| CRYPTO001 | MD5 usage for security purposes | HIGH | - | CWE-328 | +| CRYPTO002 | SHA1 usage for security purposes | HIGH | - | CWE-328 | +| CRYPTO010 | Hardcoded cryptographic key | CRITICAL | - | CWE-321 | +| CRYPTO020 | Static IV/nonce detected | CRITICAL | - | CWE-329 | +| CRYPTO040 | Quantum-vulnerable algorithm | MEDIUM | - | CWE-327 | + +## Recommendations + +### Critical Actions Required + +1. **Immediate Review**: All CRITICAL severity issues should be reviewed immediately +2. **Remediation Plan**: Create tickets for HIGH severity issues +3. **Security Best Practices**: + - Never hardcode cryptographic keys + - Use crypto/rand for IV/nonce generation + - Replace MD5/SHA1 with SHA-256 or stronger + - Consider post-quantum cryptography for long-term secrets + +### Next Steps + +- [ ] Review all CRITICAL findings +- [ ] Patch hardcoded keys immediately +- [ ] Update cryptographic algorithms +- [ ] Implement secure key management +- [ ] Run follow-up scan after remediation + +## Resources + +- [CryptoGuard-Go Documentation](https://github.com/ravisastryk/cryptoguard-go) +- [OWASP Cryptographic Storage Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html) +- [Go Crypto Best Practices](https://golang.org/pkg/crypto/) + +--- + +*Report generated by CryptoGuard-Go - Automated Cryptographic Vulnerability Scanner* +*For questions or issues, please visit: https://github.com/ravisastryk/cryptoguard-go/issues*