Fail2banで不正なアクセスをブロック(BAN)してサーバを守る

Fail2banで不正なアクセスをブロックしてサーバを守る サーバー

メールサーバーに何やら不審なアクセスが続いている。

アクセス元のIPアドレスから国を調べると「セーシェル」らしい。その他にも国外の怪しいIPアドレスからのアクセスが大量に存在する。

早速Fail2banで対策する。

※動作確認環境
CentOS 7.6

ログ調査

/var/log/maillogの状況は以下のとおりです。

Jan 24 01:52:27 150-95-xxx-xxx postfix/smtpd[9022]: connect from unknown[80.82.xx.xx]
Jan 24 01:52:28 150-95-xxx-xxx postfix/smtpd[9022]: disconnect from unknown[80.82.xx.xx]
Jan 24 01:55:48 150-95-xxx-xxx postfix/anvil[9024]: statistics: max connection rate 1/60s for (submission:80.82.xx.xx) at Jan 24 01:52:27
Jan 24 01:55:48 150-95-xxx-xxx postfix/anvil[9024]: statistics: max connection count 1 for (submission:80.82.xx.xx) at Jan 24 01:52:27
Jan 24 02:04:17 150-95-xxx-xxx postfix/smtpd[9441]: warning: hostname no-reverse-dns-configured.com does not resolve to address 80.82.xx.xx
Jan 24 02:04:17 150-95-xxx-xxx postfix/smtpd[9441]: connect from unknown[80.82.xx.xx]
Jan 24 02:04:18 150-95-xxx-xxx postfix/smtpd[9441]: disconnect from unknown[80.82.xx.xx]
Jan 24 02:15:58 150-95-xxx-xxx postfix/smtpd[9756]: warning: hostname no-reverse-dns-configured.com does not resolve to address 80.82.xx.xx
Jan 24 02:15:58 150-95-xxx-xxx postfix/smtpd[9756]: connect from unknown[80.82.xx.xx]
Jan 24 02:16:00 150-95-xxx-xxx postfix/smtpd[9756]: disconnect from unknown[80.82.xx.xx]

このようなログの内容がずっと続いています。

どう見ても不正なアクセスですね。

Fail2banとは

Fail2banとは、サーバーのログを解析して不正なアクセスしてくるIPアドレスを自動でブロック(BAN)してくれるプログラムです。

メールサーバーやWEBサーバー、SSHやFTPなど各サービスごとにJAILルール(監獄ルール)を設定して細かく指定することができます。

Fail2banのインストール

CentOS 7にインストールするには「epel」リポジトリが必要ですので、リポジトリがインストールされていない方は「epel-release」をインストールします。

# yum install epel-release

Fail2banをインストールします。

# yum --enablerepo=epel install fail2ban
読み込んだプラグイン:fastestmirror, langpacks
Loading mirror speeds from cached hostfile
epel/x86_64/metalink                                                                   | 8.7 kB  00:00:00     
 * base: ftp.iij.ad.jp
 * epel: ftp.iij.ad.jp
 * extras: ftp.iij.ad.jp
 * remi-safe: ftp.riken.jp
 * updates: ftp.iij.ad.jp
依存性の解決をしています
--> トランザクションの確認を実行しています。
---> パッケージ fail2ban.noarch 0:0.9.7-1.el7 を インストール
--> 依存性の処理をしています: fail2ban-sendmail = 0.9.7-1.el7 のパッケージ: fail2ban-0.9.7-1.el7.noarch
--> トランザクションの確認を実行しています。
---> パッケージ fail2ban-sendmail.noarch 0:0.9.7-1.el7 を インストール
--> 依存性解決を終了しました。

依存性を解決しました

==============================================================================================================
 Package                          アーキテクチャー      バージョン                  リポジトリー         容量
==============================================================================================================
インストール中:
 fail2ban                         noarch                0.9.7-1.el7                 epel                 11 k
依存性関連でのインストールをします:
 fail2ban-sendmail                noarch                0.9.7-1.el7                 epel                 14 k

トランザクションの要約
==============================================================================================================
インストール  1 パッケージ (+1 個の依存関係のパッケージ)

総ダウンロード容量: 25 k
インストール容量: 11 k
Is this ok [y/d/N]: y
Downloading packages:
(1/2): fail2ban-0.9.7-1.el7.noarch.rpm                                                 |  11 kB  00:00:00     
(2/2): fail2ban-sendmail-0.9.7-1.el7.noarch.rpm                                        |  14 kB  00:00:00     
--------------------------------------------------------------------------------------------------------------
合計                                                                           78 kB/s |  25 kB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  インストール中          : fail2ban-sendmail-0.9.7-1.el7.noarch                                          1/2 
  インストール中          : fail2ban-0.9.7-1.el7.noarch                                                   2/2 
  検証中                  : fail2ban-sendmail-0.9.7-1.el7.noarch                                          1/2 
  検証中                  : fail2ban-0.9.7-1.el7.noarch                                                   2/2 

インストール:
  fail2ban.noarch 0:0.9.7-1.el7                                                                               

