security operations

Performing Red Team Phishing With Gophish

Automate GoPhish phishing simulation campaigns using the Python gophish library. Creates email templates with tracking pixels, configures SMTP sending profiles, builds target groups from CSV, launches campaigns, and analyzes results including open rates, click rates, and credential submission statistics for security awareness assessment.

campaign-automationgophishphishing-simulationred-teamingsecurity-awarenesssocial-engineering
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

  • When conducting security assessments that involve performing red team phishing with gophish
  • 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 security operations 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

Instructions

  1. Install dependencies: pip install gophish requests
  2. Deploy GoPhish server and obtain an API key from Settings.
  3. Use the Python gophish library to automate campaign setup:
    • Create email templates with HTML body and tracking
    • Configure SMTP sending profiles
    • Import target groups from CSV
    • Create landing pages for credential capture
    • Launch and monitor campaigns
  4. Analyze campaign results: opens, clicks, submitted data, reported.
# For authorized penetration testing and lab environments only
python scripts/agent.py --gophish-url https://localhost:3333 --api-key <key> --campaign-name "Q1 Awareness" --output phishing_report.json

Examples

Create Campaign via API

from gophish import Gophish
from gophish.models import Campaign, Template, Group, SMTP, Page
api = Gophish("api_key", host="https://localhost:3333", verify=False)  # Self-signed cert on localhost lab
campaign = Campaign(name="Q1 Test", groups=[Group(name="Sales Team")],
    template=Template(name="IT Password Reset"), smtp=SMTP(name="Internal SMTP"),
    page=Page(name="Credential Page"))
api.campaigns.post(campaign)
Source materials

References and resources

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

References 1

api-reference.md1.8 KB

API Reference: GoPhish Phishing Simulation

Python gophish Library

Constructor

from gophish import Gophish
api = Gophish(api_key, host="https://localhost:3333", verify=False)

Campaigns

api.campaigns.get()                    # List all campaigns
api.campaigns.get(campaign_id=1)       # Get specific campaign
api.campaigns.post(campaign)           # Create and launch campaign
api.campaigns.summary(campaign_id=1)   # Get campaign summary
api.campaigns.delete(campaign_id=1)    # Delete campaign

Templates

api.templates.get()                    # List templates
api.templates.post(template)           # Create template
Template(name="...", subject="...", html="<html>...</html>", text="...")

Groups

api.groups.get()                       # List groups
api.groups.post(group)                 # Create group
Group(name="...", targets=[User(first_name="", last_name="", email="")])

SMTP Profiles

api.smtp.get()
api.smtp.post(smtp)
SMTP(name="...", from_address="...", host="smtp:587", username="", password="")

Landing Pages

api.pages.get()
api.pages.post(page)
Page(name="...", html="...", capture_credentials=True, redirect_url="")

Campaign Model

Campaign(
    name="Q1 Test",
    template=Template(name="Existing Template"),
    page=Page(name="Existing Page"),
    smtp=SMTP(name="Existing Profile"),
    groups=[Group(name="Existing Group")],
    url="https://phish.example.com",
    launch_date="2024-01-15T09:00:00+00:00"  # ISO8601
)

Result Statuses

Status Meaning
Email Sent Email delivered
Email Opened Tracking pixel loaded
Clicked Link Phishing URL clicked
Submitted Data Credentials entered
Reported User reported phishing

Scripts 1

agent.py7.1 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
# For authorized penetration testing and lab environments only
"""GoPhish Campaign Agent - Automates phishing simulation setup, launch, and analysis."""

import json
import csv
import logging
import argparse
from datetime import datetime

from gophish import Gophish
from gophish.models import Campaign, Template, Group, SMTP, Page, User

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)


def connect_gophish(api_key, host):
    """Connect to GoPhish server via API."""
    api = Gophish(api_key, host=host, verify=False)
    logger.info("Connected to GoPhish at %s", host)
    return api


def create_email_template(api, name, subject, html_body, text_body=""):
    """Create an email template in GoPhish."""
    template = Template(name=name, subject=subject, html=html_body, text=text_body)
    result = api.templates.post(template)
    logger.info("Created template: %s (ID: %d)", result.name, result.id)
    return result


def create_landing_page(api, name, html_content, capture_credentials=True, redirect_url=""):
    """Create a landing page for credential capture."""
    page = Page(
        name=name,
        html=html_content,
        capture_credentials=capture_credentials,
        redirect_url=redirect_url,
    )
    result = api.pages.post(page)
    logger.info("Created landing page: %s (ID: %d)", result.name, result.id)
    return result


def create_smtp_profile(api, name, smtp_from, host, port=587, username="", password="", ignore_cert=False):
    """Create an SMTP sending profile."""
    smtp = SMTP(
        name=name,
        from_address=smtp_from,
        host=f"{host}:{port}",
        username=username,
        password=password,
        ignore_cert_errors=ignore_cert,
    )
    result = api.smtp.post(smtp)
    logger.info("Created SMTP profile: %s (ID: %d)", result.name, result.id)
    return result


