iptables 1.3.7 with Linux Kernel 2.6.21

이번에 바닐라 커널

linux-2.6.21 버전과

iptables-1.3.7 버전을 설치 했다.

geoip도 함께 컴파일 하려고 했지만... 2.6.20 버전에선... 설치는 되는데

reboot가 안 되는 문제가 있는듯 하여 .21 버전으로 업그래이드 하였으나

컴파일이 정상적으로 되지 않는 문제가 생겼다.

하여 geoip는 제외 시키고 string_match 만 믿고 컴파일 하였다.

기존 iptables 1.2.x 대는 string_match 옵션에 따라서 하면 되지만

inux-2.6.14 버전 이후로??? 옵션을 추가해줘야 string_match 를 활성화 해 줄 수가있다.

관련 문서


.SS string
This modules matches a given string by using some pattern matching strategy.
It requires a linux kernel >= 2.6.14.

.TP
.BI "--algo  " "bm|kmp"
Select the pattern matching strategy. (bm = Boyer-Moore, kmp = Knuth-Pratt-Morris)
.TP
.BI "--from " "offset"
Set the offset from which it starts looking for any matching. If not passed, default is 0.
.TP
.BI "--to " "offset"
Set the offset from which it starts looking for any matching. If not passed, default is the packet size.
.TP
.BI "--string " "pattern"
Matches the given pattern.
.BI "--hex-string " "pattern"
Matches the given pattern in hex notation.

크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 삐꾸강아쥐

2007/04/29 16:47 2007/04/29 16:47
, , ,
Response
0 Trackbacks , 0 Comments
RSS :
http://blog.blog.n-nuri.com/rss/response/338

Trackback URL : http://blog.blog.n-nuri.com/trackback/338

Leave a comment
[로그인][오픈아이디란?]

iptables 특정 IP ping 허용

특정 IP에서 ping 허용

iptables -A OUTPUT -o eth0 -p icmp --icmp-type echo-reply -s 12x.140.2x8.0/24 -j ACCEPT <== 나가는측
iptables -A INPUT -i eth0 -p icmp --icmp-type echo-request -s 21x.45.1x0.0/24 -j ACCEPT <== 들어 오는측

ping을 허용 안 하면 좋겠지만

서버 모니터링 프로그램이나 기타 등등 관리 목적으로 ping을 허가해 줘야 할 경우가 생긴다

이런 이유로 특정 IP에 대하여 ping을 허가해 주자
크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)

Posted by 삐꾸강아쥐

2007/04/16 11:19 2007/04/16 11:19
Response
0 Trackbacks , 6 Comments
RSS :
http://blog.blog.n-nuri.com/rss/response/278

Trackback URL : http://blog.blog.n-nuri.com/trackback/278

Comments List

  1. 6년근홍삼 2007/09/28 16:59 # M/D Reply Permalink

    제가 사무실에서 쓸려고 리눅스방화벽을 실험해보고 있습니다. 한가지 문제가 있는데 방화벽안의 192.168.0.0/24 에서 밖의 192.168.1.0/24 으로 통신은 가능한데 방화벽안의 pc끼리는 ping 과 윈도우 작업그룹이 되지 않습니다. 80번 포트는 되더군요. 원래 리눅스 방화벽 초기 설정이 클라이언트들의 통신을 80포트 빼고 모두 차단하나요?

    1. 삐꾸강아쥐 2007/09/28 20:56 # M/D Permalink

      일반적으로... 내부는... 아무런 제한이 없이 통신이 되는데요???

      방화벽 상태를 보세요... 내부 인터페이스쪽을 막아 버렸으면 그럴수도 있습니다.


      아... 그리고 혹시 내부 컴이 윈도우 이시면... 윈도우쪽 방화벽 상태 보세요...

      윈도우에도 방화벽이 있답니다...

  2. 6년근홍삼 2007/09/29 11:32 # M/D Reply Permalink

    관심에 감사드립니다. 2)의 윈도우방화벽은 아니라고 생각됩니다. 허브로 연결할때는 되거든요. 리눅스의 내부 NIC인 eth1 의 iptables 에 원인이 있다고 생각되지만 정확히 뭔지 알수가 없군요.

    원인 파악을 위해 어떤 iptables 규칙때문에 차단되는지 알수 있는 방법이 있나요? 로그기록 같은거요.

    혹시 사용하고계신 iptables 예제를 좀 얻을수 있을까요? 그대로 적용해 보게요.

    거듭 답변에 감사드립니다.

    1. 삐꾸강아쥐 2007/09/30 09:46 # M/D Permalink

      뭐... iptables 룰 때문 이라고... 생각 되시면...

      사설 IP 인 상태시겠죠???

      그러면... iptables 룰셋을... 해제 해 보세요~!

      iptables -F

      그러면 정확하게... 룰셋 문제인지 알수가 있죠...^^

  3. 6년근홍삼 2007/10/01 13:19 # M/D Reply Permalink

    됐습니다. 혹시나 해서 보니 윈도우 방화벽문제 이더군요. 실제로 사용중인 pc들은 델인데 이번에 실험에 쓴 것들은 옛날 해커스 제품이었습니다. 서비스팩 2로 업그레이드 했는데 델하고 방화벽 설정이 다르더군요. 그래서 윈도우 방화벽문제는 아닐 것이라는 편견으로 삽질을 했군요. 정말 감사드립니다.

    1. yjj3019@empal.com 2007/10/01 14:29 # M/D Permalink

      ^^ 해결 되셨다니... 다행이네요....

