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

${AspNetRequestIp} added CheckForwardedForHeader to check for X-Forwarded-For header #325

Merged
merged 5 commits into from
Oct 31, 2018
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Globalization;

#if !ASP_NET_CORE
using System.Web;
using System.Web.Routing;
using System.Collections.Specialized;
using System.Web.SessionState;
#else
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using HttpContextBase = Microsoft.AspNetCore.Http.HttpContext;
#endif
using NLog.Web.LayoutRenderers;
using NSubstitute;
using Xunit;
using System.Net;

namespace NLog.Web.Tests.LayoutRenderers
{
public class AspNetRequestIpLayoutRendererTests : TestBase
{
private const string ForwardedForHeader = "X-Forwarded-For";

[Fact]
public void ForwardedForHeaderNotPresentRenderRemoteAddress()
{
var httpContext = Substitute.For<HttpContextBase>();
#if !ASP_NET_CORE
httpContext.Request.ServerVariables.Returns(new NameValueCollection {{"REMOTE_ADDR", "192.0.0.0"}});
httpContext.Request.Headers.Returns(new NameValueCollection());
#else
var headers = new HeaderDict();
httpContext.Request.Headers.Returns(callinfo => headers);
httpContext.Connection.RemoteIpAddress.Returns(callinfo => IPAddress.Parse("192.0.0.0"));
#endif
var renderer = new AspNetRequestIpLayoutRenderer {CheckForwardedForHeader = true};
renderer.HttpContextAccessor = new FakeHttpContextAccessor(httpContext);

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

Assert.Equal("192.0.0.0", result);
}

[Fact]
public void ForwardedForHeaderPresentRenderForwardedValue()
{
var httpContext = Substitute.For<HttpContextBase>();
#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"}});
#else
var headers = new HeaderDict();
headers.Add(ForwardedForHeader, new StringValues("127.0.0.1"));
httpContext.Request.Headers.Returns(callinfo => headers);
#endif
var renderer = new AspNetRequestIpLayoutRenderer {CheckForwardedForHeader = true};
renderer.HttpContextAccessor = new FakeHttpContextAccessor(httpContext);

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

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

[Fact]
public void ForwardedForHeaderContainsMultipleEntriesRenderFirstValue()
{
var httpContext = Substitute.For<HttpContextBase>();
#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
var renderer = new AspNetRequestIpLayoutRenderer {CheckForwardedForHeader = true};
renderer.HttpContextAccessor = new FakeHttpContextAccessor(httpContext);

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

Assert.Equal("127.0.0.1", result);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using System;
using System.Text;
#if ASP_NET_CORE
using Microsoft.AspNetCore.Http;
#endif
using NLog.LayoutRenderers;
using NLog.Web.Internal;

Expand All @@ -16,18 +19,72 @@ namespace NLog.Web.LayoutRenderers
[LayoutRenderer("aspnet-request-ip")]
public class AspNetRequestIpLayoutRenderer : AspNetLayoutRendererBase
{
private const string ForwardedForHeader = "X-Forwarded-For";

/// <summary>
/// Gets or sets whether the renderer should check value of X-Forwarded-For header
/// </summary>
/// <docgen category='Rendering Options' order='10' />
public bool CheckForwardedForHeader { get; set; }

/// <summary>
/// Render IP
/// </summary>
protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
{
var httpContext = HttpContextAccessor.HttpContext;

var request = httpContext.TryGetRequest();
if (request == null)
{
return;
}

var ip = CheckForwardedForHeader ? TryLookupForwardHeader(request) : string.Empty;

if (string.IsNullOrEmpty(ip))
{
#if !ASP_NET_CORE
var ip = httpContext.TryGetRequest()?.ServerVariables["REMOTE_ADDR"];
ip = request.ServerVariables["REMOTE_ADDR"];
#else
var ip = httpContext.Connection?.RemoteIpAddress;
ip = httpContext.Connection?.RemoteIpAddress?.ToString();
#endif
}

builder.Append(ip);
}

#if !ASP_NET_CORE
string TryLookupForwardHeader(System.Web.HttpRequestBase httpRequest)
{
var forwardedHeader = httpRequest.Headers[ForwardedForHeader];

if (!string.IsNullOrEmpty(forwardedHeader))
{
var addresses = forwardedHeader.Split(',');
if (addresses.Length > 0)
{
return addresses[0];
}
}

return string.Empty;
}
#else
string TryLookupForwardHeader(HttpRequest httpRequest)
{
if (httpRequest.Headers.ContainsKey(ForwardedForHeader))
{
var forwardedHeaders = httpRequest.Headers.GetCommaSeparatedValues(ForwardedForHeader);

if (forwardedHeaders.Length > 0)
{
return forwardedHeaders[0];
}
}

return string.Empty;
}
#endif
}
}
3 changes: 3 additions & 0 deletions NLog.Web.Tests/NLog.Web.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,9 @@
<Compile Include="..\NLog.Web.AspNetCore.Tests\LayoutRenderers\AspNetRequestFormLayoutRendererTests.cs">
<Link>AspNetRequestFormLayoutRendererTests.cs</Link>
</Compile>
<Compile Include="..\NLog.Web.AspNetCore.Tests\LayoutRenderers\AspNetRequestIpLayoutRendererTests.cs">
<Link>AspNetRequestIpLayoutRendererTests.cs</Link>
</Compile>
<Compile Include="..\NLog.Web.AspNetCore.Tests\LayoutRenderers\AspNetRequestValueLayoutRendererTests.cs" />
<Compile Include="..\NLog.Web.AspNetCore.Tests\LayoutRenderers\AspNetSessionIDLayoutRendererTests.cs" />
<Compile Include="..\NLog.Web.AspNetCore.Tests\LayoutRenderers\AspNetSessionValueLayoutRendererTests.cs" />
Expand Down