Skip to content

Add a PatternLayout conversion word that encodes special characters - #853

Open
NopeCharon wants to merge 1 commit into
apache:masterfrom
NopeCharon:encode_pattern_converter
Open

NopeCharon wants to merge 1 commit into
apache:masterfrom
NopeCharon:encode_pattern_converter

Conversation

@NopeCharon

Copy link
Copy Markdown
Contributor

Closes #852

Problem

PatternLayout outputs every value as it is. A message, NDC or MDC value, thread name or logger name that contains a line break is written as several lines, which splits or forges events for anything that reads the log one line per event. A pattern that embeds a value in HTML, XML or a JSON string produces invalid output when the value contains <, &, " or a control character.

The Apache Logging security FAQ says that when Pattern layout must be used, all fields should be sanitized explicitly, with %enc{%m}{CRLF} in Log4j Core as the example. Log4cxx had no equivalent. It also could not be added as an ordinary conversion word, because PatternParser ended every option at the first }, so %enc{%d{HH:mm:ss} %m}{CRLF} was split inside %d{HH:mm:ss}.

Change

Nested options. PatternParser::extractOptions now ends an option at its matching closing brace, so an option can contain a nested pattern with options of its own. If an option has no matching closing brace, it still ends at the first }, so every pattern that worked before is parsed the same way.

%enc / %encode. A new EncodingPatternConverter is registered in PatternLayout under the Log4j 2 names. %enc{pattern}{format} formats the nested pattern (the nested converters keep their own format modifiers) and then replaces the characters that are special in the selected format:

Format Replaced
HTML (default, as in Log4j 2) CR and LF with \r and \n; &<>"'/ with HTML character entity references
XML &<>"', tab, CR and LF with entity or character references (Transform::appendEscapingAttribute)
JSON characters not allowed in a JSON string, using the JSONLayout escapes (JSONLayout::appendItem without the enclosing quotes)
CRLF CR and LF with \r and \n
log4j.appender.A1.layout.ConversionPattern=%d %-5p [%enc{%t}{CRLF}] %c - %enc{%m %x}{CRLF}%n
log4j.appender.A2.layout.ConversionPattern={"time":"%d{ISO8601}","message":"%enc{%m}{JSON}"}%n
  • The nested pattern can use any PatternLayout conversion word. The rules come from the virtual getFormatSpecifiers(), so conversion words added by a subclass work too. A format modifier on %enc itself applies to the encoded text, e.g. %.-200enc{%m}{CRLF}.
  • The format name is case insensitive and spaces around it are ignored. An unknown format name gives a warning in the internal debugging output and HTML is used. %enc with no pattern gives a warning and outputs nothing.
  • The HTML and CRLF replacements append each run of ordinary characters in a single call.
  • handlesThrowable() returns true when the nested pattern contains a converter that handles throwables.

Documentation: an enc/encode row in the PatternLayout conversion table, a paragraph saying that options may contain balanced braces, the EncodingPatternConverter class reference, and a change log entry under the 2.0.0 new features.

Testing

New PatternLayoutTest tests:

  • testEncodeCRLF: CR and LF are replaced, the encode alias and a lower case name with spaces work, and other characters are left alone
  • testEncodeHTML: the default format and explicit HTML/html
  • testEncodeXML, testEncodeJSON: the replaced characters, including a control character, and a JSON document built in the pattern
  • testEncodeNestedPattern: a nested pattern with options, format modifiers, literal braces and an MDC value; minimum width and truncate-from-end modifiers on %enc; %enc nested in %enc
  • testEncodeInvalidOptions: no pattern, an empty pattern and an unknown format name

New PatternParserTestCase tests:

  • testNestedOptions: nested options are extracted, and an option without a matching closing brace still ends at the first }
  • testEncodeHandlesThrowable

With the extractOptions change reverted, testNestedOptions and testEncodeNestedPattern fail.

On macOS (Apple clang 21, arm64), patternlayouttest, patternparsertestcase and filenamepatterntestcase pass with the default utf-8 logchar and with -DLOG4CXX_CHAR=wchar_t. The changed library files compile with -DCMAKE_CXX_STANDARD=11 and produce no new warnings with -Wall -Wextra -Wpedantic -Wshadow -Wconversion.

Deep nesting is bounded by the pattern length. A 700-level %enc{%enc{...}} pattern (4.2 KB, more than the 4096-byte pattern limit of PatternLayoutApiFuzzer) parses and formats in a thread with an 8 MB stack. In a Debug build each nesting level uses about 2–3 KB of stack.

PatternLayout output a value exactly as it was, so a message, NDC or
MDC value, thread name or logger name containing a line break was
written as several lines, splitting or forging events for anything that
reads the log one line per event. A pattern that embedded a value in
HTML, XML or a JSON string produced invalid output when the value
contained a markup character, a quote or a control character. The
Apache Logging security FAQ recommends sanitizing every Pattern layout
field in that situation, with %enc{%m}{CRLF} as the Log4j Core example,
but Log4cxx had no equivalent.

Add EncodingPatternConverter, registered in PatternLayout as "enc" and
"encode" (the Log4j 2 names). %enc{pattern}{format} formats the nested
pattern, applying the format modifiers of each nested converter, and
replaces the characters that are special in the selected format:

- HTML (the default, as in Log4j 2): CR and LF become \r and \n, and
  &<>"'/ become HTML character entity references
- XML: &<>"', tab, CR and LF become XML entity or character references
  (Transform::appendEscapingAttribute)
- JSON: the characters not allowed in a JSON string are escaped as
  JSONLayout does (JSONLayout::appendItem without the enclosing quotes)
- CRLF: CR and LF become \r and \n

The format name is case insensitive and may be surrounded by spaces. An
unknown name, or %enc without a pattern, is reported in the internal
debugging output; HTML is used for the former and nothing is output for
the latter. The HTML and CRLF replacements append each run of ordinary
characters in one operation instead of character by character. A format
modifier on %enc applies to the encoded text.

A nested pattern needs options that contain braces, as in
%enc{%d{HH:mm:ss} %m}{CRLF}, but PatternParser ended every option at the
first closing brace. An option now ends at its matching closing brace.
When an option has no matching closing brace it still ends at the first
one, so patterns that were valid before are parsed as before.

Document the conversion word and nested braces in the PatternLayout
reference and add a change log entry.

PatternLayoutTest has tests for each format, the default format, the
encode alias, case insensitive format names, nested patterns with
options and format modifiers, format modifiers on %enc itself, nesting
%enc in %enc, and invalid options. PatternParserTestCase checks that
nested options are extracted, that an option without a matching closing
brace still ends at the first closing brace, and that the converter
reports a throwable conversion in its nested pattern.

Fixes apache#852
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.

Add a PatternLayout conversion word that encodes special characters (%enc)

1 participant