From 19d775e058bf6bb0b0e9c56f406b775f9e725355 Mon Sep 17 00:00:00 2001
From: Su_Laus <sulau@freenet.de>
Date: Sat, 2 Apr 2022 22:33:31 +0200
Subject: [PATCH] tiffcp: avoid buffer overflow in "mode" string (fixes #400)

CVE: CVE-2022-1355

Upstream-Status: Backport
[https://gitlab.com/libtiff/libtiff/-/commit/c1ae29f9ebacd29b7c3e0c7db671af7db3584bc2]

Signed-off-by: Yi Zhao <yi.zhao@windriver.com>

---
 tools/tiffcp.c | 25 ++++++++++++++++++++-----
 1 file changed, 20 insertions(+), 5 deletions(-)

diff --git a/tools/tiffcp.c b/tools/tiffcp.c
index 552d8fa..57eef90 100644
--- a/tools/tiffcp.c
+++ b/tools/tiffcp.c
@@ -274,19 +274,34 @@ main(int argc, char* argv[])
 			deftilewidth = atoi(optarg);
 			break;
 		case 'B':
-			*mp++ = 'b'; *mp = '\0';
+			if (strlen(mode) < (sizeof(mode) - 1))
+			{
+				*mp++ = 'b'; *mp = '\0';
+			}
 			break;
 		case 'L':
-			*mp++ = 'l'; *mp = '\0';
+			if (strlen(mode) < (sizeof(mode) - 1))
+			{
+				*mp++ = 'l'; *mp = '\0';
+			}
 			break;
 		case 'M':
-			*mp++ = 'm'; *mp = '\0';
+			if (strlen(mode) < (sizeof(mode) - 1))
+			{
+				*mp++ = 'm'; *mp = '\0';
+			}
 			break;
 		case 'C':
-			*mp++ = 'c'; *mp = '\0';
+			if (strlen(mode) < (sizeof(mode) - 1))
+			{
+				*mp++ = 'c'; *mp = '\0';
+			}
 			break;
 		case '8':
-			*mp++ = '8'; *mp = '\0';
+			if (strlen(mode) < (sizeof(mode)-1))
+			{
+				*mp++ = '8'; *mp = '\0';
+			}
 			break;
 		case 'x':
 			pageInSeq = 1;
