tcpdump - dump traffic on a network http://www.tcpdump.org/

tcpdump 는 네트워크 인터페이스상의 패킷 헤더를 출력한다.
그리고 파일로 출력하여 분석해 볼수도 있다. 파일로 출력할 경우에는 -w 옵션을 사용하며
저장된 파일내용을 볼때는 -r 옵션을 사용한다.

tcpdump 는 패킷을 캡쳐할 카운터를 지정하지 않는 경우에는 SIGINT 또는 SIGTERM signal 을 받을때까지
계속 실행된다.

tcpdump 사용법

tcpdump --help
tcpdump version 3.9.4
libpcap version 0.9.4
Usage: tcpdump [-aAdDeflLnNOpqRStuUvxX] [-c count] [ -C file_size ]
[ -E algo:secret ] [ -F file ] [ -i interface ] [ -M secret ]
[ -r file ] [ -s snaplen ] [ -T type ] [ -w file ]
[ -W filecount ] [ -y datalinktype ] [ -Z user ]
[ expression ]
[root@centos1 ~]#

ex)
tcpdump -i eth0 -w /tmp/tcpdump.pkt ; eth0 으로 패킷캡처하여 파일로저장
tcpdump -r /tmp/tcpdump.pkt ; 저장된 파일 모니터로 출력.
tcpdump -i eth0 -c 10 ; 10개만 캡처.
tcpdump -w /tmp/tcpdump.pkt -s 1500 tcp port 21 and host client
-s 1500 ; 캡처할 패킷길이(1500 byte 는 전체길이를 뜻한다)
tcpdump host client
tcpdump -nn host client and port 21
tcpdump -nne host client and port 21

[root@centos1 ~]# tcpdump -n host 192.168.100.100 and port 23 -w /tmp/tcpdump.pkt
[root@centos1 ~]# tcpdump -r /tmp/tcpdump.pkt | head -4
reading from file /tmp/tcpdump.pkt, link-type EN10MB (Ethernet)
20:09:51.200931 IP 192.168.100.100.59708 > 192.168.100.1.telnet: S 3013182863:3013182863(0) win 5840
20:09:51.205507 IP 192.168.100.1.telnet > 192.168.100.100.59708: S 3185271194:3185271194(0) ack 3013182864 win 5792
20:09:51.211135 IP 192.168.100.100.59708 > 192.168.100.1.telnet: . ack 1 win 92

20:09:52.719159 IP 192.168.100.1.telnet > 192.168.100.100.59708: P 1:13(12) ack 1 win 91

옵션설명
-n : Don’t convert host addresses to names. This can be used to avoid DNS lookups.
호스트 이름을 도메인 또는 호스트이름으로 풀이하지 않고 ip 주소로 출력해준다.
DNS 를 찾지 않으면 그만큼의 트래픽을 줄일 수 있다.

20:09:51.200931 : 패킷수집시간
192.168.100.100.59708 > 192.168.100.1.telnet : source ip.포트번호 > destination ip.포트번호(또는 서비스이름)
*. 포트번호가 /etc/services 파일에 등록이 되어 있는경우라면 서비스이름으로 표시된다.
S : 패킷 Sequence number
win 5840 mss 1460 : max-segment-size
sackOK :
nop:

패킷 flag
S : SYN - 연결요청
F : FIN - 연결종료요청
R : RST - 즉시연결종료
P : PSH - 프로세스로 데이터전송
U : URG - 긴급한 데이터에 데이터전송 우선순위를 할당.
. : flag 가 설정되지 않았음.

*. 패킷출력내용중 세번째 라인까지가 3way hand-shaking 이다.
* 네번째 라인부터는 데이터 전송.

[root@centos1 ~]# tcpdump -r /tmp/tcpdump.pkt | tail -5
reading from file /tmp/tcpdump.pkt, link-type EN10MB (Ethernet)
20:10:12.538184 IP 192.168.100.1.telnet > 192.168.100.100.59708: P 1075:1082(7) ack 106 win 91
20:10:12.543157 IP 192.168.100.100.59708 > 192.168.100.1.telnet: . ack 1082 win 159
20:10:12.674086 IP 192.168.100.1.telnet > 192.168.100.100.59708: F 1082:1082(0) ack 106 win 91
20:10:12.686700 IP 192.168.100.100.59708 > 192.168.100.1.telnet: F 106:106(0) ack 1083 win 159
20:10:12.688650 IP 192.168.100.1.telnet > 192.168.100.100.59708: . ack 107 win 91

[root@centos1 ~]#

* 패킷 출력 결과중 끝에서 3번째 라인부터가 접속종료 과정이다.

비활성화 되어 있는 서비스로 접속할 경우

[root@centos1 ~]# tcpdump -n host 192.168.100.100 and port 23 -w /tmp/tcpdump2.pkt
[root@centos100 ~]# telnet 192.168.100.1
Trying 192.168.100.1...
telnet: connect to address 192.168.100.1: Connection refused
telnet: Unable to connect to remote host: Connection refused
[root@centos100 ~]#
[root@centos1 ~]# tcpdump -r /tmp/tcpdump20.pkt
reading from file /tmp/tcpdump20.pkt, link-type EN10MB (Ethernet)
20:44:35.063400 IP 192.168.100.100.56378 > 192.168.100.1.telnet: S 787328461:787328461(0) win 5840
20:44:35.067331 IP 192.168.100.1.telnet > 192.168.100.100.56378: R 0:0(0) ack 787328462 win 0
[root@centos1 ~]#

