SSH 보안 - Fail2ban 설치 및 설정 - 리눅스 SSH 보안

Share

Last Updated on 2월 28, 2024 by Jade(정현호)

안녕하세요 
이번 포스팅에서는 리눅스에서 SSH 접속 보안을 위한 fail2ban 에 대한 설치 및 구성에 대해서 확인해 보도록 하겠습니다.     

Fail2ban

Fail2ban 은 침입 차단 소프트웨어 프레임워크로서 컴퓨터 서버를 무차별 대입 공격으로부터 보호합니다.

파이썬 프로그래밍 언어로 쓰여졌으며, 패킷 제어 시스템이나 로컬에 설치된 방화벽(iptables 또는 TCP 래퍼, firewalld)과의 인터페이스를 갖는 POSIX 시스템에서 실행됩니다.



Fail2ban은 로그 파일들(예를 들면 /var/log/auth.log, /var/log/apache/access.log 등)의 선택된 엔트리들과 이것에 기반한 스크립트들을 모니터링함으로써 동작합니다.

선택된 로그를 통해 IP 주소들(시스템의 보안을 위반하려는 시도를 하는)을 막는데 사용되게 됩니다.
너무 많은 로그인 시도를 하거나 의도되지 않은 행동을 수행하는 어떤 호스트 나 IP 주소를 막을 수 있습니다.

이와 같이 무차별 대입(Brute-Force) 공격 를 막기 위해서 사용되며 정해진 정책에 따라 OS 방화벽을 이용하여 차단하게 됩니다.

SSH 이외에 Apache, Lighttpd, sshd, vsftpd, qmail, Postfix 그리고 Courier 메일 서버를 위한 필터들과 함께 제공됩니다.


• 설치 환경
OS : CentOS 7.8 / Ubuntu 18.04 / CentOS 8.3
           

Fail2ban 설치 및 설정

Fail2ban 및 pyinotify 설치를 진행하도록 하겠습니다.
                  

Fail2ban 설치

• Ubuntu 에서 설치

Ubuntu$ sudo apt install fail2ban python-pip sqlite3 rsyslog

python-pip 가 없을 경우 python3-pip 로 설치를 하시면 됩니다.


• CentOS7 에서 설치

opc$ sudo yum -y install epel-release yum-utils
opc$ sudo yum install python-pip fail2ban sqlite
opc$ sudo pip install --upgrade pip


[참고] pip install --upgrade pip 시 아래와 같이 에러가 발생할 경우

Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-q4J0ib/pip/setup.py", line 7
def read(rel_path: str) -> str:
^
SyntaxError: invalid syntax


에러 발생시 아래 방법으로 진행을 하시면 됩니다.

~]# wget https://bootstrap.pypa.io/pip/2.7/get-pip.py

~]# python get-pip.py

Collecting pip<21.0
  Downloading pip-20.3.4-py2.py3-none-any.whl (1.5 MB)
     |################################| 1.5 MB 1.7 MB/s 
Collecting wheel
  Downloading wheel-0.37.0-py2.py3-none-any.whl (35 kB)
Installing collected packages: pip, wheel
  Attempting uninstall: pip
    Found existing installation: pip 8.1.2
    Uninstalling pip-8.1.2:
      Successfully uninstalled pip-8.1.2



• CentOS8 에서 설치

~]$ sudo dnf -y install dnf-plugins-core
~]$ sudo dnf -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm

-------- 아래는 종류에 따라서 설치
-- CentOS8 Repoid (8.2.2004 and before)
~]$ sudo dnf config-manager --set-enabled PowerTools

-- CentOS8 Repoid (8.3.2011 and later)
~]$ sudo dnf config-manager --set-enabled powertools

-- Oracle Linux 8
~]$ dnf config-manager --set-enabled ol8_codeready_builder

-- RHEL8
~]$ sudo subscription-manager repos --enable codeready-builder-for-rhel-8-x86_64-rpms


