GNU/Linux >> Belajar Linux >  >> Linux

Memblokir semua lalu lintas dari masing-masing negara menggunakan IPSet dan IPTables

Pendahuluan:
Saat saya melihat syslog, saya terlalu sering menemukan bahwa serangan login SSH datang dari China atau dari Rusia. Sudah cukup, dan lagi pula tidak mengharapkan lalu lintas dari salah satu negara ini, meskipun saya menggunakan fail2ban tetap saja saya memutuskan untuk memblokir lalu lintas yang datang dari 2 negara ini. Fail2ban adalah alat yang hebat untuk memblokir upaya login yang gagal. NAMUN tampaknya banyak upaya (ribuan) per hari masih berjalan. Saya hanya bisa berasumsi bahwa penyerang menggunakan pengiriman paralel upaya dan sampai Fail2ban (berdasarkan log auth) bereaksi banyak yang telah melalui.
Untuk melakukan pemblokiran penuh IP dengan daftar rentang IP yang dimuat sebelumnya, saya mulai dengan menggunakan iptables dengan satu aturan per rentang IP, TETAPI pemuatan aturan terlalu lama dan yang lebih penting, memuat semua rentang IP, sebagai aturan iptables murni, membuat server saya tidak stabil, artinya … crash!!! Dikatakan bahwa lebih dari maks. 25.000 aturan di iptables, terutama yang lebih besar dari 27.000, aturan dapat menempatkan kernel dalam keadaan tidak stabil.
Untuk mengatasinya saya menggunakan ipset dengan iptables . ipset dirancang khusus untuk menangani daftar Rentang IP besar (tabel hash akses cepat) yang dapat berisi hingga 65536 entri.

CATATAN: Script di bawah ini hanya berlaku untuk distribusi Linux berbasis Debian. Untuk distribusi lain, Anda perlu menyesuaikan skripnya.

Prinsip Perlindungan Pemblokiran Negara ini :
Rentang IP dalam format CIDR diambil dari situs web http://www.ipdeny.com/ipblocks/data/countries/ dan dimasukkan ke dalam daftar individual IPSet yang diberi nama dengan kode negara dan kemudian dirujuk oleh iptables untuk menentukan TARGET (apa yang harus dilakukan dengan IP yang cocok:DROP )
CATATAN: Dalam contoh ini, skrip menetapkan target aturan iptables ke DROP alih-alih MENOLAK untuk menghindari lalu lintas tinggi respons penolakan tumpukan TCP/IP. JAUH tidak menanggapi apa pun.

CATATAN PENTING: Skrip di bawah ini harus dijalankan SETELAH Anda memuat aturan firewall reguler Anda. Itu MASUKKAN aturan iptables baru sedemikian rupa sehingga setiap paket yang masuk dari negara-negara yang ditentukan akan diblokir SEBELUM pemrosesan lebih lanjut di firewall Anda.

