Skip to main content

Improper Certificate Validation Using ftplib

PY022
improper_certificate_validation
CWE-295
⚠️ Warning

The Python class ftplib.FTP_TLS 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 ftplib.FTP_TLS 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 ftplib


with ftplib.FTP_TLS("ftp.us.debian.org") as ftp:
ftp.cwd("debian")
ftp.retrlines("LIST")

Remediation

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

import ftplib
import ssl


with ftplib.FTP_TLS(
"ftp.us.debian.org",
context=ssl.create_default_context(),
) as ftp:
ftp.cwd("debian")
ftp.retrlines("LIST")

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

Fix Iconfix
import ftplib


# suppress: PY022
with ftplib.FTP_TLS("ftp.us.debian.org") as ftp:
ftp.cwd("debian")
ftp.retrlines("LIST")

See also