In today's web applications, security is paramount. One effective method to bolster security is to implement a client IP safelist, which ensures that only requests from trusted IP addresses are processed. In this article, we'll walk you through creating a middleware in ASP.NET Core to enforce an IP safelist, enhancing your application's security.
What is an IP Safelist?
An IP safelist (also known as an IP whitelist) is a list of trusted IP addresses that are allowed to access certain parts of your application. By filtering incoming requests based on their IP addresses, you can prevent unauthorized access from untrusted sources.
Why use an IP Safelist?
- Enhanced Security: Restricting access to known IP addresses helps protect sensitive data and endpoints.
- Control Access: Manage who can access your application, especially useful for internal tools or administrative interfaces.
- Reduce Attack Surface: Limiting access to specific IPs can reduce the risk of brute force attacks and unauthorized access.
Implementing IP Safelist Middleware in .NET
In the sample app, the IP address safelist is.
{
"AdminSafeList": "127.0.0.1;192.168.1.5;::1",
"Logging": {
In the preceding example, the IPv4 addresses of 127.0.0.1 and 192.168.1.5 and the IPv6 loopback address of :1 (compressed format for ;0:0:0:0:0:0:0:1) are allowed.
Middleware
The Startup. The Configure method adds the custom AdminSafeListMiddleware middleware type to the app's request pipeline.
The safelist is retrieved with the .NET Core configuration provider and is passed as a constructor parameter.
app.UseMiddleware<AdminSafeListMiddleware>(Configuration["AdminSafeList"]);
The middleware parses the string into an array and searches for the remote IP address in the array. If the remote IP address isn't found, the middleware returns HTTP 403 Forbidden. This validation process is bypassed for HTTP GET requests.
public class AdminSafeListMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<AdminSafeListMiddleware> _logger;
private readonly byte[][] _safelist;
public AdminSafeListMiddleware(
RequestDelegate next,
ILogger<AdminSafeListMiddleware> logger,
string safelist)
{
var ips = safelist.Split(';');
_safelist = new byte[ips.Length][];
for (var i = 0; i < ips.Length; i++)
{
_safelist[i] = IPAddress.Parse(ips[i]).GetAddressBytes();
}
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Method != HttpMethod.Get.Method)
{
var remoteIp = context.Connection.RemoteIpAddress;
_logger.LogDebug("Request from Remote IP address: {RemoteIp}", remoteIp);
var bytes = remoteIp.GetAddressBytes();
var badIp = true;
foreach (var address in _safelist)
{
if (address.SequenceEqual(bytes))
{
badIp = false;
break;
}
}
if (badIp)
{
_logger.LogWarning("Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
return;
}
}
await _next.Invoke(context);
}
}
Testing the Middleware
Run your application and make requests from different IP addresses. Requests from IPs not in the safelist should receive a "403 Forbidden" response.
Benefits of using an IP Safelist
- Enhanced Security: By filtering requests based on IP addresses, you significantly reduce the likelihood of unauthorized access. This is especially useful for administrative interfaces or sensitive data endpoints.
- Simple Implementation: The middleware approach makes it easy to integrate IP filtering into your existing ASP.NET Core application with minimal changes to your codebase.
- Scalability: You can easily manage and update the safelist without modifying your core application logic. Simply update the list of trusted IPs to reflect new requirements or changes.
Conclusion
Implementing a client IP safelist in ASP.NET Core is a straightforward and effective way to enhance the security of your web applications. By following the steps outlined above, you can ensure that only trusted IP addresses are granted access, protecting your application from unauthorized users.
Protect your application with this simple yet powerful technique and stay ahead in the game of web security!