summaryrefslogtreecommitdiff
path: root/cherrypy/lib/httputil.py
diff options
context:
space:
mode:
authorJason R. Coombs <jaraco@jaraco.com>2022-07-17 16:36:25 -0400
committerGitHub <noreply@github.com>2022-07-17 16:36:25 -0400
commit5964c48b466448a14703eecc062223fda46caf4e (patch)
tree8589e0b16b01ed6f522ef5eb597b3202884d282d /cherrypy/lib/httputil.py
parent12a06bf717effe21973953f30771a56c74130621 (diff)
parent72d94e3adf2786aaa723f3f1b5bf8a9b34f28332 (diff)
downloadcherrypy-git-18.8.0.tar.gz
Merge pull request #1976 from cherrypy/bugfix/1974-dangerous-hostv18.8.0
Fix issues with dangerous host headers.
Diffstat (limited to 'cherrypy/lib/httputil.py')
-rw-r--r--cherrypy/lib/httputil.py30
1 files changed, 30 insertions, 0 deletions
diff --git a/cherrypy/lib/httputil.py b/cherrypy/lib/httputil.py
index eedf8d89..ced310a0 100644
--- a/cherrypy/lib/httputil.py
+++ b/cherrypy/lib/httputil.py
@@ -516,3 +516,33 @@ class Host(object):
def __repr__(self):
return 'httputil.Host(%r, %r, %r)' % (self.ip, self.port, self.name)
+
+
+class SanitizedHost(str):
+ r"""
+ Wraps a raw host header received from the network in
+ a sanitized version that elides dangerous characters.
+
+ >>> SanitizedHost('foo\nbar')
+ 'foobar'
+ >>> SanitizedHost('foo\nbar').raw
+ 'foo\nbar'
+
+ A SanitizedInstance is only returned if sanitization was performed.
+
+ >>> isinstance(SanitizedHost('foobar'), SanitizedHost)
+ False
+ """
+ dangerous = re.compile(r'[\n\r]')
+
+ def __new__(cls, raw):
+ sanitized = cls._sanitize(raw)
+ if sanitized == raw:
+ return raw
+ instance = super().__new__(cls, sanitized)
+ instance.raw = raw
+ return instance
+
+ @classmethod
+ def _sanitize(cls, raw):
+ return cls.dangerous.sub('', raw)