1. 程式人生 > >使用tshark在centos6.8系統下進行網路抓包及分析

使用tshark在centos6.8系統下進行網路抓包及分析

使用wireshark的客戶端進行抓包,或者tcpdump抓包再用wireshark分析,網上已經有很多資料了,這裡就不再贅述了。不熟悉的可以看看網上的資料: http://www.jianshu.com/p/a62ed1bb5b20 或者官方文件user guide: https://www.wireshark.org/docs/wsug_html_chunked/

線上問題排查,有時候時間爭分奪秒,或者一些私有云環境完全隔離,根本沒法讓你匯出抓包的檔案,這時候需要直接使用命令列進行抓包分析。今天我們就來學習下tshark的使用。PS: tshark基本上可以替代tcpdump,抓包的檔案也可以直接用於wireshark來分析

主要先通過yum install wireshark安裝後才能使用tshark

1. tshark 選項說明一覽

這麼多引數肯定懶得看,我們繼續下一節,掌握最常用的一些引數的用法。

TShark (Wireshark) 2.5.0 (v2.5.0rc0-1500-g78f9a07f)
Dump and analyze network traffic.
See https://www.wireshark.org for more information.

Usage: tshark [options] ...

Capture interface:
  -i <interface>           name or idx of interface (def: first non-loopback)
  -f <capture filter>      packet filter in libpcap filter syntax
  -s <snaplen>             packet snapshot length (def: appropriate maximum)
  -p                       don't capture in promiscuous mode
  -I                       capture in monitor mode, if available
  -B <buffer size>         size of kernel buffer (def: 2MB)
  -y <link type>           link layer type (def: first appropriate)
  --time-stamp-type <type> timestamp method for interface
  -D                       print list of interfaces and exit
  -L                       print list of link-layer types of iface and exit
  --list-time-stamp-types  print list of timestamp types for iface and exit

Capture stop conditions:
  -c <packet count>        stop after n packets (def: infinite)
  -a <autostop cond.> ...  duration:NUM - stop after NUM seconds
                           filesize:NUM - stop this file after NUM KB
                              files:NUM - stop after NUM files
Capture output:
  -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs
                           interval:NUM - create time intervals of NUM secs
                           filesize:NUM - switch to next file after NUM KB
                              files:NUM - ringbuffer: replace after NUM files
Input file:
  -r <infile>              set the filename to read from (- to read from stdin)

Processing:
  -2                       perform a two-pass analysis
  -M <packet count>        perform session auto reset
  -R <read filter>         packet Read filter in Wireshark display filter syntax
                           (requires -2)
  -Y <display filter>      packet displaY filter in Wireshark display filter
                           syntax
  -n                       disable all name resolutions (def: all enabled)
  -N <name resolve flags>  enable specific name resolution(s): "mnNtCd"
  -d <layer_type>==<selector>,<decode_as_protocol> ...
                           "Decode As", see the man page for details
                           Example: tcp.port==8888,http
  -H <hosts file>          read a list of entries from a hosts file, which will
                           then be written to a capture file. (Implies -W n)
  --enable-protocol <proto_name>
                           enable dissection of proto_name
  --disable-protocol <proto_name>
                           disable dissection of proto_name
  --enable-heuristic <short_name>
                           enable dissection of heuristic protocol
  --disable-heuristic <short_name>
                           disable dissection of heuristic protocol
Output:
  -w <outfile|->           write packets to a pcap-format file named "outfile"
                           (or to the standard output for "-")
  -C <config profile>      start with specified configuration profile
  -F <output file type>    set the output file type, default is pcapng
                           an empty "-F" option will list the file types
  -V                       add output of packet tree        (Packet Details)
  -O <protocols>           Only show packet details of these protocols, comma
                           separated
  -P                       print packet summary even when writing to a file
  -S <separator>           the line separator to print between packets
  -x                       add output of hex and ASCII dump (Packet Bytes)
  -T pdml|ps|psml|json|jsonraw|ek|tabs|text|fields|?
                           format of text output (def: text)
  -j <protocolfilter>      protocols layers filter if -T ek|pdml|json selected
                           (e.g. "ip ip.flags text", filter does not expand child
                           nodes, unless child is specified also in the filter)
  -J <protocolfilter>      top level protocol filter if -T ek|pdml|json selected
                           (e.g. "http tcp", filter which expands all child nodes)
  -e <field>               field to print if -Tfields selected (e.g. tcp.port,
                           _ws.col.Info)
                           this option can be repeated to print multiple fields
  -E<fieldsoption>=<value> set options for output when -Tfields selected:
     bom=y|n               print a UTF-8 BOM
     header=y|n            switch headers on and off
     separator=/t|/s|<char> select tab, space, printable character as separator
     occurrence=f|l|a      print first, last or all occurrences of each field
     aggregator=,|/s|<char> select comma, space, printable character as
                           aggregator
     quote=d|s|n           select double, single, no quotes for values
  -t a|ad|d|dd|e|r|u|ud|?  output format of time stamps (def: r: rel. to first)
  -u s|hms                 output format of seconds (def: s: seconds)
  -l                       flush standard output after each packet
  -q                       be more quiet on stdout (e.g. when using statistics)
  -Q                       only log true errors to stderr (quieter than -q)
  -g                       enable group read access on the output file(s)
  -W n                     Save extra information in the file, if supported.
                           n = write network address resolution information
  -X <key>:<value>         eXtension options, see the man page for details
  -U tap_name              PDUs export mode, see the man page for details
  -z <statistics>          various statistics, see the man page for details
  --capture-comment <comment>
                           add a capture comment to the newly created
                           output file (only for pcapng)
  --export-objects <protocol>,<destdir> save exported objects for a protocol to
                           a directory named "destdir"
  --color                  color output text similarly to the Wireshark GUI,
                           requires a terminal with 24-bit color support
                           Also supplies color attributes to pdml and psml formats
                           (Note that attributes are nonstandard)
  --no-duplicate-keys      If -T json is specified, merge duplicate keys in an object
                           into a single key with as value a json array containing all
                           values
