From 03db7c81f6a8a92d896249bc673877749987fd7a Mon Sep 17 00:00:00 2001
From: Max Kellermann <max.kellermann@gmail.com>
Date: Wed, 24 Jun 2020 21:26:10 +0200
Subject: [PATCH] jp2_enc: check number of components before dereferencing them

Fixes CVE-2018-20570

Closes https://github.com/jasper-maint/jasper/issues/11
Closes https://github.com/mdadams/jasper/issues/191
---
 src/libjasper/jp2/jp2_enc.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/src/libjasper/jp2/jp2_enc.c b/src/libjasper/jp2/jp2_enc.c
index fd39a84..1b44c18 100644
--- a/src/libjasper/jp2/jp2_enc.c
+++ b/src/libjasper/jp2/jp2_enc.c
@@ -293,7 +293,8 @@ int jp2_encode(jas_image_t *image, jas_stream_t *out, const char *optstr)
 	needcdef = 1;
 	switch (jas_clrspc_fam(jas_image_clrspc(image))) {
 	case JAS_CLRSPC_FAM_RGB:
-		if (jas_image_cmpttype(image, 0) ==
+		if (jas_image_numcmpts(image) >= 3 &&
+		  jas_image_cmpttype(image, 0) ==
 		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R) &&
 		  jas_image_cmpttype(image, 1) ==
 		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G) &&
@@ -302,7 +303,8 @@ int jp2_encode(jas_image_t *image, jas_stream_t *out, const char *optstr)
 			needcdef = 0;
 		break;
 	case JAS_CLRSPC_FAM_YCBCR:
-		if (jas_image_cmpttype(image, 0) ==
+		if (jas_image_numcmpts(image) >= 3 &&
+		  jas_image_cmpttype(image, 0) ==
 		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y) &&
 		  jas_image_cmpttype(image, 1) ==
 		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB) &&
@@ -311,7 +313,8 @@ int jp2_encode(jas_image_t *image, jas_stream_t *out, const char *optstr)
 			needcdef = 0;
 		break;
 	case JAS_CLRSPC_FAM_GRAY:
-		if (jas_image_cmpttype(image, 0) ==
+		if (jas_image_numcmpts(image) >= 1 &&
+		  jas_image_cmpttype(image, 0) ==
 		  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y))
 			needcdef = 0;
 		break;