Leave a comment
[로그인][오픈아이디란?]

iptables (호스트기반의 방화벽)

출처 : http://blog.naver.com/shseyo?Redirect=Log&logNo=20031767171
사용자의 요청이 있을경우 자삭 합니다.


iptables -L  ==> 목록 열람

iptables -F  ==> 기존에 설정된 것을 전부다 없앤다.


iptables 명령어순서

1. chain name - 체인에 설정할 내용 (insert/delete/replace..) ex) -I CHAIN 3, -A, -D, -R, -F

2. table name - filter(기본값),nat,mangle ex) -t nat, -t filter(기본값)

3.Layer 3 - ex) -s ip주소, -d ip주소

4.Layer 4 - ex) -p tcp --dport 80, -p udp --sport 21

5.Target - ex) -j ACCEPT,LOG,DROP,REJECT


호스트기반의 방화벽에서, serv컴이 방화벽이 설치되어있다.

퀴즈1) serv컴퓨터로 접속할 수 있는 client 중 ip가 192.168.247.20(work)가 있다.

         serv컴에서 이 컴퓨터의 모든 접속을 차단하고자 한다.

         어떻게 방화벽을 셋팅을 해야 할까..

===>INPUT 기본 정책이 ACCEPT로 되어있기에 work컴만 DROP또는 REJECT 시키면 된다.

     iptables -I INPUT -t filter -s 192.168.247.20 -j DROP (DROP은 ping도 거절한다.모든응답차단)   

                       (REJECT는 ping응답을 받고 보낸다)


iptables-save > /root/firewall.rule  ==>룰을 저장

iptables-restore < /root/firewall.rule  ==>룰을 불러옴


컴퓨터가 재부팅되면 설정되었던 iptables룰이 없어진다.

==>/etc/sysconfig/iptables ==> 기본설정룰

    /etc/sysconfig/iptables-config  ==> 환결설정화일

vi iptables-config

19행 IPTABLES_SAVE_ON_STOP="yes"

25행 IPTABLES_SAVE_ON_RESTART="yes"

로 바꾸면 재부팅되어도 설정된 룰이 사라지지 않는다.

iptables -L -v ==> 차단한 패킷의 수와 사이즈를 확인

iptables -L --line-numbers  ==> 룰의 순서를 보여준다.

iptables -L -n ==> 문자주소가 숫자주소로 바뀌어 출력된다. or -nL



iptables -R INPUT 3 -t filter -s 10.1.1.0/24 -j REJECT

iptables -D INPUT 3


iptables -Z  ==>iptables -L -v 로 확인했던 차단패킷 사이즈등을 초기화시킴(모니터링을위해)


<사용자정의체인>:관리의 편의성을 위해서 사용한다.

iptables -X RH-Firewall-1-INPUT  ==>사용자정의 체인 삭제

iptables -N INTRANET  ==>사용자정의 생성

iptables -E INTRANET EXTRANET  ==>사용자정의 이름 변경


*매칭되는 룰이 없을경우는 기본정책의 적용을 받는다.

iptables -A EXTRANET -t filter -s 192.168.247.1 -j ACCEPT

*사용자 정의 체인은 만들어도 쓸수 없다. 링크가 되어 있어야 쓸 수 있다.(0 references)

*INPUT체인에서 EXTRANET에 링크로 갔다가 다시 INPUT으로 돌아와서 다 적용해본후 아무런 매칭된 경우가 없을 경우 INPUT의 기본정책에 적용된다.

iptables -I INPUT 2 -j EXTRANET ==>EXTRANET을 링크시킨다.

iptables -D INPUT 2



*1)사용자 정의를 삭제하기 위해서는 링크를 먼저 삭제해야한다.

*2)사용자 정의를 삭제하기 위해서는 체인내의 모든 RULE을 삭제

iptables -D INPUT 3

iptables -X EXTRANET

iptables -F EXTRANET  ==>EXTRANET 사용자정의체인내의 룰만 삭제한다..


퀴즈) serv컴퓨터에서는 work컴퓨터에서의 telnet접속만 차단할 수 있도록 rule셋팅하세요.

iptables -I INPUT -t filter -s 192.168.247.20 -p tcp --dport 23 -j DROP


iptables -P FORWARD DROP

iptables -P INPUT DROP


