2019-02-12 21:34:29 -05:00
|
|
|
|
using Microsoft.AspNetCore.Http;
|
2020-01-17 18:31:53 -05:00
|
|
|
|
using SharedLibraryCore.Interfaces;
|
2019-02-12 21:34:29 -05:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace WebfrontCore.Middleware
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Defines the middleware functioning to whitelist connection from
|
|
|
|
|
/// a set of IP Addresses
|
|
|
|
|
/// </summary>
|
|
|
|
|
internal sealed class IPWhitelist
|
|
|
|
|
{
|
2020-01-17 18:31:53 -05:00
|
|
|
|
private readonly byte[][] _whitelistedIps;
|
|
|
|
|
private readonly RequestDelegate _nextRequest;
|
|
|
|
|
private readonly ILogger _logger;
|
2019-02-12 21:34:29 -05:00
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// constructor
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="nextRequest"></param>
|
|
|
|
|
/// <param name="whitelistedIps">list of textual ip addresses</param>
|
2020-01-17 18:31:53 -05:00
|
|
|
|
public IPWhitelist(RequestDelegate nextRequest, ILogger logger, string[] whitelistedIps)
|
2019-02-12 21:34:29 -05:00
|
|
|
|
{
|
2020-01-17 18:31:53 -05:00
|
|
|
|
_whitelistedIps = whitelistedIps.Select(_ip => System.Net.IPAddress.Parse(_ip).GetAddressBytes()).ToArray();
|
|
|
|
|
_nextRequest = nextRequest;
|
|
|
|
|
_logger = logger;
|
2019-02-12 21:34:29 -05:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task Invoke(HttpContext context)
|
|
|
|
|
{
|
2020-01-17 18:31:53 -05:00
|
|
|
|
bool isAlllowed = true;
|
|
|
|
|
|
|
|
|
|
if (_whitelistedIps.Length > 0)
|
|
|
|
|
{
|
|
|
|
|
isAlllowed = _whitelistedIps.Any(_ip => _ip.SequenceEqual(context.Connection.RemoteIpAddress.GetAddressBytes()));
|
|
|
|
|
}
|
2019-02-12 21:34:29 -05:00
|
|
|
|
|
|
|
|
|
if (isAlllowed)
|
|
|
|
|
{
|
2020-01-17 18:31:53 -05:00
|
|
|
|
await _nextRequest.Invoke(context);
|
2019-02-12 21:34:29 -05:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
else
|
|
|
|
|
{
|
2020-01-17 18:31:53 -05:00
|
|
|
|
_logger.WriteInfo($"Blocking HTTP request from {context.Connection.RemoteIpAddress.ToString()}");
|
2019-02-12 21:34:29 -05:00
|
|
|
|
context.Abort();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|