*. 서버측에서 Sequence number 로 응답하는대신 R flag 를 세팅하여 보내고 클라이언트측에서 그 패킷을 받는 즉시 연결종료된다.

방화벽에 막혀있는경우
[root@centos1 ~]# iptables -F
[root@centos1 ~]# iptables -A INPUT -s 192.168.100.100 -p tcp --dport telnet -j DROP
[root@centos1 ~]# tcpdump -n host 192.168.100.100 and port 23 -w /tmp/tcpdump3.pkt
tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes

[root@centos100 ~]# telnet 192.168.100.1
Trying 192.168.100.1...
telnet: connect to address 192.168.100.1: Connection timed out
telnet: Unable to connect to remote host: Connection timed out
[root@centos100 ~]#

[root@centos1 ~]# tcpdump -r /tmp/tcpdump4.pkt
reading from file /tmp/tcpdump4.pkt, link-type EN10MB (Ethernet)
20:58:16.099647 IP 192.168.100.100.43630 > 192.168.100.1.telnet: S 1498268765:1498268765(0) win 5840
20:58:20.900736 IP 192.168.100.100.43630 > 192.168.100.1.telnet: S 1498268765:1498268765(0) win 5840
20:58:27.744399 IP 192.168.100.100.43630 > 192.168.100.1.telnet: S 1498268765:1498268765(0) win 5840
20:58:40.580851 IP 192.168.100.100.43630 > 192.168.100.1.telnet: S 1498268765:1498268765(0) win 5840
20:59:08.779405 IP 192.168.100.100.43630 > 192.168.100.1.telnet: S 1498268765:1498268765(0) win 5840
21:00:05.366996 IP 192.168.100.100.43630 > 192.168.100.1.telnet: S 1498268765:1498268765(0) win 5840
[root@centos1 ~]#

*. 클라이언트가 같은 패킷을 계속 보내지만 서버가 응답하지 않는다.

[root@centos1 ~]# iptables -F
[root@centos1 ~]# iptables -A INPUT -s 192.168.100.100 -p tcp --dport telnet -j REJECT ; REJECT 로 거부할 경우.

[root@centos1 ~]# tcpdump -n host 192.168.100.100 and port 23 -w /tmp/tcpdump5.pkt
tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes

root@centos100 ~]# telnet 192.168.100.1
Trying 192.168.100.1...
telnet: connect to address 192.168.100.1: Connection refused
telnet: Unable to connect to remote host: Connection refused
[root@centos100 ~]#

[root@centos1 ~]# tcpdump -r /tmp/tcpdump5.pkt
reading from file /tmp/tcpdump5.pkt, link-type EN10MB (Ethernet)
21:05:06.955754 IP 192.168.100.100.51055 > 192.168.100.1.telnet: S 1879397660:1879397660(0) win 5840
[root@centos1 ~]#

*. DROP 과 다른점이 없어보인다. 차이가 있다면 클라이언트가 패킷을 하나만 보내고 끝난다.

udp를 기반으로 하는 서비스인경우
[root@centos1 tftpboot]# tcpdump -n host 192.168.100.100 and port 69 -w /tmp/tcpdump9.pkt

[root@centos100 temp2]# tftp 192.168.100.1 -c get a.txt
[root@centos1 tftpboot]# tcpdump -r /tmp/tcpdump9.pkt
reading from file /tmp/tcpdump9.pkt, link-type EN10MB (Ethernet)
22:27:08.416478 IP 192.168.100.100.33136 > 192.168.100.1.tftp: 13 RRQ "1" netascii
22:27:08.734306 IP 192.168.100.100.33136 > 192.168.100.1.tftp: 13 RRQ "2" netascii
22:27:09.029195 IP 192.168.100.100.33136 > 192.168.100.1.tftp: 13 RRQ "3" netascii

* udp 는 3way - hand-shaking 이 없다.

*. udp 서비스가 방화벽에 막혀 있는 경우
[root@centos1 tftpboot]# iptables -F
[root@centos1 tftpboot]# iptables -A INPUT -p udp --dport 69 -j DROP
[root@centos1 tftpboot]# tcpdump -n host 192.168.100.100 and port 69 -w /tmp/tcpdump10.pkt
tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes

[root@centos100 temp2]# tftp 192.168.100.1 -c get a.txt b.txt c.txt
Transfer timed out.
[root@centos100 temp2]#

[root@centos1 tftpboot]# tcpdump -r /tmp/tcpdump10.pkt
reading from file /tmp/tcpdump10.pkt, link-type EN10MB (Ethernet)
22:34:29.379785 IP 192.168.100.100.49576 > 192.168.100.1.tftp: 17 RRQ "a.txt" netascii
22:34:34.796127 IP 192.168.100.100.49576 > 192.168.100.1.tftp: 17 RRQ "a.txt" netascii
22:34:40.635185 IP 192.168.100.100.49576 > 192.168.100.1.tftp: 17 RRQ "a.txt" netascii
22:34:45.510690 IP 192.168.100.100.49576 > 192.168.100.1.tftp: 17 RRQ "a.txt" netascii
22:34:51.942627 IP 192.168.100.100.49576 > 192.168.100.1.tftp: 17 RRQ "a.txt" netascii
[root@centos1 tftpboot]#

*. 패킷에서 패스워드 찾기

[root@centos1 tftpboot]# tcpdump -X -r /tmp/telnet.pkt > /tmp/telnet.txt

