Cleanse remote IP Address from trace log file

This commit is contained in:
Taloth Saldono 2020-06-02 20:54:22 +02:00 committed by Qstick
parent cc974574b2
commit 312c3b786e
2 changed files with 46 additions and 1 deletions

View File

@ -54,5 +54,26 @@ namespace NzbDrone.Common.Test.InstrumentationTests
cleansedMessage.Should().NotContain("mySecret");
cleansedMessage.Should().NotContain("01233210");
}
[TestCase(@"Some message (from 32.2.3.5 user agent)")]
[TestCase(@"Auth-Invalidated ip 32.2.3.5")]
[TestCase(@"Auth-Success ip 32.2.3.5")]
[TestCase(@"Auth-Logout ip 32.2.3.5")]
public void should_clean_ipaddress(string message)
{
var cleansedMessage = CleanseLogMessage.Cleanse(message);
cleansedMessage.Should().NotContain(".2.3.");
}
[TestCase(@"Some message (from 10.2.3.2 user agent)")]
[TestCase(@"Auth-Unauthorized ip 32.2.3.5")]
[TestCase(@"Auth-Failure ip 32.2.3.5")]
public void should_not_clean_ipaddress(string message)
{
var cleansedMessage = CleanseLogMessage.Cleanse(message);
cleansedMessage.Should().Be(message);
}
}
}

View File

@ -1,4 +1,6 @@
using System.Linq;
using System;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using NzbDrone.Common.Extensions;
@ -41,6 +43,8 @@ namespace NzbDrone.Common.Instrumentation
new Regex(@"(?<=\?|&)(authkey|torrent_pass)=(?<secret>[^&=]+?)(?=""|&|$)", RegexOptions.Compiled | RegexOptions.IgnoreCase)
};
private static readonly Regex CleanseRemoteIPRegex = new Regex(@"(?:Auth-\w+(?<!Failure|Unauthorized) ip|from) (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", RegexOptions.Compiled);
public static string Cleanse(string message)
{
if (message.IsNullOrWhiteSpace())
@ -62,7 +66,27 @@ namespace NzbDrone.Common.Instrumentation
});
}
message = CleanseRemoteIPRegex.Replace(message, CleanseRemoteIP);
return message;
}
private static string CleanseRemoteIP(Match match)
{
var group = match.Groups[1];
var valueAll = match.Value;
var valueIP = group.Value;
if (IPAddress.TryParse(valueIP, out var address) && !address.IsLocalAddress())
{
var prefix = match.Value.Substring(0, group.Index - match.Index);
var postfix = match.Value.Substring(group.Index + group.Length - match.Index);
var items = valueIP.Split('.');
return $"{prefix}{items[0]}.*.*.{items[0]}{postfix}";
}
return match.Value;
}
}
}