Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 98c66a5

Browse files
committed
Validate Sec-WebSocket-Key header in managed HttpListener
1 parent 1760734 commit 98c66a5

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

src/System.Net.HttpListener/src/System/Net/WebSockets/HttpWebSocket.cs

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,21 @@ private static void ValidateWebSocketHeaders(HttpListenerContext context)
167167
SupportedVersion));
168168
}
169169

170-
if (string.IsNullOrWhiteSpace(context.Request.Headers[HttpKnownHeaderNames.SecWebSocketKey]))
170+
string secWebSocketKey = context.Request.Headers[HttpKnownHeaderNames.SecWebSocketKey];
171+
bool isSecWebSocketKeyInvalid = string.IsNullOrWhiteSpace(secWebSocketKey);
172+
if (!isSecWebSocketKeyInvalid)
173+
{
174+
try
175+
{
176+
// key must be 16 bytes then base64-encoded
177+
isSecWebSocketKeyInvalid = Convert.FromBase64String(secWebSocketKey).Length != 16;
178+
}
179+
catch
180+
{
181+
isSecWebSocketKeyInvalid = true;
182+
}
183+
}
184+
if (isSecWebSocketKeyInvalid)
171185
{
172186
throw new WebSocketException(WebSocketError.HeaderError,
173187
SR.Format(SR.net_WebSockets_AcceptHeaderNotFound,
@@ -177,4 +191,3 @@ private static void ValidateWebSocketHeaders(HttpListenerContext context)
177191
}
178192
}
179193
}
180-

src/System.Net.HttpListener/tests/HttpListenerContextTests.cs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,6 @@ public async Task AcceptWebSocketAsync_ValidSubProtocol_Success(string[] clientP
5353
}
5454

5555
[ConditionalFact(nameof(IsNotWindows7OrUapCore))]
56-
// Both the managed and Windows implementations send headers to the socket during connection.
57-
// The Windows implementation fails with error code 1229: An operation was attempted on a nonexistent network connection.
58-
[ActiveIssue(18128, TestPlatforms.AnyUnix)]
5956
public async Task AcceptWebSocketAsync_SocketSpoofingAsWebSocket_ThrowsWebSocketException()
6057
{
6158
await GetSocketContext(new string[] { "Connection: Upgrade", "Upgrade: websocket", "Sec-WebSocket-Version: 13", "Sec-WebSocket-Key: Key" }, async context =>

0 commit comments

Comments
 (0)