From 91b823f9674a445ce3376f8247fa8f8c4415747e Mon Sep 17 00:00:00 2001 From: Jeavon Leopold Date: Thu, 4 Nov 2021 13:12:54 +0000 Subject: [PATCH] When getting users IP address first check HTTP_X_FORWARDED_FOR header to support requests from proxy servers such as Cloudflare --- .../Web/HttpModules/RequestProcessor.cs | 23 ++++++++++++++++++- .../When_Processing_Request.cs | 6 +++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/Cogworks.SiteLock/Web/HttpModules/RequestProcessor.cs b/src/Cogworks.SiteLock/Web/HttpModules/RequestProcessor.cs index 5178940..593bfcf 100644 --- a/src/Cogworks.SiteLock/Web/HttpModules/RequestProcessor.cs +++ b/src/Cogworks.SiteLock/Web/HttpModules/RequestProcessor.cs @@ -25,7 +25,7 @@ public void ProcessRequest(HttpContextBase httpContext) if (RequestHelper.IsLockedDomain(_config, requestUri.Host)) { - if (RequestHelper.IsAllowedIP(_config, httpContext.Request.UserHostAddress)) { return; } + if (RequestHelper.IsAllowedIP(_config, GetUserHostAddress(httpContext))) { return; } if (RequestHelper.IsAllowedReferrerPath(_config, absolutePath, urlReferrer)) { return; } @@ -42,5 +42,26 @@ public void ProcessRequest(HttpContextBase httpContext) } } } + + /// + /// Attempt to get the IP address of the client (as a string) + /// + /// + private static string GetUserHostAddress(HttpContextBase httpContext) + { + string ipAddress = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; + + if (!string.IsNullOrEmpty(ipAddress)) + { + string[] ipAddresses = ipAddress.Split(','); + + if (ipAddresses.Length != 0) + { + return ipAddresses[0]; + } + } + + return httpContext.Request.ServerVariables["REMOTE_ADDR"]; + } } } diff --git a/src/Tests/Cogworks.SiteLock.Test/When_Processing_Request.cs b/src/Tests/Cogworks.SiteLock.Test/When_Processing_Request.cs index c67ffaf..11597a1 100644 --- a/src/Tests/Cogworks.SiteLock.Test/When_Processing_Request.cs +++ b/src/Tests/Cogworks.SiteLock.Test/When_Processing_Request.cs @@ -40,8 +40,10 @@ public When_Processing_Request() _uriStub = new Uri("http://thecogworks.com" + AbsolutePath); _httpRequestMock.Setup(x => x.Url).Returns(_uriStub); - - _httpRequestMock.Setup(x => x.UserHostAddress).Returns("8.8.8.8"); + _httpRequestMock.Setup(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection{ + { "HTTP_X_FORWARDED_FOR", "8.8.8.8, 4.4.4.4:18104" }, + { "REMOTE_ADDR", "8.8.8.8" } + }); _contextMock.Setup(x => x.Request).Returns(_httpRequestMock.Object); _contextMock.Setup(x => x.Response).Returns(_httpResponseMock.Object);