Merge pull request #238 from pypiserver/237-CRLF-Injection

CRLF Injection Mitigation
This commit is contained in:
Matthew Planchard 2019-01-26 15:02:29 -06:00 committed by GitHub
commit 0284cb7f50
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 65 additions and 13 deletions

@ -250,7 +250,7 @@ def simpleindex():
@auth("list") @auth("list")
def simple(prefix=""): def simple(prefix=""):
# PEP 503: require normalized prefix # PEP 503: require normalized prefix
normalized = core.normalize_pkgname(prefix) normalized = core.normalize_pkgname_for_url(prefix)
if prefix != normalized: if prefix != normalized:
return redirect('/simple/{0}/'.format(normalized), 301) return redirect('/simple/{0}/'.format(normalized), 301)
@ -327,11 +327,5 @@ def server_static(filename):
@app.route('/:prefix') @app.route('/:prefix')
@app.route('/:prefix/') @app.route('/:prefix/')
def bad_url(prefix): def bad_url(prefix):
p = request.fullpath """Redirect unknown root URLs to /simple/."""
if p.endswith("/"): return redirect(core.get_bad_url_redirect_path(request, prefix))
p = p[:-1]
p = p.rsplit('/', 1)[0]
p += "/simple/%s/" % prefix
return redirect(p)

@ -11,6 +11,11 @@ import os
import re import re
import sys import sys
try: # PY3
from urllib.parse import quote
except ImportError: # PY2
from urllib import quote
import pkg_resources import pkg_resources
from . import Configuration from . import Configuration
@ -183,6 +188,11 @@ def normalize_pkgname(name):
return re.sub(r"[-_.]+", "-", name).lower() return re.sub(r"[-_.]+", "-", name).lower()
def normalize_pkgname_for_url(name):
"""Perform PEP 503 normalization and ensure the value is safe for URLs."""
return quote(re.sub(r"[-_.]+", "-", name).lower())
def is_allowed_path(path_part): def is_allowed_path(path_part):
p = path_part.replace("\\", "/") p = path_part.replace("\\", "/")
return not (p.startswith(".") or "/." in p) return not (p.startswith(".") or "/." in p)
@ -273,6 +283,17 @@ def store(root, filename, save_method):
save_method(dest_fn, overwrite=True) # Overwite check earlier. save_method(dest_fn, overwrite=True) # Overwite check earlier.
def get_bad_url_redirect_path(request, prefix):
"""Get the path for a bad root url."""
p = request.fullpath
if p.endswith("/"):
p = p[:-1]
p = p.rsplit('/', 1)[0]
prefix = quote(prefix)
p += "/simple/{}/".format(prefix)
return p
def _digest_file(fpath, hash_algo): def _digest_file(fpath, hash_algo):
""" """
Reads and digests a file according to specified hashing-algorith. Reads and digests a file according to specified hashing-algorith.

10
tests/doubles.py Normal file

@ -0,0 +1,10 @@
"""Test doubles."""
class Namespace(object):
"""Simple namespace."""
def __init__(self, **kwargs):
"""Instantiate the namespace with the provided kwargs."""
for k, v in kwargs.items():
setattr(self, k, v)

@ -20,6 +20,7 @@ import webtest
# Local Imports # Local Imports
from pypiserver import __main__, bottle from pypiserver import __main__, bottle
import tests.test_core as test_core import tests.test_core as test_core

@ -7,6 +7,7 @@ import os
import pytest import pytest
from pypiserver import __main__, core from pypiserver import __main__, core
from tests.doubles import Namespace
## Enable logging to detect any problems with it ## Enable logging to detect any problems with it
@ -90,3 +91,20 @@ def test_hashfile(tmpdir, algo, digest):
f = tmpdir.join("empty") f = tmpdir.join("empty")
f.ensure() f.ensure()
assert core.digest_file(f.strpath, algo) == digest assert core.digest_file(f.strpath, algo) == digest
def test_redirect_prefix_encodes_newlines():
"""Ensure raw newlines are url encoded in the generated redirect."""
request = Namespace(
fullpath='/\nSet-Cookie:malicious=1;'
)
prefix = '\nSet-Cookie:malicious=1;'
newpath = core.get_bad_url_redirect_path(request, prefix)
assert '\n' not in newpath
def test_normalize_pkgname_for_url_encodes_newlines():
"""Ensure newlines are url encoded in package names for urls."""
assert '\n' not in core.normalize_pkgname_for_url(
'/\nSet-Cookie:malicious=1;'
)

@ -61,8 +61,16 @@ def _run_server(packdir, port, authed, other_cli=''):
'partial': "-Ptests/htpasswd.a.a -a update", 'partial': "-Ptests/htpasswd.a.a -a update",
} }
pswd_opts = pswd_opt_choices[authed] pswd_opts = pswd_opt_choices[authed]
cmd = "%s -m pypiserver.__main__ -vvv --overwrite -p %s %s %s %s" % ( cmd = (
sys.executable, port, pswd_opts, other_cli, packdir) "%s -m pypiserver.__main__ -vvv --overwrite -i 127.0.0.1 "
"-p %s %s %s %s" % (
sys.executable,
port,
pswd_opts,
other_cli,
packdir,
)
)
proc = subprocess.Popen(cmd.split(), bufsize=_BUFF_SIZE) proc = subprocess.Popen(cmd.split(), bufsize=_BUFF_SIZE)
time.sleep(SLEEP_AFTER_SRV) time.sleep(SLEEP_AFTER_SRV)
assert proc.poll() is None assert proc.poll() is None