Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .oss-scanner/threat_model.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ Matters most:
as a format string (`EscapePercent`).
- `log4net.Appender.Internal.ContentEscape` and `RemoteSyslogAppender.AppendMessage`: the shared
escapes are `\0` for NUL, `\r` and `\n`, and `\uXXXX` for anything else. A sink that cannot carry a
character escapes it visibly; it never drops the character, the rest of the record, or the event.
character escapes it visibly; it never drops the character, the rest of the record, or the event,
except as noted under severity.
`AppenderSkeleton.RenderLoggingEvent` escapes lone surrogates for every appender, so a sink needs no
call of its own for them. NUL stays per sink.
- Anything where untrusted content reaches pattern converters, format expansion, or the appenders
Expand Down Expand Up @@ -72,6 +73,8 @@ reliability defect or hardening, and say so. That is more useful to us than a se
thread, a stack overflow from recursion driven by content).
- **Medium**: denial of service from content within normal size limits (unbounded memory, CPU, or a
hang of the logging call), or an event or part of a record silently lost because of its content.
Not a finding: `RemoteSyslogAppender` for an empty render, and `LocalSyslogAppender` in `Split`
mode for a render that is empty or only CR and LF, send no record. No text is lost.
- **Low**: resource leaks, missing escapes with no demonstrated parser impact, defense in depth.

Only claim impact you can demonstrate with the reproducer.
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,8 @@ What that leaves for this file is where the answers live in the code:
for newlines, and `\uXXXX` for anything else, in `ContentEscape` and in
`RemoteSyslogAppender.AppendMessage`. Put new ones in `ContentEscape` rather than in the
appender: four appenders have needed the same two so far. Escaping before a length limit, not
after, since an escape is longer than what it replaces.
after, since an escape is longer than what it replaces. Exceptions to the never-drop rule are
noted in `.oss-scanner/threat_model.md`.
- **Lone surrogates are the exception to escaping per sink.** `AppenderSkeleton.RenderLoggingEvent`
escapes them for every appender and has no opt-out, so a sink adds no call of its own. Only text
rendered around it needs one, such as the category of `TraceAppender`. NUL stays per sink.
Expand Down
12 changes: 12 additions & 0 deletions src/changelog/3.6.1/361-xml-tab-in-attribute-as-reference.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://logging.apache.org/xml/ns"
xsi:schemaLocation="https://logging.apache.org/xml/ns https://logging.apache.org/xml/ns/log4j-changelog-0.xsd"
type="fixed">
<issue id="361" link="https://github.com/apache/logging-log4net/issues/361"/>
<issue id="376" link="https://github.com/apache/logging-log4net/pull/376"/>
<description format="asciidoc">On .NET Framework, `XmlLayout` and `XmlLayoutSchemaLog4J` write a tab in
an attribute, such as a property value or the identity, as `+&amp;#x9;+`, as on .NET Standard
already. A parser read the literal tab back as a space (ANT-2026-8WPIUIID, fixed by
@FreeAndNil)</description>
</entry>
11 changes: 11 additions & 0 deletions src/changelog/3.6.1/374-telnet-nul-escaped.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://logging.apache.org/xml/ns"
xsi:schemaLocation="https://logging.apache.org/xml/ns https://logging.apache.org/xml/ns/log4j-changelog-0.xsd"
type="fixed">
<issue id="374" link="https://github.com/apache/logging-log4net/issues/374"/>
<issue id="376" link="https://github.com/apache/logging-log4net/pull/376"/>
<description format="asciidoc">`TelnetAppender` writes a NUL character as `\0`, as `TraceAppender` and
`LocalSyslogAppender` do. A telnet client dropped the raw NUL, so `adm\0in` showed as `admin`
(ANT-2026-O5V9EV3G, fixed by @FreeAndNil)</description>
</entry>
13 changes: 13 additions & 0 deletions src/changelog/3.6.1/375-log4j-layout-leaves-event-properties.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://logging.apache.org/xml/ns"
xsi:schemaLocation="https://logging.apache.org/xml/ns https://logging.apache.org/xml/ns/log4j-changelog-0.xsd"
type="fixed">
<issue id="375" link="https://github.com/apache/logging-log4net/issues/375"/>
<issue id="376" link="https://github.com/apache/logging-log4net/pull/376"/>
<description format="asciidoc">`XmlLayoutSchemaLog4J` formats from a copy of the event's properties and
no longer adds `log4jmachinename`, `log4japp`, `log4net:Identity` and `log4net:UserName` to the
event. Adding them could break a concurrent flush of a buffering appender. Visible change: appenders
that run after it on the same event no longer see these four keys (ANT-2026-L9XQVDSD, fixed by
@FreeAndNil)</description>
</entry>
6 changes: 6 additions & 0 deletions src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,12 @@ public void TabAndNonAsciiTextAreUnchanged()
public void SplittingDropsTheEmptyLines()
=> Assert.That(SplitLines("first\r\nsecond\n\nthird\r"), Is.EqualTo(new[] { "first", "second", "third" }));

/// <summary>A render that is empty or only line breaks sends no record, on purpose.</summary>
[TestCase("")]
[TestCase("\r\n\n")]
public void SplittingNothingButLineBreaksGivesNoRecord(string message)
=> Assert.That(SplitLines(message), Is.Empty);

/// <summary>
/// The record is the printf format string libc parses, so a percent sign in content would make
/// the callee read an argument that was never passed.
Expand Down
27 changes: 23 additions & 4 deletions src/log4net.Tests/Appender/TelnetAppenderTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,26 @@ public sealed class TelnetAppenderTest
/// </summary>
[Test]
public void ContentThatCannotBeEncodedDoesNotDisconnectTheClient()
=> Assert.That(ReceiveLogged("poison\ud800event"), Does.Contain(@"poison\ud800event"));

/// <summary>
/// A NUL is sent as <c>\0</c>, since a Telnet client drops it.
/// </summary>
[Test]
public void ANulIsSentEscaped()
{
string received = ReceiveLogged("adm\0in");

Assert.That(received, Does.Contain(@"adm\0in"));
// Ordinal, since Does.Not.Contain finds a NUL that is not there.
Assert.That(received.IndexOf("\0", StringComparison.Ordinal), Is.Negative);
}

/// <summary>
/// Logs <paramref name="content"/> and then a marker to a connected client, and returns what it received.
/// </summary>
/// <remarks>The marker only arrives if the client survived the content.</remarks>
private static string ReceiveLogged(string content)
{
StringBuilder received = new();
object receivedSyncRoot = new();
Expand Down Expand Up @@ -91,18 +111,17 @@ public void ContentThatCannotBeEncodedDoesNotDisconnectTheClient()
WaitFor("welcome message", WelcomeMessage);

ILogger logger = repository.GetLogger("Telnet");
logger.Log(typeof(TelnetAppenderTest), Level.Info, "poison\ud800event", null);
// The event after it only arrives if the client survived the one before.
logger.Log(typeof(TelnetAppenderTest), Level.Info, content, null);
logger.Log(typeof(TelnetAppenderTest), Level.Info, marker, null);
WaitFor("the event after the unencodable one", marker);
WaitFor("the marker after the content", marker);
}
}
finally
{
repository.Shutdown();
}

Assert.That(ReceivedText(), Does.Contain(@"poison\ud800event"));
return ReceivedText();

void Received(string message)
{
Expand Down
113 changes: 113 additions & 0 deletions src/log4net.Tests/Layout/XmlLayoutSchemaLog4jTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#endregion

using System;
using System.IO;
using log4net.Config;
using log4net.Core;
using log4net.Layout;
Expand Down Expand Up @@ -142,5 +143,117 @@ public void LineEndsInElementTextReadBackExactly(string element)
Assert.That(XmlRecords.RawContent(record, element), Is.EqualTo("a&#xD;&#xA;b"));
Assert.That(XmlRecords.ElementText(record, element), Is.EqualTo("a\r\nb"));
}

/// <summary>
/// A tab in a property name, a property value and the identity reads back as a tab.
/// </summary>
[Test]
public void ATabInAnAttributeReadsBackExactly()
{
StringAppender stringAppender = new() { Layout = new XmlLayoutSchemaLog4J() };
ILoggerRepository repository = LogManager.CreateRepository(Guid.NewGuid().ToString());
BasicConfigurator.Configure(repository, stringAppender);
ILog log = LogManager.GetLogger(repository.Name, "TestLogger");
LoggingEventData data = new()
{
LoggerName = "TestLogger",
Level = Level.Info,
TimeStampUtc = DateTime.UtcNow,
Message = "message",
Identity = "alice\tadmin",
Properties = new()
};
data.Properties["alice\tadmin"] = "alice\tadmin";

log.Logger.Log(new(null, repository, data));

string record = stringAppender.GetString();
Assert.That(record, Contains.Substring("name=\"alice&#x9;admin\" value=\"alice&#x9;admin\"").Using(StringComparison.Ordinal));
Assert.That(record, Contains.Substring("name=\"log4net:Identity\" value=\"alice&#x9;admin\"").Using(StringComparison.Ordinal));
Assert.That(XmlRecords.AttributeValues(record, "name"), Has.Member("alice\tadmin"));
Assert.That(XmlRecords.AttributeValues(record, "value"), Has.Exactly(2).EqualTo("alice\tadmin"));
}

