Buckets:

download
raw
19.2 kB
"""
Email Notification Backend for Zen-AI-Pentest
Supports SMTP with TLS/SSL and HTML/text formats.
"""
import logging
import smtplib
from datetime import datetime, timezone
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
logger = logging.getLogger(__name__)
class EmailBackend:
"""Email Notification Backend with retry support"""
def __init__(
self,
smtp_host: str,
smtp_port: int,
username: str,
password: str,
use_tls: bool = True,
from_email: Optional[str] = None,
from_name: str = "Zen-AI-Pentest",
timeout: int = 30,
max_retries: int = 3,
) -> None:
"""
Initialize Email backend.
Args:
smtp_host: SMTP server hostname
smtp_port: SMTP server port
username: SMTP username
password: SMTP password
use_tls: Use STARTTLS (True) or SSL (False)
from_email: Sender email address
from_name: Sender display name
timeout: Connection timeout
max_retries: Maximum retry attempts
"""
self.smtp_host = smtp_host
self.smtp_port = smtp_port
self.username = username
self.password = password
self.use_tls = use_tls
self.from_email = from_email or username
self.from_name = from_name
self.timeout = timeout
self.max_retries = max_retries
@classmethod
def from_env(cls, max_retries: int = 3) -> "EmailBackend":
"""Create backend from environment variables."""
import os
return cls(
smtp_host=os.getenv("SMTP_HOST", "smtp.gmail.com"),
smtp_port=int(os.getenv("SMTP_PORT", "587")),
username=os.getenv("SMTP_USER", ""),
password=os.getenv("SMTP_PASS", ""),
use_tls=os.getenv("SMTP_USE_TLS", "true").lower() == "true",
from_email=os.getenv("FROM_EMAIL", os.getenv("SMTP_USER", "")),
from_name=os.getenv("FROM_NAME", "Zen-AI-Pentest"),
max_retries=max_retries,
)
def validate_config(self) -> bool:
"""Validate email configuration"""
return all(
[
self.smtp_host,
self.smtp_port,
self.username,
self.password,
]
)
def send(
self,
to_email: Union[str, List[str]],
subject: str,
body: str,
html_body: Optional[str] = None,
attachments: Optional[List[Dict[str, Any]]] = None,
) -> Dict[str, Any]:
"""
Send email notification.
Args:
to_email: Recipient email(s)
subject: Email subject
body: Plain text body
html_body: Optional HTML body
attachments: List of attachment dicts with filename and content/path
Returns:
Dict with success status
"""
if not self.validate_config():
return {
"success": False,
"error": "Email configuration incomplete",
}
# Prepare recipients
if isinstance(to_email, str):
to_list = [to_email]
else:
to_list = list(to_email)
# Create message
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = f"{self.from_name} <{self.from_email}>"
msg["To"] = ", ".join(to_list)
# Attach plain text
msg.attach(MIMEText(body, "plain"))
# Attach HTML if provided
if html_body:
msg.attach(MIMEText(html_body, "html"))
# Add attachments
if attachments:
for attachment in attachments:
self._attach_file(msg, attachment)
return self._send_with_retry(to_list, msg)
def send_event(
self,
to_email: Union[str, List[str]],
event_type: str,
data: Dict[str, Any],
template_data: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""
Send event notification.
Args:
to_email: Recipient email(s)
event_type: Type of event
data: Event data
template_data: Optional pre-rendered template data
Returns:
Dict with success status
"""
if template_data:
return self.send(to_email=to_email, **template_data)
builders = {
"scan_started": self._build_scan_started,
"scan_completed": self._build_scan_completed,
"critical_finding": self._build_critical_finding,
"high_severity_cve": self._build_high_severity_cve,
"system_alert": self._build_system_alert,
"report_ready": self._build_report_ready,
}
builder = builders.get(event_type, self._build_generic)
subject, body, html_body = builder(data)
return self.send(
to_email=to_email,
subject=subject,
body=body,
html_body=html_body,
)
def _build_scan_started(self, data: Dict[str, Any]) -> tuple:
"""Build scan started email"""
subject = f"๐Ÿ” Scan Started: {data.get('target', 'Unknown')}"
body = f"""
Scan Started
============
Target: {data.get("target", "Unknown")}
Scan ID: {data.get("scan_id", "N/A")}
Scan Type: {data.get("scan_type", "N/A")}
Started By: {data.get("started_by", "N/A")}
Time: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
This scan is now running. You will receive another notification when it completes.
---
Zen-AI-Pentest
"""
html_body = self._render_html_template(
title="Scan Started",
status="info",
status_text="IN PROGRESS",
data=data,
fields=[
("Target", data.get("target", "N/A")),
("Scan ID", str(data.get("scan_id", "N/A"))),
("Scan Type", data.get("scan_type", "N/A")),
("Started By", data.get("started_by", "N/A")),
],
message="This scan is now running. You will receive another notification when it completes.",
)
return subject, body, html_body
def _build_scan_completed(self, data: Dict[str, Any]) -> tuple:
"""Build scan completed email"""
findings = data.get("findings_count", 0)
critical = data.get("critical_count", 0)
high = data.get("high_count", 0)
if critical > 0:
status = "error"
status_text = "CRITICAL ISSUES FOUND"
elif high > 0:
status = "warning"
status_text = "HIGH SEVERITY ISSUES"
elif findings > 0:
status = "warning"
status_text = "ISSUES FOUND"
else:
status = "success"
status_text = "NO ISSUES FOUND"
subject = f"{'๐Ÿ”ด' if critical > 0 else '๐ŸŸข'} Scan Completed: {data.get('target', 'Unknown')}"
body = f"""
Scan Completed
==============
Target: {data.get("target", "Unknown")}
Status: {status_text}
Scan ID: {data.get("scan_id", "N/A")}
Duration: {data.get("duration", "N/A")}s
Findings Summary
----------------
Total Findings: {findings}
Critical: {critical}
High: {high}
Medium: {data.get("medium_count", 0)}
Low: {data.get("low_count", 0)}
---
Zen-AI-Pentest
"""
html_body = self._render_html_template(
title="Scan Completed",
status=status,
status_text=status_text,
data=data,
fields=[
("Target", data.get("target", "N/A")),
("Scan ID", str(data.get("scan_id", "N/A"))),
("Duration", f"{data.get('duration', 'N/A')}s"),
("Total Findings", str(findings)),
("Critical", str(critical)),
("High", str(high)),
],
)
return subject, body, html_body
def _build_critical_finding(self, data: Dict[str, Any]) -> tuple:
"""Build critical finding email"""
subject = f"๐Ÿšจ CRITICAL: {data.get('title', 'Vulnerability Found')}"
body = f"""
CRITICAL VULNERABILITY DETECTED
================================
Title: {data.get("title", "Unknown")}
Target: {data.get("target", "Unknown")}
CVE: {data.get("cve", "N/A")}
CVSS Score: {data.get("cvss", "N/A")}
Severity: CRITICAL
Tool: {data.get("tool", "Unknown")}
Port: {data.get("port", "N/A")}
Description
-----------
{data.get("description", "No description available.")}
โš ๏ธ IMMEDIATE ACTION REQUIRED
---
Zen-AI-Pentest
"""
html_body = self._render_html_template(
title="CRITICAL VULNERABILITY",
status="error",
status_text="IMMEDIATE ACTION REQUIRED",
data=data,
fields=[
("Target", data.get("target", "N/A")),
("CVE", data.get("cve", "N/A")),
("CVSS Score", str(data.get("cvss", "N/A"))),
("Severity", "CRITICAL"),
("Tool", data.get("tool", "Unknown")),
("Port", str(data.get("port", "N/A"))),
],
message=data.get("description", ""),
alert_class="critical",
)
return subject, body, html_body
def _build_high_severity_cve(self, data: Dict[str, Any]) -> tuple:
"""Build high severity CVE email"""
subject = f"โš ๏ธ High Severity CVE: {data.get('cve', 'Unknown')}"
body = f"""
High Severity CVE Alert
=======================
CVE ID: {data.get("cve", "Unknown")}
CVSS Score: {data.get("cvss", "N/A")}
EPSS Score: {data.get("epss", "N/A")}
Affected: {data.get("affected", "N/A")}
Description
-----------
{data.get("description", "No description available.")}
---
Zen-AI-Pentest
"""
html_body = self._render_html_template(
title="High Severity CVE",
status="warning",
status_text="HIGH PRIORITY",
data=data,
fields=[
("CVE ID", data.get("cve", "N/A")),
("CVSS Score", str(data.get("cvss", "N/A"))),
("EPSS Score", str(data.get("epss", "N/A"))),
("Affected", data.get("affected", "N/A")),
],
message=data.get("description", ""),
)
return subject, body, html_body
def _build_system_alert(self, data: Dict[str, Any]) -> tuple:
"""Build system alert email"""
alert_type = data.get("alert_type", "info")
status_map = {
"error": "error",
"warning": "warning",
"info": "info",
"success": "success",
}
subject = f"๐Ÿ”” System Alert: {data.get('title', 'Notification')}"
body = f"""
System Alert
============
Title: {data.get("title", "Unknown")}
Component: {data.get("component", "N/A")}
Severity: {alert_type.upper()}
Time: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
Message
-------
{data.get("message", "")}
---
Zen-AI-Pentest System
"""
html_body = self._render_html_template(
title=f"System Alert: {data.get('title', 'Unknown')}",
status=status_map.get(alert_type, "info"),
status_text=alert_type.upper(),
data=data,
fields=[
("Component", data.get("component", "N/A")),
("Severity", alert_type.upper()),
],
message=data.get("message", ""),
)
return subject, body, html_body
def _build_report_ready(self, data: Dict[str, Any]) -> tuple:
"""Build report ready email"""
subject = f"๐Ÿ“Š Report Ready: {data.get('target', 'Unknown')}"
body = f"""
Report Ready
============
Your security report is ready for download.
Target: {data.get("target", "Unknown")}
Report ID: {data.get("report_id", "N/A")}
Scan ID: {data.get("scan_id", "N/A")}
Format: {data.get("format", "PDF").upper()}
Size: {data.get("size", "N/A")}
Generated: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
You can download the report from the dashboard or via the API.
---
Zen-AI-Pentest
"""
html_body = self._render_html_template(
title="Report Ready",
status="success",
status_text="READY FOR DOWNLOAD",
data=data,
fields=[
("Target", data.get("target", "N/A")),
("Report ID", str(data.get("report_id", "N/A"))),
("Scan ID", str(data.get("scan_id", "N/A"))),
("Format", data.get("format", "PDF").upper()),
("Size", data.get("size", "N/A")),
],
message="Your security report is ready for download.",
)
return subject, body, html_body
def _build_generic(self, data: Dict[str, Any]) -> tuple:
"""Build generic email"""
subject = data.get("title", "Zen-AI-Pentest Notification")
body = data.get("message", "")
html_body = self._render_html_template(
title=data.get("title", "Notification"),
status="info",
status_text="INFO",
data=data,
message=body,
)
return subject, body, html_body
def _render_html_template(
self,
title: str,
status: str,
status_text: str,
data: Dict[str, Any],
fields: List[tuple] = None,
message: str = "",
alert_class: str = "",
) -> str:
"""Render HTML email template"""
colors = {
"success": ("#10b981", "#d1fae5"),
"warning": ("#f59e0b", "#fef3c7"),
"error": ("#ef4444", "#fee2e2"),
"info": ("#3b82f6", "#dbeafe"),
}
header_color, bg_color = colors.get(status, colors["info"])
fields_html = ""
if fields:
fields_html = "".join(
[
f"""
<tr>
<td style="padding: 10px; border-bottom: 1px solid #e5e7eb; font-weight: bold; width: 30%;">{name}</td>
<td style="padding: 10px; border-bottom: 1px solid #e5e7eb;">{value}</td>
</tr>
"""
for name, value in fields
]
)
fields_html = f"""
<table style="width: 100%; border-collapse: collapse; margin: 20px 0;">
{fields_html}
</table>
"""
message_html = ""
if message:
message_html = f"""
<div style="background: #f9fafb; padding: 15px; border-radius: 6px; margin: 20px 0;">
<p style="margin: 0; color: #374151;">{message}</p>
</div>
"""
alert_html = ""
if alert_class == "critical":
alert_html = """
<div style="background: #ef4444; color: white; padding: 15px; border-radius: 6px; margin: 20px 0; text-align: center; font-weight: bold;">
โš ๏ธ IMMEDIATE ACTION REQUIRED
</div>
"""
return f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{title}</title>
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f3f4f6; margin: 0; padding: 20px;">
<div style="max-width: 600px; margin: 0 auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
<div style="background: {header_color}; color: white; padding: 20px; text-align: center;">
<h1 style="margin: 0; font-size: 24px;">{title}</h1>
<p style="margin: 10px 0 0 0; opacity: 0.9;">{status_text}</p>
</div>
<div style="padding: 30px;">
{alert_html}
{fields_html}
{message_html}
</div>
<div style="background: #f9fafb; padding: 20px; text-align: center; font-size: 12px; color: #6b7280; border-top: 1px solid #e5e7eb;">
<p>Zen-AI-Pentest Security Platform</p>
<p>{datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}</p>
</div>
</div>
</body>
</html>
"""
def _attach_file(self, msg: MIMEMultipart, attachment: Dict[str, Any]) -> None:
"""Attach file to message"""
filename = attachment.get("filename", "attachment")
content = attachment.get("content")
path = attachment.get("path")
part = MIMEBase("application", "octet-stream")
if content:
part.set_payload(content)
elif path and Path(path).exists():
with open(path, "rb") as f:
part.set_payload(f.read())
else:
logger.warning(f"Attachment not found: {filename}")
return
encoders.encode_base64(part)
part.add_header(
"Content-Disposition",
f"attachment; filename= {filename}",
)
msg.attach(part)
def _send_with_retry(self, recipients: List[str], msg: MIMEMultipart) -> Dict[str, Any]:
"""Send with retry logic"""
last_error = None
for attempt in range(self.max_retries):
try:
if self.use_tls:
server = smtplib.SMTP(self.smtp_host, self.smtp_port, timeout=self.timeout)
server.starttls()
else:
server = smtplib.SMTP_SSL(self.smtp_host, self.smtp_port, timeout=self.timeout)
server.login(self.username, self.password)
server.sendmail(self.from_email, recipients, msg.as_string())
server.quit()
return {
"success": True,
"recipients": recipients,
"attempt": attempt + 1,
}
except Exception as e:
last_error = str(e)
logger.warning(f"Email send error (attempt {attempt + 1}): {e}")
# Exponential backoff
if attempt < self.max_retries - 1:
import time
time.sleep(2**attempt)
return {
"success": False,
"error": last_error,
"attempts": self.max_retries,
}
def test(self, to_email: str) -> Dict[str, Any]:
"""Test the email connection"""
return self.send(
to_email=to_email,
subject="๐Ÿ”” Test Notification - Zen-AI-Pentest",
body="""
This is a test notification from Zen-AI-Pentest.
If you received this email, your notification settings are configured correctly.
---
Zen-AI-Pentest Notification System
""",
html_body=self._render_html_template(
title="Test Notification",
status="success",
status_text="CONNECTION SUCCESSFUL",
data={},
message="If you received this email, your notification settings are configured correctly.",
),
)

Xet Storage Details

Size:
19.2 kB
ยท
Xet hash:
e9b0607621e9a9e6e3a1e71a725322151f1870e1c3232a62737a34c62972355e

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.