Skip to content

bpo-29606: urllib rejects newline in FTP #2800

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Lib/test/test_urllib.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,31 @@ def test_ftp_nonexisting(self):
self.assertFalse(e.exception.filename)
self.assertTrue(e.exception.reason)

def test_ftp_illegalhost(self):
# bpo-29606: reject newline character in FTP URL
illegal_ftp_urls = [
'ftp://foo:bar%[email protected]/file.png',
'ftp://foo:bar%0d%[email protected]/file.png',
]

def check_exception_message(cmd):
msg = str(cm.exception)
self.assertTrue("ftp error: illegal newline character" in msg, msg)

for url in illegal_ftp_urls:
# test URLopener.open_ftp()
opener = urllib.request.URLopener()
with self.assertRaises(urllib.error.URLError) as cm:
opener.open_ftp(url)
check_exception_message(cm)

# test FTPHandler.ftp_open()
req = urllib.request.Request(url)
handler = urllib.request.FTPHandler()
with self.assertRaises(urllib.error.URLError) as cm:
handler.ftp_open(req)
check_exception_message(cm)

@patch.object(urllib.request, 'MAXFTPCACHE', 0)
def test_ftp_cache_pruning(self):
self.fakeftp()
Expand Down
4 changes: 4 additions & 0 deletions Lib/urllib/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -1502,6 +1502,8 @@ def ftp_open(self, req):
host = req.host
if not host:
raise URLError('ftp error: no host given')
if '\n' in unquote(host):
raise URLError("ftp error: illegal newline character")
host, port = splitport(host)
if port is None:
port = ftplib.FTP_PORT
Expand Down Expand Up @@ -2010,6 +2012,8 @@ def open_ftp(self, url):
if not isinstance(url, str):
raise URLError('ftp error: proxy support for ftp protocol currently not implemented')
import mimetypes
if '\n' in unquote(url):
raise URLError("ftp error: illegal newline character")
host, path = splithost(url)
if not host: raise URLError('ftp error: no host given')
host, port = splitport(host)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
FTPHandler.ftp_open() and URLOpener.open_ftp() of urllib.request now
raise an exception if the unquoted URL contains a newline character
(U+000A, "\n").