Loading...
Real Time Concepts

Block IP with Nginx behind CLB

If a customer is using a Cloud Load Balancer, they are restricted to only allowing/denying 100 IPs. However, they may want to block specific IPs still. Ideally, we would block these at the hardware firewall or with iptables/firewalld. In this particular situation, neither of those are an option. In this scenario we will be using Nginx to block a list of IPs.

Configuration

In this situation a customer has a standard server block configuration for their site and they have one or more Cloud Servers behind a Cloud Load Balancer. They are wanting to block a specific list of IPs. We will use the geo module to accomplish this. The `geo $allow` block needs to be before the server block. The if statement needs to be defined in the location the check should be performed. In this case, we place it in the main server block.

/etc/nginx/conf.d/test.conf

geo $allow {
default 0;
include /etc/nginx/conf.d/IPs_blocked.txt;
}

server {
listen 80 default_server;
server_name example.com www.example.com;

set_real_ip_from 10.183.0.0/16;
set_real_ip_from 127.0.0.1;
real_ip_header X-Forwarded-For;
root /var/www/html;

if ($allow = 1) {
return 403;
}

}

List of IPs that we want to block. The last IP in the list is the ORD CBAST IP for testing.

/etc/nginx/conf.d/IPs_blocked.conf

1.65.201.239 1;
103.1.206.100 1;
103.194.180.113 1;
103.194.180.52 1;
103.194.180.73 1;
103.194.180.74 1;
103.194.180.95 1;
103.194.181.13 1;
103.194.181.189 1;
103.194.181.28 1;
161.47.0.10 1;

Example curl and logs
Before:

[step9170@cbast1 ~]$ curl http://148.62.3.57/index.html -IL
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Fri, 09 Feb 2018 19:48:49 GMT
Content-Type: text/html
Content-Length: 110
Last-Modified: Fri, 09 Feb 2018 19:17:22 GMT
Connection: keep-alive
ETag: “5a7df3c2-6e”
Accept-Ranges: bytes

After:

[step9170@cbast1 ~]$ curl http://104.239.141.115/index.html -IL
HTTP/1.1 403 Forbidden
Server: nginx/1.12.2
Date: Fri, 09 Feb 2018 19:21:37 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive

Logs

[root@nginx-test ~]# tail /var/log/nginx/access.log
104.239.141.115  –  –  [09/Feb/2018:19:17:52 +0000]    “GET /index.html HTTP/1.1” 200 110 “-” “curl/7.29.0” “-”
104.239.141.115  –  –  [09/Feb/2018:19:17:56 +0000]    “HEAD /index.html HTTP/1.1” 200 0 “-” “curl/7.29.0” “-”
161.47.0.10   –   –   [09/Feb/2018:19:19:57 +0000]          “HEAD /index.html HTTP/1.1” 200 0 “-” “curl/7.29.0” “-”
161.47.0.10   –    –  [09/Feb/2018:19:21:37 +0000]          “HEAD /index.html HTTP/1.1” 403 0 “-” “curl/7.29.0” “-”

References

Leave a Reply

Your email address will not be published. Required fields are marked *