Skip to content

XSS hardening #64

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

Merged
merged 5 commits into from
Aug 22, 2023
Merged
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
31 changes: 30 additions & 1 deletion adafruit_httpserver/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,28 @@ def _add_field_value(self, field_name: str, value: Union[str, bytes]) -> None:
else:
self._storage[field_name].append(value)

def get(self, field_name: str, default: Any = None) -> Union[str, bytes, None]:
@staticmethod
def _encode_html_entities(value):
"""Encodes unsafe HTML characters."""
return (
str(value)
.replace("&", "&")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace('"', "&quot;")
.replace("'", "&apos;")
)

def get(
self, field_name: str, default: Any = None, *, safe=True
) -> Union[str, bytes, None]:
"""Get the value of a field."""
if safe:
return self._encode_html_entities(
self._storage.get(field_name, [default])[0]
)

_debug_warning_nonencoded_output()
return self._storage.get(field_name, [default])[0]

def get_list(self, field_name: str) -> List[Union[str, bytes]]:
Expand Down Expand Up @@ -348,3 +368,12 @@ def _parse_headers(header_bytes: bytes) -> Headers:
for name, value in [header_line.split(": ", 1)]
}
)


def _debug_warning_nonencoded_output():
"""Warns about XSS risks."""
print(
"WARNING: Setting safe to False makes XSS vulnerabilities possible by "
"allowing access to raw untrusted values submitted by users. If this data is reflected "
"or shown within HTML without proper encoding it could enable Cross-Site Scripting."
)