phishing defense

Implementing Mimecast Targeted Attack Protection

Deploy Mimecast Targeted Threat Protection including URL Protect, Attachment Protect, Impersonation Protect, and Internal Email Protect to defend against advanced phishing and spearphishing attacks.

attachment-sandboxingemail-securityimpersonationmimecastphishingtargeted-threat-protectionurl-protect
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

Mimecast Targeted Threat Protection (TTP) is a suite of advanced email security services designed to protect against sophisticated phishing, spearphishing, and targeted attacks. TTP consists of four core modules: URL Protect (real-time URL rewriting and click-time analysis), Attachment Protect (sandbox detonation of suspicious attachments), Impersonation Protect (BEC and whaling detection), and Internal Email Protect (scanning internal/outbound email for threats). As of November 2025, Mimecast enabled URL Pre-Delivery Action with Hold setting for all customers by default.

When to Use

  • When deploying or configuring implementing mimecast targeted attack protection capabilities in your environment
  • When establishing security controls aligned to compliance requirements
  • When building or improving security architecture for this domain
  • When conducting security assessments that require this implementation

Prerequisites

  • Mimecast Email Security license with TTP add-on
  • Administrative access to Mimecast Administration Console
  • Microsoft 365 or Google Workspace environment
  • MX records configured to route through Mimecast
  • Understanding of email authentication (SPF, DKIM, DMARC)

Key Concepts

TTP Module Overview

Module Function Key Capability
URL Protect Rewrites and scans URLs at click time Real-time sandbox, pre-delivery hold
Attachment Protect Sandboxes suspicious attachments Static + dynamic analysis
Impersonation Protect Detects BEC/whaling attacks VIP name matching, header analysis
Internal Email Protect Scans internal/outbound email Lateral phishing detection

Impersonation Protection Scenarios

  • Hit 3 (Default): Flags emails matching 3+ impersonation indicators
  • Hit 1 (VIP): Flags emails matching 1+ indicator for designated VIP users
  • Key identifiers: display name similarity, domain similarity, reply-to mismatch, newly registered domains

URL Protect Modes

  • Rewrite: URLs rewritten to route through Mimecast proxy at click time
  • Pre-Delivery Action (Hold): URLs checked before message delivery; held if suspicious
  • Pre-Delivery Action (None): URLs checked pre-delivery but not held

Workflow

Step 1: Configure URL Protect Policy

  • Navigate to Administration > Gateway > Policies > Targeted Threat Protection - URL Protect
  • Create URL Protect definition with rewriting enabled for inbound messages
  • Enable URL Pre-Delivery Action set to "Hold" for maximum protection
  • Configure scan mode: aggressive for high-risk users, moderate for general population
  • Set action for malicious URLs: block page with user notification
  • Enable URL logging for all click events

Step 2: Configure Attachment Protect Policy

  • Navigate to Administration > Gateway > Policies > Targeted Threat Protection - Attachment Protect
  • Create Attachment Protect definition for inbound email
  • Select sandbox mode: "Safe File" (converts to safe format) or "Dynamic Configuration" (full sandbox)
  • Configure attachment types to scan: executables, Office documents, PDFs, archives
  • Set timeout for sandbox analysis (default: up to 7 minutes for complex files)
  • Enable pre-emptive sandboxing for attachments from unknown senders

Step 3: Configure Impersonation Protect

  • Create Default Impersonation Protect Definition (Hit 3) for all inbound email
  • Create VIP Impersonation Protect Definition (Hit 1) for executive protection
  • Build VIP list: CEO, CFO, CTO, board members, finance leadership
  • Configure detection identifiers: display name, domain similarity, newly observed sender
  • Set actions: quarantine high-confidence impersonation, tag moderate confidence
  • Enable end-user warning banners for flagged messages

Step 4: Enable Internal Email Protect

  • Configure journaling from Microsoft 365/Google Workspace to Mimecast
  • Enable URL scanning for internal emails
  • Enable attachment scanning for internal emails
  • Configure alerts for internal account compromise indicators
  • Set up detection for internal phishing (compromised account sending malware)

