From 17e29cb8ff58a8356ad8ea363c169e227e93e444 Mon Sep 17 00:00:00 2001
From: Sebastian Pipping <sebastian@pipping.org>
Date: Mon, 19 Aug 2024 22:34:13 +0200
Subject: [PATCH] lib: Detect integer overflow in dtdCopy

Reported by TaiYou

CVE: CVE-2024-45491

Upstream-Status: Backport [https://github.com/libexpat/libexpat/pull/891/commits/8e439a9947e9dc80]

Signed-off-by: Archana Polampalli <archana.polampalli@windriver.com>
---
 lib/xmlparse.c | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/lib/xmlparse.c b/lib/xmlparse.c
index 6f0440b..adb27e3 100644
--- a/lib/xmlparse.c
+++ b/lib/xmlparse.c
@@ -6913,6 +6913,16 @@ dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,
     if (! newE)
       return 0;
     if (oldE->nDefaultAtts) {
+      /* Detect and prevent integer overflow.
+       * The preprocessor guard addresses the "always false" warning
+       * from -Wtype-limits on platforms where
+       * sizeof(int) < sizeof(size_t), e.g. on x86_64. */
+#if UINT_MAX >= SIZE_MAX
+      if ((size_t)oldE->nDefaultAtts
+          > ((size_t)(-1) / sizeof(DEFAULT_ATTRIBUTE))) {
+        return 0;
+      }
+#endif
       newE->defaultAtts
           = ms->malloc_fcn(oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
       if (! newE->defaultAtts) {
--
2.40.0
