CVE-2021-4189: Unchecked Return Value (CWE-252)
value: A flaw was found in Python, specifically in the FTP (File Transfer Protocol) client library in PASV (passive) mode. The issue is how the FTP client trusts the host from the PASV response by default. This flaw allows an attacker to set up a malicious FTP server that can trick FTP clients into connecting back to a given IP address and port. This vulnerability could lead to FTP client scanning ports, which otherwise would not have been possible.
CWE description: The product does not check the return value from a method or function, which can prevent it from detecting unexpected states and conditions.
CVSS v3 base score: 5.3
Published: 2022-08-24T16:15Z
Repository: https://github.com/python/cpython
Language: Python
Files changed: Lib/ftplib.py, Lib/test/test_ftplib.py, Misc/NEWS.d/next/Security/2021-03-13-03-48-14.bpo-43285.g-Hah3.rst
Commit date: 2021-03-15 11:39:31 -0700
Commit message: bpo-43285 Make ftplib not trust the PASV response. (GH-24838)

bpo-43285: Make ftplib not trust the PASV response.

The IPv4 address value returned from the server in response to the PASV command
should not be trusted.  This prevents a malicious FTP server from using the
response to probe IPv4 address and port combinations on the client network.

Instead of using the returned address, we use the IP address we're
already connected to.  This is the strategy other ftp clients adopted,
and matches the only strategy available for the modern IPv6 EPSV command
where the server response must return a port number and nothing else.

For the rare user who _wants_ this ugly behavior, set a `trust_server_pasv_ipv4_address`
attribute on your `ftplib.FTP` instance to True.
Diff: diff --git a/Lib/ftplib.py b/Lib/ftplib.py
index 1f760ed1ce0..7c5a50715f6 100644
--- a/Lib/ftplib.py
+++ b/Lib/ftplib.py
@@ -100,11 +100,13 @@ class FTP:
     port = FTP_PORT
     maxline = MAXLINE
     sock = None
     file = None
     welcome = None