Step 5: Create Test Group and Validate

  • Create pilot group of 50-100 users across departments
  • Apply TTP policies to pilot group first
  • Send test emails with known-safe test URLs and EICAR test files
  • Verify URL rewriting, attachment sandboxing, and impersonation detection
  • Monitor false positive rate for 1-2 weeks before organization-wide deployment

Step 6: Deploy Organization-Wide and Tune

  • Extend TTP policies to all users
  • Monitor Mimecast Threat Dashboard for detection metrics
  • Review and whitelist legitimate applications triggering false positives
  • Tune impersonation sensitivity based on false positive feedback
  • Configure exception policies for automated systems and mailing lists

Tools & Resources

  • Mimecast Administration Console: Policy configuration and management
  • Mimecast Threat Dashboard: Real-time threat visibility and analytics
  • Mimecast Awareness Training: Integrated security awareness platform
  • Mimecast API: Programmatic access to logs and threat data
  • Message Center: Quarantine management for admins and users

Validation

  • URL Protect rewrites URLs in test messages and blocks known-malicious at click
  • Attachment Protect sandboxes test file and returns verdict within SLA
  • Impersonation Protect flags test BEC email impersonating VIP
  • Internal Email Protect detects test lateral phishing scenario
  • Pre-delivery hold catches weaponized URL before reaching inbox
  • False positive rate below organizational threshold after tuning
Source materials

References and resources

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

References 3

api-reference.md1.4 KB

API Reference: Implementing Mimecast Targeted Attack Protection

Mimecast API Authentication

import requests
headers = {"Authorization": "MC access_key:secret_key",
           "x-mc-app-id": "app-id"}
resp = requests.post("https://us-api.mimecast.com/api/ttp/url/get-logs",
                     headers=headers, json={"data": [{"from": "2024-01-01"}]})

TTP API Endpoints

Endpoint Description
/api/ttp/url/get-logs URL Protection logs
/api/ttp/attachment/get-logs Attachment sandbox logs
/api/ttp/impersonation/get-logs Impersonation detections

URL Protection Actions

Action Description
allow URL permitted
block URL blocked (malicious)
warn User warned before click
sandbox Deferred for sandbox analysis

Attachment Sandbox Results

Result Severity
safe INFO
suspicious MEDIUM
malicious CRITICAL
sandbox_timeout HIGH

Impersonation Types

Type Description
Internal Employee name spoofing
External Vendor/partner spoofing
Domain Similar domain detection

References

standards.md1.7 KB

Standards & References: Implementing Mimecast Targeted Attack Protection

MITRE ATT&CK References

  • T1566.001: Phishing: Spearphishing Attachment
  • T1566.002: Phishing: Spearphishing Link
  • T1534: Internal Spearphishing
  • T1598: Phishing for Information
  • T1656: Impersonation
  • T1204.001: User Execution: Malicious Link
  • T1204.002: User Execution: Malicious File

Mimecast TTP Components

Component Version Key Feature
URL Protect Current Pre-delivery hold (Nov 2025 default)
Attachment Protect Current Safe File + Dynamic sandbox
Impersonation Protect Current Hit 1 (VIP) / Hit 3 (Default)
Internal Email Protect Current Journal-based internal scanning

Compliance Alignment

  • CIS Controls v8 Control 9.2: Use DNS filtering services
  • CIS Controls v8 Control 9.6: Block unnecessary file types
  • NIST SP 800-177: Trustworthy Email
  • SOC 2 CC6.1: Logical and physical access controls
  • ISO 27001 A.8.23: Web filtering

Impersonation Protection Indicators

Indicator Description Weight
Display name match External sender uses internal VIP display name High
Domain similarity Sender domain visually similar to internal domain High
Reply-to mismatch Reply-to differs from From address Medium
Newly observed First-time sender to recipient Medium
Header anomaly Unusual mail routing or missing authentication Medium

Integration Points

  • Microsoft 365 via connector and journaling
  • Google Workspace via gateway routing
  • SIEM via syslog or API (Splunk, QRadar, Sentinel)
  • SOAR platforms via Mimecast API
  • Directory sync via Active Directory / Azure AD
