Skip to content

imaplib — unverified context

Improper Certificate Validation Using imaplib

The Python class imaplib.IMAP4_SSL by default creates an SSL context that does not verify the server's certificate if the context parameter is unset or has a value of None. This means that an attacker can easily impersonate a legitimate server and fool your application into connecting to it.

If you use imaplib.IMAP4_SSL or starttls without a context set, you are opening your application up to a number of security risks, including:

  • Machine-in-the-middle attacks
  • Session hijacking
  • Data theft

Example

imaplib_imap4_ssl_context_unset.py
import getpass
import imaplib


imap4 = imaplib.IMAP4_SSL("domain.org")
imap4.login(getpass.getuser(), getpass.getpass())
imap4.select()
typ, data = imap4.search(None, "ALL")
for num in data[0].split():
    typ, data = imap4.fetch(num, "(RFC822)")
    print(f"Message {num}\n{data[0][1]}\n")
imap4.close()
imap4.logout()
Example Output
> precli tests/unit/rules/python/stdlib/imaplib/examples/imaplib_imap4_ssl_context_unset.py
⚠️  Warning on line 5 in tests/unit/rules/python/stdlib/imaplib/examples/imaplib_imap4_ssl_context_unset.py
PY023: Improper Certificate Validation
The 'imaplib.IMAP4_SSL' function does not properly validate certificates when context is unset or None.

Remediation

Set the value of the ssl_context keyword argument to ssl.create_default_context() to ensure the connection is fully verified.

imaplib_imap4_ssl_context_unset.py
import getpass
import imaplib
import ssl


imap4 = imaplib.IMAP4_SSL(
    "domain.org",
    ssl_context=ssl.create_default_context(),
)
imap4.login(getpass.getuser(), getpass.getpass())
imap4.select()
typ, data = imap4.search(None, "ALL")
for num in data[0].split():
    typ, data = imap4.fetch(num, "(RFC822)")
    print(f"Message {num}\n{data[0][1]}\n")
imap4.close()
imap4.logout()

Default Configuration

enabled = true
level = "warning"

See also

New in version 0.3.14