-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshadowhunter_email.py
More file actions
796 lines (686 loc) · 33.1 KB
/
shadowhunter_email.py
File metadata and controls
796 lines (686 loc) · 33.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
#!/usr/bin/env python3
"""
ShadowHunter - Dark Web Credential Intelligence Platform
Module: Email Alert System
Author: Fevra
Version: 0.1.0
Implements comprehensive email notification system with HTML templates,
severity-based routing, and delivery tracking.
"""
import smtplib
import asyncio
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from typing import List, Dict, Optional, Any
from datetime import datetime, timedelta
from pydantic import BaseModel, EmailStr
from jinja2 import Template
import logging
from enum import Enum
from dataclasses import dataclass, field
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('ShadowHunter.Email')
# ============================================================================
# CONFIGURATION
# ============================================================================
class EmailConfig(BaseModel):
"""Email configuration"""
smtp_host: str = "smtp.gmail.com"
smtp_port: int = 587
smtp_username: str = ""
smtp_password: str = ""
from_email: str = "alerts@shadowhunter.io"
from_name: str = "ShadowHunter Alerts"
use_tls: bool = True
# Rate limiting
max_emails_per_hour: int = 100
max_emails_per_day: int = 1000
# Retry settings
max_retries: int = 3
retry_delay: int = 60 # seconds
# ============================================================================
# ALERT SEVERITY & TYPES
# ============================================================================
class AlertSeverity(str, Enum):
"""Alert severity levels"""
CRITICAL = "CRITICAL"
HIGH = "HIGH"
MEDIUM = "MEDIUM"
LOW = "LOW"
INFO = "INFO"
class AlertType(str, Enum):
"""Types of security alerts"""
CREDENTIAL_LEAK = "credential_leak"
RANSOMWARE_VICTIM = "ransomware_victim"
IAB_LISTING = "iab_listing"
DATA_BREACH = "data_breach"
STEALER_LOG = "stealer_log"
DOMAIN_MENTION = "domain_mention"
THREAT_ACTOR = "threat_actor"
SYSTEM_ALERT = "system_alert"
# ============================================================================
# DATA MODELS
# ============================================================================
@dataclass
class EmailAlert:
"""Email alert data structure"""
alert_id: str
severity: AlertSeverity
alert_type: AlertType
title: str
description: str
affected_domain: str
timestamp: datetime
metadata: Dict[str, Any] = field(default_factory=dict)
def get_severity_color(self) -> str:
"""Get color for severity"""
colors = {
AlertSeverity.CRITICAL: "#dc2626",
AlertSeverity.HIGH: "#ea580c",
AlertSeverity.MEDIUM: "#ca8a04",
AlertSeverity.LOW: "#2563eb",
AlertSeverity.INFO: "#64748b"
}
return colors.get(self.severity, "#6b7280")
def get_severity_icon(self) -> str:
"""Get emoji icon for severity"""
icons = {
AlertSeverity.CRITICAL: "🔴",
AlertSeverity.HIGH: "🟠",
AlertSeverity.MEDIUM: "🟡",
AlertSeverity.LOW: "🔵",
AlertSeverity.INFO: "ℹ️"
}
return icons.get(self.severity, "⚠️")
class EmailRecipient(BaseModel):
"""Email recipient"""
email: EmailStr
name: Optional[str] = None
role: Optional[str] = None
preferences: Dict[str, Any] = {}
class EmailTemplate(BaseModel):
"""Email template"""
name: str
subject: str
html_template: str
text_template: Optional[str] = None
class EmailNotification(BaseModel):
"""Email notification record"""
notification_id: str
alert_id: str
recipient: str
subject: str
sent_at: datetime
delivered: bool
opened: bool = False
clicked: bool = False
bounce: bool = False
error: Optional[str] = None
# ============================================================================
# HTML EMAIL TEMPLATES
# ============================================================================
class EmailTemplates:
"""Pre-built email templates"""
@staticmethod
def get_critical_alert_template() -> str:
"""Critical alert template with full details"""
return """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title }}</title>
</head>
<body style="margin: 0; padding: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f3f4f6;">
<table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f3f4f6; padding: 20px;">
<tr>
<td align="center">
<table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<!-- Header -->
<tr>
<td style="background: linear-gradient(135deg, #1e40af 0%, #7c3aed 100%); padding: 30px; text-align: center;">
<h1 style="margin: 0; color: #ffffff; font-size: 28px;">🛡️ ShadowHunter</h1>
<p style="margin: 10px 0 0 0; color: #e0e7ff; font-size: 14px;">Dark Web Threat Intelligence</p>
</td>
</tr>
<!-- Alert Banner -->
<tr>
<td style="background-color: {{ severity_color }}; padding: 20px; text-align: center;">
<h2 style="margin: 0; color: #ffffff; font-size: 24px;">
{{ severity_icon }} {{ severity }} ALERT
</h2>
</td>
</tr>
<!-- Content -->
<tr>
<td style="padding: 30px;">
<h3 style="margin: 0 0 15px 0; color: #111827; font-size: 20px;">{{ title }}</h3>
<div style="background-color: #f9fafb; border-left: 4px solid {{ severity_color }}; padding: 15px; margin: 20px 0; border-radius: 4px;">
<p style="margin: 0; color: #374151; line-height: 1.6;">{{ description }}</p>
</div>
<!-- Alert Details -->
<table width="100%" cellpadding="10" cellspacing="0" style="margin: 20px 0; border: 1px solid #e5e7eb; border-radius: 6px;">
<tr style="background-color: #f9fafb;">
<td style="color: #6b7280; font-weight: 600; width: 40%;">Affected Domain:</td>
<td style="color: #111827; font-weight: 600;">{{ affected_domain }}</td>
</tr>
<tr>
<td style="color: #6b7280; font-weight: 600; border-top: 1px solid #e5e7eb;">Alert Type:</td>
<td style="color: #111827; border-top: 1px solid #e5e7eb;">{{ alert_type }}</td>
</tr>
<tr style="background-color: #f9fafb;">
<td style="color: #6b7280; font-weight: 600; border-top: 1px solid #e5e7eb;">Detection Time:</td>
<td style="color: #111827; border-top: 1px solid #e5e7eb;">{{ timestamp }}</td>
</tr>
<tr>
<td style="color: #6b7280; font-weight: 600; border-top: 1px solid #e5e7eb;">Alert ID:</td>
<td style="color: #111827; font-family: monospace; font-size: 12px; border-top: 1px solid #e5e7eb;">{{ alert_id }}</td>
</tr>
</table>
<!-- Additional Details -->
{% if metadata %}
<div style="margin: 20px 0;">
<h4 style="margin: 0 0 10px 0; color: #111827;">Additional Details:</h4>
<ul style="margin: 0; padding-left: 20px; color: #374151; line-height: 1.8;">
{% for key, value in metadata.items() %}
<li><strong>{{ key }}:</strong> {{ value }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
<!-- Action Button -->
<div style="text-align: center; margin: 30px 0;">
<a href="{{ dashboard_url }}" style="display: inline-block; background-color: #2563eb; color: #ffffff; padding: 14px 28px; text-decoration: none; border-radius: 6px; font-weight: 600; font-size: 16px;">
View in Dashboard →
</a>
</div>
<!-- Recommended Actions -->
<div style="background-color: #fef3c7; border: 1px solid #fbbf24; border-radius: 6px; padding: 15px; margin: 20px 0;">
<h4 style="margin: 0 0 10px 0; color: #92400e;">⚠️ Recommended Actions:</h4>
<ol style="margin: 0; padding-left: 20px; color: #78350f; line-height: 1.6;">
{{ recommendations }}
</ol>
</div>
</td>
</tr>
<!-- Footer -->
<tr>
<td style="background-color: #f9fafb; padding: 20px; text-align: center; border-top: 1px solid #e5e7eb;">
<p style="margin: 0 0 10px 0; color: #6b7280; font-size: 12px;">
This alert was generated by ShadowHunter at {{ timestamp }}
</p>
<p style="margin: 0; color: #6b7280; font-size: 12px;">
<a href="{{ settings_url }}" style="color: #2563eb; text-decoration: none;">Update Alert Preferences</a> |
<a href="{{ unsubscribe_url }}" style="color: #6b7280; text-decoration: none;">Unsubscribe</a>
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
"""
@staticmethod
def get_daily_digest_template() -> str:
"""Daily digest template"""
return """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Daily Threat Intelligence Digest</title>
</head>
<body style="margin: 0; padding: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f3f4f6;">
<table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f3f4f6; padding: 20px;">
<tr>
<td align="center">
<table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden;">
<!-- Header -->
<tr>
<td style="background: linear-gradient(135deg, #1e40af 0%, #7c3aed 100%); padding: 30px; text-align: center;">
<h1 style="margin: 0; color: #ffffff; font-size: 28px;">📊 Daily Threat Digest</h1>
<p style="margin: 10px 0 0 0; color: #e0e7ff; font-size: 14px;">{{ date }}</p>
</td>
</tr>
<!-- Summary Stats -->
<tr>
<td style="padding: 30px;">
<h2 style="margin: 0 0 20px 0; color: #111827; font-size: 22px;">24-Hour Summary</h2>
<table width="100%" cellpadding="15" cellspacing="0" style="margin: 20px 0;">
<tr>
<td width="50%" style="text-align: center; background-color: #fee2e2; border-radius: 8px; padding: 20px;">
<div style="font-size: 36px; font-weight: bold; color: #dc2626;">{{ critical_count }}</div>
<div style="color: #991b1b; font-size: 14px; margin-top: 5px;">Critical Alerts</div>
</td>
<td width="50%" style="text-align: center; background-color: #fef3c7; border-radius: 8px; padding: 20px;">
<div style="font-size: 36px; font-weight: bold; color: #ca8a04;">{{ high_count }}</div>
<div style="color: #854d0e; font-size: 14px; margin-top: 5px;">High Priority</div>
</td>
</tr>
</table>
<div style="margin: 20px 0; padding: 15px; background-color: #f9fafb; border-radius: 6px;">
<p style="margin: 0; color: #374151; line-height: 1.6;">
<strong>Total Threats Detected:</strong> {{ total_threats }}<br>
<strong>Monitored Domains:</strong> {{ monitored_domains }}<br>
<strong>New Threat Actors:</strong> {{ new_actors }}
</p>
</div>
<!-- Top Threats -->
<h3 style="margin: 30px 0 15px 0; color: #111827;">🔥 Top Threats</h3>
{% for alert in top_alerts %}
<div style="margin: 15px 0; padding: 15px; border-left: 4px solid {{ alert.color }}; background-color: #f9fafb; border-radius: 4px;">
<div style="font-weight: 600; color: #111827; margin-bottom: 5px;">{{ alert.title }}</div>
<div style="font-size: 14px; color: #6b7280;">{{ alert.description }}</div>
<div style="font-size: 12px; color: #9ca3af; margin-top: 5px;">{{ alert.time }}</div>
</div>
{% endfor %}
<!-- View Dashboard Button -->
<div style="text-align: center; margin: 30px 0;">
<a href="{{ dashboard_url }}" style="display: inline-block; background-color: #2563eb; color: #ffffff; padding: 14px 28px; text-decoration: none; border-radius: 6px; font-weight: 600;">
View Full Dashboard →
</a>
</div>
</td>
</tr>
<!-- Footer -->
<tr>
<td style="background-color: #f9fafb; padding: 20px; text-align: center; border-top: 1px solid #e5e7eb;">
<p style="margin: 0; color: #6b7280; font-size: 12px;">
ShadowHunter Daily Digest | <a href="{{ settings_url }}" style="color: #2563eb; text-decoration: none;">Preferences</a>
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
"""
@staticmethod
def get_weekly_report_template() -> str:
"""Weekly report template"""
return """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Weekly Threat Intelligence Report</title>
</head>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
<h1 style="color: #1e40af; border-bottom: 3px solid #1e40af; padding-bottom: 10px;">📈 Weekly Report</h1>
<p><strong>Week of:</strong> {{ week_start }} - {{ week_end }}</p>
<h2 style="color: #374151; margin-top: 30px;">Executive Summary</h2>
<p>{{ summary }}</p>
<h2 style="color: #374151; margin-top: 30px;">Key Metrics</h2>
<table style="width: 100%; border-collapse: collapse; margin: 20px 0;">
<tr style="background-color: #f3f4f6;">
<td style="padding: 12px; border: 1px solid #e5e7eb;"><strong>Metric</strong></td>
<td style="padding: 12px; border: 1px solid #e5e7eb;"><strong>This Week</strong></td>
<td style="padding: 12px; border: 1px solid #e5e7eb;"><strong>Change</strong></td>
</tr>
{% for metric in metrics %}
<tr>
<td style="padding: 12px; border: 1px solid #e5e7eb;">{{ metric.name }}</td>
<td style="padding: 12px; border: 1px solid #e5e7eb;">{{ metric.value }}</td>
<td style="padding: 12px; border: 1px solid #e5e7eb; color: {{ metric.trend_color }};">{{ metric.trend }}</td>
</tr>
{% endfor %}
</table>
<h2 style="color: #374151; margin-top: 30px;">Recommendations</h2>
<ol>
{% for rec in recommendations %}
<li style="margin: 10px 0;">{{ rec }}</li>
{% endfor %}
</ol>
<div style="margin-top: 40px; padding: 20px; background-color: #f3f4f6; border-radius: 8px; text-align: center;">
<a href="{{ report_url }}" style="display: inline-block; background-color: #2563eb; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: bold;">View Detailed Report</a>
</div>
<p style="margin-top: 30px; font-size: 12px; color: #6b7280; text-align: center;">
ShadowHunter Weekly Report | Generated on {{ generated_date }}
</p>
</body>
</html>
"""
# ============================================================================
# EMAIL SENDER
# ============================================================================
class EmailSender:
"""Email sending engine"""
def __init__(self, config: EmailConfig):
self.config = config
self.sent_count = {"hour": 0, "day": 0}
self.last_reset = {"hour": datetime.utcnow(), "day": datetime.utcnow()}
self.notification_history: List[EmailNotification] = []
def _check_rate_limit(self) -> bool:
"""Check if rate limit allows sending"""
now = datetime.utcnow()
# Reset hourly count
if now - self.last_reset["hour"] > timedelta(hours=1):
self.sent_count["hour"] = 0
self.last_reset["hour"] = now
# Reset daily count
if now - self.last_reset["day"] > timedelta(days=1):
self.sent_count["day"] = 0
self.last_reset["day"] = now
# Check limits
if self.sent_count["hour"] >= self.config.max_emails_per_hour:
logger.warning("Hourly email limit reached")
return False
if self.sent_count["day"] >= self.config.max_emails_per_day:
logger.warning("Daily email limit reached")
return False
return True
async def send_email(
self,
recipient: str,
subject: str,
html_body: str,
text_body: Optional[str] = None,
attachments: Optional[List[Dict]] = None
) -> bool:
"""Send an email"""
# Check rate limit
if not self._check_rate_limit():
logger.error(f"Rate limit exceeded, cannot send email to {recipient}")
return False
try:
# Create message
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = f"{self.config.from_name} <{self.config.from_email}>"
msg['To'] = recipient
msg['Date'] = datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S +0000")
# Add text and HTML parts
if text_body:
msg.attach(MIMEText(text_body, 'plain'))
msg.attach(MIMEText(html_body, 'html'))
# Add attachments
if attachments:
for attachment in attachments:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment['data'])
encoders.encode_base64(part)
part.add_header(
'Content-Disposition',
f"attachment; filename= {attachment['filename']}"
)
msg.attach(part)
# Send email
with smtplib.SMTP(self.config.smtp_host, self.config.smtp_port) as server:
if self.config.use_tls:
server.starttls()
if self.config.smtp_username and self.config.smtp_password:
server.login(self.config.smtp_username, self.config.smtp_password)
server.send_message(msg)
# Update counters
self.sent_count["hour"] += 1
self.sent_count["day"] += 1
# Record notification
notification = EmailNotification(
notification_id=f"notif_{datetime.utcnow().timestamp()}",
alert_id="",
recipient=recipient,
subject=subject,
sent_at=datetime.utcnow(),
delivered=True
)
self.notification_history.append(notification)
logger.info(f"Email sent successfully to {recipient}")
return True
except Exception as e:
logger.error(f"Failed to send email to {recipient}: {e}")
# Record failed notification
notification = EmailNotification(
notification_id=f"notif_{datetime.utcnow().timestamp()}",
alert_id="",
recipient=recipient,
subject=subject,
sent_at=datetime.utcnow(),
delivered=False,
error=str(e)
)
self.notification_history.append(notification)
return False
async def send_alert(
self,
alert: EmailAlert,
recipients: List[EmailRecipient],
dashboard_url: str = "https://shadowhunter.io/dashboard"
) -> Dict[str, bool]:
"""Send alert email to multiple recipients"""
# Generate recommendations based on alert type
recommendations = self._generate_recommendations(alert)
# Render template
template = Template(EmailTemplates.get_critical_alert_template())
html_body = template.render(
title=alert.title,
description=alert.description,
severity=alert.severity.value,
severity_color=alert.get_severity_color(),
severity_icon=alert.get_severity_icon(),
affected_domain=alert.affected_domain,
alert_type=alert.alert_type.value,
timestamp=alert.timestamp.strftime("%Y-%m-%d %H:%M:%S UTC"),
alert_id=alert.alert_id,
metadata=alert.metadata,
recommendations=recommendations,
dashboard_url=f"{dashboard_url}/alerts/{alert.alert_id}",
settings_url=f"{dashboard_url}/settings",
unsubscribe_url=f"{dashboard_url}/unsubscribe"
)
subject = f"{alert.get_severity_icon()} [{alert.severity.value}] {alert.title}"
# Send to all recipients
results = {}
for recipient in recipients:
# Check user preferences
if not self._should_send_alert(recipient, alert):
logger.info(f"Skipping {recipient.email} based on preferences")
continue
success = await self.send_email(
recipient=recipient.email,
subject=subject,
html_body=html_body
)
results[recipient.email] = success
return results
def _should_send_alert(self, recipient: EmailRecipient, alert: EmailAlert) -> bool:
"""Check if alert should be sent based on user preferences"""
prefs = recipient.preferences
# Check if email alerts are enabled
if not prefs.get("email_alerts", True):
return False
# Check severity preferences
severity_prefs = prefs.get("alert_severity", ["CRITICAL", "HIGH", "MEDIUM", "LOW"])
if alert.severity.value not in severity_prefs:
return False
# Check domain preferences
monitored_domains = prefs.get("monitored_domains", [])
if monitored_domains and alert.affected_domain not in monitored_domains:
return False
return True
def _generate_recommendations(self, alert: EmailAlert) -> str:
"""Generate action recommendations based on alert type"""
recommendations = {
AlertType.CREDENTIAL_LEAK: """
<li>Immediately reset all passwords for affected accounts</li>
<li>Enable or reset multi-factor authentication (MFA)</li>
<li>Review recent account activity for suspicious logins</li>
<li>Notify affected users to change their passwords</li>
<li>Conduct security awareness training</li>
""",
AlertType.RANSOMWARE_VICTIM: """
<li>Activate incident response team immediately</li>
<li>Isolate affected systems from the network</li>
<li>Contact law enforcement and cyber insurance provider</li>
<li>Do NOT pay ransom without legal consultation</li>
<li>Preserve forensic evidence for investigation</li>
""",
AlertType.IAB_LISTING: """
<li>Verify if unauthorized access has occurred</li>
<li>Change all administrative credentials immediately</li>
<li>Review VPN and RDP access logs</li>
<li>Enable additional authentication requirements</li>
<li>Contact law enforcement to report the listing</li>
""",
AlertType.DATA_BREACH: """
<li>Assess the scope and sensitivity of leaked data</li>
<li>Notify affected individuals as required by law</li>
<li>Contact data protection authorities if required</li>
<li>Implement additional data access controls</li>
<li>Review and update data handling procedures</li>
""",
}
return recommendations.get(alert.alert_type, """
<li>Investigate the alert immediately</li>
<li>Review security logs for related activity</li>
<li>Contact your security team or administrator</li>
<li>Document all findings for future reference</li>
""")
async def send_daily_digest(
self,
recipient: EmailRecipient,
digest_data: Dict[str, Any],
dashboard_url: str = "https://shadowhunter.io/dashboard"
) -> bool:
"""Send daily digest email"""
template = Template(EmailTemplates.get_daily_digest_template())
html_body = template.render(
date=datetime.utcnow().strftime("%B %d, %Y"),
critical_count=digest_data.get("critical_count", 0),
high_count=digest_data.get("high_count", 0),
total_threats=digest_data.get("total_threats", 0),
monitored_domains=digest_data.get("monitored_domains", 0),
new_actors=digest_data.get("new_actors", 0),
top_alerts=digest_data.get("top_alerts", []),
dashboard_url=dashboard_url,
settings_url=f"{dashboard_url}/settings"
)
subject = f"📊 Daily Threat Digest - {datetime.utcnow().strftime('%b %d, %Y')}"
return await self.send_email(
recipient=recipient.email,
subject=subject,
html_body=html_body
)
def get_statistics(self) -> Dict[str, Any]:
"""Get email sending statistics"""
return {
"sent_this_hour": self.sent_count["hour"],
"sent_today": self.sent_count["day"],
"total_sent": len([n for n in self.notification_history if n.delivered]),
"total_failed": len([n for n in self.notification_history if not n.delivered]),
"rate_limit_status": {
"hourly": f"{self.sent_count['hour']}/{self.config.max_emails_per_hour}",
"daily": f"{self.sent_count['day']}/{self.config.max_emails_per_day}"
}
}
# ============================================================================
# FASTAPI INTEGRATION
# ============================================================================
def get_email_router(email_sender: EmailSender):
"""Get email management router for FastAPI"""
from fastapi import APIRouter, Depends
# Assuming auth module is available
# from shadowhunter_auth import get_current_active_user, User
router = APIRouter(prefix="/api/email", tags=["email"])
@router.post("/test")
async def send_test_email(recipient: str): # , user: User = Depends(get_current_active_user)):
"""Send test email"""
success = await email_sender.send_email(
recipient=recipient,
subject="ShadowHunter Test Email",
html_body="<h1>Test Email</h1><p>This is a test email from ShadowHunter.</p>"
)
return {"success": success}
@router.get("/statistics")
async def get_email_statistics(): # user: User = Depends(get_current_active_user)):
"""Get email statistics"""
return email_sender.get_statistics()
@router.get("/notifications")
async def get_notifications(limit: int = 50): # , user: User = Depends(get_current_active_user)):
"""Get notification history"""
return email_sender.notification_history[-limit:]
return router
# ============================================================================
# USAGE EXAMPLE
# ============================================================================
async def demo_email_system():
"""Demonstrate email alert system"""
print("="*80)
print("ShadowHunter Email Alert System Demo")
print("="*80)
# Initialize email sender
config = EmailConfig(
smtp_host="smtp.gmail.com",
smtp_port=587,
smtp_username="your-email@gmail.com", # Replace with actual
smtp_password="your-app-password", # Replace with actual
from_email="alerts@shadowhunter.io"
)
sender = EmailSender(config)
# Create sample alert
alert = EmailAlert(
alert_id="alert_12345",
severity=AlertSeverity.CRITICAL,
alert_type=AlertType.CREDENTIAL_LEAK,
title="Admin Credentials Leaked on Dark Web",
description="Administrator credentials for acmecorp.com found in Lumma stealer log posted on Telegram",
affected_domain="acmecorp.com",
timestamp=datetime.utcnow(),
metadata={
"Credentials Found": 45,
"Source": "Telegram - stealer_premium",
"Stealer Type": "Lumma",
"Has Passwords": "Yes",
"Session Cookies": "Yes"
}
)
# Create recipients
recipients = [
EmailRecipient(
email="security@acmecorp.com",
name="Security Team",
role="admin",
preferences={
"email_alerts": True,
"alert_severity": ["CRITICAL", "HIGH"]
}
)
]
# Send alert
print("\n📧 Sending critical alert email...")
results = await sender.send_alert(
alert=alert,
recipients=recipients,
dashboard_url="https://shadowhunter.io/dashboard"
)
print(f"\n✅ Email sent successfully: {results}")
# Display statistics
stats = sender.get_statistics()
print(f"\n📊 Email Statistics:")
print(json.dumps(stats, indent=2))
if __name__ == "__main__":
import json
print("\n" + "="*80)
print("ShadowHunter Email Alert System")
print("="*80)
print("\n📧 Supported Alert Types:")
for alert_type in AlertType:
print(f" - {alert_type.value}")
print("\n🎨 Available Templates:")
print(" - Critical Alert (detailed)")
print(" - Daily Digest (summary)")
print(" - Weekly Report (executive)")
print("\n⚙️ Configuration Required:")
print(" - SMTP Host/Port")
print(" - Email credentials")
print(" - Rate limiting settings")
print("\n" + "="*80)
print("Run: asyncio.run(demo_email_system()) to test")
print("="*80)