-- fail2ban 설치
~]$ sudo dnf install python3-pip fail2ban sqlite
~]$ sudo pip3 install --upgrade pip

            

pyinotify 설치

• Ubuntu/CentOS7
$ sudo pip install pyinotify

• CentOS8
$ sudo pip3 install pyinotify


Fail2ban 중지

Ubuntu/CentOS 공통 - 설치 후 시작되어 있음

Ubuntu$ sudo systemctl stop fail2ban
             

정책 설정 및 시작

jail.local 파일 생성 및 작성

ubuntu$ sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
ubuntu$ sudo vi /etc/fail2ban/jail.local

아래 내용을 입력해 적절히 수정/추가하여 사용합니다.


[DEFAULT]

# 차단하지 않을 IP
ignoreip = 127.0.0.1/8 ::1


# 인증 실패시 차단할 차단시간입니다 600 = 10분
# -1이면 영구차단입니다. (단위 : 초)
# bantime = 10800 = 3시간
bantime = -1


# 아래 시간동안 maxretry 횟수만큼 실패시 차단
#findtime = 10m <-- default
#findtime = 86400 - 24시간
findtime = 24h


# 차단되기전까지 인증시도를 위한 허용횟수
maxretry = 10


backend = auto

# backend 설명
로그 파일 변경을 감지할 방법으로 pyinotify, gamin, polling,systemd, auto 방식이 있습니다

pyinotify: pyinotify (파일 변경 모니터)를 되어있어야 합니다.
pyinotify 가 설치되지 않은 경우 Fail2ban은 auto를 사용합니다.

[참고] 포스팅에서는 처음에 pyinotify 를 설치하였습니다.


- gamin: Gamin (파일 변경 모니터)을 설치해야 합니다.
Gamin이 설치되어 있지 않으면 Fail2ban은 auto를 사용합니다.


- polling: 외부 라이브러리가 필요하지 않은 polling 알고리즘을 사용합니다.


- systemd: systemd python 라이브러리를 사용하여 systemd 저널에 액세스합니다.
이 백엔드에는 "logpath" 지정이 유효하지 않을 경우 사용됩니다.("logpath" is not valid)


auto: 다음 순서대로 동작 합니다
pyinotify, gamin, polling


# 메일 알림 기능
destemail = root@localhost
# => 수신 메일 주소

sender = root@<fq-hostname>
# =>발신 메일 주소


# banaction

ip 차단 방법입니다. /etc/fail2ban/action.d 디렉토리에 있는 action 을 사용할 수 있습니다. 여러 룰이 있으며 대표적인 iptables  와 firewalld 룰은 아래와 같이 설정파일이 있습니다.

$ ls -al /etc/fail2ban/action.d | grep iptables
-rw-r--r-- 1 root root 1426 Jan 18 2018 iptables-allports.conf
-rw-r--r-- 1 root root 2738 Jan 18 2018 iptables-common.conf
-rw-r--r-- 1 root root 2000 Jan 18 2018 iptables-ipset-proto4.conf
-rw-r--r-- 1 root root 2197 Jan 18 2018 iptables-ipset-proto6-allports.conf
-rw-r--r-- 1 root root 2240 Jan 18 2018 iptables-ipset-proto6.conf
-rw-r--r-- 1 root root 2082 Jan 18 2018 iptables-multiport-log.conf
-rw-r--r-- 1 root root 1420 Jan 18 2018 iptables-multiport.conf
-rw-r--r-- 1 root root 1497 Jan 18 2018 iptables-new.conf
-rw-r--r-- 1 root root 2584 Jan 18 2018 iptables-xt_recent-echo.conf
-rw-r--r-- 1 root root 1339 Jan 18 2018 iptables.conf