퀴즈) serv컴에서는 work 컴에게 ssh접속만 허용하고 xp컴에게는 telnet 접속만 허용하도록 설정하시고 그 이외의 모든 접속을 차단하도록 설정해보세요.

iptables -P INPUT DROP

iptables -A INPUT -t filter -s 192.168.247.20 -p tcp --dport 22 -j ACCEPT

iptables -A INPUT -t filter -s 192.168.247.1 -p tcp --dport 23 -j ACCEPT



iptables -A INPUT -t filter -p tcp --sport 1:1023 -j ACCEPT  ==>1세대방화벽의 단점(ssh,telnet등의 서비스들의 ack/syn패킷을 받기 위해서 사용)



상태추적기능을 이용해보자.

*ping은 echo-request와 echo-reply를 사용한다.

              <-m state --state>

NEW상태는  접속요청하면 아무나 다 접속된다.(SYN패킷을 가져오는 컴은 다 접속된다.)

ESTABLISH상태는 접속요청에대한 응답패킷을 establish상태라고 한다.요청으로 나갔다가 다시들어오는 패킷들을 허용한다.

RELATED ftp서버를 위해서

INVALID 연결상태를 알수 없거나 잘못된 페더를 가진 경우


iptables -I INPUT 1 -t filter -m state --state ESTABLISHED,RELATED -j ACCEPT 이제는 외부로의 ftp나 ping등의 접속이 된다.나갔다가(sync) 다시 되돌아오는 패킷(sync ack)들을 허용하기위해서(상태추적테이블을 이용한다.)

cat /proc/net/ip_conntrack ==> 상태추적 테이블 저장

방화벽은 2-3계층사이에서 동작한다.

iptables -I INPUT 1 -t filter -m state --state NEW,RELATED,ESTABLISHED ==> 모든 서비스가 다 접속이 되어 버린다. ( 절대로 이런설정은 하면 안된다.)


UDP:123

SysLog-UDP:514

TFTP UDP:69

UDP포트는 서비스를 제공받을시 똑같은 포트를 이용한다. 123/UDP <---------------->123/UDP

                                                                              SERVER                             CLIENT


퀴즈) work 컴퓨터에서만 핑을 허용하고 그외의 모든 핑은 차단한다.

iptables -A INPUT -t filter -s 192.168.149.20 -p icmp --icmp-type echo-request -j ACCEPT


멀티포트

iptables -I INPUT 1 -p tcp -m multiport --dport 80,22,25 -j ACCEPT


노트북을 이용해서 이동하면서 원격접속시는 ip어드레스가 바뀌므로 방화벽에 의해 접속이 안되는 경우를 위해서 맥어드레스를 이용해서 방화벽허용을 한다.

00:0C:29:D4:46:58

iptables -I INPUT 3 -t filter -m mac --mac-source 00:0C:29:D4:46:58 -p tcp --dport 22 -j ACCEPT


-j LOG  --> /var/log/messages

vi /etc/syslog.conf

3행수정 kern.*                      /var/log/firewall

-j LOG는 순서를 맨위로 하는 것이 좋다. 로그기록을 하고 바로 밑으로 순서대로 진행한다.

iptables -I INPUT -t filter -p tcp --dport 23 -j LOG --log-prefix "Warning telnet access"

사용자체인을 걸어서 로그기록들의 링크를 걸어놓는 것이 좋은 방법이다.


우리가 열어놓지 않는 포트에의 접속시도의 로그를 남기는 것이 더 효율적이다.

퀴즈)serv컴퓨터에서 접속을 허용한 ssh,web 서비스 이외의 접속에 대해서 로그를 생성할 수 있도록 방화벽 셋팅을 하세요(단 로그를 남길때 "not permit access" 코맨트를 첨부하세요) (not,multiport이용)

==>iptables -I INPUT 1 -t filter -p tcp -m multiport --dport ! 21,22,23,80 -j LOG --log-prefix "not permit access"

크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기

Posted by 삐꾸강아쥐

2007/02/07 10:19 2007/02/07 10:19
Response
0 Trackbacks , 0 Comments
RSS :
http://blog.blog.n-nuri.com/rss/response/257

Trackback URL : http://blog.blog.n-nuri.com/trackback/257

Leave a comment
[로그인][오픈아이디란?]

SSH 자동으로 무단 접근 IP 막기

http://blog.naver.com/salpoosi/22951010

전제 조건

관리용으로 모든 아이피에서 접근 할 수 있도록 서버 설정이 되어 있는 경우, 불특정 IP에서

SSH 포트로 로그인 시도가 일어난다.

불특정 IP를 자동으로 /etc/hosts.deny 에 등록함으로서 접근 시도를 방지한다.

사용환경

fedora 5

첫번째로 ssh 에 대한 log 기록은 /var/log/secure에 기록된다.

var/log/secure에 기록된 로그 중에서 로그인 시도를 한 IP를 찾아낸다.