workflows.md2.2 KB

Workflows: Implementing Mimecast Targeted Attack Protection

Workflow 1: URL Protect Processing

Inbound email with URLs arrives
  |
  v
[Pre-delivery URL check]
  +-- Extract all URLs from body and attachments
  +-- Check against Mimecast threat intelligence
  +-- KNOWN MALICIOUS --> Hold/Block message
  +-- SUSPICIOUS --> Hold for deeper analysis
  +-- CLEAN --> Proceed to rewriting
  |
  v
[URL rewriting]
  +-- Replace original URLs with Mimecast proxy URLs
  +-- Preserve original URL in encoded format
  +-- Apply per-policy rewriting rules
  |
  v
[Message delivered to user inbox]
  |
  v
[User clicks rewritten URL]
  |
  v
[Time-of-click analysis]
  +-- Real-time page scan and sandbox
  +-- Check for credential harvesting forms
  +-- Check for malware downloads
  |
  v
[Decision]
  +-- SAFE: Redirect to original URL
  +-- MALICIOUS: Display block page
  +-- SUSPICIOUS: Display warning with proceed option

Workflow 2: Attachment Protect Pipeline

Email with attachment arrives
  |
  v
[Static analysis]
  +-- File type identification
  +-- Signature matching
  +-- Known malware hash check
  |
  v
[Policy evaluation]
  +-- Safe File mode: Convert to safe format (PDF)
  +-- Dynamic mode: Full sandbox detonation
  +-- Bypass: Whitelisted sender/type
  |
  v
[Dynamic sandbox (if configured)]
  +-- Execute in isolated environment
  +-- Monitor for malicious behavior
  +-- Check for C2 callbacks, file drops, registry changes
  +-- Timeout: up to 7 minutes
  |
  v
[Verdict]
  +-- CLEAN: Deliver original attachment
  +-- MALICIOUS: Quarantine, notify admin
  +-- TIMEOUT: Deliver with warning or hold per policy

Workflow 3: Impersonation Protect Analysis

Inbound email arrives
  |
  v
[Identifier check against VIP list]
  +-- Compare display name to VIP names
  +-- Check domain similarity to internal domains
  +-- Verify reply-to alignment
  +-- Check if sender is newly observed
  |
  v
[Hit scoring]
  +-- Hit 1 policy (VIP): 1+ indicator match
  +-- Hit 3 policy (Default): 3+ indicator matches
  |
  v
[Action based on hit level]
  +-- QUARANTINE: High confidence impersonation
  +-- TAG: Moderate confidence, add warning banner
  +-- LOG: Low confidence, record for analysis
  +-- DELIVER: No indicators matched

Scripts 2

