[Time4VPS][CentOS] 特定 IP アドレスをブロックする

以前 CentOS への不正ログイン対策として、SSH ポート番号を変更したことについて書いた。

[Time4VPS][CentOS] SSH ポートを変更する – with a Christian Wife
https://wacw.cf/2021/06/30/changing-ssh-port-number/

しかし、標準ポート番号ほどではなくとも、まだ攻撃は続いている。2ヶ月ぶりにログインすると以下のように表示された。月に 600 回以上アクセスが試みられている。

There were 1302 failed login attempts since the last successful login.

失敗したログインのログを以下のコマンドで確認してみる。

# cat /var/log/secure* | grep "sshd" | grep "Failed password"

結構同じ IP からのアクセスが多いようなので、一旦これらの IP アドレスからのアクセスをブロックすることにした。

環境:
・Time4VPS「Linux 8」(CPU: 2 x 2.60 GHz、RAM: 8192 MB、Storage: 80 GB、Bandwidth: 8 TB、Port speed: 100 Mbps、Virtualization: KVM)、CentOS 7.8
・FileMaker Server for Linux 19.0.1.22(英語)
・macOS Catalina Version 10.15.6(英語環境) で SSH 接続
・Freenom のドメイン(サブドメイン)

(1)以下のコマンドで重複した IP アドレスを除いて表示する。ユーザー名が root と、root 以外でコマンドを分けているのは、cut コマンドで指定する項目番号が root と root 以外でずれるからだ。

# cat /var/log/secure* | grep "sshd" | grep "Failed password" | grep " root " | cut -f 11 -d ' ' | sort | uniq -c | sort -nr
   4854 yyy.yy.yy.yyy
   4546 xxx.xx.x.xxx
   1302 from
# cat /var/log/secure* | grep "sshd" | grep "invalid user" | cut -f 13 -d ' ' | sort | uniq -c | sort -nr
  29770 
  18108 xxx.xx.x.xxx
  11114 yyy.yy.yy.yyy
	547 from

from がカウントされているが理由はよく分からない。

大量のクセスがあるわりに、実態はたった2つの IP アドレスである。以下のサイトで調べると、インドとドイツだった。

Where is my IP location? (Geolocation)
https://www.iplocation.net/

(2)/etc/hosts.deny に以下の書式でブロックしたい IP アドレスを記述する。複数あるのでスペースで区切る。保存。

sshd: xxx.xx.x.xxx yyy.yy.yy.yyy

これでしばらく様子を見てみよう。

参考:
[Linux] SSHのログイン時にIPアドレス制限を行う
https://blog.katsubemakito.net/linux/sshd-ipaddress-check

TCP Wrapper で SSH のアクセス制限 – さくらのクラウド超入門・サーバ編(2) – Qiita
https://qiita.com/zembutsu/items/c432a3e096729e181df9

cutコマンドについてまとめました 【Linuxコマンド集】
https://eng-entrance.com/linux-command-cut#-f–fields

【 uniq 】コマンド――重複している行を削除する:Linux基本コマンドTips(64) – @IT
https://www.atmarkit.co.jp/ait/articles/1611/14/news021.html

【 grep 】コマンド――特定の文字を含む行を抽出する:Linux基本コマンドTips(9) – @IT
https://www.atmarkit.co.jp/ait/articles/1604/07/news018.html

【Linuxコマンド】cutでファイルから指定部分を取り出す方法 | 侍エンジニアブログ
https://www.sejuku.net/blog/51830

Linuxコマンド【 cut 】ファイルの各行から一部分を切り出す – Linux入門 – Webkaru
https://webkaru.net/linux/cut-command/

【 cut 】コマンド――行から固定長またはフィールド単位で切り出す:Linux基本コマンドTips(60) – @IT
https://www.atmarkit.co.jp/ait/articles/1610/31/news026.html

【 sort 】コマンド――テキストファイルを行単位で並べ替える:Linux基本コマンドTips(63) – @IT
https://www.atmarkit.co.jp/ait/articles/1611/09/news020.html

sort と uniq でさくっとランキングを出力する – blog.nomadscafe.jp
https://blog.nomadscafe.jp/2012/07/sort-uniq.html