Simple server protection from DDoS

DDoS (Distributed Denial of Service) — is an attack where your server or website is flooded with a huge number of requests from multiple devices at the same time. Imagine, it's like having thousands of visitors trying to enter your small cafe with 10 tables at the same time - you simply don't have enough resources to serve them all. And your regular customers won't even be able to get to the door!

By the way, a brief summary of how Dos differs from DDoS:
DoS (Denial of Service) — is an attack when a single attacker or program attempts to overload a server, website, or online service to make it unavailable to normal users.

DoS (Distributed Denial of Service) — is a larger version of DoS. In this case, the attack does not come from a single source, but from multiple devices at the same time. These devices are often infected with malware and controlled by the attacker.

In DDoS attacks, attackers typically control a number of infected computers or devices (called botnets) and use them to send a large number of false requests to a target server or network, causing resources (such as bandwidth, CPU, memory) to be exhausted and the server to be unable to respond to normal user requests

As a result of such an attack, the resource becomes unavailable to users, crashes, or significantly reduces its normal performance

Can you avoid or protect against this type of attack? The answer is yes, you can.

And although it may not be easy or costly to provide real full-fledged DDoS protection, we will tell you about the simplest ways to protect yourself. In many cases, it may be enough to fend off simple attacks from intruders on the network.

Using Nginx to prevent DDOS attacks

The NGINX web server has a number of anti-DDoS tools, and its security capabilities can be extended through configuration and third-party modules. While NGINX itself is not a specialized firewall or security tool, when combined with certain configurations it can effectively mitigate and counter common DDoS attacks.

Setting limits on requests and connections

NGINX provides several built-in modules that can limit the number of client connections and frequency of requests, thereby reducing the number of requests initiated by a particular IP address or user in a short period of time, easing the pressure of DDoS attacks.

Restriction of connection speed

The `limit_conn` module allows you to limit the number of connections established by each IP simultaneously. This is very effective in preventing attacks with a large number of invalid connections (e.g. SYN Flood).

http {
    # Define the shared memory area for storing the IP address and number of connections
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
    
    server {
        listen 80;
        server_name example.com;
        
        # Limit the maximum number of connections per IP address
        limit_conn conn_limit 10;

        location / {
            # Routine request processing
        }
    }
}

In the above configuration, `limit_conn_zone` defines a shared memory zone to hold the number of connections of an IP address, and `limit_conn` limits each IP address to a maximum of 10 connections at a time.

Limiting the speed of queries

http {
    # Determine the shared memory area for storing query rate information
    limit_req_zone $binary_remote_addr zone=req_limit:10m rate=5r/s;
    
    server {
        listen 80;
        server_name example.com;
        
        # Limit up to 5 requests per second per IP address
        limit_req zone=req_limit burst=10 nodelay;

        location / {
            # Routine request processing
        }
    }
}

In this configuration, `limit_req_zone` defines the request rate limiting zone and sets a maximum of 5 requests per second for each IP address. If the number of requests exceeds this value, NGINX will discard or delay too many requests.

Blacklisting and whitelisting

NGINX allows you to control access based on IP addresses. With the `ngx_http_access_module` you can easily block (blacklist) or allow access (whitelist) to specific IP addresses. This is very effective for dealing with small DDoS attacks or malicious requests from specific IP addresses.

Blacklist Configuration
server {
    listen 80;
    server_name example.com;
    
    # Blocking access to an IP address
    deny 192.168.1.1;
    
    # Blocking access to an IP segment
    deny 192.168.1.0/24;

    location / {
        # Routine request processing
    }
}
Customizing whitelists

If you only allow certain IP addresses to access the service, you can use the `allow` directive and combine it with `deny all` to implement a whitelisting mechanism:

server {
    listen 80;
    server_name example.com;
    
    # Allow access to IP address
    allow 192.168.1.1;
    
    # Ban all other IP addresses
    deny all;

    location / {
        # Routine request processing
    }
}

Query timeout setting

Adjusting the request timeout can prevent attackers from taking up server resources for long periods of time and reduce DDoS attacks such as slowloris. By configuring the connection and request timeout settings in NGINX, you can quickly disconnect invalid connections.