Langkah-langkah:
#!/bin/bash
# Description: Uses IPSET and IPTABLES to block full countries from accessing the server for all ports and protocols
# Syntax: countries_firewall.sh countrycode [countrycode] ......
# Use the standard locale country codes to get the proper IP list. eg.
# countries_firewall.sh cn ru ro
# Will create tables that block all requests from China, Russia and Romania
# Changes: 13.11.2016 Initial creation of script
# Note: To get a sorted list of the inserted IPSet IPs for example China list(cn) run the command:
# ipset list cn | sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4
# #############################################################################
# Defining some defaults
iptables="/sbin/iptables"
tempdir="/tmp"
sourceURL="http://www.ipdeny.com/ipblocks/data/countries/"
#
# Verifying that the program 'ipset' is installed
if ! (dpkg -l | grep '^ii ipset' &>/dev/null) ; then
echo "ERROR: 'ipset' package is not installed and required."
echo "Please install it with the command 'apt-get install ipset' and start this script again"
exit 1
fi
[ -e /sbin/ipset ] && ipset="/sbin/ipset" || ipset="/usr/sbin/ipset"
#
# Verifying the number of arguments
if [ $# -lt 1 ]; then
echo "ERROR: wrong number of arguments. Must be at least one."
echo "countries_firewall.sh countrycode [countrycode] ......"
echo "Use the standard locale country codes to get the proper IP list. eg."
echo "countries_firewall.sh cn ru ro"
exit 2
fi
#
# Now load the rules for blocking each given countries and insert them into IPSet tables
for country ; do
# Read each line of the list and create the IPSet rules
# Making sure only the valid country codes and lists are loaded
if wget -q -P $tempdir ${sourceURL}${country}.zone ; then
# Destroy the IPSet list if it exists
$ipset flush $country &>/dev/null
# Create the IPSet list name
echo "Creating and filling the IPSet country list: $country"
$ipset create $country hash:net &>/dev/null
(for IP in $(cat $tempdir/${country}.zone) ; do
# Create the IPSet rule from each IP in the list
echo -n "$ipset add $country $IP --exist - "
$ipset add $country $IP -exist && echo "OK" || echo "FAILED"
done) > $tempdir/IPSet-rules.${country}.txt
# Destroy the already existing rule if it exists and insert the new one
$iptables -D INPUT -p tcp -m set --match-set $country src -j DROP &>/dev/null
$iptables -I INPUT -p tcp -m set --match-set $country src -j DROP
# Delete the temporary downloaded counties IP lists
rm $tempdir/${country}.zone
else
echo "Argument $country is invalid or not available as country IP list. Skipping"
fi
done
# Display the result of the iptables rules in INPUT chain
echo "======================================"
echo "IPSet lists registered in iptables:"
$iptables -L INPUT -n -v | grep 'match-set'
# Dispaly the number of IP ranges entered in the IPset lists
echo "--------------------------------------"
for country ; do
echo "Number of ip ranges entered in IPset list '$country' : $($ipset list $country | wc -l)"
done
echo "======================================"
#
#eof

Masuk dari operasi skrip:

Seperti yang Anda lihat di skrip, penambahan rentang IP dalam tabel IPSet dicatat:$tempdir/IPSet-rules.${country}.txt yang ditimpa setiap kali skrip dijalankan untuk negara yang sama.

Memulai skrip

Untuk memastikan add-on firewall ini dimulai dengan benar pada setiap boot, tetapi setelah firewall yang ditentukan pengguna, saya memulainya melalui cron @reboot pekerjaan setelah penundaan sekitar 40 detik (yang dapat disesuaikan dengan kebutuhan Anda) untuk memulai layanan lain, termasuk layanan firewall. Saya sadar bahwa metode memulai skrip ini tidak terlalu elegan tetapi cukup cocok untuk semua variasi distribusi Linux apakah berbasis Sysinit-V atau Systemd. Contoh pekerjaan root cron:
@reboot /bin/sleep 40 ; /bin/bash -c ". /root/.bashrc ; /root/bin/countries_firewall.sh cn ru"

Mengirim laporan lalu lintas per email

Untuk mengirim laporan lalu lintas per email setiap hari, saya mengumpulkan setiap hari data lalu lintas dari iptables, memformatnya dan mengirimkannya melalui email menggunakan skrip bash berikut. Skrip ini kemudian akan dijalankan setiap hari oleh cron (dimasukkan ke /etc/cron.daily/) dan penghitung lalu lintas akan diatur ulang.
#!/bin/bash
# Purpose: Sends the blocked traffic report per email and resets the counter
# Syntax: iptables_report
# Dependencies: Systems tools: iptables, awk, column, whois, sendmail
# Changes: 13.11.2016 First implementation of script
#----------------------------------------------------------
HOST=$(cat /etc/hostname | tr 'a-z' 'A-Z')
email="[email protected]"
reportsender="cron@$HOST"
subject="BLOCKED Packets report on $(hostname | tr 'a-z' 'A-Z')"
tempdir="/tmp"
file1="iptables_report1.txt"
file2="iptables_report2.txt"
#
#------------ Build the header of the mail to send ------------
echo "From: $reportsender" > $tempdir/$file1
echo "To: $email" >> $tempdir/$file1
echo "Subject: $subject" >> $tempdir/$file1
echo "MIME-Version: 1.0" >> $tempdir/$file1
echo 'Content-Type: text/html; charset="ISO-8859-15"' >> $tempdir/$file1
echo "" >> $tempdir/$file1
echo "<br />" >> $tempdir/$file1
echo -e "<font size=3 FACE='Courier'><pre>" >> $tempdir/$file1
# Formatted message starts here
# Add the country at the end of each line
# Load the header and data to the temporary file 2
echo -e "Packets Bytes Source \n======= ========= ======" >$tempdir/$file2
/sbin/iptables -L -n -v | /bin/grep -v '^ 0' | /bin/grep 'match-set' | /usr/bin/awk '{print $1" "$2" "$11}' >> $tempdir/$file2
#
# Format temp file2 into temp file1
cat $tempdir/$file2 | column -t >> $tempdir/$file1
#
#
# Add the last HTML preformatting End
echo -e "</pre>" >> $tempdir/$file1
echo "" >> $tempdir/$file1
#
#----------------- Send the prepared email ---------------------------
# now format the report and send it by email
cat $tempdir/$file1 | /usr/sbin/sendmail -t
rm $tempdir/$file1 $tempdir/$file2
#
# Reset the iptables counters
/sbin/iptables -Z
#
# eof

Membuat tugas cron untuk laporan harian reguler
Simpan file itu di mis. /etc/cron.daily/iptables_report
Buat agar dapat dijalankan:
chmod 755 /etc/cron.daily/iptables_report
Contoh email laporan:
Packets Bytes Source
======= ========= ======
188 7852 ru
19295 1150K cn

Status manual:
Untuk mendapatkan status manual dari aturan iptables untuk rantai INPUT jalankan perintah:
iptables -L INPUT -v -n
Untuk mendapatkan daftar daftar IP IPSet yang diurutkan, jalankan perintah (mis. untuk Rusia):
ipset list ru | sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4


Linux
  1. Memblokir daftar hitam host dan iptables

  2. Blokir rentang IP dari negara-negara dengan GeoIP dan iptables

  3. IPTables Flush:Hapus / Hapus Semua Aturan Di RedHat dan CentOS Linux

  1. Cara mengizinkan semua lalu lintas dari server menggunakan firewalld di CentOS/RHEL

  2. CentOS / RHEL :Cara memblokir port masuk dan keluar menggunakan iptables

  3. Menggunakan awk untuk mencetak semua kolom dari n ke yang terakhir

  1. Cara Daftar, Unggah, dan Unduh file dari Server SFTP menggunakan golang

  2. Konversi Semua Teks Dari Huruf Besar Ke Huruf Kecil Dan Sebaliknya?

  3. Hapus semua karakter khusus dan huruf besar-kecil dari string di bash