[Linux] tcpdump 封包/數據包剖析器 (Packet Analyzer) 指南

Intro

Wikipedia - tcpdump

tcpdump 是一個執行在命令列下的數據包剖析器。它允許使用者攔截和顯示傳送或收到過網路連接到該電腦的 TCP/IP 和其他封包。

MAN PAGE OF TCPDUMP


用法

$ tcpdump -i [interface] '[expression]'

$ tcpdump -i en0 'tcp && host www.yidas.com'

# No interface flag is equal to any
$ tcpdump -i any 'port 22'

# Full verboses mode
$ tcpdump -i any 'port 25' -vv

tcpdump Expression Manual

Filter by packet

利用tcp[tcpflags]來指定過濾 TCP 封包類型,可用的 tcpflags 如下:

  • tcp-fin
  • tcp-syn
  • tcp-rst
  • tcp-push
  • tcp-ack
  • tcp-urg
  • tcp-ece
  • tcp-cwr
# 列出所有 SYN 或 FIN 封包
$ tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-fin) != 0'

# 在 25 port 上列出 PSH-ACK 封包
$ tcpdump -i any 'port 25 && tcp[tcpflags] & (tcp-push|tcp-ack) == (tcp-push|tcp-ack)' -vv

Example of tcpdump


Output 欄位

首先以監聽 25 port (SMTP) 預設輸出結果為例:

$ sudo tcpdump -i any 'port 25'

tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on any, link-type LINUX_SLL (Linux cooked), capture size 262144 bytes
15:38:25.831589 IP yidas.com.44458 > tj-in-f27.1e100.net.smtp: Flags [S], seq 186492170, win 64240, options [mss 1460,sackOK,TS val 1855872952 ecr 0,nop,wscale 7], length 0
15:38:25.883309 IP tj-in-f27.1e100.net.smtp > yidas.com.44458: Flags [S.], seq 362477225, ack 186492171, win 65535, options [mss 1412,sackOK,TS val 4265814556 ecr 1855872952,nop,wscale 8], length 0
15:38:25.883382 IP yidas.com.44458 > tj-in-f27.1e100.net.smtp: Flags [.], ack 1, win 502, options [nop,nop,TS val 1855873004 ecr 4265814556], length 0
15:38:26.053722 IP tj-in-f27.1e100.net.smtp > yidas.com.44458: Flags [P.], seq 1:87, ack 1, win 256, options [nop,nop,TS val 4265814726 ecr 1855873004], length 86: SMTP: 220 mx.google.com ESMTP c9-20020a170903235800b001bf1973eafcsi15096307plh.571 - gsmtp
15:38:26.053756 IP yidas.com.44458 > tj-in-f27.1e100.net.smtp: Flags [.], ack 87, win 502, options [nop,nop,TS val 1855873174 ecr 4265814726], length 0
15:38:26.053844 IP yidas.com.44458 > tj-in-f27.1e100.net.smtp: Flags [P.], seq 1:17, ack 87, win 502, options [nop,nop,TS val 1855873174 ecr 4265814726], length 16: SMTP: EHLO yidas.com
15:38:26.104243 IP tj-in-f27.1e100.net.smtp > yidas.com.44458: Flags [.], ack 17, win 256, options [nop,nop,TS val 4265814777 ecr 1855873174], length 0

Packet Flag

  • [S]: SY
  • [.]: ACK
  • [P]: PSH(推送)
  • [F]: FIN (Finish connection)
  • [R]: RST(Reset connection)

[S.] 表示 SYN-ACK,也就是 SYN packet 的 reply packet。
[P.] 表示 PSH-ACK,也就是 Application data packet 的。

Ref: TCP Detailed Process · yidas/web-service-protocols

Leave a Reply

Your email address will not be published. Required fields are marked *