diff options
| author | Jason R. Coombs <jaraco@jaraco.com> | 2022-07-17 16:36:25 -0400 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-07-17 16:36:25 -0400 |
| commit | 5964c48b466448a14703eecc062223fda46caf4e (patch) | |
| tree | 8589e0b16b01ed6f522ef5eb597b3202884d282d /cherrypy/lib/httputil.py | |
| parent | 12a06bf717effe21973953f30771a56c74130621 (diff) | |
| parent | 72d94e3adf2786aaa723f3f1b5bf8a9b34f28332 (diff) | |
| download | cherrypy-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.py | 30 |
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) |
