Skip to content

Fix leak of the ARGS XML parser context on malformed documents - #3633

Open
tomsommer wants to merge 1 commit into
owasp-modsecurity:v3/masterfrom
tomsommer:fix/xml-args-parser-ctx-leak
Open

tomsommer wants to merge 1 commit into
owasp-modsecurity:v3/masterfrom
tomsommer:fix/xml-args-parser-ctx-leak

Conversation

@tomsommer

@tomsommer tomsommer commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

what

  • Free xml_data::parsing_ctx_arg in ~XML(), following the existing pattern for parsing_ctx.
  • Free and clear parsing_ctx_arg before the early return false in XML::complete() when the document is not well formed.
  • Adds test/test-cases/regression/request-body-parser-xml-into-args.json (mismatched end tag, truncated document) with SecParseXmlIntoArgs On.

why

  • With SecParseXmlIntoArgs On, XML::processChunk() creates a second libxml2 push parser context (parsing_ctx_arg) for the ARGS extraction. It was only released in the second block of XML::complete().
  • complete() finishes the main context first and returns early with "XML: Failed to parse document." when the document is not well formed, before reaching that block. ~XML() released parsing_ctx and doc but not parsing_ctx_arg, so nothing ever freed it.
  • Every request with a malformed XML body therefore leaked the ARGS parser context including its body-sized input buffer (the whole body is pushed in one chunk from Transaction::processRequestBody()).
  • The pointer copy kept in xml_data::xml_parser_state is a non-owning alias only dereferenced from SAX callbacks while parsing is in progress, so freeing in ~XML() cannot double free. Both edits are inside the existing WITH_LIBXML2 guard.

Evidence, unfixed tree, libtool --mode=execute valgrind --leak-check=full ./regression_tests test-cases/regression/request-body-parser-xml-into-args.json:

==2== 27,666 (1,504 direct, 26,162 indirect) bytes in 2 blocks are definitely lost in loss record 12 of 12
==2==    by 0x509C712: xmlNewParserCtxt (libxml2.so.2.9.14)
==2==    by 0x50B587E: xmlCreatePushParserCtxt (libxml2.so.2.9.14)
==2==    by 0x49BCC3D: modsecurity::RequestBodyProcessor::XML::processChunk(...) (xml.cc:260)
==2==    by 0x497B1EF: modsecurity::Transaction::processRequestBody() (transaction.cc:718)

With the fix: All heap blocks were freed -- no leaks are possible. make check: TOTAL 5045, PASS 5029, SKIP 16, FAIL 0.

references

Summary by CodeRabbit

  • Bug Fixes

    • Fixed a memory leak when malformed or incomplete XML request bodies fail to parse.
    • XML parsing resources are now properly released after parsing errors and when request processing completes, improving reliability for XML request handling.
  • Tests

    • Added regression coverage for malformed and truncated XML requests when XML parsing into arguments is enabled.
    • Added checks confirming failed XML parsing is reported correctly in debug logs.

@coderabbitai

coderabbitai Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 100af900-b8bb-461c-9b28-3ea2ddf4b26d
Commits

Reviewing files that changed from the base of the PR and between 030d382 and 11db826.

Files selected for processing: 2
  • src/request_body_processor/xml.cc
  • test/test-suite.in

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

Walkthrough

The XML request body parser now releases the ARGS parsing context during destruction and malformed-document handling. Two regression cases cover malformed XML with XML-to-ARGS parsing enabled.

Changes: XML parser cleanup

Layer / File(s) Summary
Parser context cleanup
src/request_body_processor/xml.h, src/request_body_processor/xml.cc
The XML class declares and uses freeArgsParserCtx(). The helper frees m_data.parsing_ctx_arg with xmlFreeParserCtxt() and resets the pointer to null during destruction and malformed-document failure handling.
Malformed XML regression coverage
test/test-cases/regression/request-body-parser-xml-into-args.json, test/test-suite.in
Two malformed XML cases verify the failure log, HTTP 200 response, and empty body. The test suite manifest registers the new test file.

