]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
is_valid_ip: Do not raise exceptions on too-long input. 3010/head
authorAlex Vandiver <alex@chmrr.net>
Wed, 7 Apr 2021 20:11:15 +0000 (13:11 -0700)
committerAlex Vandiver <alex@chmrr.net>
Mon, 10 May 2021 03:00:55 +0000 (17:00 -1000)
is_valid_ip calls `socket.getaddrinfo` with `socket.AI_NUMERICHOST` on
the potential "ip"; even though IP addresses are not hostnames and do
not use the `idna` encoding, `socket.getaddrinfo` will raise
UnicodeError if the potential "ip" is longer than 63 characters long,
the RFC-mandated max hostname length.

Catch these UnicodeErrors and return false for too-long IPs, rather
than raising an exception.

tornado/netutil.py
tornado/test/netutil_test.py

index f8a3038051b07b1a0e022d49c4159b54fe4021ca..15eea9704fe0dfbb2ed976ff4d6aed9d9d396407 100644 (file)
@@ -301,6 +301,12 @@ def is_valid_ip(ip: str) -> bool:
         if e.args[0] == socket.EAI_NONAME:
             return False
         raise
+    except UnicodeError:
+        # `socket.getaddrinfo` will raise a UnicodeError from the
+        # `idna` decoder if the input is longer than 63 characters,
+        # even for socket.AI_NUMERICHOST.  See
+        # https://bugs.python.org/issue32958 for discussion
+        return False
     return True
 
 
index f36b7c271b49e56e0499c68093883bfdfe6cf925..3911be6a250cc98384597c2daab2a17df702764f 100644 (file)
@@ -204,6 +204,7 @@ class IsValidIPTest(unittest.TestCase):
         self.assertTrue(not is_valid_ip(" "))
         self.assertTrue(not is_valid_ip("\n"))
         self.assertTrue(not is_valid_ip("\x00"))
+        self.assertTrue(not is_valid_ip("a" * 100))
 
 
 class TestPortAllocation(unittest.TestCase):