Skip to content

ftplib — unverified context

Improper Certificate Validation Using ftplib

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:

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

Example

ftplib_ftp_tls_context_unset.py
import ftplib


ftp = ftplib.FTP_TLS("ftp.us.debian.org")
ftp.login()

ftp.cwd("debian")
ftp.retrlines("LIST")

ftp.quit()
Example Output
> precli tests/unit/rules/python/stdlib/ftplib/examples/ftplib_ftp_tls_context_unset.py
⚠️  Warning on line 4 in tests/unit/rules/python/stdlib/ftplib/examples/ftplib_ftp_tls_context_unset.py
PY022: Improper Certificate Validation
The 'ftplib.FTP_TLS' function does not properly validate certificates when context is unset or None.

Remediation

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

ftplib_ftp_tls_context_unset.py
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")

Default Configuration

enabled = true
level = "warning"

See also

New in version 0.3.14