Skip to main content

Synchronous Access of IMAP4 without Timeout

PY041
no_timeout
CWE-1088
⚠️ Warning

The imaplib.IMAP4 and imaplib.IMAP4_SSL classes are used to connect to IMAP servers for retrieving emails over the Internet Message Access Protocol (IMAP). By default, these classes do not specify a timeout, which can result in the application blocking indefinitely while trying to communicate with an unresponsive server. This can lead to resource exhaustion, Denial of Service (DoS), or system instability, particularly in production environments where resilience is critical.

This rule enforces the use of a timeout parameter when creating instances of imaplib.IMAP4 and imaplib.IMAP4_SSL to avoid the risk of indefinite blocking and ensure graceful handling of network delays or failures.

Failing to specify a timeout in these classes may cause the application to block indefinitely while waiting for a response from the mail server. This can lead to Denial of Service (DoS) vulnerabilities or cause the application to become unresponsive.

Example

import imaplib
import ssl


imap = imaplib.IMAP4("imap.example.com")
imap.starttls(ssl.create_default_context())

Remediation

Always provide a timeout parameter when using imaplib.IMAP4 or imaplib.IMAP4_SSL. This ensures that if the mail server is unreachable or unresponsive, the connection attempt will fail after a set period, preventing indefinite blocking and resource exhaustion.

Alternatively, the global default timeout can be set via socket.setdefaulttimeout(). This is a good option to enforce a consistent timeout for any network library that uses sockets, including imaplib.

import imaplib
import ssl


imap = imaplib.IMAP4("imap.example.com", timeout=5)
imap.starttls(ssl.create_default_context())

False Positives

In the case of a false positive the rule can be suppressed. Simply add a trailing or preceding comment line with either the rule ID (PY041) or rule category name (no_timeout).

Fix Iconfix
import imaplib
import ssl


# suppress: PY041
imap = imaplib.IMAP4("imap.example.com")
imap.starttls(ssl.create_default_context())

See also