Priority: Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Possibly related issues

  • owasp-modsecurity/ModSecurity#3563: This issue concerns the malformed-document failure path, but this change does not alter the error decision or address the reported false positive.

Possibly related PRs

Suggested reviewers: airween

Merge Risk: Minimal · up to 11db8

The parser cleanup change is ready to merge with no established current-head risk.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "Fix leak of the ARGS XML parser context on malformed documents" matches the main change. The raw summary shows XML now frees the ARGS parser context in the destructor and before complete() …
Docstring Coverage Passed Docstring coverage is inconclusive: files from earlier reviews still need to be rechecked within the check's analysis limits. Not blocking.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "Fix leak of the ARGS XML parser context on malformed documents" matches the main change. The raw summary shows XML now frees the ARGS parser context in the destructor and before complete() returns failure for a malformed document. The objectives describe the same fix, and the regression test covers malformed XML inputs. The title is specific, short, and free of file lists or vague terms.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@tomsommer
tomsommer force-pushed the fix/xml-args-parser-ctx-leak branch from 370210c to 030d382 Compare September 19, 2026 14:42
@sonarqubecloud

Copy link
Copy Markdown

@fzipi fzipi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @tomsommer, good find, and a clean fix.

What I checked:

  • Ran macOS leaks --atExit against regression_tests with your new request-body-parser-xml-into-args.json. On master it reports 24 leaks / 34,176 bytes, rooted in two xmlNewParserCtxt allocations (one per case). With this PR it reports 0 leaks, and request-body-parser-xml.json still passes.
  • No double free: freeArgsParserCtx() nulls the pointer, and the remaining frees in complete() null it too. The copy in xml_parser_state is only used from SAX callbacks while parsing, and xmlFreeParserCtxt() doesn't call those. In ~XML() the free happens before the members holding the SAX handler and user data are destroyed.
  • The new test file is registered in test-suite.in and runs under make check. The full suite with this PR merged together with #3632, #3635 and #3636 has no failures.

Comments:

  1. (non-blocking) The new JSON cases also pass on master, since they only check the "Failed to parse document" log line. They're useful coverage of the path, but a regression of the leak itself would only show up under valgrind or leaks, and CI has no such job. No change needed; noting it for the record.
  2. (non-blocking) The only red jobs are the two macOS LMDB ones (action-expirevar.json, issue-1831.json). Nothing here touches collection/LMDB code, the same job is green on current v3/master, and these runs predate some LMDB fixes there, so a rebase or re-run should clear them.

LGTM.

With SecParseXmlIntoArgs set to On, XML::processChunk() creates a second
libxml2 push parser context, xml_data::parsing_ctx_arg, in addition to
the regular parsing_ctx. That context is only released in XML::complete(),
in the block that terminates the ARGS parsing.

XML::complete() finishes the main context first and returns early with
"XML: Failed to parse document." when the document is not well formed,
before reaching the block that frees parsing_ctx_arg. ~XML() released
parsing_ctx and doc but not parsing_ctx_arg, so nothing ever freed it.
A remote client could therefore leak the ARGS parser context, including
its body-sized input buffer, on every request carrying a malformed XML
body.

parsing_ctx_arg is now freed in ~XML() and, through the same small
helper (XML::freeArgsParserCtx()), also freed and cleared before the
early return in XML::complete() so that the memory is released as soon as the parsing
is known to have failed rather than at the end of the transaction. The
copy of the pointer kept in xml_data::xml_parser_state is only used from
the SAX callbacks while parsing is in progress, and both changes stay
inside the existing WITH_LIBXML2 guard.

A regression test covering a mismatched end tag and a truncated document
is added; under valgrind the unfixed code reports the context allocated
in xmlCreatePushParserCtxt() as definitely lost for each request.
@tomsommer
tomsommer force-pushed the fix/xml-args-parser-ctx-leak branch from 030d382 to 11db826 Compare October 27, 2026 05:43
@sonarqubecloud

Copy link
Copy Markdown

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants