Skip to content

Commit

Permalink
Fixed LoadLibrary and updated FormatDescription to use the event temp…
Browse files Browse the repository at this point in the history
…late to determine what to display as hex (#343)

Resolves #336 and #334
  • Loading branch information
jschick04 authored May 9, 2024
1 parent dced7da commit 09d8582
Show file tree
Hide file tree
Showing 2 changed files with 123 additions and 78 deletions.
198 changes: 121 additions & 77 deletions src/EventLogExpert.Eventing/EventResolvers/EventResolverBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
using EventLogExpert.Eventing.Providers;
using Microsoft.Extensions.Logging;
using System.Diagnostics.Eventing.Reader;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace EventLogExpert.Eventing.EventResolvers;

Expand All @@ -29,9 +31,29 @@ public partial class EventResolverBase
{ 0x80000000000000, "Classic" }
};

/// <summary>
/// The mappings from the outType attribute in the EventModel XML template
/// to determine if it should be displayed as Hex.
/// </summary>
private static readonly Dictionary<string, bool> XmlHexMappings = new()
{
{ "win:HexInt32", true },
{ "win:HexInt64", true },
{ "win:Pointer", true },
{ "win:SID", false },
{ "win:UnicodeString", false },
{ "win:Win32Error", true },
{ "xs:dateTime", false },
{ "xs:GUID", false },
{ "xs:string", false },
{ "xs:unsignedByte", true },
{ "xs:unsignedInt", false },
{ "xs:unsignedLong", false }
};

protected readonly Action<string, LogLevel> _tracer;

private readonly Regex _formatRegex = RegexFormatter();
private readonly Regex _sectionsToReplace = WildcardWithNumberRegex();

