Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AspNet Request-Ip with support for CheckForwardedForHeaderOffset #923

Merged
merged 5 commits into from
Jan 23, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
44 changes: 38 additions & 6 deletions src/Shared/LayoutRenderers/AspNetRequestIpLayoutRenderer.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using System;
using System.ComponentModel;
using System.ComponentModel;
using System.Text;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Web.Internal;
Expand All @@ -17,7 +15,11 @@ namespace NLog.Web.LayoutRenderers
/// ASP.NET Request IP address of the remote client
/// </summary>
/// <remarks>
/// <code>${aspnet-request-ip}</code>
/// <code>${aspnet-request-ip}</code> to return the Remote IP
/// <code>${aspnet-request-ip:CheckForwardedForHeader=true}</code> to return first element in the X-Forwarded-For header
/// <code>${aspnet-request-ip:CheckForwardedForHeader=true:Index=1}</code> to return second element in the X-Forwarded-For header
/// <code>${aspnet-request-ip:CheckForwardedForHeader=true:Index=-1}</code> to return last element in the X-Forwarded-For header
/// <code>${aspnet-request-ip:CheckForwardedForHeader=true:Index=1:ForwardedForHeader=myHeader}</code> to return second element in the myHeader header
/// </remarks>
/// <seealso href="https://github.com/NLog/NLog/wiki/AspNet-Request-IP-Layout-Renderer">Documentation on NLog Wiki</seealso>
[LayoutRenderer("aspnet-request-ip")]
Expand All @@ -35,6 +37,15 @@ public class AspNetRequestIpLayoutRenderer : AspNetLayoutRendererBase
/// <docgen category='Rendering Options' order='10' />
public bool CheckForwardedForHeader { get; set; }

/// <summary>
/// Gets or sets the array index of the X-Forwarded-For header to use, if the desired client IP is not at
/// the zeroth index. Defaults to zero. If the index is too large the last array element is returned instead.
/// If a negative index is used, this is used as the position from the end of the array.
/// Minus one will indicate the last element in the array. If the negative index is too large the first index
/// of the array is returned instead.
/// </summary>
public int Index { get; set; } = 0;
snakefoot marked this conversation as resolved.
Show resolved Hide resolved

/// <inheritdoc/>
protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
{
Expand All @@ -60,6 +71,25 @@ protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
builder.Append(ip);
}

private int CalculatePosition(string[] headerContents)
{
var position = Index;

if (position < 0)
{
position = headerContents.Length + position;
}
if (position < 0)
{
position = 0;
}
if (position >= headerContents.Length)
{
position = headerContents.Length - 1;
}
return position;
}

#if !ASP_NET_CORE
string TryLookupForwardHeader(HttpRequestBase httpRequest, LogEventInfo logEvent)
{
Expand All @@ -71,7 +101,8 @@ string TryLookupForwardHeader(HttpRequestBase httpRequest, LogEventInfo logEvent
var addresses = forwardedHeader.Split(',');
if (addresses.Length > 0)
{
return addresses[0];
var position = CalculatePosition(addresses);
return addresses[position]?.Trim();
}
}

Expand All @@ -86,7 +117,8 @@ private string TryLookupForwardHeader(HttpRequest httpRequest, LogEventInfo logE
var forwardedHeaders = httpRequest.Headers.GetCommaSeparatedValues(headerName);
if (forwardedHeaders.Length > 0)
{
return forwardedHeaders[0];
var position = CalculatePosition(forwardedHeaders);
return forwardedHeaders[position]?.Trim();
}
}

Expand Down
116 changes: 116 additions & 0 deletions tests/Shared/LayoutRenderers/AspNetRequestIpLayoutRendererTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,5 +116,121 @@ public void ForwardedForHeaderPresentWithCustomRenderForwardedValue()
// Assert
Assert.Equal("127.0.0.1", result);
}