Miscellaneous:
  -h                       display this help and exit
  -v                       display version info and exit
  -o <name>:<value> ...    override preference setting
  -K <keytab>              keytab file to use for kerberos decryption
  -G [report]              dump one of several available reports and exit
                           default report="fields"
                           use "-G help" for more help

WARNING: dumpcap will enable kernel BPF JIT compiler if available.
You might want to reset it
By doing "echo 0 > /proc/sys/net/core/bpf_jit_enable"

2. tshark常用指令

我們通過一步步的增加命令的複雜度,使用更多的過濾條件從而來學習tshark。

2.1 不使用任何選項

直接使用tshark,會抓取第一個非迴環網絡卡的所有網路包,本機時候用效果如下

可以看到包含源和目標的地址和埠資訊,還有協議和標誌位等資訊,和wireshark客戶端上看到的效果是一樣的

2.2 使用-i引數指定需要抓包的裝置

PS: 這裡可以用tshark -D檢視有哪些裝置,當然也可以通過ifconfig來檢視

tshark -i的

tshark -i en0

2.4 網路包過濾

抓包的時候根據協議和埠來過濾是比較常見的用法,比如要抓取HTTP的網路包,或者抓取TCP的網路包等等。

2.4.1 capature filter(-f引數)

capature filter實際使用的引數為-f,也是預設的過濾器,所以一般不帶這個引數也是可以的。

tshark支援不帶引數就可以使用的過濾表示式,和tcpdump的用法很接近,詳情參考: https://www.wireshark.org/docs/wsug_html_chunked/ChCapCaptureFilterSection.html

使用格式為:

[not] primitive [and|or [not] primitive ...]

幾種原語(primitive)

上面文件中4.2節羅列了可以使用的原語,為了方便學習,下面表格總結了最常見的幾種原語,多個原語之間可以採用邏輯表示式and、or和not。PS:注意不能使用|| &&等符號

原語 說明 例子
[src dst] host 根據源端和目標端的IP進行過濾
[tcp udp] [src dst] port

原語之間可以通過邏輯運算子結合起來使用:

首先採用一條原語抓包獲取發往其他主機80埠的TCP網路包:

tshark tcp dst port 80

在上面原語的基礎上增加目標端host ip的過濾條件

tshark tcp dst port 80 and dst host 60.190.116.48

PS: ip|ether proto 這個原語也挺有意思,你可以用命令tshark -G protocols檢視支援哪些協議,這裡有這些協議的縮寫和全稱

2.4.3 display filter(-Y引數)

這個選項應該是這個命令中比較複雜的一個選項了,通過指定表示式可以支援非常複雜的過濾條件。-f的過濾表示式應該是2.4.2節功能的超集。表示式支援更加細粒度的過濾,例如http.request.url或者mysql.query等等。可以按照packet型別過濾,也可以按照一些等值條件進行過濾。這些針對特定應用層協議(HTTP協議、MYSQL協議)的過濾欄位需要參考官方文件。

協議與過濾欄位

所有支援協議的表示式

https://www.wireshark.org/docs/dfref/

比較常用的是HTTP和MYSQL,可以參考如下官方文件:

  1. mysql協議: https://www.wireshark.org/docs/dfref/m/mysql.html
  2. HTTP協議: https://www.wireshark.org/docs/dfref/h/http.html

因為最常用的過濾可以用不帶引數的方式過濾,關於這種帶引數的過濾方法,有興趣的話可以參考文件: https://www.wireshark.org/docs/man-pages/wireshark-filter.html

準備知識

文件裡面幾個會用到的關係符,我這裡先羅列下,建議直接使用第二列的數學符號,比較直觀也好記

比較表示式

eq, ==    Equal
    ne, !=    Not Equal
    gt, >     Greater Than
    lt, <     Less Than
    ge, >=    Greater than or Equal to
    le, <=    Less than or Equal to

