Aug 6, 2026·7 min read·24 visits
A protocol command injection vulnerability exists in Python's standard imaplib library due to a lack of NUL, CR, and LF byte validation in argument serialization. Attackers passing crafted folder or search parameters can inject arbitrary IMAP commands. This has been remediated in updated CPython versions.
CVE-2025-15366 is a command injection vulnerability in Python's standard imaplib module, occurring due to the improper neutralization of carriage returns (\r), line feeds (\n), and null bytes (\x00). When an application passes user-controlled input into standard IMAP library calls, an attacker can break out of the line-oriented protocol context and execute arbitrary IMAP directives with the privileges of the authenticated session.
The Python standard library imaplib is the primary module for interfacing with IMAP4 mail servers. Many enterprise and mail gateway software packages rely on this built-in module to fetch, search, and manage email folders. The module supports a high-level API wrapper for executing protocol-specific commands. These wrappers abstract the complex protocol serialization away from the developer.
However, the execution path that constructs and transfers payloads to the server does not enforce robust validation on user-supplied argument values. If an application forwards untrusted variables into imaplib commands, it exposes the system to command injection. This issue represents a significant vulnerability pattern in network client components, classified under CWE-77.
The impact is tied to the design of the Internet Message Access Protocol (IMAP) specified in RFC 3501. Because IMAP uses strict line-terminated sequences, adding line delimiters alters the command execution stream. This analysis inspects the root cause of the flaw, traces its evolution through a two-phase remediation, and provides concrete detection and defense strategies.
The underlying IMAP protocol is strictly line-oriented, relying on specific sequence structures. Communication consists of commands transmitted from client to server, which are prefixed with an alphanumeric token (the command tag) and terminated by the standard Carriage Return and Line Feed (CRLF) byte sequence (\x0d\x0a or \r\n). If any field inside the client payload contains a nested CRLF sequence, the parser treats the trailing segment as the end of the current instruction and the initiation of a subsequent, distinct instruction.
Inside CPython's Lib/imaplib.py, the core serialization engine resides within the IMAP4._command(self, name, *args) private method. This function handles the generation of client tags, parses the command string, and maps arguments into raw bytes prior to writing them to the TCP socket. Historically, _command concatenated command arguments directly to the payload variable using standard space separation without searching for or neutralizing protocol-disrupting bytes.
Because there was no input validation check, an attacker-controlled variable could introduce a nested command. Once the payload arrived at the IMAP daemon, the transport layer processed the data packet containing multiple line breaks. The server parsed these line breaks as distinct, sequential execution boundaries, giving the attacker the ability to inject custom, unauthorized protocol commands.
This behavior represents a classic command injection pattern in a network protocol driver. By injecting protocol control bytes into fields intended as parameters, attackers can transition from simple values to executing administrative commands. This occurs because the library fails to guarantee that single parameters map strictly to single protocol fields.
The resolution of CVE-2025-15366 occurred in two distinct engineering phases. The initial attempt to fix the vulnerability (Commit 6262704b134db2a4ba12e85ecfbd968534f28b45) introduced an over-restrictive validation regex designed to catch all C0 control characters. This regex, compiled as re.compile(b'[\x00-\x1F\x7F]'), rejected any command argument containing bytes in this range with a ValueError.
While this prevented CRLF injection, it caused significant regression errors across production IMAP integrations. The IMAP protocol allows certain control characters, such as tabs (\t) or formatters, inside mailbox names, provided they are encapsulated within quoted strings. As a result, when compliance-conforming mail servers returned folders containing these characters, unpatched Python clients attempting to select or query them resulted in sudden application crashes.
To resolve this issue, the development team introduced a refined fix in Commit d0921efb665aff26b378f495e5ff84f7e3fe649d. This refined approach limited the blocked characters strictly to the critical protocol delimiters: NUL (\x00), CR (\r), and LF (\n). Other control characters are safely processed using imaplib's existing quoting mechanism (_non_astring_char), ensuring correct protocol encapsulation without throwing exceptions.
Below is the unified patch diff from the Python 3.14 branch (Commit 298182272a740ce2016aee2f54acbd0bba1944c1) illustrating the implementation of the narrowed sanitization filter within Lib/imaplib.py:
# Refined mitigation compiles a regex specifically targeting NUL, CR, and LF.
+# Only NUL, CR and LF are unsafe (they cannot be represented even in
+# a quoted string); other control characters are sent quoted.
+_control_chars = re.compile(b'[\\x00\\r\\n]')
_non_astring_char = re.compile(br'[(){ \\x00-\\x1f\\x7f-\\xff%*\\\\"]')The sanitization is enforced inside the central parameter processing loop of _command:
def _command(self, name, *args):
# ...
for arg in args:
if arg is None: continue
if isinstance(arg, str):
arg = bytes(arg, self._encoding)
+ if _control_chars.search(arg):
+ raise ValueError("NUL, CR and LF not allowed in commands")
data = data + b' ' + argExploitation of CVE-2025-15366 is straightforward when an application constructs IMAP command arguments using untrusted data. Consider a gateway program that exposes an endpoint for choosing a specific email folder. The target parameter is passed directly to the IMAP4.select() function, which invokes the vulnerable internal _command code path.
To trigger the vulnerability, an attacker provides a structured string containing nested carriage returns and line feeds. The payload is designed to break the existing command line structure and inject a separate command. For example, injecting INBOX\r\nA002 CREATE MALICIOUS_BOX\r\nA003 SELECT INBOX splits the request.
When Python's socket transport sends this byte sequence to the mail server, the IMAP daemon processes it sequentially. The parser reads three lines instead of one, interpreting them as distinct operations. As a result, the backend server executes the unauthorized CREATE command within the authenticated context of the application's connection.
The structural mechanics of this protocol injection flow are shown in the diagram below:
This vulnerability represents a significant risk because it bypasses application-level access controls. An attacker can execute arbitrary IMAP protocol directives as the authenticated user. Depending on the design of the vulnerable client, this can result in unauthorized folder manipulation, mailbox deletion, or administrative configuration changes.
The CVSS v4.0 base score is calculated at 5.9 (Medium). The assessment reflects high integrity impact because an attacker can write, alter, or delete messages on the target server. The attack complexity remains low, meaning standard payload injection patterns can successfully exploit the flaw without advanced bypass techniques.
However, the vulnerability requires specific preconditions. It requires the developer to pass unsanitized input to high-level imaplib calls. If the application limits parameters to static configurations, the attack surface is inaccessible from a network boundary. This structural dependency reduces the likelihood of widespread exploitation.
No known exploitation in the wild has been observed as of August 2026. The vulnerability is not listed in the CISA Known Exploited Vulnerabilities (KEV) catalog. Nevertheless, because stable Proof-of-Concept test suites are publicly accessible, organizations should verify and patch their deployments to prevent targeted attacks.
The primary remediation for CVE-2025-15366 is to upgrade the CPython runtime to a secure release. The Python Software Foundation has backported the refined fix across all supported releases. Users should transition to CPython 3.13.15+, 3.14.7+, or 3.15.0a6+ as soon as possible.
If upgrading the interpreter is not immediately possible, developers can implement manual input validation. Applications must inspect and reject any input arguments containing null bytes or line breaks before forwarding them to imaplib functions. A reference input-sanitization wrapper is shown below:
def sanitize_imap_parameter(user_provided_string: str) -> str:
# Detect and reject the core injection delimiters
invalid_bytes = ('\\x00', '\\r', '\\n')
if any(bad_char in user_provided_string for bad_char in invalid_bytes):
raise ValueError("Invalid protocol characters detected in parameter")
return user_provided_stringAdditionally, security teams should review and audit custom IMAP code bases. Ensure that low-level writing methods such as IMAP4.send(self, data) are not used with untrusted variables, as these functions bypass the standard _command input validation filters. Defensive design should follow the principle of least privilege, minimizing the permissions of the authenticated IMAP user accounts.
CVSS:4.0/AV:N/AC:L/AT:P/PR:H/UI:N/VC:L/VI:H/VA:N/SC:N/SI:N/SA:N| Product | Affected Versions | Fixed Version |
|---|---|---|
CPython Python Software Foundation | < 3.13.15 | 3.13.15 |
CPython Python Software Foundation | >= 3.14.0, < 3.14.7 | 3.14.7 |
CPython Python Software Foundation | >= 3.15.0a1, < 3.15.0a6 | 3.15.0a6 |
| Attribute | Detail |
|---|---|
| CWE ID | CWE-77 |
| Attack Vector | Network |
| CVSS v4.0 Base Score | 5.9 |
| EPSS Score | 0.0036 |
| Exploit Status | Proof-of-Concept (PoC) |
| CISA KEV Status | Not Listed |
| Impact | Integrity Compromise (High), Confidentiality (Low) |
The software constructs a command using externally-influenced input, but it does not neutralize or incorrectly neutralizes special elements that can modify the intended command when it is sent to a downstream component.
CVE-2026-12243 is a path traversal vulnerability in the Natural Language Toolkit (NLTK) version 3.9.4. The flaw exists because the input validation routine fails to account for percent-encoded directory traversal sequences like '..%2f' before passing them to urllib.request.url2pathname(), which decodes them into active traversal sequences.
CVE-2026-73654 is a high-severity prototype pollution vulnerability in Trigger.dev. The flaw occurs during the handling of run-metadata updates through the PUT /api/v1/runs/:runId/metadata endpoint. Because user-supplied keys are parsed directly by the @jsonhero/path library without sanitization, an authenticated attacker with low privileges can pollute the global Object.prototype. This causes database queries via Prisma ORM to fail validation and induces unhandled exceptions in the Prometheus metrics client, resulting in a process-wide denial of service.
CVE-2026-73559 is an uncontrolled resource consumption vulnerability in the vLLM engine, specifically within the /v1/completions API endpoint, allowing authenticated attackers to cause application-level denial of service via unbounded prompt arrays.
A critical security bypass vulnerability in Argo Workflows allows authenticated attackers with workflow submission privileges to bypass 'Strict' or 'Secure' template referencing restrictions. By injecting unvalidated fields into the nested ArtifactGC configuration, attackers can execute arbitrary pod patches, leading to host namespace escape and cluster-wide privilege escalation.
A Server-Side Request Forgery (SSRF) / Confused Deputy vulnerability has been identified in Pydantic AI UI Adapters (such as VercelAIAdapter). Under certain conditions, a malicious client can supply manipulated message history with provider metadata that forces the server to resolve files within privileged cloud environments (AWS S3, Google Cloud Storage) or model providers. This occurs because the adapters deserialize client-provided metadata structures directly into UploadedFile instances without validation, which are subsequently fetched using high-privilege server credentials.
A path traversal vulnerability in the optional dashboard server of atomic-agents-stack before version 1.1.0 allows unauthenticated remote attackers to read arbitrary files from the host filesystem.