$ ls -al | grep firewall
-rw-r--r--. 1 root root 1501 Jan 11 2020 firewallcmd-allports.conf
-rw-r--r--. 1 root root 2649 Jan 11 2020 firewallcmd-common.conf
-rw-r--r--. 1 root root 2286 Jan 11 2020 firewallcmd-ipset.conf
-rw-r--r--. 1 root root 1270 Jan 11 2020 firewallcmd-multiport.conf
-rw-r--r--. 1 root root 1898 Jan 11 2020 firewallcmd-new.conf
-rw-r--r--. 1 root root 2314 Jan 11 2020 firewallcmd-rich-logging.conf
-rw-r--r--. 1 root root 1765 Jan 11 2020 firewallcmd-rich-rules.conf


• 기본 설정 값

banaction = iptables-multiport
banaction_allports = iptables-allports


• CentOS/RHEL 7 버전 이상 일 경우

firewalld 가 설치되어있는 CentOS/RHEL7 에서는 firewall 을 통해 관리하려면 firewallcmd-new 을 입력하면 되며 또는 기본 값인 iptables 를 그대로 사용해도 됩니다.

banaction = firewallcmd-new

banaction_allports = firewallcmd-allports


• banaction

iptables 을 사용시 "iptables-multiport"

firewalld 을 사용시 "firewallcmd-new" 값 입력


포스팅에서는 기본 값으로 사용하였습니다.

[참고] firewalld 사용시 정책에 의해서 차단된 ip 리스트는 --get-all-rules 를 통해 확인할 수 있습니다.
$ firewall-cmd --direct --get-all-rules


[sshd]
#여러 포트를 사용할 경우 다음과 같이 지정: port = ssh,10022
port = ssh
enabled = true
# enabled = true 를 입력 해줍니다.

ignoreip=127.0.0.1,10.10.10.0/24,192.168.56.15
protocol = all
banaction = iptables-allports


# enabled = true

# ssh 외 여러 서비스에 대해서 감지할 수 있습니다.
# 사용하려는 항목(속성) 에서 enabled 속성을 true 로 변경 혹은 추가해야 합니다.

# ignoreip 를 지정하여 차단하지 않아야 하는 인증된 PC IP나 문제 시 꼭1개의 IP는 허용을 하여 접속을 할 수 있도록 설정이 필요합니다. 콤마나 공백(띄어쓰기) 로 여러 개의 ip를 입력할 수 있습니다. (위의 IP는 설정의 예시입니다)

# protocol 과 banaction 을 별도로 지정하지 않으면 ssh 를 통해 잘못된 접속을 시도하여 block(ban) 되었을 경우 ssh 프로토콜만 차단됩니다. ssh 외 다른 모든 포트도 차단, 즉 IP 자체를 차단하려면 위의 설정과 같이 protocol, banaction 을 추가로 입력하면 됩니다


Fail2ban 서비스 시작

위에서 추가/수정이 완료되었다면 Fail2ban 을 재시작 합니다.


ubuntu$ sudo systemctl enable fail2ban

ubuntu$ sudo systemctl restart fail2ban


ubuntu$ sudo systemctl status fail2ban

            

Fail2ban 로그 및 상태 확인

Fail2ban 로그 확인

파일 : /var/log/fail2ban.log

ubuntu$ tail -100f /var/log/fail2ban.log


차단 현황 확인

ubuntu$ sudo fail2ban-client status sshd


sqlite3 DB 확인

Fail2ban 은 차단된 IP 목록을 sqlite3 DB 파일로 저장됩니다.


파일 위치 확인