邏輯表示式

and, &&   Logical AND
or,  ||   Logical OR
not, !    Logical NOT

配合兩種過濾器使用的-T引數

-Y引數必須配合-T引數使用才能成功打印出過濾後的結果,-T引數支援多種不同的輸出格式,比如json、fields等等,最常用的是fileds,我們這裡也只介紹和演示這種格式。fields的輸出格式需要通過-e來指定需要列印的filed value,具體使用方法可以參考後面的使用案例。-T引數可以配合-f 或者-Y兩種型別的過濾器。

PS:-T引數指定field列印存在一些侷限性,就是列印之後能只能在標準輸出檢視,或者將輸出記錄到檔案,沒法通過指定-w寫入cap型別檔案供wireshark來分析。

使用案例1: 獲取HTTP請求的型別、URL、HOST等資訊

這裡同時使用了兩種過濾器

使用案例2: 獲取SQL語句

我這裡用的field是mysq.query和,配個的過濾器是表示式過濾器

實際經過測試發現,基本上也就mysql.query、mysql.login_request這兩個field比較有用,大部分MYSQL協議的packet都是這兩種型別的。

3. 其他有用的引數

3.1 -c引數指定停止條件

抓包不指定停止條件會一直抓,tshark提供了幾種停止的條件,常用的就是用-c來指定需要抓幾個包,使用效果可以參考3.2節

3.2 -V引數檢視packet詳情

-V引數可以將packet展看檢視詳情,效果如下:

PS:-V引數無法和-T一起使用,-T指定的filed之後只會輸出field的資訊了

3.3 -w寫出到檔案

-w選項後可以接路徑和檔名,儲存到檔案,預設按照cap格式儲存。另外指定-T引數之後無法再使用-w,請注意。

3.4 -r 引數讀取cap檔案分析(重要)

一般情況下,針對一次抓包之後,我們很有可能進行多個維度的分析,所以先存到檔案,再進行分析,是很常見的使用方法。下面通過一個實際案例來學習下這種抓包分析分發。

PS: -Y指定的表示式過濾不能配合寫檔案使用,要在寫檔案前進行過濾,可以使用-f的capture filter

實際案例

需求

小明同學在排查問題的時候,突然有個需求,就是需要知道當前網路包抓取的SQL來源於哪個源端,並且需要知道SQL的內容。

分析

通過mysql.query可以來獲取SQL內容,但是無法直接依靠-T引數輸出指定field來滿足該需求。因為-T指定輸出格式後,無法知道SQL來自於哪個源端。

思考後可行的方案為: 直接先用-f過濾,先過濾出指定型別和port上的packet,存入到檔案,然後利用-V展開後再來分析。這種方式既可以按照條件過濾網路包,然後又可以採用tshark來分析,知道packet的源端資訊。

操作

  1. 按照表達式過濾指定型別的packet
tshark -c 50 -f 'tcp dst port 3306 and dst host 10.195.33.7 ' -w mysql_test.cap
  1. 驗證過濾結果

  1. 讀取cap檔案,並且展開包。需要的資訊為源端和目標端的IP以及SQL內容。根據packet的格式,進行grep來獲取需要的資訊。
tshark -r mysql_test.cap -V | egrep 'Internet|Statement'

4. 總結

通過一步步由簡單到複雜,並且學習了最常用的選項之後,相信大家已經基本掌握了tshark的用法。

針對簡單的、單一維度查詢的抓包需求,可以直接通過-f 和-Y來進行過濾,按照-T進行輸出。

針對需要多維度查詢、檢視packet詳情的,可以直接通過-w匯出抓包結果,再使用-r結合grep來檢視分析。

5. 練習題

自行準備測試環境,包含主機A和主機B,其中主機B上有DB可以進行SQL操作。在主機A上啟動tshark進行抓包,將滿足以下過濾條件的抓包結果全部寫入檔案tshark_x_y.pcap,其中x為下面習題的編號,如果一個習題下需要產生多個dump檔案,可以用y進行編號,否則直接寫成tshark_x.pcap即可。

  1. 用tshark檢視自己有哪些介面,然後分別獲取Loopback和WIFI網絡卡上的網路包,檢視區別
  2. 用tshark捕獲本地的tcp網路包,持續捕獲30秒
  3. 捕獲本地3306埠上的網路包,捕獲100條
  4. 獲取本地發往百度的HTTP流量包,並且檢視cookies和METHOD資訊
  5. 獲取包含特定關鍵字“XXX”的SQL,獲取其傳送端和目標端的IP和埠資訊,以及其SQL內容,以及源端傳送的時間
  6. 指定源端的IP和協議、目標端的IP和協議,獲取MYSQL登入的userName資訊和網路包的傳送時間,要求同時使用capture filter和expression filter,並且嘗試使用-T引數在標準輸出列印userName資訊
  7. 隨便嘗試建立一個TCP連線,捕獲網路包,通過dump的pcap檔案分析三次握手和四次握手時seq、ack的變化