Skip to main content

Improper Certificate Validation Using imaplib

PY023
improper_certificate_validation
CWE-295
⚠️ Warning

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:

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

Example

import imaplib


with imaplib.IMAP4_SSL("domain.org") as imap4:
imap4.noop()
imap4.login("user", "password")

Remediation

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

import imaplib
import ssl


with imaplib.IMAP4_SSL(
"domain.org",
ssl_context=ssl.create_default_context(),
) as imap4:
imap4.noop()
imap4.login("user", "password")

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 (PY023) or rule category name (improper_certificate_validation).

Fix Iconfix
import imaplib


# suppress: PY023
with imaplib.IMAP4_SSL("domain.org") as imap4:
imap4.noop()
imap4.login("user", "password")

See also