diff --git a/Lib/http/server.py b/Lib/http/server.py index 5569037427d..bcfe89473ef 100644 --- a/Lib/http/server.py +++ b/Lib/http/server.py @@ -968,18 +968,17 @@ class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): def run_cgi(self): """Execute a CGI script.""" - path = self.path dir, rest = self.cgi_info - i = path.find('/', len(dir) + 1) + i = rest.find('/') while i >= 0: - nextdir = path[:i] - nextrest = path[i+1:] + nextdir = rest[:i] + nextrest = rest[i+1:] scriptdir = self.translate_path(nextdir) if os.path.isdir(scriptdir): dir, rest = nextdir, nextrest - i = path.find('/', len(dir) + 1) + i = rest.find('/') else: break diff --git a/Lib/test/test_httpservers.py b/Lib/test/test_httpservers.py index d71da1a83dd..f8198f8ae3d 100644 --- a/Lib/test/test_httpservers.py +++ b/Lib/test/test_httpservers.py @@ -322,6 +322,7 @@ class CGIHTTPServerTestCase(BaseTestCase): self.parent_dir = tempfile.mkdtemp() self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin') os.mkdir(self.cgi_dir) + self.nocgi_path = None self.file1_path = None self.file2_path = None @@ -342,6 +343,11 @@ class CGIHTTPServerTestCase(BaseTestCase): self.tearDown() self.skipTest("Python executable path is not encodable to utf-8") + self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py') + with open(self.nocgi_path, 'w') as fp: + fp.write(cgi_file1 % self.pythonexe) + os.chmod(self.nocgi_path, 0o777) + self.file1_path = os.path.join(self.cgi_dir, 'file1.py') with open(self.file1_path, 'w', encoding='utf-8') as file1: file1.write(cgi_file1 % self.pythonexe) @@ -359,6 +365,8 @@ class CGIHTTPServerTestCase(BaseTestCase): os.chdir(self.cwd) if self.pythonexe != sys.executable: os.remove(self.pythonexe) + if self.nocgi_path: + os.remove(self.nocgi_path) if self.file1_path: os.remove(self.file1_path) if self.file2_path: @@ -415,6 +423,10 @@ class CGIHTTPServerTestCase(BaseTestCase): self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200), (res.read(), res.getheader('Content-type'), res.status)) + def test_issue19435(self): + res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh') + self.assertEqual(res.status, 404) + def test_post(self): params = urllib.parse.urlencode( {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456}) diff --git a/Misc/NEWS b/Misc/NEWS index 6488b75f29e..e8054cf2029 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -10,6 +10,8 @@ What's New in Python 3.2.6? Library ------- +- Issue #19435: Fix directory traversal attack on CGIHttpRequestHandler. + - Issue #14984: On POSIX systems, when netrc is called without a filename argument (and therefore is reading the user's $HOME/.netrc file), it now enforces the same security rules as typical ftp clients: the .netrc file must