agent.py6.1 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Mimecast Targeted Attack Protection Agent - monitors TAP events and URL/attachment threats."""

import json
import argparse
import base64
import hashlib
import hmac
import logging
import os
import subprocess
import uuid
from collections import defaultdict
from datetime import datetime

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

MIMECAST_BASE = os.environ.get("MIMECAST_BASE_URL", "https://us-api.mimecast.com")


def mimecast_request(base_url, app_id, app_key, access_key, secret_key, endpoint, data=None):
    """Execute authenticated Mimecast API request."""
    request_id = str(uuid.uuid4())
    hdr_date = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S") + " UTC"
    data_to_sign = f"{hdr_date}:{request_id}:{endpoint}:{app_key}"
    hmac_sha1 = hmac.new(base64.b64decode(secret_key), data_to_sign.encode(), hashlib.sha1)
    sig = base64.b64encode(hmac_sha1.digest()).decode()
    headers = {
        "Authorization": f"MC {access_key}:{sig}",
        "x-mc-app-id": app_id,
        "x-mc-date": hdr_date,
        "x-mc-req-id": request_id,
        "Content-Type": "application/json",
    }
    cmd = ["curl", "-s", "-X", "POST", f"{base_url}{endpoint}"]
    for k, v in headers.items():
        cmd.extend(["-H", f"{k}: {v}"])
    if data:
        cmd.extend(["-d", json.dumps({"data": [data]})])
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
    return json.loads(result.stdout) if result.stdout else {}


def get_url_logs(base_url, app_id, app_key, access_key, secret_key, date_from=None):
    """Get URL Protection logs."""
    data = {}
    if date_from:
        data["from"] = date_from
    return mimecast_request(base_url, app_id, app_key, access_key, secret_key,
                            "/api/ttp/url/get-logs", data)


def get_impersonation_logs(base_url, app_id, app_key, access_key, secret_key, date_from=None):
    """Get impersonation protection logs."""
    data = {}
    if date_from:
        data["from"] = date_from
    return mimecast_request(base_url, app_id, app_key, access_key, secret_key,
                            "/api/ttp/impersonation/get-logs", data)


def get_attachment_logs(base_url, app_id, app_key, access_key, secret_key, date_from=None):
    """Get attachment protection logs."""
    data = {}
    if date_from:
        data["from"] = date_from
    return mimecast_request(base_url, app_id, app_key, access_key, secret_key,
                            "/api/ttp/attachment/get-logs", data)


def analyze_url_threats(url_logs):
    """Analyze URL click patterns and threat categories."""
    categories = defaultdict(int)
    blocked = 0
    permitted = 0
    users_clicked = defaultdict(int)
    for entry in url_logs:
        cat = entry.get("scanResult", "unknown")
        categories[cat] += 1
        if entry.get("action") == "block":
            blocked += 1
        else:
            permitted += 1
        users_clicked[entry.get("userEmailAddress", "")] += 1
    top_clickers = sorted(users_clicked.items(), key=lambda x: x[1], reverse=True)[:10]
    return {
        "total_url_events": len(url_logs),
        "blocked": blocked,
        "permitted": permitted,
        "categories": dict(categories),
        "top_clickers": [{"email": e, "clicks": c} for e, c in top_clickers],
    }


def analyze_impersonation(imp_logs):
    """Analyze impersonation attack patterns."""
    senders = defaultdict(int)
    targets = defaultdict(int)
    for entry in imp_logs:
        senders[entry.get("senderAddress", "")] += 1
        targets[entry.get("recipientAddress", "")] += 1
    return {
        "total_impersonation_events": len(imp_logs),
        "unique_senders": len(senders),
        "top_impersonated_senders": dict(sorted(senders.items(), key=lambda x: x[1], reverse=True)[:10]),
        "most_targeted_users": dict(sorted(targets.items(), key=lambda x: x[1], reverse=True)[:10]),
    }


def generate_report(url_analysis, imp_analysis, attachment_count):
    return {
        "timestamp": datetime.utcnow().isoformat(),
        "url_protection": url_analysis,
        "impersonation_protection": imp_analysis,
        "attachment_threats": attachment_count,
        "total_threats": url_analysis["blocked"] + imp_analysis["total_impersonation_events"] + attachment_count,
    }


def main():
    parser = argparse.ArgumentParser(description="Mimecast Targeted Attack Protection Agent")
    parser.add_argument("--base-url", default=MIMECAST_BASE)
    parser.add_argument("--app-id", required=True, help="Mimecast Application ID")
    parser.add_argument("--app-key", required=True, help="Mimecast Application Key")
    parser.add_argument("--access-key", required=True, help="Mimecast Access Key")
    parser.add_argument("--secret-key", required=True, help="Mimecast Secret Key")
    parser.add_argument("--date-from", help="Start date YYYY-MM-DD")
    parser.add_argument("--output", default="mimecast_tap_report.json")
    args = parser.parse_args()

    url_resp = get_url_logs(args.base_url, args.app_id, args.app_key, args.access_key, args.secret_key, args.date_from)
    url_logs = url_resp.get("data", [{}])[0].get("clickLogs", [])
    imp_resp = get_impersonation_logs(args.base_url, args.app_id, args.app_key, args.access_key, args.secret_key, args.date_from)
    imp_logs = imp_resp.get("data", [{}])[0].get("impersonationLogs", [])
    att_resp = get_attachment_logs(args.base_url, args.app_id, args.app_key, args.access_key, args.secret_key, args.date_from)
    att_logs = att_resp.get("data", [{}])[0].get("attachmentLogs", [])

    url_analysis = analyze_url_threats(url_logs)
    imp_analysis = analyze_impersonation(imp_logs)
    report = generate_report(url_analysis, imp_analysis, len(att_logs))
    with open(args.output, "w") as f:
        json.dump(report, f, indent=2, default=str)
    logger.info("Total threats: %d (URL blocked: %d, impersonation: %d, attachments: %d)",
                report["total_threats"], url_analysis["blocked"],
                imp_analysis["total_impersonation_events"], len(att_logs))
    print(json.dumps(report, indent=2, default=str))


if __name__ == "__main__":
    main()
process.py12.1 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Mimecast TTP Policy Configuration Auditor

Audits Mimecast Targeted Threat Protection policy configuration
and generates compliance reports. Can also analyze Mimecast
TTP log exports for threat detection metrics.

Usage:
    python process.py audit-config --config-file mimecast_config.json
    python process.py analyze-logs --log-file ttp_logs.json
    python process.py vip-check --vip-file vip_list.json --email-json email.json
"""

