From ebe46ba82340cea8f030e0c0b3bb89aabad83674 Mon Sep 17 00:00:00 2001
Message-ID: <ebe46ba82340cea8f030e0c0b3bb89aabad83674.1750520310.git.sam@gentoo.org>
From: Nick Wellnhofer <wellnhofer@aevum.de>
Date: Tue, 27 May 2025 12:53:17 +0200
Subject: [PATCH] tree: Fix integer overflow in xmlBuildQName

This issue affects memory safety and might receive a CVE ID later.

Fixes #926.

(cherry picked from commit acbbeef9f5dcdcc901c5f3fa14d583ef8cfd22f0)
---
 tree.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/tree.c b/tree.c
index f097cf87..76112e22 100644
--- a/tree.c
+++ b/tree.c
@@ -22,6 +22,7 @@
 #include <stddef.h>
 #include <limits.h>
 #include <ctype.h>
+#include <stdint.h>
 #include <stdlib.h>
 
 #ifdef LIBXML_ZLIB_ENABLED
@@ -167,10 +168,10 @@ xmlGetParameterEntityFromDtd(const xmlDtd *dtd, const xmlChar *name) {
 xmlChar *
 xmlBuildQName(const xmlChar *ncname, const xmlChar *prefix,
 	      xmlChar *memory, int len) {
-    int lenn, lenp;
+    size_t lenn, lenp;
     xmlChar *ret;
 
-    if (ncname == NULL) return(NULL);
+    if ((ncname == NULL) || (len < 0)) return(NULL);
     if (prefix == NULL) return((xmlChar *) ncname);
 
 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
@@ -181,8 +182,10 @@ xmlBuildQName(const xmlChar *ncname, const xmlChar *prefix,
 
     lenn = strlen((char *) ncname);
     lenp = strlen((char *) prefix);
+    if (lenn >= SIZE_MAX - lenp - 1)
+        return(NULL);
 
-    if ((memory == NULL) || (len < lenn + lenp + 2)) {
+    if ((memory == NULL) || ((size_t) len < lenn + lenp + 2)) {
 	ret = (xmlChar *) xmlMallocAtomic(lenn + lenp + 2);
 	if (ret == NULL)
 	    return(NULL);

base-commit: 3a1c25f5e7bbf8180690cf5c4c5a9fc1caf55c62
-- 
2.50.0