[root@centos100 temp2]# telnet 192.168.100.1
Trying 192.168.100.1...
Connected to 192.168.100.1 (192.168.100.1).
Escape character is '^]'.
CentOS release 5.3 (Final)
Kernel 2.6.18-128.el5 on an i686
login: user1
Password:
Last login: Wed Jun 2 20:24:36 from 192.168.100.100
[user1@centos1 ~]$ logout
Connection closed by foreign hos

[root@centos1 tftpboot]# tcpdump -X -r /tmp/telnet.pkt > /tmp/telnet.txt

-X : Print each packet (minus its link level header) in hex and ASCII. This is very handy for analysing new protocols.

-X 옵션을 사용하면 hexa 코드와 아스키코드로 출력해주므로 그냥 보기에는 출력결과가 많아서 어렵다.
그러므로 파일로 저장해서 특정문자열을 검색하는 방법으로 보는것이 패스워드를 쉽게
찾을수 있는 방법이다.
vi 편집기로 열어서 Password 라는 문자열을 검색한 후 아래쪽을 보면 캡쳐된 암호가
보일것이다.

패스워드는 apple 이다. 내용이 많아서 편의상 app 까지만 출력하였다.
각 패킷에서의 마지막 문자가 암호인데 한 패킷씩 건너뛰고 저장되어 있다.
당연히 그렇게 저장된다.

