
Building Phishing Reporting Button Workflow
- 137 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with automation & workflows tasks.
About
building-phishing-reporting-button-workflow is a Claude Code skill in the Automation & Workflows category.
- building-phishing-reporting-button-workflow
- Automation & Workflows
- AI-coding skill
Building Phishing Reporting Button Workflow by the numbers
- 137 all-time installs (skills.sh)
- +3 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #680 of 2,715 Automation & Workflows skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill building-phishing-reporting-button-workflowAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 137 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with automation & workflows tasks.
Files
Building Phishing Reporting Button Workflow
Overview
A phishing reporting button empowers users to flag suspicious emails directly from their email client, creating a critical feedback loop between end users and the security operations center. Microsoft's built-in Report button is now the recommended approach, replacing the deprecated Report Message and Report Phishing add-ins. When combined with automated triage using SOAR platforms, reported emails can be classified, IOCs extracted, and remediation actions taken within minutes. Organizations with effective phishing reporting programs see 70%+ report rates in phishing simulations.
When to Use
- When deploying or configuring building phishing reporting button workflow 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
- Microsoft 365 or Google Workspace with administrative access
- SOAR platform or automation capability (Microsoft Sentinel, Splunk SOAR, Cortex XSOAR)
- Dedicated reporting mailbox for phishing submissions
- Email security gateway with message retraction capability
- Security awareness training platform for feedback loop
Workflow
Step 1: Deploy Phishing Report Button
- Enable Microsoft built-in Report button via Security & Compliance Center
- Configure user reported settings: route to reporting mailbox and Microsoft
- For third-party: deploy KnowBe4 Phish Alert Button or Cofense Reporter
- Verify button appears in Outlook desktop, web, and mobile clients
- Configure report options: Report Phishing, Report Junk, Report Not Junk
Step 2: Build Automated Triage Pipeline
- Configure reporting mailbox monitored by SOAR platform
- Auto-extract IOCs from reported emails: URLs, attachments, sender info, headers
- Submit URLs to VirusTotal, URLScan.io for reputation check
- Submit attachments to sandbox for dynamic analysis
- Check sender against known threat intelligence feeds
- Auto-classify: confirmed phishing, spam, simulation, legitimate
Step 3: Implement Response Actions
- Confirmed phishing: auto-retract from all inboxes, block sender domain
- Confirmed spam: move to junk for all recipients
- Simulation email: mark as correctly reported, credit user
- Legitimate email: return to inbox, notify reporter
- Generate IOC report for threat intelligence team
Step 4: Create Feedback Loop
- Send automated thank-you response to reporter within 5 minutes
- Include classification result when analysis completes
- Track reporter accuracy and engagement metrics
- Recognize top reporters in monthly security newsletter
- Feed reporting metrics into security awareness training program
Step 5: Measure and Optimize
- Track mean time to triage (target: under 10 minutes automated)
- Monitor report volume trends and false positive rates
- Measure user reporting rate in phishing simulations
- Report on confirmed threats caught by user reports vs. gateway
- Optimize automation rules based on classification accuracy
Tools & Resources
- Microsoft Report Button: Built-in Outlook phishing reporting
- Cofense Reporter + Triage: Enterprise phishing reporting and automated analysis
- KnowBe4 Phish Alert Button: Integrated reporting with simulation platform
- Microsoft Sentinel: SOAR automation for triage workflow
- Proofpoint CLEAR: Closed-loop email analysis and response
Validation
- Report button visible and functional across all Outlook platforms
- Reported email arrives in dedicated mailbox within 60 seconds
- Automated triage classifies test phishing email correctly
- Auto-retraction removes confirmed phishing from all inboxes
- Reporter receives feedback notification with classification
- Metrics dashboard shows report volume and accuracy trends
Phishing Reporting Button Workflow Template
Reporting Button Configuration
| Setting | Value | Status |
|---|---|---|
| Button type | Microsoft built-in Report | |
| Reporting mailbox | phishing-reports@company.com | |
| Also send to Microsoft | Yes | |
| Supported platforms | Desktop, Web, Mobile |
Triage Automation Rules
| Classification | Criteria | Auto-Action |
|---|---|---|
| Confirmed Phishing | Score >= 50 | Retract + Block sender |
| Suspicious | Score 25-49 | Escalate to SOC analyst |
| Spam | Score 10-24 | Move to junk for all |
| Simulation | Matches sim subject | Credit reporter |
| Clean | Score < 10 | Return to inbox |
Reporting Metrics Dashboard
| Metric | Target | Current |
|---|---|---|
| Report volume (monthly) | ||
| Mean time to triage | < 10 min | |
| Confirmed phishing caught | ||
| User report rate (sim) | > 70% | |
| False positive rate | < 30% | |
| Top reporter recognition | Monthly |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Phishing Reporting Button Workflow
Email Parsing (Python email module)
from email import policy
from email.parser import BytesParser
with open("report.eml", "rb") as f:
msg = BytesParser(policy=policy.default).parse(f)
headers = {
"from": msg["From"], "subject": msg["Subject"],
"reply_to": msg["Reply-To"], "received": msg.get_all("Received")
}Phishing Indicators
| Indicator | Weight | Description |
|---|---|---|
| Reply-To mismatch | 20 | From and Reply-To differ |
| SPF/DKIM fail | 25 | Authentication failure |
| Suspicious language | 10 | Urgency/credential patterns |
| Suspicious URL | 15 | Known bad TLDs or redirectors |
| Dangerous attachment | 30 | Executable file extensions |
VirusTotal URL Scan
GET https://www.virustotal.com/api/v3/urls/{url_id}
x-apikey: YOUR_KEYURL ID = base64url(url) or sha256(url)
Dangerous File Extensions
| Category | Extensions |
|---|---|
| Executables | .exe, .scr, .bat, .cmd |
| Scripts | .js, .vbs, .ps1, .hta |
| Disk images | .iso, .img, .vhd |
| Archives | .zip (password-protected), .rar |
| Documents | .docm, .xlsm (macro-enabled) |
Verdict Classification
| Score | Verdict | Action |
|---|---|---|
| >= 50 | Phishing | Block sender, quarantine, create ticket |
| 25-49 | Suspicious | Analyst review required |
| < 25 | Benign | Close report, notify user |
Ticketing Integration
POST /api/v2/tickets
Authorization: Bearer TOKEN
{
"title": "Phishing Report: ...",
"severity": "high",
"description": "...",
"indicators": ["Reply-To mismatch", ...]
}Microsoft Report Message Add-in
POST https://graph.microsoft.com/v1.0/users/{id}/messages/{msgId}/move
{"destinationId": "phishing-mailbox-id"}Standards & References: Building Phishing Reporting Button Workflow
MITRE ATT&CK References
- T1566.001: Phishing: Spearphishing Attachment
- T1566.002: Phishing: Spearphishing Link
- T1204: User Execution
- D3-RERE: User Reporting (MITRE D3FEND)
Industry Standards
- NIST SP 800-61 Rev.2: Computer Security Incident Handling Guide
- CIS Controls v8 Control 14: Security Awareness and Skills Training
- ISO 27001 A.6.3: Information Security Awareness, Education and Training
Reporting Platform Comparison
| Platform | Type | Integration | Auto-Triage |
|---|---|---|---|
| Microsoft Report Button | Built-in | M365 native | Via Sentinel/API |
| Cofense Reporter + Triage | Third-party | M365, Google | Yes (Cofense Triage) |
| KnowBe4 PAB | Third-party | M365, Google | Yes (KMSAT) |
| Proofpoint CLEAR | Third-party | M365, Google | Yes (built-in) |
| Hoxhunt | Third-party | M365, Google | Yes (AI-powered) |
Key Metrics
- Report Rate: Percentage of phishing simulations reported (target: >70%)
- Mean Time to Triage: Time from report to classification (target: <10 min)
- False Positive Rate: Legitimate emails reported as phishing
- Threat Catch Rate: Real threats first detected by user reports
- Reporter Accuracy: Percentage of reports that are actual threats
Workflows: Building Phishing Reporting Button Workflow
Workflow 1: Automated Phishing Report Triage
User clicks "Report Phishing" button
|
v
[Email forwarded to reporting mailbox]
+-- Original email preserved with full headers
+-- Reporter identity recorded
|
v
[SOAR platform ingests report]
|
v
[Automated IOC extraction]
+-- Extract sender address and domain
+-- Extract all URLs from body
+-- Extract attachment hashes (MD5, SHA256)
+-- Parse email headers for authentication results
|
v
[Automated analysis (parallel)]
+-- URLs -> VirusTotal, URLScan.io, PhishTank
+-- Attachments -> Sandbox detonation
+-- Sender -> Threat intelligence lookup
+-- Headers -> SPF/DKIM/DMARC validation
|
v
[Classification]
+-- CONFIRMED PHISHING: High-confidence malicious
+-- SUSPICIOUS: Moderate indicators, needs analyst review
+-- SPAM: Unwanted but not malicious
+-- SIMULATION: Matches internal phishing test
+-- CLEAN: Legitimate email, false report
|
v
[Automated response by classification]
+-- PHISHING: Retract from all inboxes + block sender
+-- SUSPICIOUS: Escalate to SOC analyst
+-- SPAM: Move to junk for all recipients
+-- SIMULATION: Credit reporter in training platform
+-- CLEAN: Return to inbox
|
v
[Feedback to reporter]
+-- "Thank you for reporting" (immediate)
+-- Classification result (when complete)
+-- Training tip (if false positive)Workflow 2: SOC Analyst Escalation
SOAR classifies report as SUSPICIOUS
|
v
[SOC analyst reviews]
+-- Examine full email content and headers
+-- Verify automated analysis results
+-- Check for similar reports from other users
|
v
[Analyst decision]
+-- Confirm malicious --> Trigger remediation playbook
+-- Confirm clean --> Close and notify reporter
+-- Need more info --> Contact reporter for context#!/usr/bin/env python3
"""Phishing Reporting Button Workflow Agent - Processes user-reported phishing emails via button integration."""
import json
import logging
import argparse
import re
import hashlib
from datetime import datetime
from email import policy
from email.parser import BytesParser
import requests
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
SUSPICIOUS_PATTERNS = [
re.compile(r"urgent|immediate action|verify your account|click here now", re.IGNORECASE),
re.compile(r"password.*expir|account.*suspend|unusual.*activity", re.IGNORECASE),
re.compile(r"wire transfer|bitcoin|gift card|western union", re.IGNORECASE),
re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", re.IGNORECASE),
]
URL_PATTERN = re.compile(r"https?://[^\s\"'<>]+")
def parse_reported_email(eml_path):
"""Parse a reported phishing email from .eml file."""
with open(eml_path, "rb") as f:
msg = BytesParser(policy=policy.default).parse(f)
headers = {
"from": msg.get("From", ""),
"to": msg.get("To", ""),
"subject": msg.get("Subject", ""),
"date": msg.get("Date", ""),
"return_path": msg.get("Return-Path", ""),
"reply_to": msg.get("Reply-To", ""),
"message_id": msg.get("Message-ID", ""),
"received": [str(h) for h in msg.get_all("Received", [])],
}
body = ""
if msg.is_multipart():
for part in msg.walk():
ct = part.get_content_type()
if ct == "text/plain":
body = part.get_content()
break
elif ct == "text/html" and not body:
body = part.get_content()
else:
body = msg.get_content()
attachments = []
for part in msg.walk():
fn = part.get_filename()
if fn:
content = part.get_payload(decode=True)
attachments.append({"filename": fn, "size": len(content) if content else 0,
"sha256": hashlib.sha256(content).hexdigest() if content else ""})
logger.info("Parsed email: subject='%s', %d attachments", headers["subject"], len(attachments))
return {"headers": headers, "body": body[:5000], "attachments": attachments}
def analyze_email(parsed):
"""Analyze reported email for phishing indicators."""
findings = []
score = 0
headers = parsed["headers"]
body = parsed.get("body", "")
from_addr = headers.get("from", "")
reply_to = headers.get("reply_to", "")
if reply_to and reply_to != from_addr:
findings.append({"indicator": "Reply-To mismatch", "detail": f"From: {from_addr}, Reply-To: {reply_to}", "weight": 20})
score += 20
auth_results = headers.get("authentication_results", "")
if "spf=fail" in auth_results.lower() or "dkim=fail" in auth_results.lower():
findings.append({"indicator": "Email authentication failure", "detail": auth_results[:200], "weight": 25})
score += 25
for pat in SUSPICIOUS_PATTERNS:
matches = pat.findall(body)
if matches:
findings.append({"indicator": "Suspicious language", "detail": matches[0][:100], "weight": 10})
score += 10
urls = URL_PATTERN.findall(body)
suspicious_urls = [u for u in urls if any(kw in u.lower() for kw in [".tk", ".ml", ".ga", "bit.ly",
"tinyurl", "redirect", "login", "verify", "secure-"])]
if suspicious_urls:
findings.append({"indicator": "Suspicious URLs", "detail": suspicious_urls[:5], "weight": 15})
score += 15 * len(suspicious_urls[:3])
for att in parsed.get("attachments", []):
fn = att["filename"].lower()
if any(fn.endswith(ext) for ext in [".exe", ".scr", ".js", ".vbs", ".bat", ".ps1", ".hta", ".iso", ".img"]):
findings.append({"indicator": "Dangerous attachment", "detail": att["filename"], "weight": 30})
score += 30
verdict = "phishing" if score >= 50 else "suspicious" if score >= 25 else "benign"
return {"score": min(score, 100), "verdict": verdict, "findings": findings, "url_count": len(urls),
"attachment_count": len(parsed.get("attachments", []))}
def check_urls_virustotal(urls, api_key):
"""Check extracted URLs against VirusTotal."""
results = []
for url in urls[:5]:
try:
url_id = hashlib.sha256(url.encode()).hexdigest()
resp = requests.get(f"https://www.virustotal.com/api/v3/urls/{url_id}",
headers={"x-apikey": api_key}, timeout=10)
if resp.status_code == 200:
stats = resp.json().get("data", {}).get("attributes", {}).get("last_analysis_stats", {})
results.append({"url": url, "malicious": stats.get("malicious", 0), "suspicious": stats.get("suspicious", 0)})
except requests.RequestException:
results.append({"url": url, "error": "lookup_failed"})
return results
def create_ticket(analysis, parsed, ticketing_url=None, api_key=None):
"""Create incident ticket from analysis results."""
ticket = {
"title": f"Phishing Report: {parsed['headers'].get('subject', 'No Subject')[:80]}",
"severity": "high" if analysis["verdict"] == "phishing" else "medium" if analysis["verdict"] == "suspicious" else "low",
"description": f"User-reported phishing email. Verdict: {analysis['verdict']} (score: {analysis['score']})",
"indicators": [f["indicator"] for f in analysis["findings"]],
"reported_from": parsed["headers"].get("to", ""),
"suspicious_sender": parsed["headers"].get("from", ""),
}
if ticketing_url and api_key:
try:
resp = requests.post(f"{ticketing_url}/api/v2/tickets",
headers={"Authorization": f"Bearer {api_key}"}, json=ticket, timeout=10)
ticket["ticket_id"] = resp.json().get("id")
except requests.RequestException:
ticket["ticket_id"] = "creation_failed"
return ticket
def generate_report(parsed, analysis, ticket):
"""Generate phishing report workflow report."""
report = {
"timestamp": datetime.utcnow().isoformat(),
"email_subject": parsed["headers"].get("subject", ""),
"sender": parsed["headers"].get("from", ""),
"analysis": analysis,
"ticket": ticket,
}
print(f"PHISHING REPORT: {analysis['verdict'].upper()} (score={analysis['score']}), "
f"{len(analysis['findings'])} indicators")
return report
def main():
parser = argparse.ArgumentParser(description="Phishing Reporting Button Workflow Agent")
parser.add_argument("--eml-file", required=True, help="Path to reported .eml file")
parser.add_argument("--vt-key", help="VirusTotal API key for URL checks")
parser.add_argument("--output", default="phishing_report.json")
args = parser.parse_args()
parsed = parse_reported_email(args.eml_file)
analysis = analyze_email(parsed)
ticket = create_ticket(analysis, parsed)
report = generate_report(parsed, analysis, ticket)
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
logger.info("Report saved to %s", args.output)
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Phishing Report Triage Engine
Processes user-reported phishing emails, extracts IOCs,
performs automated analysis, and classifies the report.
Usage:
python process.py triage --eml-file reported_email.eml
python process.py metrics --reports-file reports.json
python process.py extract-iocs --eml-file reported_email.eml
"""
import argparse
import json
import re
import hashlib
import sys
from dataclasses import dataclass, field, asdict
from collections import Counter
from datetime import datetime
@dataclass
class ExtractedIOCs:
"""IOCs extracted from reported email."""
sender_address: str = ""
sender_domain: str = ""
reply_to: str = ""
urls: list = field(default_factory=list)
domains: list = field(default_factory=list)
attachment_names: list = field(default_factory=list)
attachment_hashes: list = field(default_factory=list)
ip_addresses: list = field(default_factory=list)
subject: str = ""
@dataclass
class TriageResult:
"""Triage classification result."""
report_id: str = ""
reporter: str = ""
classification: str = ""
confidence: float = 0.0
iocs: dict = field(default_factory=dict)
indicators: list = field(default_factory=list)
recommended_action: str = ""
auto_actionable: bool = False
@dataclass
class ReportingMetrics:
"""Phishing reporting program metrics."""
total_reports: int = 0
confirmed_phishing: int = 0
confirmed_spam: int = 0
simulation_reports: int = 0
false_positives: int = 0
mean_triage_time_min: float = 0.0
top_reporters: list = field(default_factory=list)
report_rate: float = 0.0
PHISHING_INDICATORS = [
(r'\burgent\b.*\b(action|response|attention)\b', "Urgency language", 15),
(r'\b(verify|confirm|validate)\s+your\s+(account|identity|password)\b', "Credential request", 20),
(r'\b(click|follow)\s+(here|this|the)\s+(link|button)\b', "Click-bait language", 10),
(r'\b(suspended|locked|disabled|compromised)\s+(account|access)\b', "Fear language", 15),
(r'\b(wire\s+transfer|payment|invoice|bank)\b', "Financial language", 10),
(r'\bgift\s+card\b', "Gift card request", 20),
(r'\bdo\s+not\s+(share|tell|discuss)\b', "Secrecy language", 15),
]
def extract_iocs(eml_content: str) -> ExtractedIOCs:
"""Extract IOCs from email content."""
iocs = ExtractedIOCs()
# Extract From
from_match = re.search(r'^From:\s*(?:.*<)?([^>\s]+@[^>\s]+)', eml_content,
re.MULTILINE | re.IGNORECASE)
if from_match:
iocs.sender_address = from_match.group(1).strip()
domain_match = re.search(r'@([\w.-]+)', iocs.sender_address)
if domain_match:
iocs.sender_domain = domain_match.group(1)
# Extract Reply-To
reply_match = re.search(r'^Reply-To:\s*(?:.*<)?([^>\s]+@[^>\s]+)', eml_content,
re.MULTILINE | re.IGNORECASE)
if reply_match:
iocs.reply_to = reply_match.group(1).strip()
# Extract Subject
subj_match = re.search(r'^Subject:\s*(.+)$', eml_content, re.MULTILINE | re.IGNORECASE)
if subj_match:
iocs.subject = subj_match.group(1).strip()
# Extract URLs
urls = re.findall(r'https?://[^\s<>"\']+', eml_content)
iocs.urls = list(set(urls))
# Extract domains from URLs
for url in iocs.urls:
domain_match = re.search(r'https?://([^/:\s]+)', url)
if domain_match:
domain = domain_match.group(1).lower()
if domain not in iocs.domains:
iocs.domains.append(domain)
# Extract IP addresses from headers
ips = re.findall(r'\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b', eml_content)
iocs.ip_addresses = list(set(ips))
# Extract attachment filenames
attachments = re.findall(
r'filename[*]?=(?:"([^"]+)"|([^\s;]+))',
eml_content, re.IGNORECASE
)
for groups in attachments:
name = groups[0] or groups[1]
if name and name not in iocs.attachment_names:
iocs.attachment_names.append(name)
return iocs
def triage_report(eml_content: str, simulation_subjects: list = None) -> TriageResult:
"""Classify a reported email."""
result = TriageResult()
iocs = extract_iocs(eml_content)
result.iocs = asdict(iocs)
score = 0
body_lower = eml_content.lower()
# Check if it's a known simulation
if simulation_subjects:
for sim_subj in simulation_subjects:
if sim_subj.lower() in iocs.subject.lower():
result.classification = "simulation"
result.confidence = 0.95
result.recommended_action = "Credit reporter in training platform"
result.auto_actionable = True
return result
# Check phishing indicators
for pattern, desc, weight in PHISHING_INDICATORS:
if re.search(pattern, body_lower):
result.indicators.append(desc)
score += weight
# Check for authentication failures
auth_results = re.search(r'Authentication-Results:.*?(spf=fail|dkim=fail|dmarc=fail)',
eml_content, re.IGNORECASE | re.DOTALL)
if auth_results:
result.indicators.append(f"Authentication failure: {auth_results.group(1)}")
score += 20
# Check Reply-To mismatch
if iocs.reply_to and iocs.sender_address:
reply_domain = re.search(r'@([\w.-]+)', iocs.reply_to)
sender_domain = re.search(r'@([\w.-]+)', iocs.sender_address)
if reply_domain and sender_domain:
if reply_domain.group(1) != sender_domain.group(1):
result.indicators.append("Reply-To domain mismatch")
score += 15
# Check for suspicious attachment types
risky_extensions = ['.exe', '.scr', '.bat', '.cmd', '.ps1', '.vbs',
'.js', '.wsf', '.hta', '.iso', '.img']
for att in iocs.attachment_names:
if any(att.lower().endswith(ext) for ext in risky_extensions):
result.indicators.append(f"Risky attachment: {att}")
score += 25
# Classify
if score >= 50:
result.classification = "confirmed_phishing"
result.confidence = min(score / 100, 0.95)
result.recommended_action = "Retract from all inboxes, block sender domain"
result.auto_actionable = True
elif score >= 25:
result.classification = "suspicious"
result.confidence = score / 100
result.recommended_action = "Escalate to SOC analyst for manual review"
result.auto_actionable = False
elif score >= 10:
result.classification = "spam"
result.confidence = 0.6
result.recommended_action = "Move to junk for all recipients"
result.auto_actionable = True
else:
result.classification = "clean"
result.confidence = 0.7
result.recommended_action = "Return to inbox, notify reporter"
result.auto_actionable = True
return result
def calculate_metrics(reports: list) -> ReportingMetrics:
"""Calculate phishing reporting program metrics."""
metrics = ReportingMetrics()
metrics.total_reports = len(reports)
reporter_counts = Counter()
triage_times = []
for report in reports:
classification = report.get("classification", "")
if classification == "confirmed_phishing":
metrics.confirmed_phishing += 1
elif classification == "spam":
metrics.confirmed_spam += 1
elif classification == "simulation":
metrics.simulation_reports += 1
elif classification == "clean":
metrics.false_positives += 1
reporter = report.get("reporter", "")
if reporter:
reporter_counts[reporter] += 1
triage_time = report.get("triage_time_minutes", 0)
if triage_time > 0:
triage_times.append(triage_time)
if triage_times:
metrics.mean_triage_time_min = sum(triage_times) / len(triage_times)
metrics.top_reporters = [
{"reporter": r, "count": c}
for r, c in reporter_counts.most_common(10)
]
if metrics.total_reports > 0:
metrics.report_rate = (
(metrics.confirmed_phishing + metrics.simulation_reports) /
metrics.total_reports * 100
)
return metrics
def main():
parser = argparse.ArgumentParser(description="Phishing Report Triage Engine")
subparsers = parser.add_subparsers(dest="command")
triage_parser = subparsers.add_parser("triage", help="Triage reported email")
triage_parser.add_argument("--eml-file", required=True)
triage_parser.add_argument("--sim-subjects", nargs="*", default=[])
metrics_parser = subparsers.add_parser("metrics", help="Calculate reporting metrics")
metrics_parser.add_argument("--reports-file", required=True)
ioc_parser = subparsers.add_parser("extract-iocs", help="Extract IOCs from email")
ioc_parser.add_argument("--eml-file", required=True)
parser.add_argument("--json", action="store_true")
args = parser.parse_args()
if args.command == "triage":
with open(args.eml_file, 'r', errors='replace') as f:
content = f.read()
result = triage_report(content, args.sim_subjects)
if args.json:
print(json.dumps(asdict(result), indent=2))
else:
print(f"Classification: {result.classification}")
print(f"Confidence: {result.confidence:.0%}")
print(f"Action: {result.recommended_action}")
print(f"Auto-actionable: {'Yes' if result.auto_actionable else 'No'}")
if result.indicators:
print(f"Indicators:")
for ind in result.indicators:
print(f" - {ind}")
elif args.command == "metrics":
with open(args.reports_file) as f:
reports = json.load(f)
result = calculate_metrics(reports)
if args.json:
print(json.dumps(asdict(result), indent=2))
else:
print(f"Total reports: {result.total_reports}")
print(f"Confirmed phishing: {result.confirmed_phishing}")
print(f"Spam: {result.confirmed_spam}")
print(f"Simulations reported: {result.simulation_reports}")
print(f"False positives: {result.false_positives}")
print(f"Mean triage time: {result.mean_triage_time_min:.1f} min")
elif args.command == "extract-iocs":
with open(args.eml_file, 'r', errors='replace') as f:
content = f.read()
iocs = extract_iocs(content)
print(json.dumps(asdict(iocs), indent=2))
else:
parser.print_help()
if __name__ == "__main__":
main()