Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-SkillsFramework mappings
MITRE ATT&CK
T1046 on the official MITRE ATT&CK siteT1057 on the official MITRE ATT&CK siteT1082 on the official MITRE ATT&CK siteT1083 on the official MITRE ATT&CK siteT1098 on the official MITRE ATT&CK siteT1098.002 on the official MITRE ATT&CK siteT1114 on the official MITRE ATT&CK siteT1114.002 on the official MITRE ATT&CK siteT1114.003 on the official MITRE ATT&CK siteT1547 on the official MITRE ATT&CK site
NIST CSF 2.0
When to Use
- When proactively hunting for indicators of detecting email forwarding rules attack in the environment
- After threat intelligence indicates active campaigns using these techniques
- During incident response to scope compromise related to these techniques
- When EDR or SIEM alerts trigger on related indicators
- During periodic security assessments and purple team exercises
Prerequisites
- EDR platform with process and network telemetry (CrowdStrike, MDE, SentinelOne)
- SIEM with relevant log data ingested (Splunk, Elastic, Sentinel)
- Sysmon deployed with comprehensive configuration
- Windows Security Event Log forwarding enabled
- Threat intelligence feeds for IOC correlation
Workflow
- Formulate Hypothesis: Define a testable hypothesis based on threat intelligence or ATT&CK gap analysis.
- Identify Data Sources: Determine which logs and telemetry are needed to validate or refute the hypothesis.
- Execute Queries: Run detection queries against SIEM and EDR platforms to collect relevant events.
- Analyze Results: Examine query results for anomalies, correlating across multiple data sources.
- Validate Findings: Distinguish true positives from false positives through contextual analysis.
- Correlate Activity: Link findings to broader attack chains and threat actor TTPs.
- Document and Report: Record findings, update detection rules, and recommend response actions.
Key Concepts
| Concept | Description |
|---|---|
| T1114.003 | Email Forwarding Rule |
| T1114.002 | Remote Email Collection |
| T1098.002 | Additional Email Delegate Permissions |
Tools & Systems
| Tool | Purpose |
|---|---|
| CrowdStrike Falcon | EDR telemetry and threat detection |
| Microsoft Defender for Endpoint | Advanced hunting with KQL |
| Splunk Enterprise | SIEM log analysis with SPL queries |
| Elastic Security | Detection rules and investigation timeline |
| Sysmon | Detailed Windows event monitoring |
| Velociraptor | Endpoint artifact collection and hunting |
| Sigma Rules | Cross-platform detection rule format |
Common Scenarios
- Scenario 1: BEC actor creating forwarding rule to external email
- Scenario 2: Compromised account with rule deleting security alerts
- Scenario 3: Inbox rule forwarding CEO emails to attacker mailbox
- Scenario 4: OAuth app abuse creating transport rules for data collection
Output Format
Hunt ID: TH-DETECT-[DATE]-[SEQ]
Technique: T1114.003
Host: [Hostname]
User: [Account context]
Evidence: [Log entries, process trees, network data]
Risk Level: [Critical/High/Medium/Low]
Confidence: [High/Medium/Low]
Recommended Action: [Containment, investigation, monitoring]Source materials
References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 3
api-reference.md1.8 KB
API Reference: Detecting Email Forwarding Rules Attack
Microsoft Graph API - Inbox Rules
GET https://graph.microsoft.com/v1.0/users/{user-id}/mailFolders/inbox/messageRules
Authorization: Bearer {token}
# Response
{
"value": [
{
"displayName": "Forward invoices",
"isEnabled": true,
"conditions": {"subjectContains": ["invoice", "payment"]},
"actions": {
"forwardTo": [{"emailAddress": {"address": "attacker@evil.com"}}],
"delete": true,
"markAsRead": true
}
}
]
}Exchange Online PowerShell
# List all inbox rules for a user
Get-InboxRule -Mailbox user@company.com | FL Name, ForwardTo, RedirectTo, DeleteMessage
# Find forwarding rules across all mailboxes
Get-Mailbox -ResultSize Unlimited | ForEach-Object {
Get-InboxRule -Mailbox $_.UserPrincipalName |
Where-Object { $_.ForwardTo -or $_.RedirectTo }
}
# Search unified audit log for rule creation
Search-UnifiedAuditLog -Operations "New-InboxRule","Set-InboxRule" -StartDate (Get-Date).AddDays(-30)Suspicious Rule Indicators
| Indicator | Severity | Description |
|---|---|---|
| External forwarding | HIGH | Forwards to non-org domain |
| Forward + delete | CRITICAL | Forwards then deletes original |
| Financial keywords | HIGH | Targets invoice/payment subjects |
| Forward + mark read | HIGH | Hides forwarded messages |
| Move to RSS/Junk | MEDIUM | Hides messages in unused folders |
Splunk SPL Detection
index=o365 Operation IN ("New-InboxRule", "Set-InboxRule")
| spath output=forward path=Parameters{}.Value
| where isnotnull(forward) AND NOT match(forward, "@company\\.com")CLI Usage
python agent.py --token "eyJ..." --user-id user@company.com --org-domain company.com
python agent.py --audit-log exchange_audit.logstandards.md1.6 KB
Standards and References - Detecting Email Forwarding Rules Attack
MITRE ATT&CK Mappings
| Technique | Name | Description |
|---|---|---|
| T1114.003 | Email Forwarding Rule | See attack.mitre.org/techniques/T1114/003 |
| T1114.002 | Remote Email Collection | See attack.mitre.org/techniques/T1114/002 |
| T1098.002 | Additional Email Delegate Permissions | See attack.mitre.org/techniques/T1098/002 |
Detection Data Sources
| Source | Event ID | Purpose |
|---|---|---|
| Sysmon | 1 | Process creation with command line |
| Sysmon | 3 | Network connection initiated |
| Sysmon | 7 | Image loaded (DLL) |
| Sysmon | 10 | Process access (LSASS) |
| Sysmon | 11 | File creation |
| Sysmon | 12/13 | Registry create/set |
| Sysmon | 22 | DNS query |
| Sysmon | 25 | Process tampering |
| Windows Security | 4624 | Successful logon |
| Windows Security | 4625 | Failed logon |
| Windows Security | 4648 | Explicit credential logon |
| Windows Security | 4672 | Special privileges assigned |
| Windows Security | 4688 | Process creation |
| Windows Security | 4697 | Service installed |
| Windows Security | 4698 | Scheduled task created |
| Windows Security | 4769 | Kerberos TGS requested |
| Windows Security | 5140 | Network share accessed |
References
- MITRE ATT&CK Framework: https://attack.mitre.org/
- Sigma Detection Rules: https://github.com/SigmaHQ/sigma
- LOLBAS Project: https://lolbas-project.github.io/
- Atomic Red Team Tests: https://github.com/redcanaryco/atomic-red-team
- Red Canary Threat Detection Report
- SANS Threat Hunting Summit Resources
workflows.md2.9 KB
Detailed Hunting Workflow - Detecting Email Forwarding Rules Attack
Phase 1: Data Collection and Querying
Splunk SPL Query
index=o365 Workload=Exchange Operation IN ("New-InboxRule","Set-InboxRule","Enable-InboxRule")
| where match(Parameters, "(?i)(forward|redirect|delete|move.*junk)")
| table _time UserId Operation Parameters ClientIPKQL Query (Microsoft Defender for Endpoint)
CloudAppEvents
| where ActionType in ("New-InboxRule","Set-InboxRule")
| where RawEventData has_any ("ForwardTo","RedirectTo","DeleteMessage")
| project Timestamp, AccountObjectId, ActionType, RawEventData, IPAddressPhase 2: Baseline and Anomaly Detection
Step 2.1 - Establish Normal Behavior Baseline
- Collect 30 days of historical data for the targeted technique
- Document expected patterns, frequencies, and legitimate use cases
- Identify known false positive sources and document exceptions
- Build statistical baseline (mean, standard deviation) for key metrics
Step 2.2 - Identify Anomalies
- Compare current activity against the 30-day baseline
- Flag events exceeding 3 standard deviations from normal
- Prioritize anomalies by risk score and potential business impact
- Cross-reference with threat intelligence for known IOCs
Phase 3: Investigation and Correlation
Step 3.1 - Deep Dive Analysis
- For each anomaly, collect full process tree context
- Correlate with network activity, file operations, and authentication events
- Check binary signatures, file hashes, and certificate validity
- Review user account context and access patterns
Step 3.2 - Attack Chain Reconstruction
- Map findings to MITRE ATT&CK kill chain stages
- Identify initial access vector if applicable
- Trace lateral movement and privilege escalation paths
- Determine data access and potential exfiltration
Phase 4: Validation and Response
Step 4.1 - True/False Positive Determination
- Verify findings with system owners and IT operations
- Check change management records for authorized activities
- Validate user context (authorized actions vs. compromised account)
- Document determination rationale for each finding
Step 4.2 - Response Actions
- For confirmed threats: initiate incident response procedures
- For detection gaps: create or update detection rules
- For false positives: tune existing rules and update exclusions
- Update threat hunting playbook with lessons learned
Phase 5: Documentation and Reporting
Step 5.1 - Hunt Report
- Summarize hypothesis, methodology, and findings
- Include all queries executed and their results
- Document IOCs discovered and detection rules created
- Provide recommendations for security improvements
Step 5.2 - Knowledge Base Update
- Add findings to threat intelligence platform
- Update MITRE ATT&CK coverage heatmap
- Share detection rules via Sigma format
- Schedule follow-up hunts for related techniques
Scripts 2
agent.py5.9 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Email forwarding rules attack detection agent.
Detects malicious inbox rules created by adversaries for persistent
email access (T1114.003) by querying Microsoft Graph API and analyzing
audit logs for suspicious rule creation patterns.
"""
import argparse
import json
import re
import sys
from datetime import datetime
try:
import requests
except ImportError:
print("Install requests: pip install requests")
sys.exit(1)
SUSPICIOUS_RULE_PATTERNS = {
"forward_external": {"severity": "HIGH", "desc": "Rule forwards to external domain"},
"delete_after_forward": {"severity": "CRITICAL", "desc": "Rule deletes after forwarding"},
"move_to_rss": {"severity": "HIGH", "desc": "Rule moves to RSS Feeds folder"},
"move_to_junk": {"severity": "MEDIUM", "desc": "Rule moves to Junk folder"},
"keyword_financial": {"severity": "HIGH", "desc": "Rule targets financial keywords"},
"mark_as_read": {"severity": "MEDIUM", "desc": "Rule marks messages as read"},
}
FINANCIAL_KEYWORDS = ["invoice", "payment", "wire", "transfer", "bank",
"ach", "routing", "remittance", "purchase order"]
def get_mailbox_rules(token, user_id="me"):
url = f"https://graph.microsoft.com/v1.0/users/{user_id}/mailFolders/inbox/messageRules"
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
try:
resp = requests.get(url, headers=headers, timeout=15)
if resp.status_code == 200:
return resp.json().get("value", [])
return {"error": f"HTTP {resp.status_code}: {resp.text[:200]}"}
except requests.RequestException as e:
return {"error": str(e)}
def analyze_rules(rules, org_domain=""):
findings = []
for rule in rules:
if isinstance(rules, dict) and "error" in rules:
return [rules]
rule_name = rule.get("displayName", "")
actions = rule.get("actions", {})
conditions = rule.get("conditions", {})
is_enabled = rule.get("isEnabled", True)
forward_to = actions.get("forwardTo", [])
redirect_to = actions.get("redirectTo", [])
delete = actions.get("delete", False)
move_folder = actions.get("moveToFolder", "")
mark_read = actions.get("markAsRead", False)
all_forwards = forward_to + redirect_to
for fwd in all_forwards:
addr = fwd.get("emailAddress", {}).get("address", "")
if org_domain and addr and not addr.lower().endswith(f"@{org_domain.lower()}"):
severity = "CRITICAL" if delete else "HIGH"
findings.append({
"rule_name": rule_name,
"type": "external_forwarding",
"forward_to": addr,
"delete_after": delete,
"is_enabled": is_enabled,
"severity": severity,
"mitre": "T1114.003",
})
subject_contains = conditions.get("subjectContains", [])
body_contains = conditions.get("bodyContains", [])
all_keywords = [k.lower() for k in subject_contains + body_contains]
matched_financial = [k for k in all_keywords if k in FINANCIAL_KEYWORDS]
if matched_financial and all_forwards:
findings.append({
"rule_name": rule_name,
"type": "financial_keyword_forwarding",
"keywords": matched_financial,
"forward_to": [f.get("emailAddress", {}).get("address", "") for f in all_forwards],
"severity": "CRITICAL",
"mitre": "T1114.003",
})
if mark_read and all_forwards:
findings.append({
"rule_name": rule_name,
"type": "silent_forwarding",
"mark_as_read": True,
"severity": "HIGH",
"description": "Rule forwards and marks as read to hide activity",
})
return findings
def parse_audit_log_for_rules(filepath):
findings = []
with open(filepath, "r", encoding="utf-8", errors="replace") as f:
for line in f:
if "New-InboxRule" in line or "Set-InboxRule" in line:
forward = re.search(r'ForwardTo["\s:]+([^\s"]+@[^\s"]+)', line, re.IGNORECASE)
user = re.search(r'UserId["\s:]+([^\s"]+)', line, re.IGNORECASE)
findings.append({
"type": "rule_creation_audit",
"command": "New-InboxRule" if "New-InboxRule" in line else "Set-InboxRule",
"user": user.group(1) if user else "",
"forward_to": forward.group(1) if forward else "",
"severity": "HIGH",
"raw": line.strip()[:300],
})
return findings
def main():
parser = argparse.ArgumentParser(description="Email Forwarding Rules Attack Detector")
parser.add_argument("--token", help="Microsoft Graph API bearer token")
parser.add_argument("--user-id", default="me", help="User ID or UPN")
parser.add_argument("--org-domain", default="", help="Organization email domain")
parser.add_argument("--audit-log", help="Exchange audit log file to parse")
args = parser.parse_args()
results = {"timestamp": datetime.utcnow().isoformat() + "Z", "findings": []}
if args.token:
rules = get_mailbox_rules(args.token, args.user_id)
if isinstance(rules, dict) and "error" in rules:
results["error"] = rules["error"]
else:
results["total_rules"] = len(rules)
findings = analyze_rules(rules, args.org_domain)
results["findings"].extend(findings)
if args.audit_log:
audit_findings = parse_audit_log_for_rules(args.audit_log)
results["findings"].extend(audit_findings)
results["total_findings"] = len(results["findings"])
print(json.dumps(results, indent=2))
if __name__ == "__main__":
main()
process.py3.6 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Email Forwarding Rules Detection - Analyzes logs for T1114.003 indicators."""
import json, csv, argparse, datetime, re
from collections import defaultdict
from pathlib import Path
DETECTION_PATTERNS = [
r'New-InboxRule',
r'Set-InboxRule',
r'ForwardTo',
r'RedirectTo',
r'DeleteMessage',
]
def parse_logs(path):
p = Path(path)
if p.suffix == ".json":
with open(p, encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, list) else data.get("events", [])
elif p.suffix == ".csv":
with open(p, encoding="utf-8-sig") as f:
return [dict(r) for r in csv.DictReader(f)]
return []
def analyze_event(event):
cmd = event.get("CommandLine", event.get("command_line", event.get("ProcessCommandLine", "")))
content = event.get("Task_Content", event.get("Parameters", event.get("RawEventData", "")))
search_text = f"{cmd} {content}"
risk = 0
indicators = []
for pattern in DETECTION_PATTERNS:
if re.search(pattern, search_text, re.IGNORECASE):
risk += 25
indicators.append(f"Pattern match: {pattern}")
if not indicators:
return None
risk = min(risk, 100)
return {
"technique": "T1114.003",
"command_line": cmd[:500] if cmd else content[:500],
"hostname": event.get("Computer", event.get("DeviceName", event.get("hostname", "unknown"))),
"user": event.get("User", event.get("AccountName", event.get("UserId", "unknown"))),
"timestamp": event.get("_time", event.get("timestamp", event.get("UtcTime", event.get("Timestamp", "")))),
"risk_score": risk,
"risk_level": "CRITICAL" if risk >= 75 else "HIGH" if risk >= 50 else "MEDIUM" if risk >= 25 else "LOW",
"indicators": indicators,
}
def run_hunt(input_path, output_dir):
print(f"[*] Email Forwarding Rules Hunt - {datetime.datetime.now().isoformat()}")
events = parse_logs(input_path)
findings = [f for f in (analyze_event(e) for e in events) if f]
Path(output_dir).mkdir(parents=True, exist_ok=True)
slug = "detecting_email_forw"
with open(Path(output_dir) / f"{slug}_findings.json", "w", encoding="utf-8") as f:
json.dump({"hunt_id": f"TH-{datetime.date.today()}", "total_events": len(events), "findings": findings}, f, indent=2)
with open(Path(output_dir) / "hunt_report.md", "w", encoding="utf-8") as f:
f.write(f"# Email Forwarding Rules Hunt Report\n\n")
f.write(f"**Date**: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"**Findings**: {len(findings)}\n\n")
for finding in sorted(findings, key=lambda x: x["risk_score"], reverse=True)[:20]:
f.write(f"### [{finding['risk_level']}] {finding['technique']}\n")
f.write(f"- **Host**: {finding['hostname']}\n")
f.write(f"- **Indicators**: {', '.join(finding['indicators'])}\n\n")
print(f"[+] {len(findings)} findings written to {output_dir}")
def main():
p = argparse.ArgumentParser(description="Email Forwarding Rules Detection")
sp = p.add_subparsers(dest="cmd")
h = sp.add_parser("hunt"); h.add_argument("--input", "-i", required=True); h.add_argument("--output", "-o", default="./detecting_email_output")
sp.add_parser("queries")
args = p.parse_args()
if args.cmd == "hunt": run_hunt(args.input, args.output)
elif args.cmd == "queries":
print("=== Detection Queries ===")
print("See references/workflows.md for platform-specific queries")
else: p.print_help()
if __name__ == "__main__": main()
Assets 1
template.mdtext/markdown · 2.6 KBKeep exploring