grep "Failed password for" /var/log/secure | egrep -v "invalid user|{USERID}|{LOGINIP}" | awk '{ print $11}' | uniq | sed "s/^/all:/" > /tmp/anonymous_login

grep "Failed password for invalid user" /var/log/secure.1 | awk '{ print $13}' | uniq | sed "s/^/all:/" >> /tmp/anonymous_login

{USERID} 부분에는 로그인 하기 위한 ID를 설정한다. 이것을 설정하지 않으면 자기가 로그인 시도를 하다가 실패를 할 경우 콘솔로 가거나 다른IP 장소에서 로그인하지 않으면 안된다.

{LOGINIP} 로그인 장소가 고정아이피이며 특정IP에서는 발생하는 로그인 실패기록은 무시를 할 경우 기록한다. 유동아이피 일 경우는 주의 하도록 한다.

{ print $11} 부분은 접속 실패가 일어 날 경우 접속 거부할 상대방의 IP의 위치

다른 배포판을 위하여 /var/log/secure에 기록되는 내용이 배포판마다 다를 수 있으므로 grep문에 로그를 찾기 위한 부분이나 egrep -v로 로그파일에서 취득하고 싶지 않는 내용을 적거나 awk에 의해 취득해 오기 위한 해당 열의 위치등 설정을 바꾸어 보도록 한다.

- 첫번째의 grep은 존재하는 user id 로 시도를 하려고 할 때 로그인 실패시 IP를 얻기 위한 명령어

- 두번째의 grep은 존재하지 않는 user id 로 시도를 하려고 할 때 로그인 실패시 IP를 얻기 위한 명령어

두번째로는 만들어진 접속 거부 IP와 접속거부 설정 파일과의 머지 작업을 위해 임시 파일을 만든다.

cat /tmp/anonymous_login /etc/hosts.deny | sort | uniq > /tmp/hosts.deny

마지막으로 만들어진 임시 파일을 접속 거부 설정 파일로 복사한다.

cp /tmp/hosts.deny /etc/hosts.deny

위의 내용을 crontab에 넣어 자동적으로 갱신되도록 한다.

crontab -e로 현재의 crontab 내용을 열어 다음과 같이 넣도록 한다.

00 * * * * grep "Failed password for" /var/log/secure | egrep -v "invalid user|{USERID}|{LOGINIP}" | awk '{ print $11}' | uniq | sed "s/^/all:/"  > /tmp/anonymous_login

03 * * * * grep "Failed password for invalid user" /var/log/secure.1 | awk '{ print $13}' | uniq | sed "s/^/all:/" >> /tmp/anonymous_login

05 * * * * cat /tmp/anonymous_login /etc/hosts.deny | sort | uniq > /tmp/hosts.deny

07 * * * * cp /tmp/hosts.deny /etc/hosts.deny

매 시간 한번씩 갱신이 되며 갱신 주기는 서버 로그를 보면서 조정하도록 한다.

각각의 클론 설정을 매 분 주기로 처리를 하지 않도록 한다. 로그 파일이 길어질 경우

기존의 hosts.deny 파일이 마지막으로 처리한 필터링으로만 설정될 수 있다.

자기 자신도 원격에서의 접속은 필히 주의를 하도록 한다. 실수를 하게 되면 로그에

로그인 실패 로그가 남게 되며 이 로그에 의해 원격지의 IP도 블럭이 된다.

실수를 하고 로그인을 했다면 로그 파일에서 실패 로그를 지우도록 한다.

참조

http://kltp.kldp.org/stories.php?story=05/08/02/4164861

수정 2006.04.26 필요하지 않는 sort 삭제, | sed "s/^/all:/" 추가

수정 2006.06.05 주의점 추가

수정 2006.08.28 주의점 추가

크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기

Posted by 삐꾸강아쥐

2006/09/27 21:13 2006/09/27 21:13
Response
0 Trackbacks , 0 Comments
RSS :
http://blog.blog.n-nuri.com/rss/response/201

Trackback URL : http://blog.blog.n-nuri.com/trackback/201

Leave a comment
[로그인][오픈아이디란?]

ssh 무차별 로그인 공격 막기

## 주의 ##
이 스크립트는 공개를 원칙으로 하나 재판매시는 허락을 받아야 합니다.
즉, 업체에서 이 스크립트를 이용하여 타 서버에 설정을 해주고
비용을 받을시에는 저작권에 침해됩니다.