def import_targets_from_csv(api, group_name, csv_path):
    """Import target users from a CSV file into a GoPhish group."""
    targets = []
    with open(csv_path, "r") as f:
        reader = csv.DictReader(f)
        for row in reader:
            targets.append(User(
                first_name=row.get("first_name", ""),
                last_name=row.get("last_name", ""),
                email=row.get("email", ""),
                position=row.get("position", ""),
            ))
    group = Group(name=group_name, targets=targets)
    result = api.groups.post(group)
    logger.info("Created group '%s' with %d targets", group_name, len(targets))
    return result


def launch_campaign(api, name, template_name, page_name, smtp_name, group_name, url):
    """Launch a phishing simulation campaign."""
    campaign = Campaign(
        name=name,
        template=Template(name=template_name),
        page=Page(name=page_name),
        smtp=SMTP(name=smtp_name),
        groups=[Group(name=group_name)],
        url=url,
    )
    result = api.campaigns.post(campaign)
    logger.info("Launched campaign: %s (ID: %d)", result.name, result.id)
    return result


def get_campaign_results(api, campaign_id):
    """Retrieve detailed results for a campaign."""
    campaign = api.campaigns.get(campaign_id=campaign_id)
    results = {
        "name": campaign.name,
        "status": campaign.status,
        "created_date": str(campaign.created_date),
        "launch_date": str(campaign.launch_date),
        "results": [],
    }
    for result in campaign.results:
        results["results"].append({
            "email": result.email,
            "first_name": result.first_name,
            "last_name": result.last_name,
            "status": result.status,
            "reported": result.reported,
        })
    return results


def analyze_campaign_metrics(campaign_results):
    """Calculate campaign performance metrics."""
    results = campaign_results.get("results", [])
    total = len(results)
    if total == 0:
        return {"total": 0}
    statuses = {"Email Sent": 0, "Email Opened": 0, "Clicked Link": 0, "Submitted Data": 0, "Reported": 0}
    for r in results:
        status = r.get("status", "")
        if status in statuses:
            statuses[status] += 1
        if r.get("reported"):
            statuses["Reported"] += 1
    metrics = {
        "total_targets": total,
        "emails_sent": statuses["Email Sent"],
        "opened": statuses["Email Opened"],
        "clicked": statuses["Clicked Link"],
        "submitted_credentials": statuses["Submitted Data"],
        "reported": statuses["Reported"],
        "open_rate": round(statuses["Email Opened"] / total * 100, 1),
        "click_rate": round(statuses["Clicked Link"] / total * 100, 1),
        "submission_rate": round(statuses["Submitted Data"] / total * 100, 1),
        "report_rate": round(statuses["Reported"] / total * 100, 1),
    }
    logger.info("Campaign metrics: %d targets, %.1f%% clicked, %.1f%% submitted",
                total, metrics["click_rate"], metrics["submission_rate"])
    return metrics


def list_campaigns(api):
    """List all campaigns and their statuses."""
    campaigns = api.campaigns.get()
    return [{"id": c.id, "name": c.name, "status": c.status} for c in campaigns]


def generate_report(campaign_results, metrics):
    """Generate phishing simulation report."""
    report = {
        "timestamp": datetime.utcnow().isoformat(),
        "campaign": campaign_results.get("name"),
        "status": campaign_results.get("status"),
        "metrics": metrics,
        "detailed_results": campaign_results.get("results", [])[:50],
    }
    print(f"PHISHING REPORT: {metrics.get('total_targets', 0)} targets, "
          f"{metrics.get('click_rate', 0)}% click rate, "
          f"{metrics.get('submission_rate', 0)}% credential submission")
    return report


def main():
    parser = argparse.ArgumentParser(description="GoPhish Campaign Agent")
    parser.add_argument("--gophish-url", required=True, help="GoPhish server URL")
    parser.add_argument("--api-key", required=True, help="GoPhish API key")
    parser.add_argument("--campaign-id", type=int, help="Existing campaign ID to analyze")
    parser.add_argument("--campaign-name", help="Name for new campaign")
    parser.add_argument("--template-name", help="Email template name")
    parser.add_argument("--group-name", help="Target group name")
    parser.add_argument("--targets-csv", help="CSV file with targets")
    parser.add_argument("--output", default="phishing_report.json")
    args = parser.parse_args()

    api = connect_gophish(args.api_key, args.gophish_url)

    if args.targets_csv and args.group_name:
        import_targets_from_csv(api, args.group_name, args.targets_csv)

    if args.campaign_id:
        results = get_campaign_results(api, args.campaign_id)
        metrics = analyze_campaign_metrics(results)
        report = generate_report(results, metrics)
    else:
        campaigns = list_campaigns(api)
        report = {"campaigns": campaigns, "timestamp": datetime.utcnow().isoformat()}
        logger.info("Listed %d campaigns", len(campaigns))

    with open(args.output, "w") as f:
        json.dump(report, f, indent=2, default=str)
    logger.info("Report saved to %s", args.output)


if __name__ == "__main__":
    main()
Keep exploring