tcpdump必知必会

发布时间 2023-11-10 10:58:17作者: 博客猿马甲哥
  1. tcpdump原理 & 在tcp协议栈的位置
  2. tcpdump用法
  • 基于协议、主机、端口过滤
  • 使用and or逻辑运算符做复杂的过滤操作
  • tcpdump flags

1. tcpdump原理

linux中非常有用的网络工具,运行在用户态


数据包到达网卡,经过数据包过滤器bpf筛选后,拷贝至用户态的tcpdump程序。

tcpdump抓包

“抓” 这个动作是由数据包过滤器bpf完成, bpf的主要作用就是根据用户输入的过滤规则,直将用户关心的数据包拷贝至tcpdump。注意是拷贝,不是剪切。

面试题: 某些数据包被iptables封禁,是否可通过tcpdump抓包?

linux中netfilter是工作在tcp协议栈阶段, tcpdump的过滤器bpf是工作在更底层,所以当然是可以抓到包。

2. tcpdump常规用法

抓包上帝视角:

  • 可将tcpdump当做网络请求的对端。
  • tcpdump 支持网络层、协议、铸就、网络或端口的过滤,并提供and、or、not等逻辑语句来帮助过滤。

2.1抓包前置参数:

  • -D: 提供可以捕获流量的设备列表
  • -c n:捕获n个包后终止
  • -n: tcpdump默认会对(ip:port)转换为主机名,影响抓包效率,-n可设置不做转换,直接显示ip地址;
  • -s 0 : 设置抓取(已经筛选出的数据包的)长度,如果不设置默认是68 字节,0 意味着tcpdump自动选择合适的长度抓包;
  • -w: 抓取的内容输出到文件
  • -r : 跟-w 是对应的,从文件读取
  • -vvv :输出详细的最高级别

2.2 抓包筛选参数:

  • host: 过滤特定主机的流量,可填hostname或者ip;

注意:命令中的hostname会被解析成ip地址,如果解析出来的是vip(可能会作用到多个实际的业务Host),会抓取到非预期的数据包。

可以使用 src host 或者 dst host来抓取特定方向的流量。

tcpdump -n -i eth0 host janus.qa.xxxx.com -vvv -tttt

2023-11-08 14:37:48.478256 IP (tos 0x0, ttl 64, id 47134, offset 0, flags [DF], proto TCP (6), length 554)
    10.178.75.56.44054 > 10.98.21.3.http: Flags [P.], cksum 0x776b (incorrect -> 0x1251), seq 514:1028, ack 186, win 589, length 514: HTTP, length: 514
	POST /janus-api/api/agent/tasks HTTP/1.1
	Host: janus.qa.****.com
	User-Agent: Go-http-client/1.1
	Content-Length: 366
	Accept-Encoding: gzip

	{"groupId":"63fefa20b1e3c135612005c9","ip":"10.178.75.56","env":"qa","idc":"officeidc_hd2","tags":["10.178.75.56","officeidc_hd2","machine"],"lastTaskId":"202303210000000017","versionInfo":{"staticConfigVersionId":"v2023.03.20.004","autoConfigVersionId":"v2023.03.20.004","configVersionId":"0","status":true,"ipTime":"2019-12-04 01:06:06"},"lastTasks":{"status":[]}}[!http]
2023-11-08 14:37:48.520706 IP (tos 0x0, ttl 52, id 64787, offset 0, flags [DF], proto TCP (6), length 40)
    10.98.21.3.http > 10.178.75.56.44054: Flags [.], cksum 0xa1f6 (correct), seq 186, ack 1028, win 150, length 0
2023-11-08 14:37:48.523697 IP (tos 0x0, ttl 52, id 64788, offset 0, flags [DF], proto TCP (6), length 225)
    10.98.21.3.http > 10.178.75.56.44054: Flags [P.], cksum 0xb2f6 (correct), seq 186:371, ack 1028, win 150, length 185: HTTP, length: 185
	HTTP/1.1 200 OK
	Content-Type: application/json; charset=utf-8
	Content-Length: 38
	Connection: keep-alive
	Date: Wed, 08 Nov 2023 06:37:48 GMT

2023-11-08 14:37:48.523718 IP (tos 0x0, ttl 64, id 47135, offset 0, flags [DF], proto TCP (6), length 40)
    10.178.75.56.44054 > 10.98.21.3.http: Flags [.], cksum 0x7569 (incorrect -> 0x9f7e), seq 1028, ack 371, win 597, length 0
    
  • port : 指定抓取某个X端口的网络数据包。

  • and or not逻辑运算符
    tcpdump -i eth0 “host redhat.com and (port 80 or port 443)”

  • tcp/udp: 过滤tcp/udp流量: tcpdump -i eth0 host janus.t.17usoft.com and tcp


2.3 tcpdump [Flags]