From e865c24efc40ebc52e75979c94cdd4ee2c1495b0 Mon Sep 17 00:00:00 2001
From: akallabeth <akallabeth@posteo.net>
Date: Thu, 13 Oct 2022 09:09:28 +0200
Subject: [PATCH] Added missing length checks in zgfx_decompress_segment

(cherry picked from commit 64716b335858109d14f27b51acc4c4d71a92a816)
---
 libfreerdp/codec/zgfx.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/libfreerdp/codec/zgfx.c b/libfreerdp/codec/zgfx.c
index 20fbd354571..e260aa6e28a 100644
--- a/libfreerdp/codec/zgfx.c
+++ b/libfreerdp/codec/zgfx.c
@@ -230,19 +230,19 @@ static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t
 	BYTE* pbSegment;
 	size_t cbSegment;
 
-	if (!zgfx || !stream)
+	if (!zgfx || !stream || (segmentSize < 2))
 		return FALSE;
 
 	cbSegment = segmentSize - 1;
 
-	if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1) ||
-	    (segmentSize > UINT32_MAX))
+	if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize > UINT32_MAX))
 		return FALSE;
 
 	Stream_Read_UINT8(stream, flags); /* header (1 byte) */
 	zgfx->OutputCount = 0;
 	pbSegment = Stream_Pointer(stream);
-	Stream_Seek(stream, cbSegment);
+	if (!Stream_SafeSeek(stream, cbSegment))
+		return FALSE;
 
 	if (!(flags & PACKET_COMPRESSED))
 	{
@@ -346,6 +346,9 @@ static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t
 						if (count > sizeof(zgfx->OutputBuffer) - zgfx->OutputCount)
 							return FALSE;
 
+						if (count > zgfx->cBitsRemaining / 8)
+							return FALSE;
+
 						CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent,
 						           count);
 						zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count);