Customize Timeout Settings

server {
    listen 80;
    server_name example.com;

    # Setting the client connection idle timeout
    keepalive_timeout 10;

    # Set the maximum request body size to prevent large requests
    client_max_body_size 1m;
    
    # Setting the timeout for reading client requests
    client_body_timeout 10s;

    # Setting the timeout for reading client headers
    client_header_timeout 10s;

    location / {
        #  Routine request processing
    }
}

  • `keepalive_timeout`: Limit the maximum idle time of the connection to prevent occupying server connection resources.
  • `client_max_body_size`: Limit the size of the request body to prevent overly large requests from exhausting server resources.
  • `client_body_timeout` and `client_header_timeout`: Limit the time to read the request content and header to prevent slow attacks.

Optimization of cache and static resources

By setting up caching and optimizing the delivery of static resources, you can reduce the number of requests that NGINX directly handles on the backend, thereby reducing the impact of DDoS attacks. Caching is an effective way to reduce traffic peaks and reduce the load on backend servers.

Caching is an effective way to reduce traffic peaks and reduce the load on backend servers.

proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=cache_zone:10m max_size=10g inactive=60m use_temp_path=off;

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_cache cache_zone;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_pass http://backend;
    }
}

When cache is configured, NGINX will cache responses from the backend, reducing the load on the backend server from repeated requests. This allows you to directly respond to a large number of static resource requests from NGINX during DDoS attacks, thereby reducing the load on the server

Using HTTP request queue

With the `ngx_http_limit_req_module` module, you can place incoming requests in a queue. If a request exceeds the capacity of the queue, an error is returned to prevent the server from being overloaded with too many requests.

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

    server {
        listen 80;
        server_name example.com;

        location / {
            limit_req zone=one burst=5 nodelay;
            proxy_pass http://backend;
        }
    }
}

This configuration allows a maximum of 1 request per second. If a request exceeds this rate, it will be placed in the `burst` queue, and new requests will be rejected when the queue is full.

Use third-party security modules

NGINX supports the use of third-party modules to extend protection capabilities. Here are some frequently used DDoS protection modules and tools:

  • ModSecurity: This is an open source web application firewall (WAF) that can detect and block common attack patterns, including SQL injection, XSS, etc., and also has a certain effect of protecting against DDoS attacks.
  • NAXSI: A firewall module designed specifically for NGINX to protect web applications from various attacks. It is characterized by lightweight and high performance.

Combining firewalls with external tools

Although NGINX can mitigate some DDoS attacks, a combination of other security tools and mechanisms is usually required for more effective protection:

  • iptables:  With the Linux’`iptables` configuration, some attacks can be blocked directly at the network layer.
  • Cloudflare or other CDN:  Using a content delivery network (CDN) such as Cloudflare can provide additional DDoS protection. The web application firewall and traffic scrubbing services provided by Cloudflare can effectively counter large-scale DDoS attacks.
  • Fail2ban: Combine NGINX logs to automatically block malicious IP addresses with `fail2ban`.

Dynamic load balancing and elastic scaling

The combination of NGINX with platforms such as Kubernetes allows you to respond to large-scale DDoS attacks through elastic scaling. For example, with Kubernetes' elastic scaling feature, when traffic peaks, the number of NGINX instances is automatically increased to share the traffic, and when traffic drops, resources are automatically reduced.

Summary

In this article we briefly explained what DDoS is, how to protect yourself from attacks with the help of simple NGinx settings.
Recall that a reliable hosting provider provides shared hosting with DDoS protection. But when you use a virtual server service, we recommend you to perform fine-tuning of the server by yourself to minimize the possibility of a cyberattack on the site.

Methods to prevent DDoS attacks in NGINX include rate limiting, IP address blacklisting and whitelisting, request timeout settings, cache optimization, use of request queues, third-party security modules, and a combination of firewalls and CDNs.

Through intelligent customization and the use of external tools, NGINX can effectively thwart DDoS attacks of various sizes and types.