/
ClientIpCheckPageFilter.cs
67 lines (59 loc) · 1.88 KB
/
ClientIpCheckPageFilter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System.Net;
namespace ClientIpSafelistComponents.Filters
{
#region snippet_ClassOnly
public class ClientIpCheckPageFilter : IPageFilter
{
private readonly ILogger _logger;
private readonly IPAddress[] _safelist;
public ClientIpCheckPageFilter(
string safelist,
ILogger logger)
{
var ips = safelist.Split(';');
_safelist = new IPAddress[ips.Length];
for (var i = 0; i < ips.Length; i++)
{
_safelist[i] = IPAddress.Parse(ips[i]);
}
_logger = logger;
}
public void OnPageHandlerExecuting(PageHandlerExecutingContext context)
{
var remoteIp = context.HttpContext.Connection.RemoteIpAddress;
if (remoteIp.IsIPv4MappedToIPv6)
{
remoteIp = remoteIp.MapToIPv4();
}
_logger.LogDebug(
"Remote IpAddress: {RemoteIp}", remoteIp);
var badIp = true;
foreach (var testIp in _safelist)
{
if (testIp.Equals(remoteIp))
{
badIp = false;
break;
}
}
if (badIp)
{
_logger.LogWarning(
"Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);
context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
return;
}
}
public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
{
}
public void OnPageHandlerSelected(PageHandlerSelectedContext context)
{
}
}
#endregion snippet_ClassOnly
}