From f2fce93826ff2e7a94b948cd7961f1ae3f8bc784 Mon Sep 17 00:00:00 2001
From: Jonas Jenwald <jonas.jenwald@gmail.com>
Date: Thu, 19 Jan 2023 17:08:13 +0100
Subject: [PATCH] [JBIG2] Ensure that the `decodeInteger` function returns
 valid integers (issue 15942)

The JBIG2 images in this PDF document are corrupt enough that even Adobe Reader warns about it when opening the file.
*Please note:* I don't really know the JBIG2 image format at all, however from a very brief look at the specification it seems that integers should be 32-bit.
---
 src/core/jbig2.js             | 12 ++++++++++--
 test/pdfs/issue15942.pdf.link |  1 +
 test/test_manifest.json       |  8 ++++++++
 3 files changed, 19 insertions(+), 2 deletions(-)
 create mode 100644 test/pdfs/issue15942.pdf.link

diff --git a/src/core/jbig2.js b/src/core/jbig2.js
index a34303f03..e360ce015 100644
--- a/src/core/jbig2.js
+++ b/src/core/jbig2.js
@@ -52,6 +52,9 @@ class DecodingContext {
   }
 }
 
+const MAX_INT_32 = 2 ** 31 - 1;
+const MIN_INT_32 = -(2 ** 31);
+
 // Annex A. Arithmetic Integer Decoding Procedure
 // A.2 Procedure for decoding values
 function decodeInteger(contextCache, procedure, decoder) {
@@ -83,10 +86,15 @@ function decodeInteger(contextCache, procedure, decoder) {
                   readBits(4) + 4) :
                 readBits(2);
   /* eslint-enable no-nested-ternary */
+  let signedValue;
   if (sign === 0) {
-    return value;
+    signedValue = value;
   } else if (value > 0) {
-    return -value;
+    signedValue = -value;
+  }
+  // Ensure that the integer value doesn't underflow or overflow.
+  if (signedValue >= MIN_INT_32 && signedValue <= MAX_INT_32) {
+    return signedValue;
   }
   return null;
 }
diff --git a/test/pdfs/issue15942.pdf.link b/test/pdfs/issue15942.pdf.link
new file mode 100644
index 000000000..aa147f37e
--- /dev/null
+++ b/test/pdfs/issue15942.pdf.link
@@ -0,0 +1 @@
+https://github.com/mozilla/pdf.js/files/10455335/3024388_99997342-a484-416f-9eb9-9a796ada1e2c.pdf
diff --git a/test/test_manifest.json b/test/test_manifest.json
index accc73184..f40e08e5d 100644
--- a/test/test_manifest.json
+++ b/test/test_manifest.json
@@ -2002,6 +2002,14 @@
        "rounds": 1,
        "type": "eq"
     },
+    {  "id": "issue15942",
+       "file": "pdfs/issue15942.pdf",
+       "md5": "d690e16e6a3a8486ebf7289a9c43ba39",
+       "rounds": 1,
+       "link": true,
+       "lastPage": 1,
+       "type": "eq"
+    },
     {  "id": "bug1046314",
        "file": "pdfs/bug1046314.pdf",
        "md5": "fc658439f44cd2dd27c8bee7e7a8344e",