How to Block IP Targeting Specific Domains

Selain menggunakan ModSecurity, cara alternatif untuk memblokir pengakses yang membuat permintaan ke domain tertentu adalah dengan menggunakan iptables. IPtables adalah utilitas linux yang memungkinkan Anda mengonfigurasi aturan firewall pada tingkat OS seperti memblokir berdasarkan alamat IP, port dan protokol.

iptables

Berikut adalah aturan firewall yang dapat Anda gunakan untuk memblokir IP yang membuat permintaan ke domain tertentu.

iptables -A INPUT -p tcp --match multiport --dport 80,443 \
 -m string --string 'DOMAIN' --algo bm -j DROP

iptables + ipset

Buat file index.php lalu tambahkan baris berikut.

<?php
// contents of FORBIDDEN.YourDomain.com/index.php
// spits out one UDP packet at the web visitor's port 911
// the 911 packet is intended to be detected, processed and dropped with firewall rules
$remoteaddr = $_SERVER['REMOTE_ADDR'];
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_sendto($sock, "NOPE", 4, 0, $remoteaddr, 911);
socket_close($sock);

Kemudian buat ipset baru dengan nama ipset_temp_blocklist lalu atur timeout selama 4 jam (14400 detik).

ipset create ipset_temp_blocklist \
    hash:ip \
        family inet \
        hashsize 4096 \
        maxelem 65536 \
        timeout 14400 \
        counters \
        comment

Selanjutnya buat rule iptables dengan chain ADD_TEMP_BAN seperti berikut.

iptables -N ADD_TEMP_BAN
iptables -A ADD_TEMP_BAN -j SET --add-set ipset_temp_blocklist dst
iptables -A ADD_TEMP_BAN -j DROP
iptables -A OUTPUT -p udp --dport 911 -j ADD_TEMP_BAN

Rule iptables tersebut akan membuat IP pengakses skrip PHP dapat dikumpulkan ke dalam ipset ipset_temp_blocklist.

Lalu tambahkan rule berikut untuk memblokir akses masuk ke port 80 (http) dan 443 (https).

iptables -A INPUT -i eth0 -p tcp -m multiport --dports 80,443 -m set --match-set ipset_temp_blocklist src -j DROP

Gunakan perintah berikut untuk melihat list IP yang diblokir.

ipset list ipset_temp_blocklist

Referensi: