賊船

Fail2ban與Fortigate防火牆做聯防

Fail2ban可以做防堵暴力登入跟DDOS如果我們把攻擊者IP另外再給Fortigate防火牆來擋這樣攻擊者不是就不能另外攻擊其他台主機了嗎?忽然有這個想法所以上網搜尋了一下~咦~還真有人這樣做網址但是不是我想要的所以就做了一個小修改。

首先我先在防火牆上面建立了管理帳號設定了只能由指定的伺服器SSH進來管理防火牆,另外新增了IP物件群組名稱IPG_black及防火牆DENY政策。

首先我的伺服器上有網頁與SSH埠這兩個是我不想關掉的Port,之前我有一篇Fail2Ban文章幫我阻擋了外部來這台伺服器的攻擊,但是我的伺服器還蠻多台的所以藉由這篇文章統一交給上層的Fortigate 200E與80E學校公司家中三台防火牆來阻擋聯防,教學僅作學校與主機之間。

#安裝 expect
yum -y install expect

再寫兩個檔案分別是主機SSH到防火牆的Script

#vi /root/add.sh
#檔案內容如下
#!/usr/bin/expect -f

set force_conservative 0  ;# set to 1 to force conservative mode even if
              ;# script wasn't run conservatively originally
if {$force_conservative} {
    set send_slow {1 .1}
    proc send {ignore arg} {
        sleep .1
        exp_send -s -- $arg
    }
}

set ipaddress [lindex $argv 0]
set timeout -1
log_user 0
spawn ssh 192.168.0.254 -l 防火牆帳號
match_max 100000
expect -exact "防火牆帳號@192.168.0.254's password: "
send "我的防火牆密碼\r"
expect  "\# "
send -- "config firewall address\r"
expect "(address) \# "
send -- "edit \"BL_$ipaddress\"\r"
expect "\# "
send -- "set type ipmask\r"
expect "\# "
send -- "set subnet $ipaddress/32\r"
expect "\# "
send -- "end\r"
expect "\# "
send -- "config firewall addrgrp\r"
expect "\# "
send -- "edit IPG_black\r"
expect "\# "
send -- "append member BL_$ipaddress\r"
expect "\# "
send -- "end\r"
expect "\# "
send -- "exit\r"
expect eof
#vi /root/del.sh
#檔案內容如下
#!/usr/bin/expect -f

set force_conservative 0  ;# set to 1 to force conservative mode even if
              ;# script wasn't run conservatively originally
if {$force_conservative} {
    set send_slow {1 .1}
    proc send {ignore arg} {
        sleep .1
        exp_send -s -- $arg
    }
}

set ipaddress [lindex $argv 0]
set timeout -1
log_user 0
spawn ssh 192.168.0.254 -l 防火牆帳號
match_max 100000
expect -exact "防火牆帳號@192.168.0.254's password: "
send "防火牆密碼\r"
expect  "\# "
send -- "config firewall addrgrp\r"
expect "\# "
send -- "edit IPG_black\r"
expect "\# "
send -- "unselect member BL_$ipaddress\r"
expect "\# "
send -- "end\r"
expect "\# "
send -- "config firewall address\r"
expect "\# "
send -- "delete \"BL_$ipaddress\"\r"
expect "\# "
send -- "end\r"
expect "\# "
send -- "exit\r"
expect eof
# 將add.sh與del.sh加入執行權限
chmod 755 /root/*.sh

新增Fail2ban的設定與規則

#vi /etc/fail2ban/action.d/fortigate.conf
#檔案內容如下
#/etc/fail2ban/action.d/fortigate.conf
# Fail2Ban configuration file
# Author: Shane Chrisp
[Definition]
actionstart =
actionstop =
actioncheck =
actionban = /root/add.sh <ip>
actionunban = /root/del.sh <ip>

最後一個Fail2ban哪些服務要讓防火牆阻擋就加入一行action=fortigate就可以了

#vi /etc/fail2ban/jail.local
#哪些服務啟動fail2ban管理的就新增下面這行
action   = fortigate

重新啟動Fail2Ban

systemctl restart fail2ban
密密麻麻一頁看不盡的阻擋IP
伺服器群組顯示109個其實有一個無法移除的所以我用虛擬IP所以真正的會有108個

Exit mobile version