tcpdump

|

  • Tcpdump란?

    Tcpdump는 주어진 조건식을 만족하는 네트워크 인터페이스를 거치는 패킷들의 헤더들 을 출력해 주는 프로그램이다. 프로그램의 특성상, 네트워크 인터페이스를 아주 심도 있게 사용하기 때문에, 실행하는 사람은 반드시 네트워크 인터페이스에 대한 읽기 권 한이 있어야만 한다.
    OS dependent)
    위에서 말하는 읽기 권한을 가지고 있어야 하는 파일, 혹은 Tcpdump의 퍼미션 이다.

    • SunOS : /dev/nit, /dev/bpf*
    • Solaris(SunOS 5.x) : /dev/le 등
    • HP-UX & IRIX & Linux : root에서 실행하거나, root로 setuid를 설정해야 함
    • Ultrix & Digital UNIX : root가 pfconfig를 이용하여, promiscuous-mode를 가능하게 설정하면 어떤 유저라도 사용할 수 있다.
    • BSD : /dev/bpf*


  • Tcpdump의 패키지 구하기

    Tcpdump는 ftp://ftp.ee.lbl.gov/tcpdump.tar.Z에서 최신 버전을 구할 수 있다. 유명 한 프로그램이기 때문에, 시스템소프트웨어를 패키지형태로 제공해 주는 OS들의 경우 Vendor에서 패키징된(컴파일된) 버전으로도 구할 수 있을 것이다.


  • Tcpdump의 설치

    Tcpdump는 libpcap(Protocol Capture Library)라는 것을 사용한다. 이 라이브러리는 Platform에 상관없이 동일한 방법으로 사용자 레벨에서 패킷들을 캡춰할 수 있게 해 준다. 따라서 이 라이브러리가 없다면, ftp://ftp.ee.lbl.gov/libpcap.tar.Z에서 구하 여 설치하도록 한다.

    ANSI C 컴파일러는 아마 대부분의 시스템에서 구비하고 있을 것이다. 만약 없다면 ftp://prep.ai.mit.edu/pub/gnu/gcc.tar.gz를 받아서 설치하기 바란다.

    libpcap라이브러리가 완벽하게 설치되었다는 가정하에서 다음의 절차에 따라 설치를 시작한다.

    • Makefile.in의 BINDEST와 MANDEST 항목에 각각, tcpdump 실행파일과 메뉴얼 페이 지가 설치될 디렉토리들을 입력해 준다.
    • Tcpdump 패키지와 함께 제공되는 ./configure 스크립트를 실행시킨다. 이 스크립트는 현재 시스템의 환경들을 검사하고 이에 맞추어서 Makefile을 생성해 준다.
    • make를 실행한다.
    • 컴파일이 다 됐으면, make install을 수행하여 실행파일을 설치하고, make install-man을 실행하여 메뉴얼 페이지도 설치한다.
    • tcpdump의 퍼미션이 제대로 되었는지를 검사한다. setgid가 설정되어 있기 때문에, 원하지 않는 사람이 실행하게 된다면 위험하다.
    위에서 설명한 절차를 그대로 옮겨 본다.
    # vi Makefile.in
    # ./configure
    # make
    # make install
    # make install-man
    
    OS dependent)
    • DEC/OSF and BSD/386, etc : tcpdump가 OS와 함께 제공되는 경우가 있다. 이럴 경우 tcpdump를 업그레이드 하기 전에 반드시 기존의 tcpdump를 백업해 두도록 하자.
    • Linux : libpcap 라이브러리는 2.0.25 커널에서 테스트 됐다. 2.0.x 대 커널 에서 25이하의 버전에서는 실행이 아마 가능할 것이다. 그러나 1.x대의 커널에서는 동작 여부가 입증되지 않았으므로 주의해야 한다.
    • OSF 4 : OSF4에서는 stack C 컴파일러에 치명적인 버그가 있다. 이 버그를 피해가려면, ./configure를 실행한 후 컴파일 하기 전에 Makefile에서 다음의 문장을 삭제한 후 컴파일해 주면 된다.
                -DETHER_HEADER_HAS_EA=1 -DETHER_ARP_HAS_EA=1
    


  • Tcpdump Source의 간략한 설명


  • Tcpdump의 옵션들

    • -a : Network & Broadcast 주소들을 이름들로 바꾼다.
    • -c Number : 제시된 수의 패킷을 받은 후 종료한다.
    • -d : comile된 packet-matching code를 사람이 읽을 수 있도록 바꾸어 표준 출력으로 출력하고, 종료한다.
    • -dd : packet-matching code를 C program의 일부로 출력한다.
    • -ddd : packet-matching code를 숫자로 출력한다.
    • -e : 출력되는 각각의 행에 대해서 link-level 헤더를 출력한다.
    • -f : 외부의 internet address를 가급적 심볼로 출력한다(Sun의 yp server와의 사용은 가급적 피하자).
    • -F file : filter 표현의 입력으로 파일을 받아들인다. 커맨드라인에 주어진 추가의 표현들은 모두 무시된다.
    • -i device : 어느 인터페이스를 경유하는 패킷들을 잡을지 지정한다. 지저되지 않으면 시스템의 인터페이스 리스트를 뒤져서 가장 낮은 번호를 가진 인터페이스를 선택한다(이 때 loopback은 제외된다).
    • -l : 표준 출력으로 나가는 데이터들을 line buffering한다. 다른 프로그램에서 tcpdump로부터 데이터를 받고자 할 때, 유용하다.
    • -n : 모든 주소들을 번역하지 않는다(port,host address 등등)
    • -N : 호스트 이름을 출력할 때, 도메인을 찍지 않는다.
    • -O : packet-matching code optimizer를 실행하지 않는다. 이 옵션은 optimizer에 있는 버그를 찾을 때나 쓰인다.
    • -p : 인터페이스를 promiscuous mode로 두지 않는다.
    • -q : 프로토콜에 대한 정보를 덜 출력한다. 따라서 출력되는 라인이 좀 더 짧아진다.
    • -r file : 패킷들을 '-w'옵션으로 만들어진 파일로 부터 읽어 들인다. 파일에 "-" 가 사용되면 표준 입력을 통해서 받아들인다.
    • -s length: 패킷들로부터 추출하는 샘플을 default값인 68Byte외의 값으로 설정할 때 사용한다(SunOS의 NIT에서는 최소가 96Byte이다). 68Byte는 IP,ICMP, TCP, UDP등에 적절한 값이지만 Name Server나 NFS 패킷들의 경우에는 프로토콜의 정보들을 Truncation할 우려가 있다. 이 옵션을 수정할 때는 신중해야만 한다. 이유는 샘플 사이즈를 크게 잡으면 곧 패킷 하나하나를 처리하는데 시간이 더 걸릴 뿐만아니라 패킷 버퍼의 사이즈도 자연히 작아지게 되어 손실되는 패킷들이 발생할 수 있기 때문이다. 또, 작게 잡으면 그만큼의 정보를 잃게되는 것이다. 따라서 가급적 캡춰하고자 하는 프로토콜의 헤더 사이즈에 가깝게 잡아주어야 한다.
    • -T type : 조건식에 의해 선택된 패킷들을 명시된 형식으로 표시한다. type에는 다음과 같은 것들이 올 수 있다. rpc(Remote Procedure Call), rtp(Real-Time Applications protocol), rtcp(Real-Time Application control protocal), vat(Visual Audio Tool), wb(distributed White Board)
    • -S : TCP sequence번호를 상대적인 번호가 아닌 절대적인 번호로 출력한다.
    • -t : 출력되는 각각의 라인에 시간을 출력하지 않는다.
    • -tt : 출력되는 각각의 라인에 형식이 없는 시간들을 출력한다.
    • -v : 좀 더 많은 정보들을 출력한다.
    • -vv : '-v'보다 좀 더 많은 정보들을 출력한다.
    • -w : 캡춰한 패킷들을 분석해서 출력하는 대신에 그대로 파일에 저장한다.
    • -x : 각각의 패킷을 헥사코드로 출력한다.

    조건식(expression)

    옵션의 제일 마지막인 조건식은 어떤 패킷들을 출력할지를 선택하는데 쓰인다. 조건식이 주어지지 않는 다면 모든 패킷들이 그 대상이 될 것이다. 일단 주어지면, 아무리 패킷들이 많아도 조 건식에 부합하는 패킷만을 출력한다.

    조건식들은 하나 또는 몇 개의 primitive들로 구성되어 있다. primitive들은 보통 하나 혹은 몇개의 qualifier들 다음에 오는 하나의 값으로 이루어진다. Qualifier들은 모두 3 종류이며 다음과 같다.

    • type : 주어진 값의 종류가 무엇인지를 나타낸다. 가능한 type들은 'host', 'net', 'port'가 있다. type이 없는 값들은 type을 host라 가정한다.
    • dir : id로 부터의 어떤 특정한 전송 방향을 나타낸다. 가능한 방향은 'src', 'dst', 'src or dst', 'src and dst'이다. 만약 방향이 정해지지 않았다면, src or dst라 가정한다. "For `null' link layers (i.e. point to point protocols such as slip) the inb ound and out bound qualifiers can be used to specify a desired direction."
    • proto : 매칭을 특정 프로토콜에 한해서 수행한다. 가능한 프로토콜들은 ether, fddi, ip, arp, rarp, decnet, lat, sca, moprc, mopdl, tcp, udp이다. 만약 프로토콜이 명시되지 않았다면, 해당하는 값의 type에 관련된 모든 프로토콜들이 그 대상이 된다.

    이 밖에도 위의 패턴을 따르지 않는 Primitive들이 존재한다(gateway, broadcst, less, greater, 산술식).

    좀 더 정교한 조건식들을 사용하려면, 'and(&&)', 'or(||)', 'not(!)'들을 사용하여 여러 primitive들을 연결하면 된다. 같은 표현들은 생략될 수 있다.

    사용 가능한 Primitive들

    • dst host HOST
      packet의 IP destination 항목이 HOST일때 참이 된다.
    • src host HOST
      packet의 IP source 항목이 HOST일때 참이 된다.
    • host HOST
      IP source, IP destination 항목 중 어느 하나라도 HOST이면 참이다.
    • ether dst ehost
      ethernet destination 주소가 ehost일 때 참이다.
    • ether src ehost
      ethernet source 주소가 ehost일 때 참이다.
    • ether host ehost
      ethernet source, destination 항목들 중 어느 하나라도 ehost이면 참이다.
    • gateway host
      패킷이 host를 게이트웨이로 사용하면 참이다. 이 말의 의미는 ethernet sour ce나 destination 항목은 host이지만, IP source와 destination은 host가 아닐 때를 말한다.
    • dst net NET
      패킷의 IP destination 주소가 NET의 network number를 가지고 있을 때 참이 다.
    • src net NET
      패킷의 IP source 주소가 NET의 network number를 가지고 있을 때 참이다.
    • net NET
      패킷의 IP source 주소 혹은 destination 주소가 NET의 network number를 가 지고 있을 때 참이다.
    • net netmask mask
      IP 어드레스가 지정된 netmask를 통해서 net과 매칭되면 참이다.
    • net net/len
      IP 어드레스가 netmask와 len 비트만큼 매치되면 참이다.
    • dst port PORT
      패킷이 ip/tcp, ip/udp 프로토콜의 패킷이고 destination port의 값이 PORT일 때 참이다. port는 /etc/services에 명시된 이름일 수도 있고 그냥 숫자일 수도 있다. 만약 이름이 사용됐다면 port 번호와 프로토콜이 같이 체크될 것이다. 만약 숫자나 불 확실한 이름이 사용됐을 경우에는 port 번호만이 체크될 것이다.
    • src port PORT
      패킷의 source port의 값으로 PORT를 가지면 참이다.
    • port PORT
      패킷의 source, destination port 중에 하나라도 PORT이면 참이다.
    • less length
      패킷이 length보다 짧거나 같으면 참이다.(len <= length)
    • greater length
      패킷이 length보다 짧거나 같으면 참이다.(len >= length)
    • ip proto protocol
      패킷이 지정된 종류의 프로토콜의 ip패킷이면 참이다. Protocol은 icmp, igrp, udp, nd, tcp 중의 하나 혹은 몇 개가 될 수 있다. 주의할 점은 tcp, udp, icmp들은 '\'로 escape되어야 한다.
    • ehter broadcast
      패킷이 ethernet broadcast 패킷이라면 참이다. ehter는 생략 가능하다.
    • ip broadcast
      패킷이 IP broadcast 패킷이라면 참이다.
    • ether multicast
      패킷이 IP multicast 패킷이라면 참이다.
    • ether proto protocol
      패킷이 ether type의 protocol이라면 참이다. protocol은 ip, arp, rarp 중에 하나 혹은 몇개가 될 수 있다. ip proto protocol에서와 마찬가지로 ip, arp, rarp는 escape 되어야 한다.
    • decnet src host
      만약 DECNET의 source address가 host이면 참이다. 이 어드레스는 '10.123'이 나 DECNET의 host name일 수 있다. DECNET host name은 DECNET에서 돌아가도록 설정된 Ultrix 시스템에서만 사용 가능하다.
    • decnet dst host
      DECNET destination address가 host이면 참이다.
    • decnet host HOST
      DECNET source, destination address중의 하나라도 HOST이면 참이다.
    • ip, arp, rarp, decnet
      ether proto [ip|arp|rarp|decnet]의 약어
    • lat, moprc, mopdl
      ether proto [lat|moprc|mopdl]의 약어
    • tcp, udp, icmp
      ip proto [tcp|udp|icmp]의 약어
    • expr relop expr
      • EXPR
        proto [expr:size]의 형식을 띤다. proto, expr, size에 올 수 있는 것들은 다음과 같다.
        • proto : ether, fddi, ip, arp, rarp, tcp, udp, icmp
        • expr : indicate Byte offset of packet of proto
        • size : optional. indicate the size of bytes in field of interest
        • default is one, and can be two or four
      • RELOP
        !=, =, <=, >=, etc.

      이 조건식을 사용하기 위해서는 먼저 해당하는 Protocol(proto)의 헤더에 관련된 것들을 자세히 알아야만 한다. proto에는 대상이 될 프로토콜을 지정한다. expr에는 프로토콜 헤더의 처음부터의 Byte Offset을 지정하는 식이 들어가게 된다. Size는 Option이며 지정이 안 되어 있을 경우에는 자동으로 1byte를 지칭한다. 따라서 이 조건식을 사용하게 되면 헤더에 포함된 정보를 Bitmask를 사용하여 직 접 원하는 패킷인지를 가려낼 수 있기 때문에, 보다 정밀한 사용이 가능하게 된다.


  • Tcpdump의 사용 예제들

    • security라는 호스트로부터 날아오고, 날아가는 패킷들을 출력
      # tcpdump host security
    • security와 mazinga, getarobo 사이에 날아다니고 있는 패킷들을 출력
      # tcpdump host security and \( mazinga or getarobo \)
    • security에서 elgaim을 제외한 모든 호스트로 날아다니는 IP 패킷들을 출력
      # tcpdump ip host security and not elgaim
    • gateway amurorei를 거치는 ftp에 관련된 패킷들을 출력
      # tcpdump 'gateway amurorei and ( port ftp or ftp-data )'
    • local호스트가 아닌 호스트와 로컬호스트가 맺는 TCP 커넥션의 시작과 마지막 패 킷들을 출력한다(SYN, FIN 패킷).
      # tcpdump 'tcp[13] & 3 != 0 and not src and dst net non-local'
    • gateway amurorei를 지나는 576Byte보다 큰 패킷들을 출력한다
      # tcpdump 'gateway amurorei and ip[2:2] > 576'
    • Ethernet boradcast 혹은 multicast를 통해서 보내진 것이 아닌, IP broadcast 혹 은 multicast 패킷들을 출력한다.
      # tcpdump 'ehter[0] & 1 = 0 and ip[16] >= 224'
    • Echo request/reply가 아닌 ICMP 패킷들을 모두 출력한다.
      # tcpdump 'icmp[0] != 8 and icmp[0] != 0'


  • Tcpdump의 평가

    TCPDUMP는 여러모로 좋은 툴이다. libpcap을 거의 100% 활용한 프로그램의 예이며, 실제로 많은 툴들이 TCPDUMP와 병행하여 돌아가거나, TCPDUMP를 기반으로 제작되었다. TCPDUMP의 막강한 packet filter는 현재 로컬 네트워크 상에서 날아다니고 있는 특정한 패킷들을 실시간으로 기록해 줄 수 있으며, 이를 이용하여 네트워크에서 벌어지는 일들을 네트워크 관리자가 원하는 대로 뽑아 볼 수 있게 해 준다. 또한, 시스템 관리자들에게는 로컬 유저의 외부로의 커넥션들을 감시하고, 또 특정 침입자가 침투 경로로 자주 이용하는 호스트, 혹은 원하지 않는 호스트로부터의 커넥션을 실시간으로 감시할 수 있게 해 준다. libpcap을 이용하여 비슷한 툴을 제작하고자 하는 사람들에게도 TCPDUMP는 가장 훌륭한 예제가 될 것이다.


  •  

    Table of Contents

    tcpdump is the premier network analysis tool for information security professionals. Having a solid grasp of this über-powerful application is mandatory for anyone desiring a thorough understanding of TCP/IP. Many prefer to use higher level analysis tools such as Ethereal Wireshark, but I believe this to usually be a mistake.

    In a discipline so dependent on a true understanding of concepts vs. rote learning, it's important to stay fluent in the underlying mechanics of the TCP/IP suite. A thorough grasp of these protocols allows one to troubleshoot at a level far beyond the average analyst, but mastery of the protocols is only possible through continued exposure to them.

    When using a tool that displays network traffic a more natural (raw) way the burden of analysis is placed directly on the human rather than the application. This approach cultivates continued and elevated understanding of the TCP/IP suite, and for this reason I strongly advocate using tcpdump instead of other tools whenever possible.

    15:31:34.079416 IP (tos 0x0, ttl  64, id 20244, offset 0, flags [DF], proto: 
    TCP (6), length: 60) source.35970 > dest.80: S, cksum 0x0ac1 
    (correct), 2647022145:2647022145(0) win 5840
    0x0000:  4500 003c 4f14 4000 4006 7417 0afb 0257  E..
    0x0010:  4815 222a 8c82 0050 9dc6 5a41 0000 0000  H."*...P..ZA....
    0x0020:  a002 16d0 0ac1 0000 0204 05b4 0402 080a  ................
    0x0030:  14b4 1555 0000 0000 0103 0302            ...U........


     

    Options

    Below are a few options (with examples) that will help you greatly when working with the tool. They're easy to forget and/or confuse with other types of filters, i.e. ethereal, so hopefully this page can serve as a reference for you, as it does me.

    First off, I like to add a few options to the tcpdump command itself, depending on what I'm looking at. The first of these is -n, which requests that names are not resolved, resulting in the IPs themselves always being displayed. The second is -X, which displays both hex and ascii content within the packet. The final one is -S, which changes the display of sequence numbers to absolute rather than relative. The idea there is that you can't see weirdness in the sequence numbers if they're being hidden from you. Remember, the advantage of using tcpdump vs. another tool is getting manual interaction with the packets.

    It's also important to note that tcpdump only takes the first 68 96 bytes of data from a packet by default. If you would like to look at more, add the -s number option to the mix, where number is the number of bytes you want to capture. I recommend using 0 (zero) for a snaplength, which gets everything. Here's a short list of the options I use most:

    • -i any : Listen on all interfaces just to see if you're seeing any traffic.
    • -n : Don't resolve hostnames.
    • -nn : Don't resolve hostnames or port names.
    • -X : Show the packet's contents in both hex and ASCII.
    • -XX : Same as -X, but also shows the ethernet header.
    • -v, -vv, -vvv : Increase the amount of packet information you get back.
    • -c : Only get x number of packets and then stop.
    • -s : Define the size of the capture (use -s0 unless you are intentionally capturing less.)
    • -S : Print absolute sequence numbers.
    • -e : Get the ethernet header as well.
    • -q : Show less protocol information.
    • -E : Decrypt IPSEC traffic by providing an encryption key.
    • -s : Set the snaplength, i.e. the amount of data that is being captured in bytes
    • -c : Only capture x number of packets, e.g. 'tcpdump -c 3'

    [ The default snaplength as of tcpdump 4.0 has changed from 68 bytes to 96 bytes. While this will give you more of a packet to see, it still won't get everything. Use -s 1514 to get full coverage ]

    Basic Usage

    So, based on the kind of traffic I'm looking for, I use a different combination of options to tcpdump, as can be seen below:

    1. Basic communication // see the basics without many options

      # tcpdump -nS


    2. Basic communication (very verbose) // see a good amount of traffic, with verbosity and no name help

      # tcpdump -nnvvS


    3. A deeper look at the traffic // adds -X for payload but doesn't grab any more of the packet

      # tcpdump -nnvvXS


    4. Heavy packet viewing // the final "s" increases the snaplength, grabbing the whole packet

      # tcpdump -nnvvXSs 1514

    Here's a capture of exactly two (-c2) ICMP packets (a ping and pong) using some of the options described above. Notice how much we see about each packet.

    hermes root # tcpdump -nnvXSs 0 -c2 icmp
    tcpdump: listening on eth0, link-type EN10MB (Ethernet), 23:11:10.370321 IP 
    (tos 0x20, ttl  48, id 34859, offset 0, flags [none], length: 84) 
    69.254.213.43 > 72.21.34.42: icmp 64: echo request seq 0
    
            0x0000:  4520 0054 882b 0000 3001 7cf5 45fe d52b  E..T.+..0.|.E..+
            0x0010:  4815 222a 0800 3530 272a 0000 25ff d744  H."*..50'*..%..D
            0x0020:  ae5e 0500 0809 0a0b 0c0d 0e0f 1011 1213  .^..............
            0x0030:  1415 1617 1819 1a1b 1c1d 1e1f 2021 2223  .............!"#
            0x0040:  2425 2627 2829 2a2b 2c2d 2e2f 3031 3233  $%&'()*+,-./0123
            0x0050:  3435 3637                                4567
    23:11:10.370344 IP (tos 0x20, ttl  64, id 35612, offset 0, flags [none], 
    length: 84) 72.21.34.42 > 69.254.213.43: icmp 64: echo reply seq 0
            0x0000:  4520 0054 8b1c 0000 4001 6a04 4815 222a  E..T....@.j.H."*
            0x0010:  45fe d52b 0000 3d30 272a 0000 25ff d744  E..+..=0'*..%..D
            0x0020:  ae5e 0500 0809 0a0b 0c0d 0e0f 1011 1213  .^..............
            0x0030:  1415 1617 1819 1a1b 1c1d 1e1f 2021 2223  .............!"#
            0x0040:  2425 2627 2829 2a2b 2c2d 2e2f 3031 3233  $%&'()*+,-./0123
            0x0050:  3435 3637                                4567
    2 packets captured
    2 packets received by filter
    0 packets dropped by kernel
    hermes root # 
    


     

    Common Syntax

    Expressions allow you to trim out various types of traffic and find exactly what you're looking for. Mastering the expressions and learning to combine them creatively is what makes one truly powerful with tcpdump. There are three main types of expression: type, dir, and proto.

    Type options are host, net, and port. Direction is indicated by dir, and there you can have src, dst, src or dst, and src and dst. Here are a few that you should definitely be comfortable with:

    • host // look for traffic based on IP address (also works with hostname if you're not using -n)

      # tcpdump host 1.2.3.4


    • src, dst // find traffic from only a source or destination (eliminates one side of a host conversation)

      # tcpdump src 2.3.4.5
      # tcpdump dst 3.4.5.6


    • net // capture an entire network using CIDR notation

      # tcpdump net 1.2.3.0/24


    • proto // works for tcp, udp, and icmp. Note that you don't have to type proto

      # tcpdump icmp


    • port // see only traffic to or from a certain port

      # tcpdump port 3389

    • src, dst port // filter based on the source or destination port

      # tcpdump src port 1025
      # tcpdump dst port 389


    • src/dst, port, protocol // combine all three

      # tcpdump src port 1025 and tcp
      # tcpdump udp and src port 53

    You also have the option to filter by a range of ports instead of declaring them individually, and to only see packets that are above or below a certain size.

    • Port Ranges // see traffic to any port in a range
      tcpdump portrange 21-23
    • Packet Size Filter // only see packets below or above a certain size (in bytes)
      tcpdump less 32
      tcpdump greater 128

      [ You can use the symbols for less than, greater than, and less than or equal / greater than or equal signs as well. ]

      // filtering for size using symbols
      tcpdump > 32
      tcpdump <= 128

    Writing to a File

    tcpdump allows you to send what you're capturing to a file for later use using the -w option, and then to read it back using the -r option. This is an excellent way to capture raw traffic and then run it through various tools later.

    The traffic captured in this way is stored in tcpdump format, which is pretty much universal in the network analysis space. This means it can be read in by all sorts of tools, including Wireshark, Snort, etc.


     

    Capture all Port 80 Traffic to a File

    # tcpdump -s 1514 port 80 -w capture_file

    Then, at some point in the future, you can then read the traffic back in like so:


     

    Read Captured Traffic back into tcpdump

    # tcpdump -r capture_file

    Getting Creative

    Expressions are nice, but the real magic of tcpdump comes from the ability to combine them in creative ways in order to isolate exactly what you're looking for. There are three ways to do combinations, and if you've studied computers at all they'll be pretty familar to you:

    1. AND
      and or &&
    2. OR
      or or ||
    3. EXCEPT
      not or !

    More Examples

    # TCP traffic from 10.5.2.3 destined for port 3389

    tcpdump -nnvvS and src 10.5.2.3 and dst port 3389

    # Traffic originating from the 192.168 network headed for the 10 or 172.16 networks

    tcpdump -nvX src net 192.168.0.0/16 and dst net 10.0.0.0/8 or 172.16.0.0/16

    # Non-ICMP traffic destined for 192.168.0.2 from the 172.16 network

    tcpdump -nvvXSs 1514 dst 192.168.0.2 and src net and not icmp

    # Traffic originating from Mars or Pluto that isn't to the SSH port

    tcpdump -vv src mars and not dst port 22

    As you can see, you can build queries to find just about anything you need. The key is to first figure out precisely what you're looking for and then to build the syntax to isolate that specific type of traffic.

    Grouping

    Also keep in mind that when you're building complex queries you might have to group your options using single quotes. Single quotes are used in order to tell tcpdump to ignore certain special characters -- in this case the "( )" brackets. This same technique can be used to group using other expressions such as host, port, net, etc. Take a look at the command below:

    # Traffic that's from 10.0.2.4 AND destined for ports 3389 or 22 (incorrect)

    tcpdump src 10.0.2.4 and (dst port 3389 or 22)

    If you tried to run this otherwise very useful command, you'd get an error because of the parenthesis. You can either fix this by escaping the parenthesis (putting a \ before each one), or by putting the entire command within single quotes:

    # Traffic that's from 10.0.2.4 AND destined for ports 3389 or 22 (correct)

    tcpdump 'src 10.0.2.4 and (dst port 3389 or 22)'


     

    Advanced

    You can also filter based on specific portions of a packet, as well as combine multiple conditions into groups. The former is useful when looking for only SYNs or RSTs, for example, and the latter for even more advanced traffic isolation.

    [ Hint: An anagram for the TCP flags: Unskilled Attackers Pester Real Security Folk ]

    Show me all URGENT (URG) packets...

    # tcpdump 'tcp[13] & 32!=0'

    Show me all ACKNOWLEDGE (ACK) packets...

    # tcpdump 'tcp[13] & 16!=0'

    Show me all PUSH (PSH) packets...

    # tcpdump 'tcp[13] & 8!=0'

    Show me all RESET (RST) packets...

    # tcpdump 'tcp[13] & 4!=0'

    Show me all SYNCHRONIZE (SYN) packets...

    # tcpdump 'tcp[13] & 2!=0'

    Show me all FINISH (FIN) packets...

    # tcpdump 'tcp[13] & 1!=0'

    Show me all SYNCHRONIZE/ACKNOWLEDGE (SYNACK) packets...

    # tcpdump 'tcp[13] & =18'

    [ Note: Only the PSH, RST, SYN, and FIN flags are displayed in tcpdump's flag field output. URGs and ACKs are displayed, but they are shown elsewhere in the output rather than in the flags field ]

    Keep in mind the reasons these filters work. The filters above find these various packets because tcp[13] looks at offset 13 in the TCP header, the number represents the location within the byte, and the !=0 means that the flag in question is set to 1, i.e. it's on.

    As with most powerful tools, however, there are multiple ways to do things. The example below shows another way to capture packets with specific TCP flags set.

    Capture TCP Flags Using the tcpflags Option...

    # tcpdump 'tcp[tcpflags] & & tcp-syn != 0'

    Specialized Traffic

    Finally, there are a few quick recipes you'll want to remember for catching specific and specialized traffic, such as IPv6 and malformed/likely-malicious packets.

    IPv6 traffic

    # tcpdump ip6

    Packets with both the RST and SYN flags set (why?)

    # tcpdump 'tcp[13] = 6'

    Traffic with the 'Evil Bit' Set

    # tcpdump 'ip[6] & 128 != 0'


     

    '개발/활용정보 > Linux' 카테고리의 다른 글

    bootchart  (0) 2011.12.29
    Shell Script  (0) 2011.12.29
    리눅스 명령어 목록  (0) 2011.10.10
    linux 브릿지 설정 brctl  (0) 2011.10.10
    ip forwarding, sniffing, nat  (0) 2011.10.07
    And