0x0030: 06b2 00d3 5061 7373 776f 7264 3a20 ....Password:.
22:50:28.490812 IP 192.168.100.100.55824 > 192.168.100.1.telnet: . ack 146 win 92
0x0000: 4510 0034 1460 4000 4006 dc9d c0a8 6464 E..4.`@.@.....dd
0x0010: c0a8 6401 da10 0017 e1f1 fd47 1bf1 13c1 ..d........G....
0x0020: 8010 005c fad9 0000 0101 080a 06b2 0140 ...\...........@
0x0030: 1114 2fb7 ../.
22:50:29.198462 IP 192.168.100.100.55824 > 192.168.100.1.telnet: P 90:91(1) ack 146 win 92
0x0000: 4510 0035 1461 4000 4006 dc9b c0a8 6464 E..5.a@.@.....dd
0x0010: c0a8 6401 da10 0017 e1f1 fd47 1bf1 13c1 ..d........G....
0x0020: 8018 005c 9716 0000 0101 080a 06b2 03fa ...\............
0x0030: 1114 2fb7 61 ../.a
22:50:29.242685 IP 192.168.100.1.telnet > 192.168.100.100.55824: . ack 91 win 91
0x0000: 4510 0034 050c 4000 4006 ebf1 c0a8 6401 E..4..@.@.....d.
0x0010: c0a8 6464 0017 da10 1bf1 13c1 e1f1 fd48 ..dd...........H
0x0020: 8010 005b f52a 0000 0101 080a 1114 32ac ...[.*........2.
0x0030: 06b2 03fa ....
22:50:29.494741 IP 192.168.100.100.55824 > 192.168.100.1.telnet: P 91:92(1) ack 146 win 92
0x0000: 4510 0035 1462 4000 4006 dc9a c0a8 6464 E..5.b@.@.....dd
0x0010: c0a8 6401 da10 0017 e1f1 fd48 1bf1 13c1 ..d........H....
0x0020: 8018 005c 8420 0000 0101 080a 06b2 04fa ...\............
0x0030: 1114 32ac 70 ..2.p
22:50:29.497150 IP 192.168.100.1.telnet > 192.168.100.100.55824: . ack 92 win 91
0x0000: 4510 0034 050d 4000 4006 ebf0 c0a8 6401 E..4..@.@.....d.
0x0010: c0a8 6464 0017 da10 1bf1 13c1 e1f1 fd49 ..dd...........I
0x0020: 8010 005b f32a 0000 0101 080a 1114 33ab ...[.*........3.
0x0030: 06b2 04fa ....
22:50:29.615998 IP 192.168.100.100.55824 > 192.168.100.1.telnet: P 92:93(1) ack 146 win 92
0x0000: 4510 0035 1463 4000 4006 dc99 c0a8 6464 E..5.c@.@.....dd
0x0010: c0a8 6401 da10 0017 e1f1 fd49 1bf1 13c1 ..d........I....
0x0020: 8018 005c 82a4 0000 0101 080a 06b2 0576 ...\...........v
0x0030: 1114 33ab 70 ..3.p

이하 생략...

Let’s assume that we want to watch packets used in establishing a TCP connection. Recall that TCP uses a 3-way handshake protocol
when it initializes a new connection; the connection sequence with regard to the TCP control bits is

1) Caller sends SYN
2) Recipient responds with SYN, ACK
3) Caller sends ACK



URG | ACK | PSH | RST | SYN | FIN

URG : Urgent pointer is valid
RST: Reset the connection
ACK : Acknowlegement is valid
SYN : Syncronize sequence numbers
PSH : Request for push
FIN : Terminate the connection


TCP 연결 (3way hand shaking)

Client Server
Segment 1: SYN
| ---------------- seq : 1000, ack : - --------------> |
| |
| Segment 2: SYN ACK |
|<---------------- seq : 4000, ack : 1001 ---------|
| |
| Segment 3: ACK |
| -------------------------- ack ------------------->|
| |
v v
Time Time

TCP data 전송

Client Server
Segment 1:
| ---------------- seq : 2000, 200bytes : - -------------->|
|| |
| <-------------------- ACK :2200 ------------------------- |
| | | Segment 2: |
|<---------------- seq : 2200, 200 bytes ----------------- |
| |
| -------------------- ACK : 2400 -------------------------> |
| |
| Segment 3: |
| -------------------- seq : 2400, 200 bytes -----------> |

time out 까지 응답없음.
| |
| Segment 3: (다시 전송) |
| ----------------- seq : 2400, 200bytes ---------------> |
| |
v v
Time Time

TCP 연결 종료 과정

Client Server
Segment 1: FIN
| ---------------- seq : 2000, ack : - --------------> |
| |
| Segment 2: ACK |
|<---------------- seq : 5000, ack : 2001 ---------|
| |
| Segment 3: FIN |
| <-------------------- seq : 5001, ack 2001 -------- |
| |
| Segment 4: ACK |
| ----------------- ack 5002 ------------------------->|
| |
v v
Time Time

TCP 상태
state Description
--------------------------------------------------------------------------------
closed : There is no connection. (연결되지 않았다)
listen : The server is waiting for calls from the client (클라이언트의 접속을 기다리고 있다)
syn-sent : A connection request is sent; waiting for acknowlegement. (접속 요청을 보내고 응답을 기다리고 있다)
syn-recvd : A connection request is received (접속요청에 대한 응답을 받았다)
established : Connection is established (접속완료)

fin-wait-1 : The application has requested the closing of the connection. (연결 끊기를 요청)
fin-wait-2 : The other side has accepted the closing of the connection. (요청에 대한 응답을 받았다)
time-wait : Waiting for retransmitted segments to die.(연결 끊기에 대한 응답을 다시 기다림)
close-wait : The server is waiting for the application to close.(서버가 클라이언트로부터 연결종료를 기다림)
last-ack : The server is waiting for the last acknowlegement. (서버가 클라이언트로부터 연결종료에 대한 마지막 응답을 기다림)

'Log > Linux' 카테고리의 다른 글

samba 서비스  (0) 2011.11.28
IDS - snort 1  (0) 2011.11.28
포트스캔 및 차단  (0) 2011.11.28
로그서비스 - syslog / logrotate / logwatch  (0) 2011.11.28
리눅스 방화벽 - iptables  (0) 2011.11.28
Posted by logwatch

2011. 11. 28. 19:34 Log/Linux

포트스캔 및 차단

Nmap (http://www.nmap.org)

특징

1. 호스트가 존재하는지 검사
2. 어떤 서비스가 실행중인지 검사
3. 운영체제 검사

scan 유형

connect scan : connect 함수의 에러값을 검사해서 포트가 닫혔는지 열렸는지 검사한다.
패킷을 변경하지 않으므로 일반 사용자도 사용가능

장점 : 빠르고 정확하며 특별한 권한이 필요없다.
단점 : 쉽게 탐지되고 기록된다.

1. 포트가 열려 있는경우.
Client -> SYN
Server -> SYN|ACK
Client -> ACK

2. 포트가 닫혀 있는경우
Client -> SYN
Server -> RST|ACK
Client -> RST

RST|ACK flag 는 클라이언트의 연결 요청을 취소
즉 포트는 lisening 상태가 아니며 닫혀 있음을 의미.

half open
syn scan : syn 패킷을 보내면 Three way handshaking 때문에 상대편에서 오는 syn 패킷의 내용을
보고 포트가 닫혔는지 열렸는지 검사한다.

Client -> SYN
Server -> SYN|ACK
Client -> RST

시스템의 포트가 열려 있으면, SYN|ACK flag로 답한다. RST flag는 커널의 tcp/ip 스택코드에서
자동으로 보내므로 클라이언트에서는 RST 패킷을 보낼필요가 없다.
닫힌 포트에서는 RST|ACK 로 응답한다.


stealth
FIN scan : FIN 패킷을 보내면 포트가 닫혀 있을경우,RST 패킷을 보내는 Unix 서버들의 특징을 이용해서
포트가 닫혔는지 열렸는지 검사한다.
Null scan : 어떤 flag도 없는 패킷을 보내 되돌아오는 RST 값을 검사한다.
Xmas scan : 모든 flag 를 세팅한 패킷을 보내 RST 값을 검사한다.
ACK scan : 포트에 ACK 패킷을 보내 RST 응답을 받으면 그 포트는 unfilterd 이며 아무런 응답이 없으면
filterd 이다.
Fragment scan : 패킷을 2개로 쪼개어 보낸다.
Window scan : ACK 패킷을 보내어 TCP window 크기의 변화를 살핀다.

기타
ping scan : icmp 의 echo 기능을 이용한다.
TCP ping scan : 80 포트에 syn 패킷을 보낸다.

*. nmap 사용옵션 예제

nmap -sT localhost
nmap abc.co.kr/24 192.168.10/24 192.168.100.0-255 192.168.1.*

usage : nmap
nmap [Scan Type...] [Options] {target specification}

[root@centos1 /]# nmap -sT localhost

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2010-02-09 15:28 KST
Interesting ports on centos1 (127.0.0.1):
Not shown: 1668 closed ports
PORT STATE SERVICE
21/tcp open ftp
22/tcp open ssh
23/tcp open telnet
25/tcp open smtp
53/tcp open domain
80/tcp open http
111/tcp open rpcbind
443/tcp open https
631/tcp open ipp
672/tcp open unknown
953/tcp open rndc
3306/tcp open mysql

Nmap finished: 1 IP address (1 host up) scanned in 0.700 seconds


-sT :

[root@centos1 /]# nmap -sS client

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2010-02-09 15:44 KST
Interesting ports on centos100 (192.168.100.100):
Not shown: 1676 closed ports
PORT STATE SERVICE
22/tcp open ssh
23/tcp open telnet
111/tcp open rpcbind
669/tcp open unknown
MAC Address: 00:0C:29:C7:CA:72 (VMware)

Nmap finished: 1 IP address (1 host up) scanned in 1.590 seconds
[root@centos1 /]# nmap client

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2010-02-09 15:46 KST
Interesting ports on centos100 (192.168.100.100):
Not shown: 1676 closed ports
PORT STATE SERVICE
22/tcp open ssh
23/tcp open telnet
111/tcp open rpcbind
669/tcp open unknown
MAC Address: 00:0C:29:C7:CA:72 (VMware)

Nmap finished: 1 IP address (1 host up) scanned in 1.437 seconds
[root@centos1 /]# nmap -sT client

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2010-02-09 15:46 KST
Interesting ports on centos100 (192.168.100.100):
Not shown: 1676 closed ports
PORT STATE SERVICE
22/tcp open ssh
23/tcp open telnet
111/tcp open rpcbind
669/tcp open unknown
MAC Address: 00:0C:29:C7:CA:72 (VMware)

Nmap finished: 1 IP address (1 host up) scanned in 3.296 seconds

[root@centos1 ~]# nmap -A redhat

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2010-03-22 05:48 KST
Interesting ports on redhat (192.168.203.3):
Not shown: 1674 closed ports
PORT STATE SERVICE VERSION
21/tcp open ftp vsftpd 1.1.3
22/tcp open ssh OpenSSH 3.5p1 (protocol 1.99)
23/tcp open telnet Linux telnetd
53/tcp open domain ISC Bind 9.2.1
80/tcp open http Apache httpd 2.0.40 ((Red Hat Linux))
111/tcp open rpcbind 2 (rpc #100000)
MAC Address: 00:0C:29:85:50:D9 (VMware)
Device type: general purpose
Running: Linux 2.4.X|2.5.X|2.6.X
OS details: Linux 2.4.0 - 2.5.20, Linux 2.4.7 - 2.6.11
Service Info: OSs: Unix, Linux

Nmap finished: 1 IP address (1 host up)


portsentry

portsentry는 실시간으로 이런 portscan을 탐지하고 대응하기 위해 만들어진 프로그램.
portsentry는 정상적인 스캔과 스탤스스캔 모두 탐지가능
(패키지에 포함되어 있는 README.install을 참조)

주요 옵션

-tcp - Basic port-bound TCP mode (기본 포트 제한 TCP 모드)
-udp - Basic port-bound UDP mode (기본 포트 제한 UDP 모드)
-stcp - Stealth TCP scan detection mode (스텔스 TCP 스캔 탐지 모드)
호스트로 들어오는 패킷이 감시되고 있는 포트로 향한다면, PortSentry는 호스트를 방어하기
위해 동작한다.
이 방법은 connect() 스캔과 SYN/half-open 스캔과 FIN 스캔을 탐지할 것이다.
UDP/스텔스 스캔 경고가 적용된다. (README.stealth파일 참조)

-sudp - "Stealth" UDP scan detection mode (스텔스 UDP 스캔 탐지 모드)
이것은 위의 TCP stealth mode와 작동방법은 동일하다. UDP 포트들을 나열하면, 그 포트들은
감시된다. 이것은 어떠한 소켓도 묶지 않으며, 실제 스텔스 스캔 탐지 모드가 아닌 중에도 거의
동일하게 동작한다.( 모든 UDP 패킷에 반응한다.)
UDP/스텔스 스캔 경고가 적용된다. (README.stealth파일 참조)

-atcp - Advanced TCP stealth scan detection mode (advanced TCP 스텔스 스캔 탐지 모드)
PortSentry는 ADVANCED_PORTS_TCP 옵션에 지정된 최상의 포트번호이하의 모든 열려진 포트에
대한 목록을 만들면서 시작하고, 이러한 포트들을 기초로 제외(exclusion)목록을 만들 것이다.
제외되지 않은( 예를 들어, [SMTP, HTTP, 등의] 열려진[listening] network daemon이 아닌, )
영역내의 임의의 포트에 연결된 호스트들은 접속이 금지된다.

-audp - Advanced UDP stealth scan detection mode (advanced UDP 스탤스 스캔 탐지 모드)
UDP 프로토콜을 사용한다는 점을 제외하고는 위와 같다. Advanced UDP stealth scan detection은
지원되지 않는 트래픽을 즉시 알 수 있기 때문에 강력하지만 부정확한 경보의 가능성이 높다.

실행하기

[root@centos100 portsentry]# portsentry -tcp
[root@centos100 portsentry]# portsentry -udp
[root@centos100 portsentry]# portsentry -stcp
[root@centos100 portsentry]# portsentry -sudp
[root@centos100 portsentry]# portsentry -atcp
[root@centos100 portsentry]#portsentry -audp

[root@chtla portsentry]# pgrep -fl portsentry
303 portsentry -tcp
32671 /usr/sbin/portsentry -atcp
32673 /usr/sbin/portsentry -audp
[root@centos100 portsentry]#

*. rpm 패키지를 설치할 경우 설정파일이 저장되는 디렉토리는
/etc/portsentry 이다.

[root@centos100 portsentry]# ls
portsentry.blocked.atcp portsentry.conf portsentry.history portsentry.modes
portsentry.blocked.audp portsentry.ignore

*. portsentry.conf ; 주 설정 파일
*. portsentry.ignore ; 차단하지 않을 주소 지정.

'Log > Linux' 카테고리의 다른 글

IDS - snort 1  (0) 2011.11.28
tcpdump - packet capture / 분석  (0) 2011.11.28
로그서비스 - syslog / logrotate / logwatch  (0) 2011.11.28
리눅스 방화벽 - iptables  (0) 2011.11.28
apache / php / mysql 설치 및 연동  (0) 2011.11.28
Posted by logwatch
로그서비스(syslog)

로그파일 종류

/var/log 디렉토리에 위치
- messages : 시스템 운영에 대한 전반적인 기록
- boot.log : 부팅될때 출력되는 메시지 기록
cron : cron log
secure : 원격접속기록
xferlog : ftp 서비스의 파일 송수신 기록
wtmp : 사용자 접속기록
lastlog : 각 계정의 가장 최근 로그인 시간 기록
(로그인시 이정보가 자동 출력된다)

syslog.conf

모든 룰은 두개의 필드, 셀렉터 필드와 액션 필드로 구성된다.
그리고 이 두개의 필드는 한개이상의 스페이스 문자 또는 탭문자로 구분되어진다.


설정문법
selecter 한개이상의 스페이스 또는 탭문자 action
selector 는 facility.priority 로 구성된다.

facility 및 priority (또는 level 이라고도 한다)
/usr/include/sys/syslog.h 에 정의되어 있다.

* priorities (these are ordered)
*/
#define LOG_EMERG 0 /* system is unusable */
#define LOG_ALERT 1 /* action must be taken immediately */
#define LOG_CRIT 2 /* critical conditions */
#define LOG_ERR 3 /* error conditions */
#define LOG_WARNING 4 /* warning conditions */
#define LOG_NOTICE 5 /* normal but significant condition */
#define LOG_INFO 6 /* informational */
#define LOG_DEBUG 7 /* debug-level messages */


/* facility codes */
#define LOG_KERN (0<<3) /* kernel messages */
#define LOG_USER (1<<3) /* random user-level messages */
#define LOG_MAIL (2<<3) /* mail system */
#define LOG_DAEMON (3<<3) /* system daemons */
#define LOG_AUTH (4<<3) /* security/authorization messages */
#define LOG_SYSLOG (5<<3) /* messages generated internally by syslogd */
#define LOG_LPR (6<<3) /* line printer subsystem */
#define LOG_NEWS (7<<3) /* network news subsystem */
#define LOG_UUCP (8<<3) /* UUCP subsystem */
#define LOG_CRON (9<<3) /* clock daemon */
#define LOG_AUTHPRIV (10<<3) /* security/authorization messages (private) */
#define LOG_FTP (11<<3) /* ftp daemon */

/* other codes through 15 reserved for system use */
#define LOG_LOCAL0 (16<<3) /* reserved for local use */
#define LOG_LOCAL1 (17<<3) /* reserved for local use */
#define LOG_LOCAL2 (18<<3) /* reserved for local use */
#define LOG_LOCAL3 (19<<3) /* reserved for local use */
#define LOG_LOCAL4 (20<<3) /* reserved for local use */
#define LOG_LOCAL5 (21<<3) /* reserved for local use */
#define LOG_LOCAL6 (22<<3) /* reserved for local use */
#define LOG_LOCAL7 (23<<3) /* reserved for local use */

*. auth 와 authpriv는 비슷하지만 조금 차이가 있다.
auth는 원격서비스 접속기록을 남기며
authpriv 는 su 명령어 사용기록, 로그인 성공 및 실패여부의 기록을 남긴다.

*. facility LOCAL0 ~ LOCAL7은 booting 기록이나 기타 여분의 용도로 사용한다.

syslog.conf 파일에서 facility 를 지정할때는 위에 정의된 LOG_KERN 인경우
kern 으로 설정한다. priority 도 마찬가지로 소문자로 crit 이런식으로 표기한다.
예) kern.crit;user.err

로그 설정에 대한 몇가지 예
kern.* /var/adm/kernel
=> 커널로부터 발생된 모든 레벨의 메세지를 오른쪽의 파일에 기록
kern.crit @unix1
=> 커널로부터 발생된 메세지중 crit 이상의 레벨 메세지를 unix1 호스트로 포워딩.
kern.crit /dev/console
=> 커널로부터 발생된 메세지중 crit 이상의 레벨 메세지를 console(tty1,tty2...) 에 보냄
kern.info;kern.!err /var/adm/kernel-info
=> 커널로부터 발생된 메세지중 info 레벨부터 err 레벨 바로 아래까지의 레벨메세지를
kernel-info 파일에 기록
*.info /var/log/messages
=> info 레벨 이상의 모든 facility 의 메세지를 오른쪽 파일에 기록
*.* /var/log/messages
=> 모든 selector 의 메세지를 /var/log/messages 파일에 기록
user.info user1,user2
=> 사용자 프로세스로부터 발생된 메세지중 info 레벨 이상의 메세지를 user1과 user2
사용자에게 보냄
mail.* *
=> mail 서비스로부터 발생된 메세지를 접속해 있는 모든사용자에게 보냄.

*. 기타 자세한 설정 방법은 syslog.conf 의 메뉴얼 페이지 참조.

로그서비스 테스트

로그서비스를 가장 간단히 시험할수 있는 툴로 logger 가 있다.

간단한 사용법은 아래와 같다.
logger [ -p selector ] message
ex) logger -p daemon.notice "daemon log test ....."

* Remote log

원격지에서 보내지는 로그를 받기위해서는

/etc/sysconfig/syslog

=> SYSLOGD_OPTIONS="-m 0" => SYSLOGD_OPTIONS="-m 0 -r" 로 수정한다.

/etc/syslog.conf에는

*.* @host이름


logrotate - rotates, compresses, and mails system logs

로그파일을 적절하게 관리하지 않으면 계속 쌓여서 너무 커질 수 있으며
그것으로 인하여 디스크가 Full 이 될수 있다.
또한 로그파일이 커질수록 syslog 데몬이 로그파일에 메세지를 남기는데
더 많은 부하를 초래하게 된다.
그러므로 로그파일이 너무 커지지 않게 관리해주어야 하는데 이때 필요한것이
logrotate 이다.
logrotate 는 로그파일을 주기적으로 백업시켜주고, 압축, 삭제, 메일로 전송등의
작업을 할 수 있다.

확인해보고 설치 안되어 있으면 yum 으로 설치한다.
[root@centos1 ~]# rpm -q logrotate
logrotate-3.7.4-9
[root@centos1 ~]#

[root@centos1 ~]# rpm -ql logrotate
/etc/cron.daily/logrotate
/etc/logrotate.conf
/etc/logrotate.d
/usr/sbin/logrotate
/usr/share/doc/logrotate-3.7.4
/usr/share/doc/logrotate-3.7.4/CHANGES
/usr/share/man/man8/logrotate.8.gz
/var/lib/logrotate.status
[root@centos1 ~]#

logrotate 를 설치하게 되면 자동으로 crontab 에 등록된다.

root@centos1 etc]# ls /etc/cron.daily/logrotate
/etc/cron.daily/logrotate
[root@centos1 etc]#

[root@centos1 etc]# grep cron.daily /etc/crontab
02 4 * * * root run-parts /etc/cron.daily
[root@centos1 etc]#
*. 위에처처럼 확인할 수 있다.

rogloate.conf 파일 - 아래처럼 되어 있다.

1 # see "man logrotate" for details
2 # rotate log files weekly
3 weekly
4
5 # keep 4 weeks worth of backlogs ; 백업된 로그파일을 4주간 남겨둠
(한주에 한개씩 rotate)
6 rotate 4
7
8 # create new (empty) log files after rotating old ones ; 오래된 파일을 rotate(순환)시킨후
새로운 빈 로그파일을 만든다.
9 create
10
11 # uncomment this if you want your log files compressed
12 #compress < = 로그파일을 압축하려면 주석을 풀어주면 된다.
13
14 # RPM packages drop log rotation information into this directory
15 include /etc/logrotate.d <= 이 디렉토리의 모든 파일을 여기에 포함하라는 의미.
16
17 # no packages own wtmp -- we'll rotate them here
18 /var/log/wtmp {
19 monthly
20 minsize 1M
21 create 0664 root utmp
22 rotate 1
23 }
24

[root@centos1 logrotate.d]# cat /etc/logrotate.d/vsftpd.log
/var/log/vsftpd.log {
# ftpd doesn't handle SIGHUP properly
nocompress <= 로그파일을 압축하지 않는다.
missingok <= 로그파일(vsftpd.log)이 없어도 에러를 발생시키지 않는다.
(nomissingok 는 반대되는 의미이며 생략했을때 디폴트값)
}

[root@centos1 logrotate.d]#

[root@centos1 logrotate.d]# cat /etc/logrotate.d/samba
/var/log/samba/*.log {
notifempty
missingok
sharedscripts
copytruncate
postrotate
/bin/kill -HUP `cat /var/run/smbd.pid /var/run/nmbd.pid /var/run/winbindd.pid 2> /dev/null` 2> /dev/null || true
endscript
}
[root@centos1 logrotate.d]#

notifempty : 로그파일이 비어 있을경우에는 rotate 하지 않는다.
디폴트는 ifempty이며 로그파일이 비어 있을경우에도 rotate 한다.
missingok : 로그파일이 없어도 에러를 발생시키지 않는다.
디폴트는 nomissingok 이며 로그파일이 없는 경우 에러를 발생시킨다.
sharedscripts : 로그파일이 rotate 될때 단 한번 prerotate 와 postrotate 가 실행된다.
nosharedscipts : 로그파일이 rotate 될때마다 prerotate와 postrotate 를 실행한다.
postrotate / endscript : rotate 한후의작업.
prerotate / endscript : rotate 하기전의 작업
copytruncate : 로그파일의 복사본을 만든후 원래의 로그파일 내용을 비우고 거기에 log를 새로 기록한다.
로그를 발생시키는 어떤 프로그램은 log 파일을 계속 열어두어야 하는것도 있다.
/bin/kill -HUP `cat /var/run/smbd.pid /var/run/nmbd.pid /var/run/winbindd.pid 2> /dev/null` 2> /dev/null || true
smbd 데몬과 nmbd 데몬 재시작, 재시작할때 에러가 발생되더라도 모니터로 출력하지 않으며 실행여부에 관계없이
참을 리턴한다.(리턴값은 항상 shell 이 받습니다. 리턴값을 가지고 다른 일을 처리하는경우 유용합니다.)



logwatch
- 로그를 정리해서 지정된 메일주소로 보내준다.(설치할때 크론에 하루 한번 실행되게 등록된다)
[root@centos1 ~]# ls -l /usr/sbin/logwatch
lrwxrwxrwx 1 root root 39 6월 25 2009 /usr/sbin/logwatch -> /usr/share/logwatch/scripts/logwatch.pl
[root@centos1 ~]#
logwatch는 바이너리 파일이 아니라 펄(perl)로 작성된 프로그램이다.

주요옵션
--detail level ( level 은 low, medium, high 또는 0,5,10)
--service servicename (특정서비스의 기록만 출력할 경우)
--print 표준출력으로 출력
--range (yesterday,today,all)
--save file명 (출력을 파일로 저장)
--logdir 디렉토리명 (디폴트 디렉토리대신 사용)

ex) root@server /root# logwatch --service sshd --detail low --print

################### Logwatch 7.3 (03/24/06) ####################
Processing Initiated: Mon Dec 6 11:20:49 2010
Date Range Processed: yesterday
( 2010-Dec-05 )
Period is day.
Detail Level of Output: 0
Type of Output: unformatted
Logfiles for Host: linux1
##################################################################

--------------------- SSHD Begin ------------------------

Disconnecting after too many authentication failures for user:
root : 1 Time(s)

Failed logins from:
192.168.197.1: 4 times

Users logging in through sshd:
root:
192.168.197.1: 12 times
172.20.10.101 (linux101): 1 time
user1:
172.20.10.101 (linux101): 1 time
192.168.197.1: 1 time

---------------------- SSHD End -------------------------


###################### Logwatch End #########################

root@server /root#


주요 로그설정파일
기록될 서비스 경로

주요설정항목

LogDir = /var/log
MailTo = root ; 계정을 적거나 완전한 이메일 주소를 적는다.
MailFrom = logwatch ; 메일로 받았을때 수신자가 logwatch로 표시된다.
Detail = Low ; High 로 설정하면 좀 더 자세한 로그를 볼수 있다.

설치하면 크론에 자동으로 등록된다.

-----------------------------------------------------------------------------------------------------------------------------------------

log service 예제

1.에러 이상의 priority를 갖는 메일 facility를 /var/log/mailerror 파일에 기록되게 설정하시오
2. sysadmin 이라는 사용자를 생성하고 ftp facility 의 모든 priority를 /var/log/ftplog 에 기록되게 설정하고 sysadmin 계정에게도 메세지가 전달되게 하시오.
(* su - sysadmin 으로 계정을 바꿔서 테스트하면 메시지를 못 받을수 있습니다.
반드시 sysadmin 으로 로그인 한다음 테스트 하시기 바랍니다)
3. selector 가 local0.err 인 경우 /var/log/local0 파일에 기록되게 설정하고
logger 명령으로 테스트하시오.
4. 사용자 인증시 info level 이상의 priority를 /var/log/auth_log 파일에 기록되게 설정하시오
(*. 테트스 방법은 su - 계정명 또는 telnet localhost 명령어로 su 명령어 사용기록 또는 로그인정보가 남는지를 확인하면 됩니다)
5. selector가 local1.info 인 경우 메시지를 접속해 있는 모든사용자의 콘솔에 뿌려지게 설정하시오.
6. selector가 local2.notice인 경우 메시지를 /var/log/local2 파일에 기록되게 하고 동시에
remote 서버(clone 머신)의 /var/log/remote_log 파일에도 저장되게 하시오.
7. 사용자 로그인정보(인증정보)를 로컬서버의 /var/log/secure 파일과 remote 서버의
/var/log/secure 파일에도 기록되게 설정하시오 (*. 테스트 방법은 4번과 동일합니다)
----------------------------------------------------------------------------------------------------------------------------------
logrotate 예제
아래와 같은 조건으로 로그파일을 백업하시오.
조건.
1. 파일명은 /var/log/test.log 로 한다.
(파일이 없으면 파일을 만들고 몇줄 추가해서 테스트하도록 합니다
-> ex) echo "log rotate test..." > /var/log/test.log
2. 백업로그파일을 3일간 남겨둔다.
3. rotate 주기는 매일.
4. 3일이 지난 로그파일은 logadmin@localhost 로 메일로 자동전송되게한후 삭제되게한다.
5. 로그파일이 압축되어 저장되게 한다.
6. 로그파일이 rotate 될때마다 syslog 서버를 재시작 되게 한다.
----------------------------------------------------------------------------------------------------------------------------------
logwatch 예제

아래 조건에 맞게 logwatch 를 설정하시오

조건.
1. log 출력의 detail level을 medium 으로 하시오.
2. logwatch 관리자에게 매일 새벽 두시에 log를 메일로 전송되게
설정하시오.

'Log > Linux' 카테고리의 다른 글

tcpdump - packet capture / 분석  (0) 2011.11.28
포트스캔 및 차단  (0) 2011.11.28
리눅스 방화벽 - iptables  (0) 2011.11.28
apache / php / mysql 설치 및 연동  (0) 2011.11.28
fedora9 dns 서버 설정 테스트 내용.  (0) 2011.11.28
Posted by logwatch
이전버튼 1 2 3 4 5 6 7 ··· 14 이전버튼

블로그 이미지
내가 나에게 확인 하는 블로그
logwatch

태그목록

공지사항

Yesterday
Today
Total

달력

 « |  » 2025.4
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

최근에 올라온 글

최근에 달린 댓글

글 보관함