tcpdump 應(yīng)該掌握的抓包技巧
tcpdump 是 Linux/Unix 系統(tǒng)的網(wǎng)絡(luò)抓包分析神器。它能像監(jiān)控?cái)z像頭一樣,實(shí)時(shí)捕獲流經(jīng)網(wǎng)卡的數(shù)據(jù)包,并將這些二進(jìn)制數(shù)據(jù)翻譯成可讀信息。無(wú)論是排查網(wǎng)絡(luò)故障、分析協(xié)議交互,還是安全檢測(cè),它都是工程師工具箱里的“瑞士軍刀”。
一、語(yǔ)法
tcpdump [ -AbdDefhHIJKlLnNOpqStuUvxX# ] [ -B buffer_size ]
[ -c count ]
[ -C file_size ] [ -G rotate_seconds ] [ -F file ]
[ -i interface ] [ -j tstamp_type ] [ -m module ] [ -M secret ]
[ --number ] [ -Q|-P in|out|inout ]
[ -r file ] [ -V file ] [ -s snaplen ] [ -T type ] [ -w file ]
[ -W filecount ]
[ -E spi@ipaddr algo:secret,... ]
[ -y datalinktype ] [ -z postrotate-command ] [ -Z user ]
[ --time-stamp-precision=tstamp_precision ]
[ --immediate-mode ] [ --version ]
[ expression ]
二、常見(jiàn)參數(shù)
- -i:指定網(wǎng)卡(如 -i eth0),-i any 監(jiān)聽(tīng)所有接口
- -c:限制抓包數(shù)量(如 -c 100 捕獲100個(gè)包后停止)
- -s:設(shè)置抓包長(zhǎng)度(-s 0 捕獲完整數(shù)據(jù)包)
- -w:保存到文件(如 -w capture.pcap)
- -d:把編譯過(guò)的數(shù)據(jù)包編碼轉(zhuǎn)換成可閱讀的格式
- -e:用來(lái)顯示源、目標(biāo)ip的mac地址
- -r: 讀取文件分析
- -n:禁用域名解析,直接顯示IP
- -l:開(kāi)啟行緩沖模式
- -A/-X:ASCII或十六進(jìn)制格式顯示內(nèi)容
三、過(guò)濾表達(dá)式
1. 主機(jī)、網(wǎng)絡(luò)與端口過(guò)濾:
- host:主機(jī),如host 192.168.1.100
- net:網(wǎng)絡(luò),如net 192.168.1.0/24
- port:端口,如port 80或port http
2. 協(xié)議過(guò)濾
tcp、udp、arp、rarp、icmp、ssh、telnet、ntp、ftp等等
3. 方向過(guò)濾
src、dst、src and dst、dst or src、in、out、inout
4. 邏輯組合
and/or/not(&& || !):如 src host 192.168.1.100 and dst port 443
四、場(chǎng)景舉例
抓包立即寫(xiě)入磁盤(pán):
tcpdump -i eth0 -U -w live.pcap
捕獲特定主機(jī)的HTTP/HTTPS流量:
tcpdump -i eth0 -n 'src host 192.168.1.1 and (dst port 80 or 443) and tcp'
抓取來(lái)自源地址為192.168.1.100的主機(jī)發(fā)送的icmp報(bào)文:
tcpdump -i eth0 -nn 'icmp and src host 192.168.1.100'
監(jiān)控網(wǎng)卡 eth0,捕獲IP 192.168.1.100 發(fā)出的、基于TCP協(xié)議的、HTTP流量(端口80),直接顯示IP地址和端口號(hào),并打印數(shù)據(jù)包中的明文內(nèi)容:
tcpdump -i eth0 -nnA 'port 80 and tcp and src host 192.168.1.100'
1. -Q (--direction):流量方向控制
只抓取進(jìn)入網(wǎng)卡的流量 (Inbound):
tcpdump -i eth0 -Q in -nn 'tcp port 22'
抓取發(fā)送到主機(jī)192.168.1.100的icmp報(bào)文:
tcpdump -i eth0 -Q out -nn 'host 192.168.1.100' and icmp
等同于:
tcpdump -i eth0 -nn 'dst host 192.168.1.100' and icmp
2. -tttt:打印完整可讀時(shí)間戳
捕獲ssh連接流量,并使用標(biāo)準(zhǔn)時(shí)間格式輸出:
tcpdump -tttt -i eth0 'port 22'
-e 用來(lái)顯示源、目標(biāo)ip的mac地址:
tcpdump -i eth0 -e 'arp'
協(xié)議與端口組合,抓取端口80或443且協(xié)議為T(mén)CP的報(bào)文:
tcpdump -i eth0 -n 'tcp and (port 80 or port 443)' -vvv
3. -vvv:獲取更詳細(xì)的輸出信息
抓取TCP握手異常 (SYN無(wú)響應(yīng))的報(bào)文:
tcpdump -i eth0 -n 'tcp[tcpflags] & (tcp-syn) != 0 and tcp[tcpflags] & (tcp-ack) = 0'
實(shí)時(shí)提取IP地址為192.168.1.100的HTTP報(bào)文:
tcpdump -i eth0 -l -A -s0 'port 80' | grep -i '192.168.1.100'
捕獲進(jìn)出IP為192.168.1.100的HTTPS流量,每文件100MB,保留最后10個(gè)文件,帶納秒時(shí)間戳:
tcpdump -i eth0 -Q inout -nn 'host 192.168.1.100 and port 443' \
-C 100 -W 10 -w https_trace.pcap \
--time-stamp-precision nano \
-z gzip # 自動(dòng)壓縮完成文件
?? 趣味冷知識(shí):tcpdump 誕生于 1987 年,比萬(wàn)維網(wǎng)(WWW)還早 4 年!它的設(shè)計(jì)理念至今仍影響著現(xiàn)代網(wǎng)絡(luò)分析工具。