[Fact]
public void ForwardedForHeaderContainsMultipleEntriesRendersIndexValue()
{
// Arrange
var (renderer, httpContext) = CreateWithHttpContext();

#if !ASP_NET_CORE
httpContext.Request.ServerVariables.Returns(new NameValueCollection {{"REMOTE_ADDR", "192.0.0.0"}});
httpContext.Request.Headers.Returns(
new NameValueCollection {{ForwardedForHeader, "192.168.1.1, 127.0.0.1"}});
#else
var headers = new HeaderDict();
headers.Add(ForwardedForHeader, new StringValues("192.168.1.1, 127.0.0.1"));
httpContext.Request.Headers.Returns(callinfo => headers);
#endif
renderer.CheckForwardedForHeader = true;
renderer.Index = 1;

// Act
string result = renderer.Render(new LogEventInfo());

// Assert
Assert.Equal("127.0.0.1", result);
}

[Fact]
public void ForwardedForHeaderContainsMultipleEntriesRendersLastValue()
{
// Arrange
var (renderer, httpContext) = CreateWithHttpContext();

#if !ASP_NET_CORE
httpContext.Request.ServerVariables.Returns(new NameValueCollection {{"REMOTE_ADDR", "192.0.0.0"}});
httpContext.Request.Headers.Returns(
new NameValueCollection {{ForwardedForHeader, "192.168.1.1, 127.0.0.1"}});
#else
var headers = new HeaderDict();
headers.Add(ForwardedForHeader, new StringValues("192.168.1.1, 127.0.0.1"));
httpContext.Request.Headers.Returns(callinfo => headers);
#endif
renderer.CheckForwardedForHeader = true;
renderer.Index = -1;

// Act
string result = renderer.Render(new LogEventInfo());

// Assert
Assert.Equal("127.0.0.1", result);
}

[Fact]
public void ForwardedForHeaderContainsMultipleEntriesExcessiveIndexRendersLastValue()
{
// Arrange
var (renderer, httpContext) = CreateWithHttpContext();

#if !ASP_NET_CORE
httpContext.Request.ServerVariables.Returns(new NameValueCollection {{"REMOTE_ADDR", "192.0.0.0"}});
httpContext.Request.Headers.Returns(
new NameValueCollection {{ForwardedForHeader, "192.168.1.1, 127.0.0.1"}});
#else
var headers = new HeaderDict();
headers.Add(ForwardedForHeader, new StringValues("192.168.1.1, 127.0.0.1"));
httpContext.Request.Headers.Returns(callinfo => headers);
#endif
renderer.CheckForwardedForHeader = true;
renderer.Index = 2;

// Act
string result = renderer.Render(new LogEventInfo());

// Assert
Assert.Equal("127.0.0.1", result);

renderer.Index = 3;

// Act
result = renderer.Render(new LogEventInfo());

// Assert
Assert.Equal("127.0.0.1", result);
}

[Fact]
public void ForwardedForHeaderContainsMultipleEntriesExcessiveNegativeIndexRendersFirstValue()
{
// Arrange
var (renderer, httpContext) = CreateWithHttpContext();

#if !ASP_NET_CORE
httpContext.Request.ServerVariables.Returns(new NameValueCollection {{"REMOTE_ADDR", "192.0.0.0"}});
httpContext.Request.Headers.Returns(
new NameValueCollection {{ForwardedForHeader, "127.0.0.1, 192.168.1.1"}});
#else
var headers = new HeaderDict();
headers.Add(ForwardedForHeader, new StringValues("127.0.0.1, 192.168.1.1"));
httpContext.Request.Headers.Returns(callinfo => headers);
#endif
renderer.CheckForwardedForHeader = true;
renderer.Index = -3;

// Act
string result = renderer.Render(new LogEventInfo());

// Assert
Assert.Equal("127.0.0.1", result);

renderer.Index = -4;

// Act
result = renderer.Render(new LogEventInfo());

// Assert
Assert.Equal("127.0.0.1", result);
}
}
}