In this article we will learn about DDoS attack and its prevention using .NET core
What is a DDoS (Distributed Denial of Service (DDoS) attack?
When there are millions of requests sent to particular server or set of servers so that server become busy to serve the request, in other words making server overloaded via sending false or malicious requests. Result of this attack is to make server unavailable to serve request and then server becomes unavailable.
A DDoS attack aims to disable or take down a web site, web application, cloud service or other online resource by overwhelming it with pointless connection requests, fake packets or other malicious traffic.
How to identify if Server having such attack.
Symptom of a DDoS attack is a site or service suddenly becoming slow or unavailable, in this case further investigation is required to see if there is suspicious traffic or web server have genuine traffic.
a. It is required to check logs and traffic analytic tools which can be used to see IP address of sources
b. If traffic originating from a single IP address or IP range then this must be DDoS
c. Odd traffic patterns such as spikes at odd hours of the day or patterns that appear to be unnatural (e.g. a spike every 10 minutes)
Solution
- Prevention Technique : Rate Limiter At application level if we want to restrict traffic to application, we can use Rate Limiter in .Net core
In this example we will configure our service to accept only 20 request per second and after that it will reject to accept any requests.
Steps
a.** Create Web api .net core project**
This is default template and contains Weather controller.
b. Program .cs -> Add below code
`builder.Services.AddRateLimiter(options => {
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext => RateLimitPartition.GetFixedWindowLimiter(partitionKey: httpContext.User.Identity?.Name ?? httpContext.Request.Headers.Host.ToString(), factory: partition => new FixedWindowRateLimiterOptions
{
AutoReplenishment = true,
PermitLimit = 20,
QueueLimit = 0,
Window = TimeSpan.FromMinutes(1)
}));
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseRateLimiter();
app.MapControllers();
app.Run();`
Understanding builder.Services.AddRateLimiter
The method is used to configure and register the rate limiter service with the application’s service container. Once added to the application, the rate limiter can be used to control access to certain routes or endpoints, ensuring that they are not overwhelmed by too many requests.
Now if we want to set a global rate limiter for all requests GlobalLimiter option is set to any PartitionedRateLimiter. In the above example, we have added a FixedWindowLimiter, and configured it to apply “per authenticated username (or hostname if not authenticated)” — the partition. The FixedWindowLimiter is then configured to automatically replenish permitted requests and permits 20 requests per minute.
Testing
I have created console application which is making http requests to weather API
// See https://aka.ms/new-console-template for more information
using System.Text.Json;
Console.WriteLine("Making connections....!");
var apiUrl = "https://localhost:44316/WeatherForecast"; // Example API endpoint
using var client = new HttpClient();
try
{
for (int i = 0; i < 21; i++)
{
// Making the GET request
var response = await client.GetAsync(apiUrl);
// Ensure the request was successful
response.EnsureSuccessStatusCode();
// Read the response content as a string
var content = await response.Content.ReadAsStringAsync();
if(content!=null && content.Length>0)
Console.WriteLine("Getting response from server ->" + i.ToString());
}
}
catch (Exception e)
{
Console.WriteLine($"Request error: {e.Message}");
Console.ReadKey();
}
Above code contains loop for making api calls for 21 times.
we are logging Console.WriteLine(“Getting response from server ->” + i.ToString());
- Above code is making http calls api
var apiUrl = "https://localhost:44316/WeatherForecast"; //
Running application
API
Console : we can see requests are getting response till 19 and get exception after 19.
Specific error code: we can add below code and can get specifc exception.
options.RejectionStatusCode = 429;
We have multiple ways to implement ratelimiter and have below types, but all those i will be explananing into seprate article
- Prevention Technique: IP Blocking and Geo-Blocking: If we know range of IP’s from where we are getting attacks, we can restrict specific IP address. we can use below approach in .net core
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Use(async (context, next) =>
{
var ipAddress = context.Connection.RemoteIpAddress.ToString();
if (ipAddress == "blocked_ip")
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Forbidden");
}
else
{
await next.Invoke();
}
});
app.UseMvc();
}
Prevention Technique: Monitoring and Alerting
We should keep tracing logs using Application Insights to see if we have lot of requests are coming from suspicious IP’s
Set up alerts for unusual traffic patterns.Prevention Technique: Throttling and Circuit Breaker Patterns
Implement throttling to control the usage of resources.
Use libraries like Polly for resilience and transient fault handling.
var circuitBreaker = Policy.Handle<Exception>()
.CircuitBreakerAsync(2, TimeSpan.FromMinutes(1));
- Prevention Technique: Caching DDoS can also happen in case of real traffic, in case of Ecom site like Flipkart, Amazon have huge traffic during sale and if we keep posting request to servers then servers can be busy and result of DDoS.
in this case we can at least if apply cache for frequently used data or data from master tables we can limit number of requests to server.
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCaching();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseResponseCaching();
app.UseMvc();
}
[HttpGet]
[ResponseCache(Duration = 60)]
public IActionResult Get()
{
return Ok("This response is cached for 60 seconds.");
}
- Prevention Technique: Network Level , Load Balancers and Firewall's DDoS can also happen in case of real traffic, in case of Ecom site like Flipkart, Amazon have huge traffic during sale and if we keep posting request to servers then servers can be busy and result of DDoS
We can use Azure Load Balancer or AWS Elastic Load Balancing (ELB) to distrubute load to multiple servers.
In case of False traffic or malicious traffic we can implement rules at network level here we can add such rules which can filter range of IP’s and also divert IP address to multiple servers.
Conclusion
We have covered What is DDoS and multiple ways to prevent.
Thanks
Follow me on https://medium.com/@devesh.akgec
Top comments (0)