-    passiveserver = 1
+    passiveserver = True
+    # Disables https://bugs.python.org/issue43285 security if set to True.
+    trust_server_pasv_ipv4_address = False
 
     def __init__(self, host='', user='', passwd='', acct='',
                  timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None, *,
                  encoding='utf-8'):
         """Initialization method (called by class instantiation).
@@ -318,12 +320,17 @@ def makeport(self):
         if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:
             sock.settimeout(self.timeout)
         return sock
 
     def makepasv(self):
+        """Internal: Does the PASV or EPSV handshake -> (address, port)"""
         if self.af == socket.AF_INET:
-            host, port = parse227(self.sendcmd('PASV'))
+            untrusted_host, port = parse227(self.sendcmd('PASV'))
+            if self.trust_server_pasv_ipv4_address:
+                host = untrusted_host
+            else:
+                host = self.sock.getpeername()[0]
         else:
             host, port = parse229(self.sendcmd('EPSV'), self.sock.getpeername())
         return host, port
 
     def ntransfercmd(self, cmd, rest=None):
diff --git a/Lib/test/test_ftplib.py b/Lib/test/test_ftplib.py
index 2424911c7ac..154dce15e2c 100644
--- a/Lib/test/test_ftplib.py
+++ b/Lib/test/test_ftplib.py
@@ -101,10 +101,14 @@ def __init__(self, conn, encoding=DEFAULT_ENCODING):
         self.next_data = None
         self.rest = None
         self.next_retr_data = RETR_DATA
         self.push('220 welcome')
         self.encoding = encoding
+        # We use this as the string IPv4 address to direct the client
+        # to in response to a PASV command.  To test security behavior.
+        # https://bugs.python.org/issue43285/.
+        self.fake_pasv_server_ip = '252.253.254.255'
 
     def collect_incoming_data(self, data):
         self.in_buffer.append(data)
 
     def found_terminator(self):
@@ -141,11 +145,12 @@ def cmd_port(self, arg):
         self.push('200 active data connection established')
 
     def cmd_pasv(self, arg):
         with socket.create_server((self.socket.getsockname()[0], 0)) as sock:
             sock.settimeout(TIMEOUT)
-            ip, port = sock.getsockname()[:2]
+            port = sock.getsockname()[1]
+            ip = self.fake_pasv_server_ip
             ip = ip.replace('.', ','); p1 = port / 256; p2 = port % 256
             self.push('227 entering passive mode (%s,%d,%d)' %(ip, p1, p2))
             conn, addr = sock.accept()
             self.dtp = self.dtp_handler(conn, baseclass=self)
 
@@ -705,10 +710,30 @@ def test_makepasv(self):
         conn = socket.create_connection((host, port), timeout=TIMEOUT)
         conn.close()
         # IPv4 is in use, just make sure send_epsv has not been used
         self.assertEqual(self.server.handler_instance.last_received_cmd, 'pasv')
 
+    def test_makepasv_issue43285_security_disabled(self):
+        """Test the opt-in to the old vulnerable behavior."""
+        self.client.trust_server_pasv_ipv4_address = True
+        bad_host, port = self.client.makepasv()
+        self.assertEqual(
+                bad_host, self.server.handler_instance.fake_pasv_server_ip)
+        # Opening and closing a connection keeps the dummy server happy
+        # instead of timing out on accept.
+        socket.create_connection((self.client.sock.getpeername()[0], port),
+                                 timeout=TIMEOUT).close()
+
+    def test_makepasv_issue43285_security_enabled_default(self):
+        self.assertFalse(self.client.trust_server_pasv_ipv4_address)
+        trusted_host, port = self.client.makepasv()
+        self.assertNotEqual(
+                trusted_host, self.server.handler_instance.fake_pasv_server_ip)
+        # Opening and closing a connection keeps the dummy server happy
+        # instead of timing out on accept.
+        socket.create_connection((trusted_host, port), timeout=TIMEOUT).close()
+
     def test_with_statement(self):
         self.client.quit()
 
         def is_client_connected():
             if self.client.sock is None:
diff --git a/Misc/NEWS.d/next/Security/2021-03-13-03-48-14.bpo-43285.g-Hah3.rst b/Misc/NEWS.d/next/Security/2021-03-13-03-48-14.bpo-43285.g-Hah3.rst
new file mode 100644
index 00000000000..8312b7e8854
--- /dev/null
+++ b/Misc/NEWS.d/next/Security/2021-03-13-03-48-14.bpo-43285.g-Hah3.rst
@@ -0,0 +1,8 @@
+:mod:`ftplib` no longer trusts the IP address value returned from the server
+in response to the PASV command by default.  This prevents a malicious FTP
+server from using the response to probe IPv4 address and port combinations
+on the client network.
+
+Code that requires the former vulnerable behavior may set a
+``trust_server_pasv_ipv4_address`` attribute on their
+:class:`ftplib.FTP` instances to ``True`` to re-enable it.

Vulnerable code:     passiveserver = 1
            host, port = parse227(self.sendcmd('PASV'))
            ip, port = sock.getsockname()[:2]
Fixed code:     passiveserver = True
    # Disables https://bugs.python.org/issue43285 security if set to True.
    trust_server_pasv_ipv4_address = False
        """Internal: Does the PASV or EPSV handshake -> (address, port)"""
            untrusted_host, port = parse227(self.sendcmd('PASV'))
            if self.trust_server_pasv_ipv4_address:
                host = untrusted_host
            else:
                host = self.sock.getpeername()[0]
        # We use this as the string IPv4 address to direct the client
        # to in response to a PASV command.  To test security behavior.
        # https://bugs.python.org/issue43285/.
        self.fake_pasv_server_ip = '252.253.254.255'
            port = sock.getsockname()[1]
            ip = self.fake_pasv_server_ip
    def test_makepasv_issue43285_security_disabled(self):
        """Test the opt-in to the old vulnerable behavior."""
        self.client.trust_server_pasv_ipv4_address = True
        bad_host, port = self.client.makepasv()
        self.assertEqual(
                bad_host, self.server.handler_instance.fake_pasv_server_ip)
        # Opening and closing a connection keeps the dummy server happy
        # instead of timing out on accept.
        socket.create_connection((self.client.sock.getpeername()[0], port),
                                 timeout=TIMEOUT).close()

    def test_makepasv_issue43285_security_enabled_default(self):
        self.assertFalse(self.client.trust_server_pasv_ipv4_address)
        trusted_host, port = self.client.makepasv()
        self.assertNotEqual(
                trusted_host, self.server.handler_instance.fake_pasv_server_ip)
        # Opening and closing a connection keeps the dummy server happy
        # instead of timing out on accept.
        socket.create_connection((trusted_host, port), timeout=TIMEOUT).close()

:mod:`ftplib` no longer trusts the IP address value returned from the server
in response to the PASV command by default.  This prevents a malicious FTP
server from using the response to probe IPv4 address and port combinations
on the client network.

Code that requires the former vulnerable behavior may set a
``trust_server_pasv_ipv4_address`` attribute on their
:class:`ftplib.FTP` instances to ``True`` to re-enable it.