import argparse
import json
import re
import sys
from dataclasses import dataclass, field, asdict
from collections import defaultdict, Counter
from datetime import datetime


@dataclass
class PolicyAudit:
    """TTP policy configuration audit result."""
    url_protect_enabled: bool = False
    url_rewriting: bool = False
    url_predelivery_hold: bool = False
    attachment_protect_enabled: bool = False
    attachment_sandbox_mode: str = ""
    impersonation_protect_enabled: bool = False
    impersonation_vip_count: int = 0
    internal_email_protect: bool = False
    findings: list = field(default_factory=list)
    score: int = 0
    max_score: int = 100


@dataclass
class TTPMetrics:
    """TTP detection metrics from log analysis."""
    total_emails: int = 0
    url_threats_blocked: int = 0
    attachment_threats_blocked: int = 0
    impersonation_detected: int = 0
    internal_threats: int = 0
    top_threat_types: dict = field(default_factory=dict)
    top_targeted_users: list = field(default_factory=list)
    daily_stats: dict = field(default_factory=dict)


@dataclass
class ImpersonationCheck:
    """VIP impersonation check result."""
    from_display_name: str = ""
    from_email: str = ""
    matched_vip: str = ""
    indicators: list = field(default_factory=list)
    hit_count: int = 0
    is_impersonation: bool = False
    action: str = ""


REQUIRED_POLICIES = {
    "url_protect": {
        "enabled": True,
        "rewriting": True,
        "predelivery_hold": True,
        "weight": 25
    },
    "attachment_protect": {
        "enabled": True,
        "sandbox_mode": "dynamic",
        "weight": 25
    },
    "impersonation_protect": {
        "enabled": True,
        "min_vips": 5,
        "weight": 25
    },
    "internal_email_protect": {
        "enabled": True,
        "weight": 25
    }
}


