commit 25f4e86a2b3e8d1e12c4fcd6ba0ef182e2d0a387
Author: Tomas Korbar <tkorbar@redhat.com>
Date: Mon Feb 21 16:55:36 2022 +0100
CVE-2021-45960
diff --git a/lib/xmlparse.c b/lib/xmlparse.c
index d4f30b7..e743f78 100644
--- a/lib/xmlparse.c
+++ b/lib/xmlparse.c
@@ -2922,7 +2922,13 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
if (nPrefixes) {
int j; /* hash table index */
unsigned long version = nsAttsVersion;
- int nsAttsSize = (int)1 << nsAttsPower;
+ /* Detect and prevent invalid shift */
+ if (parser->m_nsAttsPower >= sizeof(unsigned int) * 8 /* bits per byte */) {
+ return XML_ERROR_NO_MEMORY;
+ }
+
+ unsigned int nsAttsSize = 1u << parser->m_nsAttsPower;
+ unsigned char oldNsAttsPower = parser->m_nsAttsPower;
/* size of hash table must be at least 2 * (# of prefixed attributes) */
if ((nPrefixes << 1) >> nsAttsPower) { /* true for nsAttsPower = 0 */
NS_ATT *temp;
@@ -2930,10 +2936,34 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
while (nPrefixes >> nsAttsPower++);
if (nsAttsPower < 3)
nsAttsPower = 3;
- nsAttsSize = (int)1 << nsAttsPower;
+
+ /* Detect and prevent invalid shift */
+ if (parser->m_nsAttsPower >= sizeof(nsAttsSize) * 8 /* bits per byte */) {
+ /* Restore actual size of memory in m_nsAtts */
+ parser->m_nsAttsPower = oldNsAttsPower;
+ return XML_ERROR_NO_MEMORY;
+ }
+
+ nsAttsSize = 1u << parser->m_nsAttsPower;
+
+ /* Detect and prevent integer overflow.
+ * The preprocessor guard addresses the "always false" warning
+ * from -Wtype-limits on platforms where
+ * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */
+#if UINT_MAX >= SIZE_MAX
+ if (nsAttsSize > (size_t)(-1) / sizeof(NS_ATT)) {
+ /* Restore actual size of memory in m_nsAtts */
+ parser->m_nsAttsPower = oldNsAttsPower;
+ return XML_ERROR_NO_MEMORY;
+ }
+#endif
+
temp = (NS_ATT *)REALLOC(nsAtts, nsAttsSize * sizeof(NS_ATT));
- if (!temp)
+ if (!temp) {
+ /* Restore actual size of memory in m_nsAtts */
+ parser->m_nsAttsPower = oldNsAttsPower;
return XML_ERROR_NO_MEMORY;
+ }
nsAtts = temp;
version = 0; /* force re-initialization of nsAtts hash table */
}