From ca1fc2aefe9796e321d0589afe7efb35063c8b2a Mon Sep 17 00:00:00 2001
From: Zdenek Hutyra <zhutyra@centrum.cz>
Date: Fri, 30 Aug 2024 13:11:53 +0100
Subject: PS interpreter - check Indexed colour space index

Bug #707990 "Out of bounds read when reading color in "Indexed" color space"

Check the 'index' is in the valid range (0 to hival) for the colour
space.

Also a couple of additional checks on the type of the 'proc' for
Indexed, DeviceN and Separation spaces. Make sure these really are
procs in case the user changed the colour space array.

CVE-2024-46955

Upstream-Status: Backport [import from ubuntu https://git.launchpad.net/ubuntu/+source/ghostscript/tree/debian/patches/CVE-2024-46955.patch?h=ubuntu/jammy-security
Upstream commit https://cgit.ghostscript.com/cgi-bin/cgit.cgi/ghostpdl.git/commit/?id=ca1fc2aefe9796e321d0589afe7efb35063c8b2a]
CVE: CVE-2024-46955
Signed-off-by: Vijay Anusuri <vanusuri@mvista.com>
---
 psi/zcolor.c | 6 ++++++
 1 file changed, 6 insertions(+)

--- a/psi/zcolor.c
+++ b/psi/zcolor.c
@@ -3628,6 +3628,7 @@ static int septransform(i_ctx_t *i_ctx_p
         code = array_get(imemory, sepspace, 3, &proc);
         if (code < 0)
             return code;
+        check_proc(proc);
         *esp = proc;
         return o_push_estack;
     }
@@ -4449,6 +4450,7 @@ static int devicentransform(i_ctx_t *i_c
         code = array_get(imemory, devicenspace, 3, &proc);
         if (code < 0)
             return code;
+        check_proc(proc);
         *esp = proc;
         return o_push_estack;
     }
@@ -4864,6 +4866,7 @@ static int indexedbasecolor(i_ctx_t * i_
             code = array_get(imemory, space, 3, &proc);
             if (code < 0)
                 return code;
+            check_proc(proc);
             *ep = proc;	/* lookup proc */
             return o_push_estack;
         } else {
@@ -4877,6 +4880,9 @@ static int indexedbasecolor(i_ctx_t * i_
             if (!r_has_type(op, t_integer))
                 return_error (gs_error_typecheck);
             index = op->value.intval;
+            /* Ensure it is in range. See bug #707990 */
+            if (index < 0 || index > pcs->params.indexed.hival)
+                return_error(gs_error_rangecheck);
             /* And remove it from the stack. */
             ref_stack_pop(&o_stack, 1);
             op = osp;
