#!/usr/bin/env bash
set -euo pipefail

# Script Name: bb-report-generator
# Description: Generate bug bounty recon report from bb-recon output
# Based on Jason Haddix's "Find Features First, Bugs Second" philosophy

VERSION="1.0.0"

# Colors
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly CYAN='\033[0;36m'
readonly MAGENTA='\033[0;35m'
readonly BOLD='\033[1m'
readonly NC='\033[0m'

show_help() {
  echo -e "${BOLD}bb-report-generator${NC} - Bug Bounty Recon Report Generator v${VERSION}"
  echo
  echo -e "${BOLD}USAGE:${NC}"
  echo "  bb-report-generator <recon-directory>"
  echo
  echo -e "${BOLD}DESCRIPTION:${NC}"
  echo "  Analyzes bb-recon output and generates prioritized manual testing guide"
  echo "  Based on Jason Haddix's Bug Hunter Methodology"
  echo
  echo -e "${BOLD}EXAMPLES:${NC}"
  echo "  bb-report-generator ./bb-recon-target.com-20240101-120000"
  echo "  bb-report-generator ./bb-recon-*"
  echo
  echo -e "${BOLD}OUTPUT:${NC}"
  echo "  Creates manual-testing-guide.md in the recon directory"
}

if [[ $# -eq 0 ]] || [[ "$1" =~ ^(-h|--help|help)$ ]]; then
  show_help
  exit 0
fi

RECON_DIR="$1"

if [[ ! -d "$RECON_DIR" ]]; then
  echo -e "${RED}Error:${NC} Directory not found: $RECON_DIR"
  exit 1
fi

echo -e "${CYAN}${BOLD}"
echo "╔════════════════════════════════════════════════════════════╗"
echo "║      Bug Bounty Recon Report Generator                    ║"
echo "║      Jason Haddix Methodology: Features → Bugs            ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

REPORT_FILE="$RECON_DIR/manual-testing-guide.md"

# Start report
cat > "$REPORT_FILE" << 'EOF'
# Bug Bounty Manual Testing Guide

**Generated:** $(date)
**Philosophy:** Find FEATURES first, then BUGS second (Jason Haddix)

---

## 🎯 High Priority Testing Areas

Based on Jason Haddix's "Heat Map" - where bugs normally hide:

### 1. Upload Functions 🔥 (HIGHEST PRIORITY)
**Why:** Always vulnerable! XSS, XXE, SSRF, Shell upload

**Actions:**
- [ ] Find all file upload endpoints
- [ ] Test XML-based uploads (Docs/PDFs) for XXE and SSRF
- [ ] Test image uploads for XSS in filename/EXIF/binary header
- [ ] Check where uploaded files are stored (S3 misconfigurations?)
- [ ] Try polyglot files (valid image + shell code)

### 2. APIs 🔥
**Why:** Hidden HTTP methods, lack of auth, mass assignment, excessive data exposure

**Actions:**
- [ ] Test PUT, DELETE, PATCH methods (not just GET/POST)
- [ ] Check for missing authentication
- [ ] Test for mass assignment vulnerabilities
- [ ] Look for excessive data exposure in responses
- [ ] Analyze API versioning (v1, v2, etc.) for inconsistencies

### 3. Account Section (Profile/Settings) 🔥
**Why:** Stored XSS, SSTI, SSRF

**Actions:**
- [ ] Test ALL custom fields for Stored XSS
- [ ] Check bio, name, location, custom fields
- [ ] Test webhook URLs and callback URLs for SSRF
- [ ] Look for integrations that import external content

### 4. Content Types 🔥
**Why:** Multipart-forms "always have a vulnerability"

**Actions:**
- [ ] Test `multipart/form-data` for shell uploads, injections, bypasses
- [ ] Test `Content-Type: application/xml` for XXE
- [ ] Test `Content-Type: application/json` for API vulnerabilities

### 5. Error Messages
**Why:** Information disclosure, exotic injection vectors

**Actions:**
- [ ] Trigger errors intentionally
- [ ] Check stack traces for paths, versions, database types
- [ ] Test for Application DoS via resource exhaustion

### 6. URLs/Paths as Values
**Why:** SSRF, Open Redirects

**Actions:**
- [ ] Find parameters like: `?url=`, `?redirect=`, `?next=`, `?callback=`
- [ ] Test for SSRF vulnerabilities
- [ ] Test for open redirects

---

## 📊 Recon Summary

EOF

# Add Technology Stack section
echo "### Technology Stack Identified" >> "$REPORT_FILE"
echo >> "$REPORT_FILE"
if [[ -f "$RECON_DIR/httpx.txt" ]]; then
  echo "**Technologies detected (httpx):**" >> "$REPORT_FILE"
  echo '```' >> "$REPORT_FILE"
  cat "$RECON_DIR/httpx.txt" | head -20 >> "$REPORT_FILE"
  echo '```' >> "$REPORT_FILE"
elif [[ -f "$RECON_DIR/whatweb.txt" ]]; then
  echo "**Technologies detected (whatweb):**" >> "$REPORT_FILE"
  grep -oE '\[[^\]]+\]' "$RECON_DIR/whatweb.txt" | sort -u | head -20 >> "$REPORT_FILE" || echo "None found" >> "$REPORT_FILE"
else
  echo "*No technology fingerprinting data available*" >> "$REPORT_FILE"
fi
echo >> "$REPORT_FILE"

# Add Nuclei Findings section
echo "### Nuclei Findings (Info/Low Severity)" >> "$REPORT_FILE"
echo >> "$REPORT_FILE"
if [[ -f "$RECON_DIR/nuclei.txt" ]] && [[ -s "$RECON_DIR/nuclei.txt" ]]; then
  NUCLEI_COUNT=$(wc -l < "$RECON_DIR/nuclei.txt")
  echo "**Total findings:** $NUCLEI_COUNT" >> "$REPORT_FILE"
  echo >> "$REPORT_FILE"
  echo '```' >> "$REPORT_FILE"
  head -20 "$RECON_DIR/nuclei.txt" >> "$REPORT_FILE"
  echo '```' >> "$REPORT_FILE"
else
  echo "*No Nuclei findings*" >> "$REPORT_FILE"
fi
echo >> "$REPORT_FILE"

# Add Subdomain Takeover section
echo "### Subdomain Takeover Check" >> "$REPORT_FILE"
echo >> "$REPORT_FILE"
if [[ -f "$RECON_DIR/takeover.txt" ]] && [[ -s "$RECON_DIR/takeover.txt" ]]; then
  echo "**⚠️ POTENTIAL TAKEOVER VULNERABILITIES FOUND!**" >> "$REPORT_FILE"
  echo >> "$REPORT_FILE"
  echo '```' >> "$REPORT_FILE"
  cat "$RECON_DIR/takeover.txt" >> "$REPORT_FILE"
  echo '```' >> "$REPORT_FILE"
else
  echo "✅ No subdomain takeover vulnerabilities detected" >> "$REPORT_FILE"
fi
echo >> "$REPORT_FILE"

# Add Endpoints Discovered section
echo "### Endpoints Discovered (Katana Crawler)" >> "$REPORT_FILE"
echo >> "$REPORT_FILE"
if [[ -f "$RECON_DIR/katana_urls.txt" ]] && [[ -s "$RECON_DIR/katana_urls.txt" ]]; then
  URL_COUNT=$(wc -l < "$RECON_DIR/katana_urls.txt")
  echo "**Total URLs crawled:** $URL_COUNT" >> "$REPORT_FILE"
  echo >> "$REPORT_FILE"
  echo "**Sample URLs (first 20):**" >> "$REPORT_FILE"
  echo '```' >> "$REPORT_FILE"
  head -20 "$RECON_DIR/katana_urls.txt" >> "$REPORT_FILE"
  echo '```' >> "$REPORT_FILE"
else
  echo "*No URLs discovered*" >> "$REPORT_FILE"
fi
echo >> "$REPORT_FILE"

# Add JavaScript Endpoints section
echo "### JavaScript Endpoints & Paths" >> "$REPORT_FILE"
echo >> "$REPORT_FILE"
if [[ -f "$RECON_DIR/katana_paths.txt" ]] && [[ -s "$RECON_DIR/katana_paths.txt" ]]; then
  PATH_COUNT=$(wc -l < "$RECON_DIR/katana_paths.txt")
  echo "**Total paths discovered:** $PATH_COUNT" >> "$REPORT_FILE"
  echo >> "$REPORT_FILE"
  echo "**Interesting paths (first 20):**" >> "$REPORT_FILE"
  echo '```' >> "$REPORT_FILE"
  head -20 "$RECON_DIR/katana_paths.txt" >> "$REPORT_FILE"
  echo '```' >> "$REPORT_FILE"
else
  echo "*No JavaScript paths discovered*" >> "$REPORT_FILE"
fi
echo >> "$REPORT_FILE"

# Add "The Big 6 Questions" section
cat >> "$REPORT_FILE" << 'EOF'

---

## 🔍 The Big 6 Questions (Jason Haddix)

Answer these before testing:

### 1. How does the app pass data?
**Map ALL input methods:**
- [ ] GET parameters
- [ ] POST parameters
- [ ] JSON body data
- [ ] XML body data
- [ ] Cookies
- [ ] Custom headers (X-*)
- [ ] WebSocket messages
- [ ] GraphQL queries

### 2. How/Where does the app talk about users?
**Find user identifiers for IDOR/Authorization testing:**
- [ ] User IDs in URLs
- [ ] UUIDs
- [ ] Email addresses
- [ ] Usernames
- [ ] Session tokens
- [ ] JWT tokens (decode and analyze!)

**Tip:** IDOR → XSS chain for higher severity!

### 3. Does the site have multi-tenancy or user levels?
**Test for authorization bugs:**
- [ ] Regular user vs Admin
- [ ] Free tier vs Premium tier
- [ ] Organization A vs Organization B
- [ ] Test horizontal access (User A → User B data)
- [ ] Test vertical access (User → Admin escalation)

**Use Burp's Autorize extension!**

### 4. Does the site have a unique threat model?
**Beyond PII, look for:**
- [ ] API keys and secrets (developer portals)
- [ ] Doxing opportunities (social platforms)
- [ ] Financial data (payment platforms)
- [ ] Healthcare data (HIPAA)

### 5. Has there been past security research?
**Search for previous vulnerabilities:**
- [ ] HackerOne disclosed reports
- [ ] Bugcrowd disclosures
- [ ] CVE databases
- [ ] Security researcher blogs
- [ ] Conference presentations

**Google:** `site:hackerone.com "target.com" disclosed`

### 6. How does the app handle XSS? CSRF? Injection?
**Understand defenses:**
- [ ] WAF presence (Cloudflare, Akamai, ModSecurity)
- [ ] XSS filters (CSP, Chrome Auditor)
- [ ] CSRF tokens (present? validated? reusable?)
- [ ] Input sanitization
- [ ] Output encoding

**Adaptive Strategy:** Don't waste time on hardened areas - find soft spots!

---

## 📋 Manual Testing Checklist

Based on findings, prioritize testing:

### Phase 1: Quick Wins
- [ ] Test all file upload endpoints (if any)
- [ ] Check for subdomain takeovers (already scanned)
- [ ] Test exposed admin panels (from Nuclei)
- [ ] Check for default credentials
- [ ] Test open redirects in `?url=` parameters

### Phase 2: Authorization Testing
- [ ] Create 2+ accounts at different privilege levels
- [ ] Test IDOR on all endpoints with user identifiers
- [ ] Test horizontal access (User A → User B)
- [ ] Test vertical access (User → Admin)
- [ ] Use Burp Autorize for automated testing

### Phase 3: Input Validation
- [ ] Test XSS in all input fields
- [ ] Test SQL injection in parameters
- [ ] Test SSRF in URL/webhook parameters
- [ ] Test XXE in XML endpoints
- [ ] Test SSTI in template fields

### Phase 4: Business Logic
- [ ] Test race conditions (payments, redemptions)
- [ ] Test negative quantities
- [ ] Test price manipulation
- [ ] Test insecure password reset flows

### Phase 5: Deep Dive
- [ ] JavaScript analysis for hidden endpoints
- [ ] API testing (hidden methods, versions)
- [ ] Session management testing
- [ ] CSRF testing

---

## 🛠️ Recommended Tools for Manual Testing

**Burp Suite Extensions:**
- LinkFinder - Parse JS for endpoints
- Hunt Scanner RMX - Highlight interesting parameters
- Autorize - Automated authorization testing
- Burp Bounty - Custom scan checks + Blind XSS

**Command-line:**
- `sqlmap` - SQL injection testing
- `ffuf` - Directory/parameter fuzzing (if needed)
- `dalfox` - XSS scanner
- `nuclei` - CVE and exploit template scanning

**Remember:** Run aggressive tools ONLY if within bug bounty program rules!

---

## 📚 Resources

- [Jason Haddix - The Bug Hunter's Methodology](https://www.youtube.com/watch?v=uKWu6yhnhbQ)
- [PortSwigger Web Security Academy](https://portswigger.net/web-security)
- [OWASP Testing Guide](https://owasp.org/www-project-web-security-testing-guide/)
- [HackerOne Disclosed Reports](https://hackerone.com/hacktivity)

---

**Generated by bb-report-generator v1.0.0**
EOF

echo -e "${GREEN}✓ Report generated:${NC} $REPORT_FILE"
echo
echo -e "${CYAN}Next steps:${NC}"
echo "  1. Read the manual testing guide"
echo "  2. Answer 'The Big 6 Questions'"
echo "  3. Follow the prioritized testing checklist"
echo "  4. Find FEATURES first, then BUGS second!"
