From b7c8d5cd42d3f72d7177b1fee4d0eeae49a9d419 Mon Sep 17 00:00:00 2001 From: Chris Ross Date: Thu, 23 Oct 2014 09:15:11 -0700 Subject: [PATCH] #17 - Validate close frame body. --- .../CommonWebSocket.cs | 14 +++++++++++++- .../project.json | 1 + 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.AspNet.WebSockets.Protocol/CommonWebSocket.cs b/src/Microsoft.AspNet.WebSockets.Protocol/CommonWebSocket.cs index 41219be884..a045609012 100644 --- a/src/Microsoft.AspNet.WebSockets.Protocol/CommonWebSocket.cs +++ b/src/Microsoft.AspNet.WebSockets.Protocol/CommonWebSocket.cs @@ -414,7 +414,19 @@ namespace Microsoft.AspNet.WebSockets.Protocol Utilities.MaskInPlace(_frameInProgress.MaskKey, new ArraySegment(_receiveBuffer, _receiveBufferOffset, (int)_frameBytesRemaining)); } _closeStatus = (WebSocketCloseStatus)((_receiveBuffer[_receiveBufferOffset] << 8) | _receiveBuffer[_receiveBufferOffset + 1]); - _closeStatusDescription = Encoding.UTF8.GetString(_receiveBuffer, _receiveBufferOffset + 2, (int)_frameBytesRemaining - 2) ?? string.Empty; + try + { + var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + _closeStatusDescription = encoding.GetString(_receiveBuffer, _receiveBufferOffset + 2, (int)_frameBytesRemaining - 2) ?? string.Empty; + } + catch (DecoderFallbackException) + { + await SendErrorAbortAndThrow(WebSocketCloseStatus.ProtocolError, "Invalid UTF-8 close message.", cancellationToken); + } + } + else if (_frameBytesRemaining == 1) + { + await SendErrorAbortAndThrow(WebSocketCloseStatus.ProtocolError, "Invalid close body.", cancellationToken); } else { diff --git a/src/Microsoft.AspNet.WebSockets.Protocol/project.json b/src/Microsoft.AspNet.WebSockets.Protocol/project.json index 8094991757..3bf854488d 100644 --- a/src/Microsoft.AspNet.WebSockets.Protocol/project.json +++ b/src/Microsoft.AspNet.WebSockets.Protocol/project.json @@ -14,6 +14,7 @@ "System.Security.Cryptography.Hashing.Algorithms": "4.0.0-beta-*", "System.Threading": "4.0.0-beta-*", "System.Threading.Tasks": "4.0.10-beta-*", + "System.Text.Encoding.Extensions": "4.0.10-beta-*", "System.Threading.Timer": "4.0.0-beta-*" } }