依存性関連をインストールしました:
  fail2ban-sendmail.noarch 0:0.9.7-1.el7                                                                      

完了しました!

インストール完了です。

Fail2banの設定

設定するルール内容

今回設定するルールは以下の内容で行います。

  • 5分間で3回アクセス失敗したIPアドレスは1時間アクセスが禁止される。
  • BANが発動した場合はIPアドレスのWHOIS情報をメール送信する。
  • [sshd]、[proftpd]、[postfix] 、[dovecot]、[postfix-sasl]でFail2banを有効とする。
  • 1日間に5回BANされたIPアドレスは1週間BANする。(recidive設定)

設定

設定ファイルの/etc/fail2ban/fail2ban.confを直接編集せずに、/etc/fail2ban/jail.localを編集して設定します。

# vi /etc/fail2ban/jail.local
[DEFAULT]

#■基本設定
backend  = systemd ; ContOS7用設定
ignoreip = 127.0.0.0/8 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 ; 無視するIPアドレス(ホワイトリスト)

#■BAN設定
bantime  = 3600 ; BANされたIPアドレスがアクセスを禁止される期間(秒)
findtime = 300 ; BANの判定時間(秒)
maxretry = 3 ; アクセス回数

#■メール設定
destemail  = mail@example.com ; アラートメールの送信先アドレス
sender     = fail2ban@example.com ; メールの送信元

#■その他
action  = %(action_mw)s ; BANされたIPアドレスのWHOIS情報をメール送信

[sshd]
enabled = true port = ssh 

[proftpd]
enabled = true port = ftp,ftp-data,ftps,ftps-data 

[postfix]
enabled = true port = smtp,465,submission 

[dovecot]
enabled = true port = pop3,pop3s,imap,imaps,submission,465,sieve 

[postfix-sasl]
enabled = true port = smtp,465,submission,imap3,imaps,pop3,pop3s

#■再犯者用設定 
[recidive]
enabled = true backend = auto ; ログの監視方法 
logpath = /var/log/fail2ban.log ; BAN回数を集計するログ 
bantime = 604800 ; BANされる期間(秒) 
findtime = 86400 ; BANの回数判定時間(秒) 
maxretry = 5 ; BAN回数 

BANされたパケットを拒否せずにドロップ(破棄)する設定を行います。(※iptables-common.localというファイルを新規作成して編集します。)

# vi /etc/fail2ban/action.d/iptables-common.local
[Init] 
blocktype = DROP

このまま起動すると「 NOTICE Jail started without 'journalmatch' set. Jail regexs will be checked against all journal entries, which is not advised for performance reasons.」というエラーがFail2banのログファイル(/var/log/fail2ban.log)に出力されますので、その原因の「proftpd」の設定ファイルを編集します。

# vi /etc/fail2ban/filter.d/proftpd.conf
#journalmatchエラー対策
#ファイル末尾に以下を追加
[Init]
journalmatch = _SYSTEMD_UNIT=proftpd.service

Fail2ban起動

# systemctl start fail2ban

Fail2banの自動起動をオン

# systemctl enable fail2ban

これで完了です。

念のために正常に稼働しているか「systemctl status fail2ban」「fail2ban-client status」及びFail2banのログファイル(/var/log/fail2ban.log)でチェックしましょう。

【備考】ログにjournalmatchのエラーが表示されている場合

もしFail2banのログファイル(/var/log/fail2ban.log)に「 NOTICE Jail started without 'journalmatch' set. Jail regexs will be checked against all journal entries, which is not advised for performance reasons.」というエラーが表示されている場合は以下の対策を行ってください。

まずログを調査します。

jail.localで設定したFail2banを適用させるサービスの中で、「INFO Added journal match for: '_SYSTEMD_UNIT=サービス名.service'」という行がログに存在しないサービスを探します。

そのサービス名の設定ファイルが/etc/fail2ban/filter.d/ディレクトリの中にありますので、以下のフォーマットで情報を追加します。

#journalmatchエラー対策(ファイル末尾に以下を追加)
[Init]
journalmatch = _SYSTEMD_UNIT=サービス名.service

Fail2banを再起動で完了です。

# systemctl start fail2ban

もう一度ログをチェックしてエラーが無いか確認してみてください。

【備考】アラートメールにmissing whois programと表示されている場合

BANされたIPアドレスのWHOIS情報をメール送信するという設定をした際に、BANアラートメールに「missing whois program」と記載されていた場合は、IPアドレスからWHOIS情報をしらべる「whois」というパッケージがインストールされていませんのでインストールしましょう。
whoisをインストール
# yum -y install whois
読み込んだプラグイン:fastestmirror
Loading mirror speeds from cached hostfile
 * base: ftp.iij.ad.jp
 * extras: ftp.iij.ad.jp
 * remi-safe: ftp.riken.jp
 * updates: ftp.iij.ad.jp
依存性の解決をしています
--> トランザクションの確認を実行しています。
---> パッケージ whois.x86_64 0:5.1.1-2.el7 を インストール
--> 依存性解決を終了しました。

依存性を解決しました

