iptables정보를 저장하고 재부팅 이후에도 동작하도록 설정함. <= vi 로 열어서 맨 마지막에 추가함.
1 2 3
sudo sh -c "iptables-save > /backup/iptables.rules" sudo vi /etc/network/interfaces pre-up iptables-restore < /etc/iptables.rules
Web
기본 httpd 사용을 위한 80번 포트 개방과, node.js, python 등 실습을 위한 8080번 포트를 열어 주기 위해서 /etc/sysconfig/iptables 에 아래와 같이 입력한다.
1 2 3 4 5
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT -A OUTPUT -p tcp -m tcp --dport 80 -j ACCEPT -A INPUT -p tcp -m tcp --dport 8080 -j ACCEPT -A OUTPUT -p tcp -m tcp --dport 8080 -j ACCEPT -A INPUT -j REJECT --reject-with icmp-host-prohibited
iptables 규칙을 만들 때는 순서가 매우 중요하다. 이 때 주의해야 할 것은 위의 4개 코드가 빨간 색의 코드보다 반드시 위에 적혀 있어야 한다.
예를 들어 만일 chain에서 로컬 192.168.100.0/24 서브넷에서 들어오는 모든 패킷을 drop하도록 지정한 후 (drop 하도록 지정된 서브넷에 포함되는) 192.168.100.13에서 들어오는 패킷을 모드 허용하는 chain (-A)을 그 후에 추가하면 뒤에 추가된 추가 규칙이 무시된다. 먼저 192.168.100.13를 허용하는 규칙을 설정한 후 서브넷을 drop하는 규칙을 설정해야한다.
이후에
service iptables restart
명령어를 실행해주면 2개의 포트가 열러서 정상적으로 외부접속이 가능해지는 것을 확인할 수 있다.
jail.conf: jail 이라 불리는 모니터링할 대상에 대한 기본 옵션과 행위를 선언한다.
action.d/iptables-multiport.conf: fila2ban 이 jail에 맞게 거부(Ban)한 IP를 다루는 기본 액션이다.
fail2ban.local : fail2ban 주요 설정 파일
jail.local: jail 설정 파일
jaild.d/defaults-debian.conf: jail enable/disable
paths-common.conf: 로그 파일 경로
paths-debian.conf: 로그 파일 경로
설정
fail2ban은 jail 을 구성하고 jail의 filter 그리고 action으로 나뉘어 있다.
fail2ban.conf 구성
fail2ban.conf는 기본 구성 변수로 loggin, socket 그리고 PID 파일 등등이 설정된다. 별도의 파일로 Jail을 구성할 때 fail2ban.local 같은 이름을 사용하고 새로 설정되는 값은 기본 설정 값을 재정의 하게 된다.
단 같은 [default] 섹션이 존재하면 구성된 내용 적용이 잘 안된다.
다음 스크립을 사용하면 모둔 변수를 주석 처리하고 수정할 옵션만 복사해 준다.
1
sed 's/\(^[[:alpha:]]\)/# \1/' fail2ban.conf | sudo tee fail2ban.local 1&> /dev/null
fail2ban.local 파일은 다음과 같은 내용을 담을 것이다.
loglevel: The level of detail that Fail2ban’s logs provide can be set to 1 (error), 2 (warn), 3 (info), or 4 (debug).
logtarget: Logs actions into a specific file. The default value of /var/log/fail2ban.log puts all logging into the defined file. Alternately, you can change the value to STDOUT, which will output any data; STDERR, which will output any errors; SYSLOG, which is message-based logging; and FILE, which outputs to a file.
socket: The location of the socket file.
pidfile: The location of the PID file.
jail.conf
/etc/fail2ban/jail.conf 는 데몬, 서비스에 대한 jail을 구성한다. jail은 log를 읽어 불필요한 것을 찾아 낸다. 다음은 jail.conf에서 주석이 달린 jail.local을 생성해 준다.
1
sed 's/\(^[[:alpha:]]\)/# \1/' jail.conf | sudo tee jail.local 1&> /dev/null
If using CentOS or Fedora open jail.local and set the backend to systemd. This is not necessary on Debian 8, even though it is a SystemD system.
/etc/fail2ban/jail.local
1
backend = systemd
화이트리스트 IP
먼저 검출된 IP 중에 무시할 영역, 화이트리스트를 선언해 줍니다. 리스트는 ‘,’로 구분하고 서브넷 혹은 IP주소를 입력한다.
1 2
[DEFAULT] ignoreip = 127.0.0.1/8 192.168.0.1/24
차단 시간과 재시도 횟수
bantime, findtime, maxretry 은 차단 시간에 대한 구성이다.
1 2 3
bantime = 2592000 findtime = 600 maxretry = 3
bantime: 검출된 IP가 접속 차단 시간을 초단위로 선언해 준다. -1 이면 영속적으로 밴 된다.
fail2ban에 검출되는 jail이 있으면 이메일 설정에 따라 메일로 경고를 받을 수 있다.
destemail: The email address where you would like to receive the emails.
sendername: The name under which the email shows up.
sender: The email address from which Fail2ban will send emails.
그리고 action 설정을 조절할 필요가 있다, 이것은 ban 상황이 기준점에 닿으면 발생한다. 기본 액션 %(action_)s은 사용자만 ban 한다. action_mw 액션은 ban을 실행하고 WhoIS 리포트로 메일을 보내준다. action_mwl은 모든 로그까지 함께 보내준다.
You will also need to adjudst the action setting, which defines what actions occur when the threshold for ban is met. The default, %(action_)s, only bans the user. action_mw will ban and send an email with a WhoIs report; while action_mwl will ban and send an email with the WhoIs report and all relevant lines in the log file. This can also be changed on a jail-specific basis.
1
action = %(action_)s
1
$ sudo service fail2ban restart
각 서버스에 대한 Jail 설정
필터를 이용해 Jail을 만들어 의심스런 접근을 막아 보자. 앞서 복사한 jail.local 파일에는 주요 서비스가 모두 선언되어 있고 sshd 만 활성화 되어 있다.
enabled: Determines whether or not the filter is turned on.
port: The port Fail2ban should be referencing in regards to the service. If using the default port, then the service name can be placed here. If using a non-traditional port, this should be the port number. For example, if you moved your SSH port to 3456, you would replace ssh with 3456.
filter: The name of the file located in /etc/fail2ban/filter.d that contains the failregex information used to parse log files appropriately. The .conf suffix need not be included.
logpath: Gives the location of the service’s logs.
maxretry: Will override the global maxretry for the defined service. findtime and bantime can also be added. action: This can be added as an additional setting, if the default action is not suitable for the jail. Additional actions can be found in the action.d folder.
각 서비스에 대한 jail은 jail.d에 설정 파일을 구성해도 된다.
(1) sshd
Brute-force Attack과 같은 접근을 차단하는 필터로 로그에 아래와 유사한 패턴이 나오면 IP를 검출한다.
Jul 22 06:56:50 foo sshd[14984]: Failed password for invalid user a from xxx.xxx.xxx.xxx port 55452 ssh2
jail.config 혹은 jail.local 에서 기본으로 활성화 되어 있다.
(2) ssh-ddos
sshd-ddos Filter를 사용해 SSH Service를 Scanning하거나 telnet으로 접속할 떄 발생하는 Message를 검사하여 해당 IP의 접근을 차단할 수 있습니다.
이 Filter로 검출되는 /var/log/auth.log의 Message는 다음과 같습니다.
Jul 23 13:16:25 foo sshd[21989]: Did not receive identification string from xxx.xxx.xxx.xxx
Jail 설정을 위해서 다음과 같이 입력합니다.
1 2
[sshd-ddos] enabled = true
혹은 $ sudo vi /etc/fail2ban/jail.d/sshd-ddos.conf
1
$ sudo service fail2ban restart
Failregrexs
다양한 필터를 사용할 수있다. 의심스런 동작을 Filter로 선언해서 사용하는데 해당 필터를 점검해야할 필요가 있다. 다음
$ sudo fail2ban-client status Status |- Number of jail: 6 `- Jail list: nginx-noproxy, nginx-noscript, nginx-nohome, nginx-badbots, ssh-ddos, ssh
그리고 iptable의 서비스로 방화벽 규칙에 fail2ban 규칙이 동작중인지 확인한다.
1 2 3 4 5 6 7 8 9 10 11 12
$ sudo iptables -S ...
-A fail2ban-nginx-badbots -j RETURN -A fail2ban-nginx-nohome -j RETURN -A fail2ban-nginx-noproxy -j RETURN -A fail2ban-nginx-noscript -j RETURN -A fail2ban-ssh -j RETURN -A fail2ban-ssh-ddos -j RETURN
...
그리고 fail2ban 의 jail 실행 상태를 자세히 보고 싶므면 status 뒤에 jail 이름을 주면 된다.
1 2 3 4 5 6 7 8 9 10
$ sudo fail2ban-client status nginx-badbots Status for the jail: nginx-badbots |- filter | |- File list: /var/log/nginx/access.log | |- Currently failed: 0 | `- Total failed: 0 `- action |- Currently banned: 0 | `- IP list: `- Total banned: 0
Testing
의심스런 동작을 Filter로 선언해서 사용하는데 해당 필터를 점검해야할 필요가 있다. 다음
nginx 인증 요구시 잘못된 인증을 시도하면 fail2ban 규칙에 따라 접근이 금지당한다. 그리고 jail 규칙이 잘 적용 됐는지 결과를 다음 같이 확인할 수 있다:
1 2 3 4 5 6 7 8 9 10 11
$ sudo fail2ban-client status nginx-http-auth Output Status for the jail: nginx-http-auth |- filter | |- File list: /var/log/nginx/error.log | |- Currently failed: 0 | \- Total failed: 12 \- action |- Currently banned: 1 | \- IP list: 111.111.111.111 \- Total banned: 1
인증 규칙에 어긋나는 접근을 시도한 IP인 111.111.111.111을 확인 할 수 잇다. 금지된 IP는 해당 jail을 이용해 다음 같이 해제할 수 있다.
1
$ sudo fail2ban-client set nginx-http-auth unbanip 111.111.111.111
$ tmux # 세션을 시작하고 참가한다. $ tmux new -s foo # 세션 foo를 시작하고 참가한다
세션에 참가하면 하나 혹은 그 이상의 윈도우에서 Pane을 배치해 사용할 수 있다.
[그림. Tmux window layout]
Control와 Meta key
Tmux 세션 참가후 Window에서는 Prefix key로 Session, Window, Pane 관련 명령을 키로 조합해 사용한다. 기본 Prefix key는 Control+b key고 옵션으로 사용하는 Meta key는 Alt 키 이다.
여기서 Prefix key는 C와 조합으로 표기하고, Meta key인 Alt는 M으로 표기한다.
윈도우 명령 control, meta 키 조합과 병행해 윈도우에서 명령모드를 사용할 수 있다. 명령모드는 C-: 키로 시작하고, 명령모드에서 명령 자동 완성을 지원한다.
[그림. Window command mode]
Pane 다루기
윈도우는 수직/수평으로 구획을 나눌수 있다. C-“ 키로 현재 Pane 아래에 수평으로 새 Pane을 나눈다. 그리고 **C-%**키로 수직으로 새 Pane을 나눌 수 있다.
[그림. Tmux Window Pane]
C-q : pane 번호를 표시하고 번호를 눌러서 이동
C-o : pane을 순서대로 이동
C-방향키 : 해당 방향으로 이동
C-M-방향키 : 해당 방향으로 크기 조절
C-M-1~5 : 몇 가지 미리 설정된 레이아웃을 고를 수 있고, prefix space로 이 레이아웃을 순서대로 - 돌아가며 선택 가능
C-z : 특정화면만 확대하기 다시 예전 Panes상태로 돌아오기
Pane을 지우려면 터미널 exit 명령 혹은 C-x 키로 빠져 나올 수 있다.
Window 다루기
윈도우는 명령모드에서 new-window 혹은 C-c 키로 새 윈도우를 추가할 수 있다.
[그림. new Window ]
윈도우 사이의 이동은 윈도우 번호에 따라 단축키 C-0,1,2…9를 사용하거나 C-w로 윈도우 목록에서 선택해 이동할 수 있다.
C-n, C-p : 다음 윈도우, 이전 윈도우로 이동
C-l : 직전 사용하던 윈도우로 이동
C-w : 윈도우 리스트를 띄우고 선택
C-, : 윈도우 이름 바꾸기
세션 사용중에 세션을 빠져 나오려면 C-d 로 detach 하거나, 명령모드 C-:에서 detach 명령을 준다.
복사와 스크롤
Tmux 화면 버퍼는 한 화면분 밖에 안되서, 이전 화면 내용을 보려면 스크롤 기능을 켜야 한다. C+[ 키는 스크롤 키고, 우측상단에 페이지 표시가 나타난다. 키보드 방향키나 Page Up/Down키로 스크롤이 가능하다.
세션 연결
세션은 하나 혹은 그 이상 만들고 attach 명령으로 세션에 참가할 수 있다.
1 2 3 4
$ tmux new -s foo -d # 세션 foo를 시작하고 빠져나온다. $ tmux ls # 세션 목록을 출력한다. 0: 1 windows (created Fri May 12 10:26:00 2017) [80x24] (attached) foo: 1 windows (created Fri May 12 10:34:18 2017) [80x24]
터미널에서 세션에 참가하려면 attach 명령과 대상 세션을 지정해 준다. 대상 세션은 tmux ls 명령에 표시되는 세션번호 혹은 세션이름을 지정한다.
set -g @plugin 'tmux-plugins/tmux-resurrect' set -g @plugin 'tmux-plugins/tmux-continuum'
tmux 에서 플러그인 설치를 위해서 C-I (대문자) 를 실행
그리고 .tmux.conf 파일에 continuum-restore 을 on으로 해준다.
1
set -g @continuum-restore 'on'
tmux 세션을 모두 나와서 tmux 서버를 모두 kill-session 같은 명령으로 종료시킨후 tmux를 다시 시작하면 .tmux/resurrect 에 저장된 마지막 세션이 복구되는 것을 확인할 수 있다.
이제부터 15분 마다 자동 저장하고 서버를 재시작한 후에 tmux를 다시 시작하면 저장한 환경을 자동으로 복구해 준다.
tmux status 표시
tmux-continuum 의 상태를 tmux status line에 표시할 수 있다.
1
set -g status-right 'Continuum status: #{continuum_status}'
Linux에서 tmux 자동 시작
tmux-continuum 은 Linux systemd, macOS 에서 자동 시작을 지원한다.
Linux는 .tmux.conf 파일에 다음 부트 옵션을 추가한다.
1
set -g @continuum-boot 'on'
그리고 현재 실행중인 세션에 변경한 설정을 적용하려면
1
$ tmux source-file ~/.tmux.conf
macOS에서 tmux 자동 시작
.tmux.conf 파일에 다음 부트 옵션을 추가한다.
1
set -g @continuum-boot 'on'
그리고 현재 실행중인 세션에 변경한 설정을 적용한다.
1
$ tmux source-file ~/.tmux.conf
맥이 재시작 하면 자동으로 Terminal.app 이 실행된다. 터미널 크기는 다음 옵션으로 지정한다:
1 2 3 4
set -g @continuum-boot-options 'fullscreen'# terminal window will go fullscreen set -g @continuum-boot-options 'iterm'# start iTerm instead of Terminal.app set -g @continuum-boot-options 'iterm,fullscreen'# start iTerm in fullscreen
다중 tmux 서버는 지원하지 않는다.
tmux 로 서버를 하나 시작하고, tmux -S /tmp/foo 같이 다른 소켓을 사용했다고 자동 저장/복구가 별도로 진행되지 않는다. [^10]