From 716560bf5f2bc4b821ca6924ec648ca4949826bb Mon Sep 17 00:00:00 2001
From: Sebastian Rasmussen <sebras@gmail.com>
Date: Sun, 15 Sep 2019 17:31:48 +0200
Subject: [PATCH] jbig2dec: Handle under-/overflow detection and messaging
 better.

Previously SYMWIDTH was capped too early in order to prevent underflow
Moreover TOTWIDTH was allowed to overflow.

Now the value DW is checked compared to SYMWIDTH, preventing over
underflow and overflow at the correct limits, and an overflow
check has been added for TOTWIDTH.
---
 jbig2dec/jbig2_symbol_dict.c | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/jbig2dec/jbig2_symbol_dict.c b/jbig2dec/jbig2_symbol_dict.c
index e606529..bc6e98c 100644
--- a/jbig2dec/jbig2_symbol_dict.c
+++ b/jbig2dec/jbig2_symbol_dict.c
@@ -428,14 +428,24 @@ jbig2_decode_symbol_dict(Jbig2Ctx *ctx,
                 break;
             }
 
+            if (DW < 0 && SYMWIDTH < (uint32_t) -DW) {
+                code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "DW value (%d) would make SYMWIDTH (%u) negative at symbol %u", DW, SYMWIDTH, NSYMSDECODED + 1);
+                goto cleanup;
+            }
+            if (DW > 0 && DW > UINT32_MAX - SYMWIDTH) {
+                code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "DW value (%d) would make SYMWIDTH (%u) too large at symbol %u", DW, SYMWIDTH, NSYMSDECODED + 1);
+                goto cleanup;
+            }
+
             SYMWIDTH = SYMWIDTH + DW;
-            TOTWIDTH = TOTWIDTH + SYMWIDTH;
-            if ((int32_t) SYMWIDTH < 0) {
-                code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "invalid SYMWIDTH value (%d) at symbol %d", SYMWIDTH, NSYMSDECODED + 1);
+            if (SYMWIDTH > UINT32_MAX - TOTWIDTH) {
+                code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "SYMWIDTH value (%u) would make TOTWIDTH (%u) too large at symbol %u", SYMWIDTH, TOTWIDTH, NSYMSDECODED + 1);
                 goto cleanup;
             }
+
+            TOTWIDTH = TOTWIDTH + SYMWIDTH;
 #ifdef JBIG2_DEBUG
-            jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, "SYMWIDTH = %d TOTWIDTH = %d", SYMWIDTH, TOTWIDTH);
+            jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, "SYMWIDTH = %u TOTWIDTH = %u", SYMWIDTH, TOTWIDTH);
 #endif
             /* 6.5.5 (4c.ii) */
             if (!params->SDHUFF || params->SDREFAGG) {
-- 
1.8.3.1