/// <summary>
/// Formatting leaves the event's properties as they were: the event is shared with other appenders.
/// </summary>
[TestCase(true, TestName = "FixedEvent")]
[TestCase(false, TestName = "UnfixedEvent")]
public void FormattingLeavesTheEventsPropertiesAlone(bool isFixed)
{
ILoggerRepository repository = LogManager.CreateRepository(Guid.NewGuid().ToString());
LoggingEvent loggingEvent = isFixed
? new(null, repository, CreateData())
: new(typeof(XmlLayoutSchemaLog4JTest), repository, "TestLogger", Level.Info, "message", null);
string[] keys = loggingEvent.GetProperties().GetKeys();
using StringWriter writer = new();

new XmlLayoutSchemaLog4J().Format(writer, loggingEvent);

Assert.That(loggingEvent.GetProperties().GetKeys(), Is.EquivalentTo(keys));
Assert.That(loggingEvent.LookupProperty("log4japp"), Is.Null);
}

/// <summary>
/// The translated properties still reach the output.
/// </summary>
[Test]
public void TheTranslatedPropertiesAreWritten()
{
ILoggerRepository repository = LogManager.CreateRepository(Guid.NewGuid().ToString());
using StringWriter writer = new();

new XmlLayoutSchemaLog4J().Format(writer, new(null, repository, CreateData()));

string record = writer.ToString();
Assert.That(record, Does.Contain("name=\"log4jmachinename\" value=\"host\""));
Assert.That(record, Does.Contain("name=\"log4japp\" value=\"domain\""));
Assert.That(record, Does.Contain("name=\"log4net:Identity\" value=\"alice\""));
Assert.That(record, Does.Contain("name=\"log4net:UserName\" value=\"bob\""));
}

/// <summary>
/// A property the event already has wins over the translated value.
/// </summary>
[Test]
public void AnExistingPropertyWins()
{
ILoggerRepository repository = LogManager.CreateRepository(Guid.NewGuid().ToString());
LoggingEventData data = CreateData();
data.Properties!["log4japp"] = "mine";
using StringWriter writer = new();

new XmlLayoutSchemaLog4J().Format(writer, new(null, repository, data));

Assert.That(XmlRecords.AttributeValues(writer.ToString(), "value"), Has.Member("mine").And.No.Member("domain"));
}

/// <summary>
/// An empty identity is not translated.
/// </summary>
[Test]
public void AnEmptyValueIsNotTranslated()
{
ILoggerRepository repository = LogManager.CreateRepository(Guid.NewGuid().ToString());
LoggingEventData data = CreateData();
data.Identity = "";
using StringWriter writer = new();

new XmlLayoutSchemaLog4J().Format(writer, new(null, repository, data));

Assert.That(XmlRecords.AttributeValues(writer.ToString(), "name"), Has.No.Member(LoggingEvent.IdentityProperty));
}

private static LoggingEventData CreateData() => new()
{
LoggerName = "TestLogger",
Level = Level.Info,
TimeStampUtc = DateTime.UtcNow,
Message = "message",
Domain = "domain",
Identity = "alice",
UserName = "bob",
Properties = new() { [LoggingEvent.HostNameProperty] = "host" }
};
}
}
38 changes: 38 additions & 0 deletions src/log4net.Tests/Layout/XmlLayoutTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,44 @@ public void ExceptionTextKeepsItsLineEnds()
Assert.That(XmlRecords.ElementText(record, "exception"), Is.EqualTo(evt.ExceptionString));
}

/// <summary>
/// A tab in an attribute is a character reference, since a parser reads a literal one back as a space.
/// </summary>
[TestCase("alice\tadmin", "alice&#x9;admin", TestName = "TabInTheMiddle")]
[TestCase("\ta\t\tb\t", "&#x9;a&#x9;&#x9;b&#x9;", TestName = "LeadingDoubledAndTrailingTabs")]
public void ATabInAPropertyReadsBackExactly(string text, string expected)
{
LoggingEventData evt = CreateBaseEvent();
evt.Properties![text] = text;
StringAppender stringAppender = new() { Layout = new XmlLayout() };
ILoggerRepository repository = LogManager.CreateRepository(Guid.NewGuid().ToString());
BasicConfigurator.Configure(repository, stringAppender);

LogManager.GetLogger(repository.Name, "TestLogger").Logger.Log(new LoggingEvent(evt));

string record = stringAppender.GetString();
Assert.That(record, Is.EqualTo(CreateEventNode(expected, expected)));
Assert.That(XmlRecords.AttributeValues(record, "name"), Is.EqualTo(new[] { text }));
Assert.That(XmlRecords.AttributeValues(record, "value"), Is.EqualTo(new[] { text }));
}

