C#

Protecting Against DDoS Attacks: Best Practices for Securing Your API

In this article we will learn about DDoS attack and its prevention using .NET core

In today's digital landscape, securing your API against DDoS attacks is crucial to ensure the availability and reliability of your services. With the increasing frequency and sophistication of DDoS attacks, it's essential to implement best practices to protect your API from potential threats.


Understanding DDoS Attacks

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.

DDoS (Distributed Denial of Service) attacks are malicious attempts to disrupt the normal traffic of a targeted server, service, or network by overwhelming it with a flood of internet traffic. These attacks can lead to downtime, performance issues, and potential data breaches, making them a significant threat to API security.

Symptoms of DDoS attack : How to identify if Server having such attack.

If 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

1. 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

1 .Create Web api .net core project

2. 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 and Execution

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(); }


Understanding of above code

Above code contains loop for making api calls for 21 times.

we are logging Console.WriteLine(“Getting response from server ->” + i.ToString());


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;


2. 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(); }




There are various types of DDoS attacks, including:

  • Syn Flood
  • UDP Flood
  • HTTP Flood
  • ICMP Flood

Best Practices for Securing Your API

Implementing the following best practices can help defend your API against DDoS attacks:

1. Use DDoS Protection Services

Consider using DDoS protection services that can detect and mitigate attacks in real-time, safeguarding your API from potential threats.

2. Implement Rate Limiting

Set rate limits on your API endpoints to prevent abuse and limit the number of requests from a single source, reducing the impact of potential DDoS attacks.

3. Monitor Traffic Patterns

Regularly monitor your API traffic patterns to detect any unusual spikes or anomalies that could indicate a DDoS attack in progress.

4. Secure Your Infrastructure

Ensure that your server infrastructure is secure by applying the latest security patches, using firewalls, and implementing encryption protocols to protect your API endpoints.

Frequently Asked Questions

Q: What is the impact of a DDoS attack on an API?

A: A DDoS attack can disrupt the availability and performance of an API, leading to downtime and potential data breaches.

Q: How can I protect my API from DDoS attacks?

A: Implementing DDoS protection services, rate limiting, monitoring traffic patterns, and securing your infrastructure are key steps to defend your API against DDoS attacks.

Conclusion

Securing your API against DDoS attacks is essential to maintain the integrity and availability of your services. By following best practices and staying vigilant against potential threats, you can protect your API from malicious attacks and ensure a seamless user experience for your customers.

line

Copyrights © 2024 letsupdateskills All rights reserved