Skip to content
Open
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
39 changes: 32 additions & 7 deletions src/wsproto/handshake.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,31 @@

from .typing import Headers


def _decode_host_header(value: bytes) -> str:
try:
return value.decode("idna")
except UnicodeDecodeError as exc:
msg = "Host header value is not valid IDNA"
raise RemoteProtocolError(msg, event_hint=RejectConnection()) from exc


def _decode_ascii_header(value: bytes) -> str:
try:
return value.decode("ascii")
except UnicodeDecodeError as exc:
msg = "Header value is not valid ASCII"
raise RemoteProtocolError(msg, event_hint=RejectConnection()) from exc


def _split_comma_header(value: bytes) -> list[str]:
try:
return split_comma_header(value)
except UnicodeDecodeError as exc:
msg = "Header value is not valid ASCII"
raise RemoteProtocolError(msg, event_hint=RejectConnection()) from exc


# RFC6455, Section 4.2.1/6 - Reading the Client's Opening Handshake
WEBSOCKET_VERSION = b"13"

Expand Down Expand Up @@ -208,17 +233,17 @@ def _process_connection_request(
for name, value in event.headers:
name = name.lower()
if name == b"connection":
connection_tokens = split_comma_header(value)
connection_tokens = _split_comma_header(value)
elif name == b"host":
host = value.decode("idna")
host = _decode_host_header(value)
continue # Skip appending to headers
elif name == b"sec-websocket-extensions":
extensions.extend(split_comma_header(value))
extensions.extend(_split_comma_header(value))
continue # Skip appending to headers
elif name == b"sec-websocket-key":
key = value
elif name == b"sec-websocket-protocol":
subprotocols.extend(split_comma_header(value))
subprotocols.extend(_split_comma_header(value))
continue # Skip appending to headers
elif name == b"sec-websocket-version":
version = value
Expand Down Expand Up @@ -401,16 +426,16 @@ def _establish_client_connection(
for name, value in event.headers:
name = name.lower()
if name == b"connection":
connection_tokens = split_comma_header(value)
connection_tokens = _split_comma_header(value)
continue # Skip appending to headers
if name == b"sec-websocket-extensions":
accepts = split_comma_header(value)
accepts = _split_comma_header(value)
continue # Skip appending to headers
if name == b"sec-websocket-accept":
accept = value
continue # Skip appending to headers
if name == b"sec-websocket-protocol":
subprotocol = value.decode("ascii")
subprotocol = _decode_ascii_header(value)
continue # Skip appending to headers
if name == b"upgrade":
upgrade = value
Expand Down
57 changes: 55 additions & 2 deletions tests/test_handshake.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import pytest

from wsproto.connection import CLIENT, SERVER, ConnectionState
from wsproto.events import AcceptConnection, Ping, Request
from wsproto.events import AcceptConnection, Ping, RejectConnection, Request
from wsproto.handshake import H11Handshake
from wsproto.utilities import LocalProtocolError, RemoteProtocolError
from wsproto.utilities import LocalProtocolError, RemoteProtocolError, generate_accept_token


def test_successful_handshake() -> None:
Expand Down Expand Up @@ -102,3 +102,56 @@ def test_h11_multiple_headers_handshake() -> None:
"this-extension; were-gonna-see",
"and-another-extension; were-also; gonna-see=100; percent",
]


def _assert_rejection(excinfo: pytest.ExceptionInfo[RemoteProtocolError]) -> None:
hint = excinfo.value.event_hint
assert isinstance(hint, RejectConnection)
assert hint.status_code == 400


@pytest.mark.parametrize(
"header",
[
b"Host: \xff\xfe",
b"Host: localhost\r\nConnection: Upgrade, \xff",
b"Host: localhost\r\nSec-WebSocket-Extensions: \xff",
b"Host: localhost\r\nSec-WebSocket-Protocol: \xff",
],
)
def test_obs_text_header_rejected(header: bytes) -> None:
# obs-text (non-ASCII) bytes in these header values must be rejected
# with a RemoteProtocolError, not an uncaught UnicodeDecodeError.
server = H11Handshake(SERVER)
with pytest.raises(RemoteProtocolError) as excinfo:
server.receive_data(
b"GET / HTTP/1.1\r\n" + header + b"\r\n"
b"Upgrade: websocket\r\n"
b"Connection: Upgrade\r\n"
b"Sec-WebSocket-Key: VQr8cvwwZ1fEk62PDq8J3A==\r\n"
b"Sec-WebSocket-Version: 13\r\n"
b"\r\n",
)
_assert_rejection(excinfo)


def test_obs_text_response_header_rejected() -> None:
# obs-text in a handshake response header value must be rejected with a
# RemoteProtocolError, not an uncaught UnicodeDecodeError.
client = H11Handshake(CLIENT)
data = client.send(Request(host="localhost", target="/"))
key = b""
for line in data.split(b"\r\n"):
if line.lower().startswith(b"sec-websocket-key: "):
key = line.split(b": ", 1)[1]
accept = generate_accept_token(key)
with pytest.raises(RemoteProtocolError) as excinfo:
client.receive_data(
b"HTTP/1.1 101 Switching Protocols\r\n"
b"Upgrade: websocket\r\n"
b"Connection: Upgrade\r\n"
b"Sec-WebSocket-Accept: " + accept + b"\r\n"
b"Sec-WebSocket-Protocol: \xff\r\n"
b"\r\n",
)
_assert_rejection(excinfo)