def audit_config(config: dict) -> PolicyAudit:
    """Audit Mimecast TTP configuration against best practices."""
    audit = PolicyAudit()

    # Check URL Protect
    url_config = config.get("url_protect", {})
    audit.url_protect_enabled = url_config.get("enabled", False)
    audit.url_rewriting = url_config.get("rewriting", False)
    audit.url_predelivery_hold = url_config.get("predelivery_hold", False)

    if audit.url_protect_enabled:
        audit.score += 10
        if audit.url_rewriting:
            audit.score += 8
        else:
            audit.findings.append("URL rewriting not enabled - URLs not protected at click time")
        if audit.url_predelivery_hold:
            audit.score += 7
        else:
            audit.findings.append(
                "URL Pre-Delivery Hold not enabled - "
                "Mimecast recommends Hold setting (default since Nov 2025)"
            )
    else:
        audit.findings.append("CRITICAL: URL Protect not enabled")

    # Check Attachment Protect
    att_config = config.get("attachment_protect", {})
    audit.attachment_protect_enabled = att_config.get("enabled", False)
    audit.attachment_sandbox_mode = att_config.get("sandbox_mode", "none")

    if audit.attachment_protect_enabled:
        audit.score += 10
        if audit.attachment_sandbox_mode == "dynamic":
            audit.score += 15
        elif audit.attachment_sandbox_mode == "safe_file":
            audit.score += 10
            audit.findings.append(
                "Attachment Protect in Safe File mode - consider Dynamic for full sandbox"
            )
        else:
            audit.findings.append("Attachment sandbox mode not configured")
    else:
        audit.findings.append("CRITICAL: Attachment Protect not enabled")

    # Check Impersonation Protect
    imp_config = config.get("impersonation_protect", {})
    audit.impersonation_protect_enabled = imp_config.get("enabled", False)
    audit.impersonation_vip_count = len(imp_config.get("vip_list", []))

    if audit.impersonation_protect_enabled:
        audit.score += 10
        if audit.impersonation_vip_count >= 5:
            audit.score += 15
        elif audit.impersonation_vip_count > 0:
            audit.score += 8
            audit.findings.append(
                f"Only {audit.impersonation_vip_count} VIPs configured - "
                "recommend adding all executives and finance leadership"
            )
        else:
            audit.findings.append("No VIPs configured for Impersonation Protect")
    else:
        audit.findings.append("CRITICAL: Impersonation Protect not enabled")

    # Check Internal Email Protect
    int_config = config.get("internal_email_protect", {})
    audit.internal_email_protect = int_config.get("enabled", False)

    if audit.internal_email_protect:
        audit.score += 25
    else:
        audit.findings.append(
            "Internal Email Protect not enabled - "
            "lateral phishing from compromised accounts undetected"
        )

    return audit


def analyze_ttp_logs(logs: list) -> TTPMetrics:
    """Analyze Mimecast TTP logs for threat metrics."""
    metrics = TTPMetrics()
    threat_types = Counter()
    targeted_users = Counter()
    daily = defaultdict(lambda: {"total": 0, "threats": 0})

    for entry in logs:
        metrics.total_emails += 1
        date_str = entry.get("date", "unknown")
        daily[date_str]["total"] += 1

        category = entry.get("category", "").lower()
        if category in ("url_threat", "url_blocked"):
            metrics.url_threats_blocked += 1
            daily[date_str]["threats"] += 1
            threat_types["URL Threat"] += 1
        elif category in ("attachment_threat", "attachment_blocked"):
            metrics.attachment_threats_blocked += 1
            daily[date_str]["threats"] += 1
            threat_types["Attachment Threat"] += 1
        elif category in ("impersonation", "impersonation_detected"):
            metrics.impersonation_detected += 1
            daily[date_str]["threats"] += 1
            threat_types["Impersonation"] += 1
        elif category in ("internal_threat",):
            metrics.internal_threats += 1
            daily[date_str]["threats"] += 1
            threat_types["Internal Threat"] += 1

        recipient = entry.get("recipient", "")
        if recipient and category != "clean":
            targeted_users[recipient] += 1

    metrics.top_threat_types = dict(threat_types.most_common(10))
    metrics.top_targeted_users = [
        {"user": user, "threat_count": count}
        for user, count in targeted_users.most_common(10)
    ]
    metrics.daily_stats = dict(daily)

    return metrics