안녕하세요 후비고닷컴(http://hubgo.com)의 이진명입니다.

ssh의 무차별 공격을 막기위해 시스템의 로그를 자동분석하여

공격을 막아주는 스크립트를 소개합니다.

2005년 2월 8일에 작성한 스크립트로서 이에 관련해

제가 알기론 뻥좀보태서 세계에서 가장 빨리 작성되지 않았나 싶습니다. ㅋ

문자열치환은 스크립트로 치환하도록 하였습니다.
(sed로 안에 포함시킬수 있지만 여러개 만들다 보면.. )

아래의 스크립트를 /etc/cron.hourly에 넣으면 한시간에 한번씩 실행됩니다.

스크립트 생성후

chmod 700 /etc/cron.hourly/ssh_defense.sh

해주셔야 실행됩니다.


잘 쓰셔서 아주 단순한 기법에 해킹당하는 일이 없도록 하세요.. ㅋㅋ

그리고 패쓰워드는 항상 영문과 특수문자의 조합으로..




vi /etc/cron.hourly/ssh_defense.sh
#!/bin/sh
#############
# 2005/02/08
# http://hubgo.com 이진명
# 아래 ch.sh라는 치환스크립트를 /var/log 에 옮겨놓아야 합니다.
# cron.hourly 에 등록하여 사용합니다.
# 제가 알기론 아래 링크 사이트도 후비고닷컴보다 릴리즈 날짜가 느리고
# 세계최초쯤 되지 않을까 싶네요..
#############
cd /var/log
grep "anonymous" secure | egrep -v '127.0.0.1|218.54.191.21|220.95.230.222' | awk '{ print $17}' > anonymous_login
grep "no such user" secure | egrep -v '127.0.0.1|218.54.191.21|220.95.230.222' | awk '{print $17}' >> anonymous_login
grep illegal secure | egrep -v '127.0.0.1|218.54.191.21|220.95.230.222' | awk '{print $12 $13 }' > illegal

## 문자 치환작업
sh ch.sh '\]' '' anonymous_login >> temp2
sh ch.sh '\[' ALL: temp2 > anonymous_login
sh ch.sh from ALL: illegal >> anonymous_login

sort anonymous_login | uniq >> /etc/hosts.deny
sort /etc/hosts.deny | uniq > temp
cat temp > /etc/hosts.deny


vi /var/log/ch.sh
#!/bin/bash
### ch.sh
# "subst", 파일에서 어떤 패턴을 다른 패턴으로 바꿔주는 스크립트.
# 즉, "subst Smith Jones letter.txt".

ARGS=3
E_BADARGS=65 # 필요한 인자가 빠져있음.

if [ $# -ne "$ARGS" ]
# 스크립트로 넘겨진 인자의 갯수를 확인(항상 이렇게 하세요).
then
echo "사용법: `basename $0` old-pattern new-pattern filename"
exit $E_BADARGS
fi

old_pattern=$1
new_pattern=$2

if [ -f "$3" ]
then
file_name=$3
else
echo "\"$3\" 은 없는 파일입니다."
exit $E_BADARGS
fi

# 여기가 가장 중요한 부분입니다.
sed -e "s/$old_pattern/$new_pattern/g" $file_name
# 's'는 sed의 치환(substitution) 명령어이고,
# /pattern/ 은 주소 매칭을 실행시킵니다.
# 전역(global) 플래그인 "g"를 쓰면 단지 첫번째 일치하는 $old_pattern만
#+ 치환시키지 않고 각 줄에서 일치하는 "모든" $old_pattern을 치환시킵니다.
# 더 자세한 설명은 'sed' 문서를 읽어보세요.

exit 0 # 스크립트의 실행이 성공이라면 0을 리턴.



그리고 마지막으로.... 하나더..

레드헷계열 리눅스는 설치후 아무런설정을 하지 않았다면

root로 ssh를 로그인 가능합니다.

그러므로 root의 직접적인 ssh login은 막고

일반계정으로 접속후 su - root 를 통해 root권한을 획득하여 작업하도록 합니다.

ssh 설정화일을 아래와 같이 열어 PermitRootLogin yes를 no로 변경합니다.


vi /etc/ssh/sshd_config
PermitRootLogin no


변경후 /etc/init.d/sshd restart 하여

sshd를 재시작 해줍니다.

여러분은 이것으로 기초적이지만 강력한 보안설정을 하셨습니다.


참고로 OS별 로그가 다를수 있습니다.
(Invalid, illegal 등)

자세한것은 제 홈페이지로 로그와 함께 문의주시면 수정해드리겠습니다.

감사합니다.


아참.. 디자이너분들이 제 홈피를 보시면 디자인좀 부탁드리겠습니다.

비영리 사이트이기 때문에 물론 무상으로요..

제글을 읽고 도움이 되셨다면 여러분들도 도와주세요.. ㅋ



리눅스~? 윈도우~? 다~ 후벼버리겠다~~ ㅋ
-------------------------------------------------
http://hubgo.com
크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기

Posted by 삐꾸강아쥐

2006/09/27 21:13 2006/09/27 21:13
Response
0 Trackbacks , 0 Comments
RSS :
http://blog.blog.n-nuri.com/rss/response/200

Trackback URL : http://blog.blog.n-nuri.com/trackback/200

Leave a comment
[로그인][오픈아이디란?]

ssh dictionary attack 막기 ver.2

ssh dictionary attack 막기 ver.2
출처 : http://my.oops.org/56
요즘 ssh dictionary attack 이 심합니다. (정확히 말하자면.. ssh brute force attack 이라고 하더군요 ^^) 일전에 제 blog 에서 geoip 를 이용해서 막는 방법을 소개를 했었습니다.

외국에서의 공격, 특히 중국에서의 공격을 막아서인지 현저하게 시도는 줄었지만.. 그래도 3일에 한번꼴로 국낸 IP (특히 대학이나 초등학교 서버에서..) 에서 5000번 이상의 scan 을 하고 지나가는 꼴을 보니 또 오기가 생기기 시작했습니다.

설마 막는 방법에 없겠느냐는 생각에 iptables 의 extension 을 탐색하던 중 ipt_recent extension 을 발견 했습니다. recent extension 은 iptables 의 기본 extension 이므로 따로 빌드할 필요도 없고, seconds 별 hitcount 를 계산할 수 있는 듯 합니다.

아래의 예제를 보죠. (oops.org 에 기본으로 적용한 rule 입니다.)

# ssh buste attack rule%-A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set --name SSHSCAN%-A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update \ --seconds 60 --hitcount 8 --rttl --name SSHSCAN -j LOG --log-prefix SSH_Scan:%-A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update \ --seconds 60 --hitcount 8 --rttl --name SSHSCAN -j DROP


1. 처음에 22 번으로 NEW state 의 session 을 SSHSCAN 이라는 이름으로 list 를 만듭니다.
2. 60 초 동안 8 번의 히트를 기록하면, 60초 동안 DROP 합니다.
3. 그리고 SSH_Scan 이라는 prefix 로 logging 을 합니다.

문서들이 영어라서.. 결국에는 습관대로 대충 읽고 반영해서 보자는 식으로 하게 되어서 정확한 정보는 되지 않을 것 같습니다. 정확한 정보를 얻고 싶은 분들은.. 다음의 링크를 참조 하십시오.

http://snowman.net/projects/ipt_recent/
http://users-x.757.org/~joat/wiki/index.php/Slowing_down_SSH_brute_force_attacks
http://la-samhna.de/library/brutessh.html

전 영어가 딸려서 ^^; 정확한 설명을 알려 주시면 고맙겠습니다. (아 이 귀차니즘의 압박이여.. -_-;)

P.S
안녕 리눅스를 사용하시는 분들은 oops-firewall 을 5.0.0 으로 올리시고 위의 rule 을 user.conf 에 반영하시면 됩니다. 5.0.0 부터는 ALLOWALL 이 user pre command 보다 먼저 실행이 되기 때문에 ALLOWALL 에 등록된 site 는 최소한 이 rule 에 영향을 받지 않습니다.
크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기

Posted by 삐꾸강아쥐

2006/09/27 20:57 2006/09/27 20:57
Response
0 Trackbacks , 0 Comments
RSS :
http://blog.blog.n-nuri.com/rss/response/199

Trackback URL : http://blog.blog.n-nuri.com/trackback/199

Leave a comment
[로그인][오픈아이디란?]

Defending against brute force ssh attacks

Defending against brute force ssh attacks

By Rainer Wichmann [ support@la-samhna.de]    (last update: Sep 11, 2006)

Introduction

During 2005, bute force attacks on the ssh (secure shell) service became pretty popular. These attacks are based on a rather simple idea: use an automated program for trying, one after the other, many combinations of standard or frequently used account names and likewise frequently used password (e.g.: guest/guest).

Defence methods

There are a number of methods to defend against such brute force attacks. The following list is intended to give an overview of them, and briefly mention their respective advantages and disadvantages.

Strong passwords

Neither in a dictionary, nor trivial variations of trivial passwords (guest1 is just as bad as guest). Using the initials of the words in some sentence is a simple method to have a strong password that is easy to remind (Peter, Paul, and Mary went to school yesterday = PPaMwtsy).

  • Advantage: Simple
  • Disadvantages:
    • Requires enforcement (regular checks of user passwords with tools like e.g. john ("John the Ripper").
    • Does not reduce the (network, sshd) load caused by the attacks.

RSA authentication

If you don't use passwords, but only RSA keys for authentication, a brute force search for a valid password will obviously be useless.

(1) Generate an RSA key with ssh-keygen -t rsa. This will create the files /home/username/.ssh/id_rsa (the private key) and /home/username/.ssh/id_rsa.pub (the public key).

sh$ ssh-keygen -t rsaGenerating public/private rsa key pair.Enter file in which to save the key (/home/username/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/username/.ssh/id_rsa.Your public key has been saved in /home/username/.ssh/id_rsa.pub.The key fingerprint is:32-digit_hexadecimal_fingerprint username@hostname

(2) On each machine to which where you want to login, copy /home/username/.ssh/id_rsa.pub into /home/username/.ssh/authorized_keys. This file can hold more than one key, so it may be wise to concatenate the freshly generated key.

sh$ cat /home/username/.ssh/id_rsa >> /home/username/.ssh/authorized_keys

(3) On each machine from which you want to login, place the file /home/username/.ssh/id_rsa into the directory /home/username/.ssh/.

(4) Disable password-based login by setting 'PasswordAuthentication no' in /etc/ssh/sshd_config, and restart the sshd daemon with /etc/init.d/sshd restart

  • Advantage: Pretty secure, if done properly
  • Disadvantages:
    • Users may use private keys without setting a passphrase to protect them. This implies that getting access to the private key would allow to login to any machine where the corresponding public key is installed.
    • Non-tech users may need help to generate RSA key for themselves (and for using them).
    • It is neccessary to carry the private key along to login from another host.

Using 'iptables' to block the attack

It is possible to set up iptables rules to block ssh attacks. The following ruleset (seen in the blog of Andrew Pollock) will allow at most 3 connections per minute from any host, and will block the host for another minute if this rate is exceeded.

iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set \  --name SSH -j ACCEPTiptables -A INPUT -p tcp --dport 22 -m recent --update --seconds 60 --hitcount 4 --rttl \ --name SSH -j LOG --log-prefix "SSH_brute_force "iptables -A INPUT -p tcp --dport 22 -m recent --update --seconds 60 \ --hitcount 4 --rttl --name SSH -j DROP

For whitelisting, a possible variation (also described by Andrew Pollock) would be:

(1) Create a custom chain for whitelisting first:

iptables -N SSH_WHITELIST

(2) Whitelist any host(s) that you like:

iptables -A SSH_WHITELIST -s TRUSTED_HOST_IP -m recent --remove --name SSH -j ACCEPT

(3) Add the blocking rules:

iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set \ --name SSHiptables -A INPUT -p tcp --dport 22 -m state --state NEW -j SSH_WHITELISTiptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update \ --seconds 60 --hitcount 4 --rttl --name SSH -j ULOG --ulog-prefix SSH_brute_forceiptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update \ --seconds 60 --hitcount 4 --rttl --name SSH -j DROP
  • Advantage: Transparent for users
  • Disadvantages:
    • Does not distinguish between successful logins and unsuccessful login attempts (i.e. three successful logins within one minute will trigger just like three unsuccessful login attempts).
    • As pointed out by one reader (L. Hamel), this method requires 'recent' (http://snowman.net/projects/ipt_recent/), an ipfilters patch that may not be in every distro's default kernel. So to use this technique with typical linux distros, you may have to patch the kernel.

Using the sshd log to block attacks

It is possible to scan the syslog entries written by the sshd daemon for ongoing attacks, and block the attacker. There are several programs/scripts available that are specifically written for this purpose:

ssdfilter uses iptables for blocking (i.e. it dynamically adds custom firewall rules to block a specific attacker). You need to run sshdfilter instead of sshd. Sshdfilter will then start sshd and monitor its log.

Fail2Ban is a Python script which adds custom firewall rules to block an attacker. It can use the iptables, ipfwadm, or ipfw.

DenyHosts does not use firewall rules to block an attack. Rather, it writes blocking rules to /etc/hosts.deny. Thus, it requires an sshd daemon compiled with support for tcp_wrappers (default on most Linux distributions). Like Fail2Ban, DenyHosts is a Python script.

To find out whether your sshd daemon supports tcp_wrappers, you could use the command ldd /usr/sbin/sshd | grep libwrap. With tcp_wrappers supported you should get a line similar to libwrap.so.0 => /lib/libwrap.so.0 (0xb7f7e000) (numbers may be different). Without tcp_wrappers support, the output will be empty.

sh$ ldd /usr/sbin/sshd | grep libwrap      libwrap.so.0 => /lib/libwrap.so.0 (0xb7f7e000)

Another method to test for tcp_wrappers support would be to add the line sshd: 127.0.0.1 to the file /etc/hosts.deny, and then try to connect to the local ssh server with the command ssh localhost. As you have just blocked localhost, this should fail with the error message ssh_exchange_identification: Connection closed by remote host:

sh$ ssh localhostssh_exchange_identification: Connection closed by remote host
  • Advantages:
    • Transparent for users
    • Can distinguish between unsuccessful login attempts (which are blocked) and successful logins (which are not blocked).
  • Disadvantages:
    • Many ssh attacks are fast and short (many connections in a short time). Thus, running a cron script to check the sshd logs for an ongoing attack may be pointless, as it may notice the attack only after it has finished (and the next attack will come from a different machine anyway).
    • Continuously monitoring the sshd log for an attack requires to run yet another daemon (in the case of sshdfilter, you have to run sshdfilter instead of sshd anyway).

Using tcp_wrappers to block attacks

In the preceding section the DenyHosts script was discussed, which scans the sshd logs to detect an attack, and then blocks it with a rule in /etc/hosts.deny. However, it is actually not necessary to scan the logs. It is possible to let the tcp wrapper library start a script whenever a connection is made, and let this script add rules to /etc/hosts.deny or /etc/hosts.allow, if the connecting host should be blocked.

(1) Download the sshblock.sh shell script (PGP signature), and copy it to /usr/local/bin/sshblock.sh (or wherever you like).

(2) Make it executable using the command chmod 755 /usr/local/bin/sshblock.sh

(3) Add the following three lines at the bottom of /etc/hosts.allow

#__START_SSHBLOCK__#__END_SSHBLOCK__sshd : ALL : spawn (/usr/local/bin/sshblock.sh %a)&

This will call the script /usr/local/bin/sshblock.sh for each ssh connection. The script will receive the remote IP address as the first and only argument. The script will write a temporary file /root/hosts.allow, and copy it to /etc/hosts.allow if it differs from that.

Requirements:

  • The sshd daemon must support tcp_wrappers (see preceding section on methods to test this).
  • The date command must support the '%s' format specifier to print seconds after the Epoch (use date +%s to test). Both GNU/Linux and FreeBSD date support this.

Configuration: at the top of the script, there are four variables that can be set: DONTBLOCK is the prefix of an address block that you do never want to be blocked (i.e. your own domain). The default is 192.168, which you can safely keep if you have no own domain, as this is a 'private' address block). At most (2) BURST_MAX connections from a host within BURST_TIM seconds are allowed (default: 5 within 60 sec), and blocks are removed after PURGE_TIM seconds (default: 3600 sec). In the script, this looks like:

# your own domain DONTBLOCK=192.168# block host if more than BURST_MAX connections within BURST_TIM secondsBURST_MAX=5BURST_TIM=60# remove block after PURGE_TIM secondsPURGE_TIM=3600
  • Advantage: Transparent for users
  • Disadvantages:
    • Does not distinguish between successful logins and unsuccessful login attempts (i.e. five successful logins within one minute will trigger just like three unsuccessful login attempts).
    • To remove a block, the script must run, which requires a connection from a non-blocked host (or follow a suggestion by Andreas Rizzi and install a cron job that calls the script with the parameter 127.0.0.0 once per hour).

Using knockd

As pointed out by Imre Veres, another solution to the problem is using knockd, which eliminates the need for having ssh listen on an open port.

Knockd watches predefined patterns in iptables' log, e.g. one hit to port 6356, one hit to port 9356 and two hits to port 3356. I.e. this is equivalent to knocking at a closed door with a "code" that is recognized by knockd. Knockd will then use iptables to open a predefined port (e.g. tcp/22 for sshd) for a predefined time (e.g. one minute). If a ssh session is opened within that time frame, it will remain open, though the ssh port will get closed by knockd after the predefined timeframe expires.

  • Advantage: Very secure
  • Disadvantages:
    • Rather complicated scheme, not suitable for 'mere mortals'.
    • Requires a suitable program (e.g. knockd-client) for "port knocking" on the client (as well as knockd on the server)
크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기

Posted by 삐꾸강아쥐

2006/09/27 20:56 2006/09/27 20:56
Response
0 Trackbacks , 0 Comments
RSS :
http://blog.blog.n-nuri.com/rss/response/198

Trackback URL : http://blog.blog.n-nuri.com/trackback/198

Leave a comment
[로그인][오픈아이디란?]

ssh dictionary attack 막기

ssh dictionary attack 막기
출처 : http://my.oops.org/42
요즘 로그를 보다 보면 ssh 사전 공격이 worm 으로 변하여 엄청나게 시도를 하는 것을 볼 수 있습니다. (흐흐.. 문제를 존대로 바꾸어 보았습니다.) logwatch 의 ssh login 시도 log 분석을 잠시 보면



그래서, 안녕 리눅스의 커널과 iptables 에 geoip extension 을 붙여서 외국에서의 접근을 막아 보려고 시도 중입니다.

oops-firewall 에도 연동을 할까 생각 중이지만, 이건 나중의 일이고, 일단, oops.org 의 서버에

iptables -A INPUT -p tcp -i eth0 --dport 22 -m geoip ! --src-cc KR -j DROP


과 같이 한국 외에서의 접근을 막아 버렸습니다. 이제 내일의 logwatch 결과를 기다려 봐야 겠네요.

뭐, 이 작업 한다고 닥질도 많이 했습니다. 새벽에 졸린 눈으로 작업을 하다보니.. 어처구니 없게

iptables -A INPUT -m geoip --src-cc KR -j DROP


를 실행해서 한국에서 접속을 못하게 만들어 외국의 계정을 찾느라고 고생도 했습니다.

이제 주사위는 던져 졌고, 얼마나 효과가 있는지만 기다려 보면 되겠네요.
크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기

Posted by 삐꾸강아쥐

2006/09/27 20:56 2006/09/27 20:56
Response
0 Trackbacks , 0 Comments
RSS :
http://blog.blog.n-nuri.com/rss/response/197

Trackback URL : http://blog.blog.n-nuri.com/trackback/197

Leave a comment
[로그인][오픈아이디란?]