ubuntu$ sudo fail2ban-client get dbfile
Current database file is:
`- /var/lib/fail2ban/fail2ban.sqlite3


sqlite 로 DB 파일 내용 확인

$ sudo sqlite3 /var/lib/fail2ban/fail2ban.sqlite3 .table


sqlite3 스키마 정보 확인

$ sudo sqlite3 /var/lib/fail2ban/fail2ban.sqlite3 .schema


Bans 테이블에서 차단된 IP 조회

$ sudo sqlite3 /var/lib/fail2ban/fail2ban.sqlite3 "select distinct ip from bips;"

xxx.xxx.xxx.101
xxx.xxx.xxx.103
xxx.xxx.xxx.105


차단된 IP해제(복구) 하기

다음 명령어로 IP 차단을 해제합니다.


ubuntu$ sudo fail2ban-client set sshd unbanip IP주소


수동으로 IP 차단 추가하기

firewalld/iptables 에 차단할 IP 정책(룰)을 추가하는 것처럼 fail2ban 에서 아이피 별로 별도로 추가를 할 수 있습니다.

# ip ban/unban 기능 명령어
sudo fail2ban-client set <JAIL> banip <IP>
sudo fail2ban-client set <JAIL> unbanip <IP>


# Jail 목록 조회
sudo fail2ban-client status
Status
|- Number of jail:      1
`- Jail list:   sshd


# Jail - sshd 로 차단 된 내역 확인
sudo fail2ban-client status sshd 
Status for the jail: sshd
|- Filter
|  |- Currently failed: 131
|  |- Total failed:     13290
|  `- File list:        /var/log/auth.log
`- Actions
   |- Currently banned: 493
   |- Total banned:     494
   `- Banned IP list:   123.123.123.123 


# 차단/차단 해제 명령어 실제 예시
fail2ban-client set sshd banip 12.12.12.12
fail2ban-client set sshd unbanip 12.12.12.12

             

SSH 보안 옵션 설정

보안 관련하여 ssh 서버 설정을 확인해보겠습니다. 설정 파일은 /etc/ssh/sshd_config 입니다.

• Protocol 2
ssh 1 과 2 중 2.0만 사용하겠다 라는 의미입니다.
1.0 버전이 취약하며 공격자는 중간자 공격으로 SSH Downgrade Attack 할 수 있으므로 반드시 2.0만 사용하도록 sshd_config 설정을 해야 합니다


• LoginGraceTime

=>LoginGraceTime 60
해석을 해보면 "로그인 허용 시간" 정도가 되겠는데요
주석을 풀고 60을 써주면 60초 만 허용하겠다 라는 의미로써 시간은 짧은 수록 좋을 것 같습니다


• PermitRootLogin no
root 계정의 접속을 허용치 않겠다 라는 것입니다 yes는 접속을 허용한다는 것임으로 no 로 설정하시면 됩니다.


• Allow/Deny 옵션
주석에는 없지만 쓸수 있는 옵션으로 아래와 같은 옵션이 있습니다.

AllowGroups

AllowUsers
DenyGoups
DenyUsers

예를 들어 OS 계정의 그룹을 member 라고 설정하였다면 아래와 같이 설정할 수 있습니다.

AllowGroups member

DenyGroups root

위와 같이 구성 시 member 그룹에 속한 일반계정만 접속이 가능하게 됩니다.
또한 AllowUsers testuser@192.168.0.25 와 같이 IP까지 접속 가능/불가 정책의 기준으로 내용을 넣을 수도 있습니다.

정리하면 root 계정의 로그인 차단/거부와 AllowGroups 나 AllowUsers 를 이용하여 실제 사용하는 유저들만 접속 가능하게 설정할 수 있습니다.


• PasswordAuthentication no

password 인증을 비활성화 함으로써 키 인증으로만 사용 가능하도록 설정하는 내역입니다. 

추가적으로 같이 설정할 부분이 공개키 정보의 인증키 파일명입니다.
AuthorizedKeysFile .ssh/authorized_keys

공개키 정보를 입력할 인증키 파일을 설정하는 옵션 으로 기본값인 authorized_keys 파일을 사용하면 됩니다.



연관된 다른 글

 

 

 

 

 

0
글에 대한 당신의 생각을 기다립니다. 댓글 의견 주세요!x