def check_impersonation(email_data: dict, vip_list: list) -> ImpersonationCheck:
    """Check if an email impersonates a VIP."""
    check = ImpersonationCheck()
    check.from_display_name = email_data.get("from_display_name", "")
    check.from_email = email_data.get("from", "")

    from_domain = ""
    match = re.search(r'@([\w.-]+)', check.from_email)
    if match:
        from_domain = match.group(1).lower()

    name_lower = check.from_display_name.lower()

    for vip in vip_list:
        vip_name = vip.get("name", "").lower()
        vip_domain = vip.get("domain", "").lower()

        # Check display name match
        if vip_name and vip_name in name_lower:
            check.indicators.append(f"Display name matches VIP: {vip.get('name')}")
            check.hit_count += 1
            check.matched_vip = vip.get("name", "")

            # Check domain mismatch
            if from_domain and vip_domain and from_domain != vip_domain:
                check.indicators.append(
                    f"Email domain ({from_domain}) differs from VIP domain ({vip_domain})"
                )
                check.hit_count += 1

        # Check domain similarity (lookalike)
        if vip_domain and from_domain:
            if _domain_similarity(from_domain, vip_domain) > 0.8 and from_domain != vip_domain:
                check.indicators.append(
                    f"Domain '{from_domain}' is visually similar to '{vip_domain}'"
                )
                check.hit_count += 1

    # Check reply-to mismatch
    reply_to = email_data.get("reply_to", "")
    if reply_to and reply_to != check.from_email:
        check.indicators.append("Reply-To differs from From address")
        check.hit_count += 1

    # Determine action
    if check.hit_count >= 3:
        check.is_impersonation = True
        check.action = "QUARANTINE (Hit 3 - Default policy)"
    elif check.hit_count >= 1 and check.matched_vip:
        check.is_impersonation = True
        check.action = "QUARANTINE (Hit 1 - VIP policy)"
    else:
        check.action = "DELIVER"

    return check


def _domain_similarity(d1: str, d2: str) -> float:
    """Calculate visual similarity between two domain names."""
    if d1 == d2:
        return 1.0
    longer = max(len(d1), len(d2))
    if longer == 0:
        return 0.0
    matches = sum(1 for a, b in zip(d1, d2) if a == b)
    return matches / longer


def main():
    parser = argparse.ArgumentParser(description="Mimecast TTP Auditor")
    subparsers = parser.add_subparsers(dest="command")

    audit_parser = subparsers.add_parser("audit-config", help="Audit TTP configuration")
    audit_parser.add_argument("--config-file", required=True)

    log_parser = subparsers.add_parser("analyze-logs", help="Analyze TTP logs")
    log_parser.add_argument("--log-file", required=True)

    vip_parser = subparsers.add_parser("vip-check", help="Check for VIP impersonation")
    vip_parser.add_argument("--vip-file", required=True)
    vip_parser.add_argument("--email-json", required=True)

    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()

    if args.command == "audit-config":
        with open(args.config_file) as f:
            config = json.load(f)
        result = audit_config(config)
        if args.json:
            print(json.dumps(asdict(result), indent=2))
        else:
            print(f"TTP Configuration Score: {result.score}/{result.max_score}")
            print(f"URL Protect: {'Enabled' if result.url_protect_enabled else 'DISABLED'}")
            print(f"Attachment Protect: {'Enabled' if result.attachment_protect_enabled else 'DISABLED'}")
            print(f"Impersonation Protect: {'Enabled' if result.impersonation_protect_enabled else 'DISABLED'}")
            print(f"Internal Email Protect: {'Enabled' if result.internal_email_protect else 'DISABLED'}")
            if result.findings:
                print(f"\nFindings ({len(result.findings)}):")
                for i, f_item in enumerate(result.findings, 1):
                    print(f"  {i}. {f_item}")

    elif args.command == "analyze-logs":
        with open(args.log_file) as f:
            logs = json.load(f)
        result = analyze_ttp_logs(logs)
        if args.json:
            print(json.dumps(asdict(result), indent=2))
        else:
            print(f"Total emails: {result.total_emails}")
            print(f"URL threats: {result.url_threats_blocked}")
            print(f"Attachment threats: {result.attachment_threats_blocked}")
            print(f"Impersonation: {result.impersonation_detected}")
            print(f"Internal threats: {result.internal_threats}")

    elif args.command == "vip-check":
        with open(args.vip_file) as f:
            vip_list = json.load(f)
        with open(args.email_json) as f:
            email_data = json.load(f)
        result = check_impersonation(email_data, vip_list)
        if args.json:
            print(json.dumps(asdict(result), indent=2))
        else:
            print(f"From: {result.from_display_name} <{result.from_email}>")
            print(f"Matched VIP: {result.matched_vip or 'None'}")
            print(f"Hit Count: {result.hit_count}")
            print(f"Impersonation: {'YES' if result.is_impersonation else 'No'}")
            print(f"Action: {result.action}")

    else:
        parser.print_help()


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 1.3 KB
Keep exploring