/// <summary>
/// A tab in the identity reads back as a tab.
/// </summary>
[Test]
public void ATabInTheIdentityReadsBackExactly()
{
LoggingEventData evt = CreateBaseEvent();
evt.Identity = "alice\tadmin";
using StringWriter writer = new();

new XmlLayout().Format(writer, new LoggingEvent(evt));

string record = writer.ToString();
Assert.That(record, Contains.Substring(" identity=\"alice&#x9;admin\" ").Using(StringComparison.Ordinal));
Assert.That(XmlRecords.AttributeValues(record, "identity"), Is.EqualTo(new[] { "alice\tadmin" }));
}

private string FormatMessage(string message)
{
LoggingEventData evt = CreateBaseEvent();
Expand Down
16 changes: 13 additions & 3 deletions src/log4net.Tests/Layout/XmlRecords.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,20 @@ internal static class XmlRecords
/// <summary>
/// Parses the records and returns the text of the one element named <paramref name="localName"/>.
/// </summary>
/// <remarks>net462 writes the prefixes undeclared, so a wrapper declares them.</remarks>
internal static string ElementText(string records, string localName)
=> XDocument.Parse($"<events xmlns:log4net=\"log4net\" xmlns:log4j=\"log4j\">{records}</events>")
.Descendants().Single(element => element.Name.LocalName == localName).Value;
=> Parse(records).Descendants().Single(element => element.Name.LocalName == localName).Value;

/// <summary>
/// Parses the records and returns the values of every attribute named <paramref name="name"/>.
/// </summary>
internal static string[] AttributeValues(string records, string name)
=> [.. Parse(records).Descendants().Attributes(name).Select(attribute => attribute.Value)];

/// <summary>
/// Parses the records inside a wrapper that declares the prefixes, which net462 writes undeclared.
/// </summary>
private static XDocument Parse(string records)
=> XDocument.Parse($"<events xmlns:log4net=\"log4net\" xmlns:log4j=\"log4j\">{records}</events>");

/// <summary>
/// Returns the content of the one element named <paramref name="localName"/> as written.
Expand Down
1 change: 1 addition & 0 deletions src/log4net/Appender/LocalSyslogAppender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,7 @@ private string[] GetRecords(string message)
{
string[] records = NewLineHandling switch
{
// Empty lines are dropped on purpose, see .oss-scanner/threat_model.md.
SyslogNewLineHandling.Split => Array.ConvertAll(SplitLines(message), line => line.EscapeOtherLineBreaks()),
SyslogNewLineHandling.Keep => [message],
// Escape, also for undefined values.
Expand Down
1 change: 1 addition & 0 deletions src/log4net/Appender/RemoteSyslogAppender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,7 @@ protected override void Append(LoggingEvent loggingEvent)

StringBuilder builder = new();

// An empty render sends no record on purpose, see .oss-scanner/threat_model.md.
while (i < message.Length)
{
// Clear StringBuilder
Expand Down
9 changes: 6 additions & 3 deletions src/log4net/Appender/TelnetAppender.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using log4net.Appender.Internal;
using log4net.Core;
using log4net.Util;

Expand All @@ -52,6 +53,9 @@ namespace log4net.Appender;
/// is not encrypted. Keeping untrusted parties away from the port is the operator's
/// responsibility, exactly as it is for a log file.
/// </para>
/// <para>
/// A NUL character is written as <c>\0</c>, since a Telnet client drops it.
/// </para>
/// </remarks>
/// <author>Keith Long</author>
/// <author>Nicko Cadell</author>
Expand Down Expand Up @@ -293,7 +297,7 @@ protected override void Append(LoggingEvent loggingEvent)
if (_handler is not null && _handler.HasConnections)
{
// Queued, not written: a client that stops reading must not hold up the logging thread.
_sender?.TryEnqueue(RenderLoggingEvent(loggingEvent), EnqueueTimeoutMillis);
_sender?.TryEnqueue(RenderLoggingEvent(loggingEvent).EscapeNulCharacters(), EnqueueTimeoutMillis);
}
}

Expand Down Expand Up @@ -342,8 +346,7 @@ public SocketClient(Socket socket)
_socket = socket;
try
{
// Belt and braces. Send escapes what cannot be encoded; this keeps a future gap costing
// one character rather than failing the write.
// Belt and braces: an unencodable character becomes U+FFFD instead of failing the write.
_writer = new(new NetworkStream(socket), new UTF8Encoding(false));
}
catch (Exception e) when (!e.IsFatal())
Expand Down
Loading
Loading