================================================================================================================
 Package                 アーキテクチャー         バージョン                       リポジトリー            容量
================================================================================================================
インストール中:
 whois                   x86_64                   5.1.1-2.el7                      base                    72 k

トランザクションの要約
================================================================================================================
インストール  1 パッケージ

総ダウンロード容量: 72 k
インストール容量: 222 k
Downloading packages:
whois-5.1.1-2.el7.x86_64.rpm                                                             |  72 kB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  インストール中          : whois-5.1.1-2.el7.x86_64                                                        1/1 
  検証中                  : whois-5.1.1-2.el7.x86_64                                                        1/1 

インストール:
  whois.x86_64 0:5.1.1-2.el7                                                                                    

完了しました!

Fail2banの代表的な設定オプション

enabledルールを発動するか否か。(true 又は false)
portサービス名又はポート番号
filterログファイル解析用のfailregex情報を含むファイルの名前
logpathサービスのログの場所
backendログの監視方法(CentOS 7の場合はsystemdと設定)
ignoreipホワイトリストIPアドレス
bantimeIPアドレスがBANされる期間(秒)。デフォルト値は600(10分間)。負の数に設定すると永久BANになります。
findtimeBANが発動するまでの判定時間(※この判定時間内にmaxretryで設定した回数に達するとBANが発動します。)
maxretryBANが発動するまでの回数
actionBANが発動したときのアクション。デフォルトは「%(action_)s
%(action_)s」:BANのみ。
%(action_mw)s」:BANしてWhois情報を含めてメール通知
%(action_mwl)s」:BANしてWhois情報とログ情報をメール通知

状況確認とBAN解除は「fail2ban-client」コマンド

現在のBANの状況確認

現在のFail2banのBAN状況は以下のfail2ban-clientコマンドで確認できます。

fail2ban-client status <JAILルール名>

▼sshd

# fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     0
|  - Journal matches:  _SYSTEMD_UNIT=sshd.service + _COMM=sshd
- Actions
   |- Currently banned: 0
   |- Total banned:     0
   - Banned IP list:

▼proftpd

# fail2ban-client status proftpd
Status for the jail: proftpd
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     0
|  - Journal matches:  _SYSTEMD_UNIT=proftpd.service
- Actions
   |- Currently banned: 0
   |- Total banned:     0
   - Banned IP list:

▼postfix

# fail2ban-client status postfix
Status for the jail: postfix
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     4
|  - Journal matches:  _SYSTEMD_UNIT=postfix.service
- Actions
   |- Currently banned: 0
   |- Total banned:     0
   - Banned IP list:

▼dovecot

# fail2ban-client status dovecot
Status for the jail: dovecot
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     0
|  - Journal matches:  _SYSTEMD_UNIT=dovecot.service
- Actions
   |- Currently banned: 0
   |- Total banned:     0
   - Banned IP list:

▼postfix-sasl

# fail2ban-client status postfix-sasl
Status for the jail: postfix-sasl
|- Filter
|  |- Currently failed: 1
|  |- Total failed:     1
|  - Journal matches:  _SYSTEMD_UNIT=postfix.service
- Actions
   |- Currently banned: 0
   |- Total banned:     0
   - Banned IP list:

▼recidive

# fail2ban-client status recidive
Status for the jail: recidive
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     0
|  - Journal matches:  _SYSTEMD_UNIT=fail2ban.service PRIORITY=5
- Actions
   |- Currently banned: 0
   |- Total banned:     0
   - Banned IP list:

BANの解除方法

もし、BANされているIPアドレスをBANから解除したい場合は以下のfail2ban-clientコマンドで解除できます。

fail2ban-client set <JAILルール名> unbanip <IPアドレス>

# fail2ban-client set sshd unbanip 80.82.xxx.xxx

代表的なfail2ban-clientコマンド一覧

fail2ban-client startFail2banサーバ起動(※非推奨 systemctl で起動する方が良い)
fail2ban-client reloadFail2banの設定ファイルを再読み込み
fail2ban-client reload <JAILルール名>指定したJAILルールをリロード
fail2ban-client stopFail2banサーバ停止(※非推奨 systemctl で停止する方が良い)
fail2ban-client statusFail2banサーバのステータスを表示
fail2ban-client status <JAILルール名>指定したJAILルールのステータスとBAN状況を表示
fail2ban-client set <JAILルール名> banip <IPアドレス>指定したJAILルールで指定したIPアドレスを手動でBAN
fail2ban-client set <JAILルール名> unbanip <IPアドレス>指定したJAILルールで指定したIPアドレスをBAN解除
fail2ban-client stopでFile2banを停止した場合、fail2ban-client startで再度起動しようと思ってもERROR Server already runningというエラーが出て起動できなくなります。
File2banの起動と停止は、systemdのsystemctl start fail2ban及びsystemctl stop fail2banで行いましょう。

まとめ

怪しいアクセスを発見したらFail2banで不正アクセスをブロック。

むしろ怪しいアクセスを発見する前に、設定も簡単なのでFail2banを導入しておきましょう。

以上で解決です。

タイトルとURLをコピーしました