17
0

1 Commits

Author SHA256 Message Date
John Paul Adrian Glaubitz
e9aad3801e Backport fix for CVE-2025-9375
- Cherry-pick CVE-2025-9375.patch to fix multiple XML Injection
  vulnerabilities in XML parser (bsc#1249036, CVE-2025-9375)
2025-11-18 11:28:55 +01:00
6 changed files with 260 additions and 63 deletions

222
CVE-2025-9375.patch Normal file
View File

@@ -0,0 +1,222 @@
From 065c500169f9c4f5109df1902027f778d2ee8730 Mon Sep 17 00:00:00 2001
From: Martin Blech <78768+martinblech@users.noreply.github.com>
Date: Thu, 4 Sep 2025 17:25:39 -0700
Subject: [PATCH] Merge the following three upstream commits as a combined fix
for CVE-2025-9375
- Prevent XML injection: reject '<'/'>' in element/attr names (incl. @xmlns) (ecd456a)
- Enhance unparse() XML name validation with stricter rules and tests (f98c90f)
- Harden XML name validation: reject quotes and '='; add tests (8860b0e)
---
tests/test_dicttoxml.py | 106 ++++++++++++++++++++++++++++++++++++++++
xmltodict.py | 56 ++++++++++++++++++++-
2 files changed, 160 insertions(+), 2 deletions(-)
diff --git a/tests/test_dicttoxml.py b/tests/test_dicttoxml.py
index 470aca9..1fa5ba7 100644
--- a/tests/test_dicttoxml.py
+++ b/tests/test_dicttoxml.py
@@ -231,3 +231,109 @@ xmlns:b="http://b.com/"><x a:attr="val">1</x><a:y>2</a:y><b:z>3</b:z></root>'''
expected_xml = '<?xml version="1.0" encoding="utf-8"?>\n<x>false</x>'
xml = unparse(dict(x=False))
self.assertEqual(xml, expected_xml)
+
+ def test_rejects_tag_name_with_angle_brackets(self):
+ # Minimal guard: disallow '<' or '>' to prevent breaking tag context
+ with self.assertRaises(ValueError):
+ unparse({"m><tag>content</tag": "unsafe"}, full_document=False)
+
+ def test_rejects_attribute_name_with_angle_brackets(self):
+ # Now we expect bad attribute names to be rejected
+ with self.assertRaises(ValueError):
+ unparse(
+ {"a": {"@m><tag>content</tag": "unsafe", "#text": "x"}},
+ full_document=False,
+ )
+
+ def test_rejects_malicious_xmlns_prefix(self):
+ # xmlns prefixes go under @xmlns mapping; reject angle brackets in prefix
+ with self.assertRaises(ValueError):
+ unparse(
+ {
+ "a": {
+ "@xmlns": {"m><bad": "http://example.com/"},
+ "#text": "x",
+ }
+ },
+ full_document=False,
+ )
+
+ def test_attribute_values_with_angle_brackets_are_escaped(self):
+ # Attribute values should be escaped by XMLGenerator
+ xml = unparse({"a": {"@attr": "1<middle>2", "#text": "x"}}, full_document=False)
+ # The generated XML should contain escaped '<' and '>' within the attribute value
+ self.assertIn('attr="1&lt;middle&gt;2"', xml)
+
+ def test_rejects_tag_name_starting_with_question(self):
+ with self.assertRaises(ValueError):
+ unparse({"?pi": "data"}, full_document=False)
+
+ def test_rejects_tag_name_starting_with_bang(self):
+ with self.assertRaises(ValueError):
+ unparse({"!decl": "data"}, full_document=False)
+
+ def test_rejects_attribute_name_starting_with_question(self):
+ with self.assertRaises(ValueError):
+ unparse({"a": {"@?weird": "x"}}, full_document=False)
+
+ def test_rejects_attribute_name_starting_with_bang(self):
+ with self.assertRaises(ValueError):
+ unparse({"a": {"@!weird": "x"}}, full_document=False)
+
+ def test_rejects_xmlns_prefix_starting_with_question_or_bang(self):
+ with self.assertRaises(ValueError):
+ unparse({"a": {"@xmlns": {"?p": "http://e/"}}}, full_document=False)
+ with self.assertRaises(ValueError):
+ unparse({"a": {"@xmlns": {"!p": "http://e/"}}}, full_document=False)
+
+ def test_rejects_non_string_names(self):
+ class Weird:
+ def __str__(self):
+ return "bad>name"
+
+ # Non-string element key
+ with self.assertRaises(ValueError):
+ unparse({Weird(): "x"}, full_document=False)
+ # Non-string attribute key
+ with self.assertRaises(ValueError):
+ unparse({"a": {Weird(): "x"}}, full_document=False)
+
+ def test_rejects_tag_name_with_slash(self):
+ with self.assertRaises(ValueError):
+ unparse({"bad/name": "x"}, full_document=False)
+
+ def test_rejects_tag_name_with_whitespace(self):
+ for name in ["bad name", "bad\tname", "bad\nname"]:
+ with self.assertRaises(ValueError):
+ unparse({name: "x"}, full_document=False)
+
+ def test_rejects_attribute_name_with_slash(self):
+ with self.assertRaises(ValueError):
+ unparse({"a": {"@bad/name": "x"}}, full_document=False)
+
+ def test_rejects_attribute_name_with_whitespace(self):
+ for name in ["@bad name", "@bad\tname", "@bad\nname"]:
+ with self.assertRaises(ValueError):
+ unparse({"a": {name: "x"}}, full_document=False)
+
+ def test_rejects_xmlns_prefix_with_slash_or_whitespace(self):
+ # Slash
+ with self.assertRaises(ValueError):
+ unparse({"a": {"@xmlns": {"bad/prefix": "http://e/"}}}, full_document=False)
+ # Whitespace
+ with self.assertRaises(ValueError):
+ unparse({"a": {"@xmlns": {"bad prefix": "http://e/"}}}, full_document=False)
+
+ def test_rejects_names_with_quotes_and_equals(self):
+ # Element names
+ for name in ['a"b', "a'b", "a=b"]:
+ with self.assertRaises(ValueError):
+ unparse({name: "x"}, full_document=False)
+ # Attribute names
+ for name in ['@a"b', "@a'b", "@a=b"]:
+ with self.assertRaises(ValueError):
+ unparse({"a": {name: "x"}}, full_document=False)
+ # xmlns prefixes
+ for prefix in ['a"b', "a'b", "a=b"]:
+ with self.assertRaises(ValueError):
+ unparse({"a": {"@xmlns": {prefix: "http://e/"}}}, full_document=False)
diff --git a/xmltodict.py b/xmltodict.py
index 098f627..15e2748 100755
--- a/xmltodict.py
+++ b/xmltodict.py
@@ -360,7 +360,54 @@ def parse(xml_input, encoding=None, expat=expat, process_namespaces=False,
return handler.item
+def _has_angle_brackets(value):
+ """Return True if value (a str) contains '<' or '>'.
+
+ Non-string values return False. Uses fast substring checks implemented in C.
+ """
+ return isinstance(value, str) and ("<" in value or ">" in value)
+
+
+def _has_invalid_name_chars(value):
+ """Return True if value (a str) contains any disallowed name characters.
+
+ Disallowed: '<', '>', '/', or any whitespace character.
+ Non-string values return False.
+ """
+ if not isinstance(value, str):
+ return False
+ if "<" in value or ">" in value or "/" in value:
+ return True
+ # Check for any whitespace (spaces, tabs, newlines, etc.)
+ return any(ch.isspace() for ch in value)
+
+
+def _validate_name(value, kind):
+ """Validate an element/attribute name for XML safety.
+
+ Raises ValueError with a specific reason when invalid.
+
+ kind: 'element' or 'attribute' (used in error messages)
+ """
+ if not isinstance(value, str):
+ raise ValueError(f"{kind} name must be a string")
+ if value.startswith("?") or value.startswith("!"):
+ raise ValueError(f'Invalid {kind} name: cannot start with "?" or "!"')
+ if "<" in value or ">" in value:
+ raise ValueError(f'Invalid {kind} name: "<" or ">" not allowed')
+ if "/" in value:
+ raise ValueError(f'Invalid {kind} name: "/" not allowed')
+ if '"' in value or "'" in value:
+ raise ValueError(f"Invalid {kind} name: quotes not allowed")
+ if "=" in value:
+ raise ValueError(f'Invalid {kind} name: "=" not allowed')
+ if any(ch.isspace() for ch in value):
+ raise ValueError(f"Invalid {kind} name: whitespace not allowed")
+
+
def _process_namespace(name, namespaces, ns_sep=':', attr_prefix='@'):
+ if not isinstance(name, str):
+ return name
if not namespaces:
return name
try:
@@ -393,6 +440,8 @@ def _emit(key, value, content_handler,
if result is None:
return
key, value = result
+ # Minimal validation to avoid breaking out of tag context
+ _validate_name(key, "element")
if not hasattr(value, '__iter__') or isinstance(value, (str, dict)):
value = [value]
for index, v in enumerate(value):
@@ -416,17 +465,20 @@ def _emit(key, value, content_handler,
if ik == cdata_key:
cdata = iv
continue
- if ik.startswith(attr_prefix):
+ if isinstance(ik, str) and ik.startswith(attr_prefix):
ik = _process_namespace(ik, namespaces, namespace_separator,
attr_prefix)
if ik == '@xmlns' and isinstance(iv, dict):
for k, v in iv.items():
+ _validate_name(k, "attribute")
attr = 'xmlns{}'.format(f':{k}' if k else '')
attrs[attr] = str(v)
continue
if not isinstance(iv, str):
iv = str(iv)
- attrs[ik[len(attr_prefix):]] = iv
+ attr_name = ik[len(attr_prefix) :]
+ _validate_name(attr_name, "attribute")
+ attrs[attr_name] = iv
continue
children.append((ik, iv))
if isinstance(indent, int):
--
2.51.0

View File

@@ -1,63 +1,8 @@
-------------------------------------------------------------------
Mon Nov 24 09:03:54 UTC 2025 - John Paul Adrian Glaubitz <adrian.glaubitz@suse.com>
Tue Sep 9 08:38:44 UTC 2025 - John Paul Adrian Glaubitz <adrian.glaubitz@suse.com>
- Update to 1.0.2
* allow DOCTYPE with disable_entities=True (default)
- from version 1.0.1
* fail closed when entities disabled
* validate XML comments
* add SECURITY.md
* clarify behavior for empty lists
* clarify process_comments docs
* clarify strip whitespace comment behavior
* create AGENTS.md for coding agents
* replace travis with actions badge
* update CONTRIBUTING.md
- Drop skip-tests-expat-245.patch, no longer required
-------------------------------------------------------------------
Fri Sep 12 19:34:16 UTC 2025 - Martin Hauke <mardnh@gmx.de>
- Update to version 1.0.0
BREAKING CHANGES
* modernize for Python 3.9+; drop legacy compat paths.
Features
* unparse: add limited XML comment round-trip; unify _emit
behavior (e43537e).
* unparse: add selective force_cdata support
(bool/tuple/callable) (a497fed), closes #375.
Bug Fixes
* namespaces: attach [@xmlns](https://github.com/xmlns) to
declaring element when process_namespaces=True.
* streaming: avoid parent accumulation at item_depth; add
regression tests (220240c).
* unparse: handle non-string #text with attributes; unify
value conversion (927a025).
* unparse: skip empty lists to keep pretty/compact outputs
consistent (ab4c86f).
Reverts
* remove initial Release Drafter config (c0b74ed).
-------------------------------------------------------------------
Tue Sep 9 07:46:33 UTC 2025 - John Paul Adrian Glaubitz <adrian.glaubitz@suse.com>
- Update to version 0.15.1
* Security: Further harden XML injection prevention during unparse (follow-up
to v0.15.0). In addition to '<'/'>' rejection, now also reject element and
attribute names (including `@xmlns` prefixes) that:
- start with '?' or '!'
- contain '/' or any whitespace
- contain quotes (' or ") or '='
- are non-strings (names must be `str`; no coercion)
-------------------------------------------------------------------
Mon Sep 8 11:26:39 UTC 2025 - John Paul Adrian Glaubitz <adrian.glaubitz@suse.com>
- Update to version 0.15.0
* Security: Prevent XML injection (CVE-2025-9375) by rejecting '<'/'>' in
element and attribute names (including `@xmlns` prefixes) during unparse.
This limits validation to avoiding tag-context escapes; attribute values
continue to be escaped by the SAX `XMLGenerator`. (bsc#1249036, CVE-2025-9375)
- Cherry-pick CVE-2025-9375.patch to fix multiple XML Injection
vulnerabilities in XML parser (bsc#1249036, CVE-2025-9375)
-------------------------------------------------------------------
Tue Oct 29 16:11:13 UTC 2024 - Martin Hauke <mardnh@gmx.de>

View File

@@ -1,7 +1,7 @@
#
# spec file for package python-xmltodict
#
# Copyright (c) 2025 SUSE LLC and contributors
# Copyright (c) 2024 SUSE LLC
#
# All modifications and additions to the file contributed by third parties
# remain the property of their copyright owners, unless otherwise agreed
@@ -18,12 +18,14 @@
%{?sle15_python_module_pythons}
Name: python-xmltodict
Version: 1.0.2
Version: 0.14.2
Release: 0
Summary: Module to make XML working resemble JSON
License: MIT
URL: https://github.com/martinblech/xmltodict
Source: https://files.pythonhosted.org/packages/source/x/xmltodict/xmltodict-%{version}.tar.gz
Patch0: skip-tests-expat-245.patch
Patch1: CVE-2025-9375.patch
BuildRequires: %{python_module pip}
BuildRequires: %{python_module pytest}
BuildRequires: %{python_module setuptools}

View File

@@ -0,0 +1,28 @@
Index: xmltodict-0.12.0/tests/test_xmltodict.py
===================================================================
--- xmltodict-0.12.0.orig/tests/test_xmltodict.py
+++ xmltodict-0.12.0/tests/test_xmltodict.py
@@ -8,6 +8,7 @@ except ImportError:
from xml.parsers.expat import ParserCreate
from xml.parsers import expat
+import pyexpat
def _encode(s):
@@ -167,6 +168,7 @@ class XMLToDictTestCase(unittest.TestCas
self.assertEqual(parse(xml),
parse(xml.encode('utf-8')))
+ @unittest.skipIf(pyexpat.version_info >= (2, 4, 5), reason="Makes no sense with current Expat")
def test_namespace_support(self):
xml = """
<root xmlns="http://defaultns.com/"
@@ -195,6 +197,7 @@ class XMLToDictTestCase(unittest.TestCas
res = parse(xml, process_namespaces=True)
self.assertEqual(res, d)
+ @unittest.skipIf(pyexpat.version_info >= (2, 4, 5), reason="Makes no sense with current Expat")
def test_namespace_collapse(self):
xml = """
<root xmlns="http://defaultns.com/"

BIN
xmltodict-0.14.2.tar.gz LFS Normal file

Binary file not shown.

View File

@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:54306780b7c2175a3967cad1db92f218207e5bc1aba697d887807c0fb68b7649
size 25725