Author: Thorsten Alteholz <debian@alteholz.de>
Description: Backport upstream fix for CVE-2022-29458
 Add a limit-check to guard against corrupt terminfo data
 (report/testcase by NCNIPC of China), fix backported from the
 20220416 upstream patchlevel.
Bug-Debian: https://bugs.debian.org/1009870
Forwarded: Not-needed
Last-Update: 2023-01-28

---
 ncurses/tinfo/alloc_entry.c |   10 ++++------
 ncurses/tinfo/read_entry.c  |   17 +++++++++++++++--
 2 files changed, 19 insertions(+), 8 deletions(-)

--- a/ncurses/tinfo/alloc_entry.c
+++ b/ncurses/tinfo/alloc_entry.c
@@ -53,8 +53,6 @@ MODULE_ID("$Id: alloc_entry.c,v 1.64 202
 #define ABSENT_OFFSET    -1
 #define CANCELLED_OFFSET -2
 
-#define MAX_STRTAB	4096	/* documented maximum entry size */
-
 static char *stringbuf;		/* buffer for string capabilities */
 static size_t next_free;	/* next free character in stringbuf */
 
@@ -72,7 +70,7 @@ _nc_init_entry(ENTRY * const tp)
 #endif
 
     if (stringbuf == 0)
-	TYPE_MALLOC(char, (size_t) MAX_STRTAB, stringbuf);
+	TYPE_MALLOC(char, (size_t) MAX_ENTRY_SIZE, stringbuf);
 
     next_free = 0;
 
@@ -108,11 +106,11 @@ _nc_save_str(const char *const string)
 	 * Cheat a little by making an empty string point to the end of the
 	 * previous string.
 	 */
-	if (next_free < MAX_STRTAB) {
+	if (next_free < MAX_ENTRY_SIZE) {
 	    result = (stringbuf + next_free - 1);
 	}
-    } else if (next_free + len < MAX_STRTAB) {
-	_nc_STRCPY(&stringbuf[next_free], string, MAX_STRTAB);
+    } else if (next_free + len < MAX_ENTRY_SIZE) {
+	_nc_STRCPY(&stringbuf[next_free], string, MAX_ENTRY_SIZE);
 	DEBUG(7, ("Saved string %s", _nc_visbuf(string)));
 	DEBUG(7, ("at location %d", (int) next_free));
 	next_free += len;
--- a/ncurses/tinfo/read_entry.c
+++ b/ncurses/tinfo/read_entry.c
@@ -145,6 +145,7 @@ convert_strings(char *buf, char **String
 {
     int i;
     char *p;
+    bool corrupt = FALSE;
 
     for (i = 0; i < count; i++) {
 	if (IS_NEG1(buf + 2 * i)) {
@@ -154,8 +155,20 @@ convert_strings(char *buf, char **String
 	} else if (MyNumber(buf + 2 * i) > size) {
 	    Strings[i] = ABSENT_STRING;
 	} else {
-	    Strings[i] = (MyNumber(buf + 2 * i) + table);
-	    TR(TRACE_DATABASE, ("Strings[%d] = %s", i, _nc_visbuf(Strings[i])));
+	    int nn = MyNumber(buf + 2 * i);
+	    if (nn >= 0 && nn < size) {
+		Strings[i] = (nn + table);
+		TR(TRACE_DATABASE, ("Strings[%d] = %s", i,
+				    _nc_visbuf(Strings[i])));
+	    } else {
+		if (!corrupt) {
+		    corrupt = TRUE;
+		    TR(TRACE_DATABASE,
+		       ("ignore out-of-range index %d to Strings[]", nn));
+		    _nc_warning("corrupt data found in convert_strings");
+		}
+		Strings[i] = ABSENT_STRING;
+	    }
 	}
 
 	/* make sure all strings are NUL terminated */