protected EventResolverBase(Action<string, LogLevel> tracer)
{
Expand Down Expand Up @@ -68,7 +90,7 @@ protected static IEnumerable<string> GetKeywordsFromBitmask(long? bitmask, Provi
}

protected string? FormatDescription(
IList<EventProperty> properties,
List<string> properties,
string? descriptionTemplate,
List<MessageModel> parameters)
{
Expand All @@ -79,96 +101,71 @@ protected static IEnumerable<string> GetKeywordsFromBitmask(long? bitmask, Provi
.Replace("%n\r\n", "\r\n ")
.Replace("%n", "\r\n");

var matches = _formatRegex.Matches(description);
var matches = _sectionsToReplace.Matches(description);

if (matches.Count > 0)
if (matches.Count <= 0)
{
try
{
var sb = new StringBuilder();
var lastIndex = 0;
var anyParameterStrings = parameters.Count <= 0;

for (var i = 0; i < matches.Count; i++)
{
if (matches[i].Value.StartsWith("%%"))
{
// The % is escaped, so skip it.
continue;
}

sb.Append(description.AsSpan(lastIndex, matches[i].Index - lastIndex));
var propIndex = int.Parse(matches[i].Value.Trim(['{', '}', '%']));
return description.TrimEnd(['\r', '\n']);
}

if (propIndex - 1 >= properties.Count) { return null; }
try
{
var sb = new StringBuilder();
var lastIndex = 0;

var valueFormatted = false;
var propValue = properties[propIndex - 1].Value;
for (var i = 0; i < matches.Count; i++)
{
if (matches[i].Value.StartsWith("%%"))
{
// The % is escaped, so skip it.
continue;
}

if (propValue is DateTime eventTime)
{
// Exactly match the format produced by EventRecord.FormatMessage().
// I have no idea why it includes Unicode LRM marks, but it does.
sb.Append(eventTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffff00K"));
valueFormatted = true;
}
else if (anyParameterStrings && propValue is string propString && propString.StartsWith("%%"))
{
var endParameterId = propString.IndexOf(' ');
var parameterIdString = endParameterId > 2 ? propString[2..endParameterId] : propString[2..];
sb.Append(description.AsSpan(lastIndex, matches[i].Index - lastIndex));
var propIndex = int.Parse(matches[i].Value.Trim(['{', '}', '%']));

if (int.TryParse(parameterIdString, out var parameterId))
{
var parameterMessage = parameters.FirstOrDefault(m => m.ShortId == parameterId);
if (propIndex - 1 >= properties.Count) { return null; }

if (parameterMessage != null)
{
propString = endParameterId > 2 ?
parameterMessage.Text + propString[++endParameterId..] :
parameterMessage.Text;
var propString = properties[propIndex - 1];

sb.Append(propString);
valueFormatted = true;
}
}
}
if (propString.StartsWith("%%") && parameters.Count > 0)
{
var endParameterId = propString.IndexOf(' ');
var parameterIdString = endParameterId > 2 ? propString[2..endParameterId] : propString[2..];

if (!valueFormatted)
if (int.TryParse(parameterIdString, out var parameterId))
{
if (propValue is byte[] bytes)
{
sb.Append(Convert.ToHexString(bytes));
}
else
var parameterMessage = parameters.FirstOrDefault(m => m.ShortId == parameterId);

if (parameterMessage != null)
{
sb.Append(propValue);
propString = endParameterId > 2 ?
parameterMessage.Text.TrimEnd(['\r', '\n']) + propString[++endParameterId..] :
parameterMessage.Text.TrimEnd(['\r', '\n']);
}
}

lastIndex = matches[i].Index + matches[i].Length;
}

if (lastIndex < description.Length)
{
sb.Append(description[lastIndex..]);
}
sb.Append(propString);

description = sb.ToString();
lastIndex = matches[i].Index + matches[i].Length;
}
catch (Exception ex)
{
_tracer($"FormatDescription exception was caught: {ex}", LogLevel.Information);

return null;
if (lastIndex < description.Length)
{
sb.Append(description[lastIndex..]);
}
}

while (description.EndsWith("\r\n"))
description = sb.ToString();
}
catch (Exception ex)
{
description = description.Remove(description.Length - "\r\n".Length);
_tracer($"FormatDescription exception was caught: {ex}", LogLevel.Information);

return null;
}

return description;
return description.TrimEnd(['\r', '\n']);
}

/// <summary>Resolve event descriptions from a provider.</summary>
Expand All @@ -189,7 +186,6 @@ protected DisplayEventModel ResolveFromProviderDetails(
{
string? description = null;
string? taskName = null;
string? template = null;

if (eventRecord is { Version: not null, LogName: not null })
{
Expand Down Expand Up @@ -224,6 +220,8 @@ protected DisplayEventModel ResolveFromProviderDetails(

providerDetails.Tasks.TryGetValue(e.Task, out taskName);

var properties = GetFormattedProperties(e.Template, eventProperties);

// If we don't have a description
if (string.IsNullOrEmpty(e.Description))
{
Expand All @@ -243,17 +241,15 @@ protected DisplayEventModel ResolveFromProviderDetails(
}
else
{
description = FormatDescription(eventProperties, e.Description, providerDetails.Parameters);
description = FormatDescription(properties, e.Description, providerDetails.Parameters);
}

template = e.Template;
}
}

if (description == null)
{
description = providerDetails.Messages?.FirstOrDefault(m => m.ShortId == eventRecord.Id)?.Text;
description = FormatDescription(eventProperties, description, providerDetails.Parameters);
var properties = GetFormattedProperties(null, eventProperties);
description = FormatDescription(properties, providerDetails.Messages.FirstOrDefault(m => m.ShortId == eventRecord.Id)?.Text, providerDetails.Parameters);
}

if (taskName == null && eventRecord.Task.HasValue)
Expand All @@ -262,7 +258,7 @@ protected DisplayEventModel ResolveFromProviderDetails(

if (taskName == null)
{
var potentialTaskNames = providerDetails.Messages?
var potentialTaskNames = providerDetails.Messages
.Where(m => m.ShortId == eventRecord.Task && m.LogLink != null && m.LogLink == eventRecord.LogName)
.ToList();

Expand Down Expand Up @@ -305,6 +301,54 @@ protected DisplayEventModel ResolveFromProviderDetails(
eventRecord.ToXml());
}

private static List<string> GetFormattedProperties(string? template, IList<EventProperty> properties)
{
List<string> providers = [];
XmlNodeList? dataNodes = null;

if (!string.IsNullOrWhiteSpace(template))
{
XmlDocument xml = new();
xml.LoadXml(template);

// Select all the 'data' nodes in the XML
dataNodes = xml.SelectNodes("/*/*");
}

for (int i = 0; i < properties.Count; i++)
{
string? outType = dataNodes?[i]?.Attributes?["outType"]?.Value;

switch (properties[i].Value)
{
case DateTime eventTime:
// Exactly match the format produced by EventRecord.FormatMessage().
// I have no idea why it includes Unicode LRM marks, but it does.
providers.Add(eventTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffff00K"));
continue;
case byte[] bytes:
providers.Add(Convert.ToHexString(bytes));
continue;
case SecurityIdentifier sid:
providers.Add(sid.Value);
continue;
default:
if (!string.IsNullOrEmpty(outType) && XmlHexMappings.TryGetValue(outType, out bool isHex))
{
providers.Add(isHex ? $"0x{properties[i].Value:X}" : $"{properties[i].Value}");
}
else
{
providers.Add($"{properties[i].Value}");
}

continue;
}
}

return providers;
}

[GeneratedRegex("%+[0-9]+")]
private static partial Regex RegexFormatter();
private static partial Regex WildcardWithNumberRegex();
}
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,8 @@ public static List<MessageModel> GetMessages(IEnumerable<string> legacyProviderF
* issue.
*/

hModule = NativeMethods.LoadLibraryEx(file, nint.Zero, NativeMethods.LoadLibraryFlags.LOAD_LIBRARY_AS_DATAFILE);
// Splitting file path because this will not resolve %systemroot% and will instead try to use drive:\windows\%systemroot%\system32\...
hModule = NativeMethods.LoadLibraryEx(file.Split("\\").Last(), nint.Zero, NativeMethods.LoadLibraryFlags.LOAD_LIBRARY_AS_DATAFILE);

// TODO: Evaulate if there's any need to EnumResourceTypes.
// This is an alternative approach to FindResource. Leaving it here until we're sure FindResource is good enough.
Expand Down

0 comments on commit 09d8582

Please sign in to comment.