Update tshark DNS resolution due to deprecated asynchronous flag 'C'
[anna.git] / example / diameter / pcapDecoder / tsharkDecoder.sh
1 #!/bin/bash
2
3 # ANNA - Anna is Not Nothingness Anymore
4 #
5 # (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
6 #
7 # http://redmine.teslayout.com/projects/anna-suite
8 #
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions
11 # are met:
12 #
13 #     * Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 #     * Redistributions in binary form must reproduce the above
16 # copyright notice, this list of conditions and the following disclaimer
17 # in the documentation and/or other materials provided with the
18 # distribution.
19 #     *  Neither the name of the copyright holder nor the names of its
20 # contributors may be used to endorse or promote products derived from
21 # this software without specific prior written permission.
22 #
23 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 #
35 # Authors: eduardo.ramos.testillano@gmail.com
36 #          cisco.tierra@gmail.com
37
38
39 # Decoder version using tshark tool
40 #
41 # RESTRICTIONS: TCP & SCTP datagrams. Allow split diameter messages between frames, but not, several messages into single datagram.
42 #               If sniffing fails, try to create the <frame>.hex and <frame>.metadata files manually (try 'tshark -nr input.pcap -Vx' and so on ...)
43
44 #############
45 # VARIABLES #
46 #############
47 tmpdir=$(mktemp -d)
48 TSHARK=tshark
49
50 #############
51 # FUNCTIONS #
52 #############
53
54 usage() {
55   echo
56   echo "Usage: $0 [-h|--help] [-o|--other-ports <list>] [-d|--results-dir <dir>] [-s|--sids <file>] <pcap>"
57   echo
58   echo "       -h|--help:                this usage help."
59   echo "       -o|--other-ports <list>:  space-separated list of ports which frames"
60   echo "                                 will be decoded as diameter protocol although"
61   echo "                                 not being standard. For example, we could use"
62   echo "                                 \"13868\" to disect the Ericsson Sy variant."
63   echo "       -d|--results-dir <dir>:   directory where results are stored."
64   echo "                                 By default, pcap dirname."
65   echo "       -s|--sids <file>:         file containing a list of Session-Id values"
66   echo "                                 (one per line) to be taken into account."
67   echo "                                 If missing, all the frames will be extracted."
68   echo
69   echo "       pcap:                     pcap formatted file to be processed."
70   echo
71   echo "       The utility, dumps the extracted hexadecimal content and useful information"
72   echo "       (timestamps, source, destination, etc.) within a metadata file:"
73   echo
74   echo "          <results directory>/<frame sequence>.hex"
75   echo "          <results directory>/<frame sequence>.metadata"
76   echo
77   _exit
78 }
79
80 parse_arguments() {
81   OTHER_PORTS=
82   RESULTS_DIR=
83   SIDS_FILE=
84   PCAP_FILE=
85
86   while [ $# -gt 0 ]; do
87     case $1 in
88       -h|--help)
89         usage
90       ;;
91
92       -o|--other-ports)
93         OTHER_PORTS="$2"
94         [ -z "$OTHER_PORTS" ] && _exit "Missing non-standard ports list"
95         shift
96       ;;
97
98       -d|--results-dir)
99         RESULTS_DIR=$2
100         shift
101       ;;
102
103       -s|--sids)
104         SIDS_FILE=$2
105         shift
106       ;;
107
108       *)
109         first=$(echo $1 | cut -c1)
110         [ "$first" = "-" ] && _exit "Unsupported script option: $1. Type '$SCR_BN -h' (or --help) to print the available options."
111         PCAP_FILE=$1
112       ;;
113     esac
114     shift
115   done
116
117   [ -z "$PCAP_FILE" ] && _exit "Missing pcap file"
118   [ ! -f "$PCAP_FILE" ] && _exit "Cannot found provided pcap file '$PCAP_FILE' !!"
119   [ -z "$RESULTS_DIR" ] && RESULTS_DIR=`dirname $PCAP_FILE`
120   [ ! -d $RESULTS_DIR ] && _exit "The results directory '$RESULTS_DIR' must exists !!"
121   if [ -n "$SIDS_FILE" ]
122   then
123     [ ! -f $SIDS_FILE ] && _exit "The Session-Id list file '$SIDS_FILE' provided, does not exist !!"
124   fi
125 }
126
127 _exit () {
128   echo
129   echo -e $1
130   echo
131
132   # Cleanup
133   rm -rf $tmpdir
134
135   rc=1
136   [ -n "$2" ] && rc=$2
137   exit $rc
138 }
139
140
141 #############
142 # EXECUTION #
143 #############
144
145 echo
146 echo "============================================"
147 echo "Diameter buffer extractor from PCAP raw file"
148 echo "============================================"
149 echo
150
151 # Arguments:
152 [ "$1" = "" -o "$1" = "--help" -o "$1" = "-h" ] && usage
153 parse_arguments "$@"
154
155 # Tshark available:
156 which $TSHARK >/dev/null 2>/dev/null
157 [ $? -ne 0 ] && _exit "Missing 'tshark' tool !!"
158
159 # Get the frames with diameter content (take care about '-2' two-pass option and don't add it, because we need to get reassembled parts in their corresponding frames):
160 # Fields needed (we won't need diameter.hopbyhopid & diameter.endtoendid to verify diameter message as hint patterns; length management will be enough): see https://www.wireshark.org/docs/dfref/d/diameter.html
161 FIELDS="-e frame.number -e frame.time_epoch -e ip.src_host -e ip.dst_host -e diameter.cmd.code -e diameter.flags.request -e diameter.applicationId -e diameter.hopbyhopid -e diameter.endtoendid -e diameter.Session-Id -e diameter.Origin-Host -e diameter.Subscription-Id-Data -e diameter.Subscription-Id-Type -e frame.len -e tcp.len -e diameter.length -e frame.protocols -e tcp.segment -e sctp.chunk_length"
162 # Disect selectors for non-standard diameter ports:
163 for port in $OTHER_PORTS
164 do
165   echo "Taking tcp port $port to be decoded as diameter protocol"
166   DISECT_SELECTORS="$DISECT_SELECTORS -d tcp.port=$port,diameter"
167 done
168
169 # Changes in project wireshark (see commits e005bc819c2 and 8dfaa8fa7c9): https://github.com/wireshark/wireshark.git
170 # Change name resolution resolving flags: 'C' is deprecated. Change '-N mntC' by '-N mntdv':
171 $TSHARK -E separator="|" -r $PCAP_FILE -N mntdv -Tfields $FIELDS $DISECT_SELECTORS 2>/dev/null > $tmpdir/all_frames
172 grep -i diameter $tmpdir/all_frames > $tmpdir/diameter_frames
173 #cat $tmpdir/all_frames
174
175 # Example output:
176 #                                                                                         / lengths \
177 # frm timestamp src   dst   code R  App-ID   HopByHop   EndToEnd  Sid OHost Subs SubsType FRM TCP DIA   protocol                              segments    sctp chunk length
178 #   1   2      3       4      5  6    7          8          9     10   11    12     13    14   15  16      17                                    18             19
179 #   1|tt.tt|gt_traf|vcbavipt|272|1|16777238|0x0004e6e6|0x000bd986|xxx|xxxxx|xxxxx|xxxxxxx|fff|432|432|eth:ip:tcp:diameter:diameter:diameter3gpp|
180 #   3|tt.tt|vcbavipt|gt_traf|272|0|16777238|0x0004e6e6|0x000bd986|xxx|xxxxx|xxxxx|xxxxxxx|fff|292|292|eth:ip:tcp:diameter:diameter:diameter3gpp|
181 #   5|tt.tt|gt_traf|vcbavipt||||||ffff|1400||eth:ip:tcp:diameter|
182 #   6|tt.tt|gt_traf|vcbavipt|265|1|16777236|0x000c73c3|0x0004cee4|xxx|xxxxx|xxxxx|xxxxxxx|fff|572|1972|eth:ip:tcp:diameter:diameter:diameter3gpp|5,6
183 #   8|tt.tt|vcbavipt|gt_traf|265|0|16777236|0x000c73c3|0x0004cee4|xxx|xxxxx|xxxxx|xxxxxxx|fff|248|248|eth:ip:tcp:diameter:diameter:diameter3gpp|
184 cat $tmpdir/diameter_frames | cut -d\| -f1 > $tmpdir/frames_num
185 all_frames=( $(cat $tmpdir/frames_num) )
186
187 # Segments groups (TCP or SCTP):
188 segmentsGroups=
189
190 # The case of SCTP is precalculated:
191 tshark -nr $PCAP_FILE $DISECT_SELECTORS -Tfields -e frame.number -e sctp.chunk_flags 2>/dev/null | awk '{ if ( $2 !~ "0x03" && $2 != "" ) print $1 }' > $tmpdir/extra_frames_num
192 if [ -s $tmpdir/extra_frames_num ]
193 then
194   # Take into account these frames in all_frames array:
195
196   cat $tmpdir/extra_frames_num >> $tmpdir/frames_num
197   all_frames=( $(cat $tmpdir/frames_num | sort -un) )
198
199   # Prepare as groups (1,2 7,8 ...)
200   segmentsGroups=$(tshark -nr $PCAP_FILE $DISECT_SELECTORS -Tfields -e frame.number -e sctp.chunk_flags 2>/dev/null | awk '{ if ( $2 !~ "0x03" && $2 != "" ) print $1; else print "\n" }' | uniq | tr '\n' ',' | sed 's/,,/ /g')
201 fi
202
203
204 # Reassemble procedure (using frame 1 as example):
205 # (for non segmented frames, it is enough with tcp or diameter length within the frame content itself)
206 # 1) Get the TCP length: 432 bytes. 432*2 = 864 characters per byte in hexadecimal string format
207 # 2) Get the frame length: `wc -c $tmpdir/block.$frame` => 997
208 # 3) Get 864 from the tail: `cat $tmpdir/block.$frame | cut -c133
209
210 # Dump the hex blocks for all the diameter frames:
211 cat $PCAP_FILE | rawshark -s -r - -d proto:diameter -F data 2>/dev/null > $tmpdir/all_hex_data
212 for frame in ${all_frames[@]}; do
213   grep "^$frame " $tmpdir/all_hex_data | cut -d\" -f2 | sed 's/://g' > $tmpdir/block.$frame
214   frame_info=$(grep "^${frame}|" $tmpdir/diameter_frames)
215
216   ##########################################################################################
217   # Get the diameter part:
218   frm_len=$(echo $frame_info | cut -d\| -f14)
219   tcp_len=$(echo $frame_info | cut -d\| -f15)
220   dia_len=$(echo $frame_info | cut -d\| -f16)
221   protocol=$(echo $frame_info | cut -d\| -f17)
222
223   # TCP and SCTP supported:
224   transport=$(echo $protocol | grep -ow tcp)
225   [ -z "$transport" ] && transport=$(echo $protocol | grep -ow sctp)
226   # in case of segmented SCTP frames, protocol won't be sctp ...:
227   if [ -s "$tmpdir/extra_frames_num" -a -z "$transport" ]
228   then
229     grep -qw ^${frame} $tmpdir/extra_frames_num
230     if [ $? -eq 0 ]
231     then
232       transport=sctp
233       frame_info=$(grep "^${frame}|" $tmpdir/all_frames)
234     fi
235   fi
236
237   case $transport in
238     sctp)
239       chunk_length=$(echo $frame_info | cut -d\| -f19)
240       dia_partial_len=$((chunk_length-16))
241       if [ "$dia_len" != "$dia_partial_len" ]
242       then
243         #echo "Segmented SCTP frame $frame; taking partial diameter length = $dia_partial_len"
244         dia_len=$dia_partial_len
245       fi 
246       cut_len=$((2*dia_len))
247       cat $tmpdir/block.$frame | rev | cut -c-${cut_len} | rev > $RESULTS_DIR/$frame.hex
248       ;;
249
250     tcp)
251       cut_len=$((2*(frm_len-tcp_len) + 1))
252       cat $tmpdir/block.$frame | cut -c${cut_len}- > $RESULTS_DIR/$frame.hex
253       cp $tmpdir/block.$frame /tmp/block
254       segments=$(echo $frame_info | cut -d\| -f18)
255       segmentsGroups="$segmentsGroups $segments"
256       ;;
257
258     *) _exit "Only TCP and SCTP transports supported !!"
259       ;;
260   esac
261   ##########################################################################################
262
263   echo -n "Created $RESULTS_DIR/$frame.hex"
264
265   # Metadata:
266   ts=$(echo $frame_info | cut -d\| -f2)
267   date=$(date -d @$ts)
268   src=$(echo $frame_info | cut -d\| -f3)
269   dst=$(echo $frame_info | cut -d\| -f4)
270   code=$(echo $frame_info | cut -d\| -f5)
271   isreq=$(echo $frame_info | cut -d\| -f6)
272   appid=$(echo $frame_info | cut -d\| -f7)
273   sid=$(echo $frame_info | cut -d\| -f10)
274   oh=$(echo $frame_info | cut -d\| -f11)
275   subscriber=$(echo $frame_info | cut -d\| -f12)
276   subscribertype=$(echo $frame_info | cut -d\| -f13)
277   [ "$subscribertype" = "0" ] && subscribertype=msisdn
278   [ "$subscribertype" = "1" ] && subscribertype=imsi
279
280
281   #hbh=$(echo $frame_info | cut -d\| -f8)
282   #e2e=$(echo $frame_info | cut -d\| -f9)
283   # HBH and ETE To decimal:
284   #hbh=$(printf "%d\n" $hbh)
285   #e2e=$(printf "%d\n" $e2e)
286   echo "date=$date" > $RESULTS_DIR/$frame.metadata
287   echo "timestamp=$ts" >> $RESULTS_DIR/$frame.metadata
288   echo "src=$src" >> $RESULTS_DIR/$frame.metadata
289   echo "dst=$dst" >> $RESULTS_DIR/$frame.metadata
290   echo "code=$code" >> $RESULTS_DIR/$frame.metadata
291   echo "isrequest=$isreq" >> $RESULTS_DIR/$frame.metadata
292   echo "applicationid=$appid" >> $RESULTS_DIR/$frame.metadata
293   [ -n "$sid" ] && echo "sessionid=$sid" >> $RESULTS_DIR/$frame.metadata
294   echo "originhost=$oh" >> $RESULTS_DIR/$frame.metadata
295   if [ -n "$subscriber" ]
296   then
297     echo "subscriber=$subscriber" >> $RESULTS_DIR/$frame.metadata
298     echo "subscribertype=$subscribertype" >> $RESULTS_DIR/$frame.metadata
299   fi
300   #echo "hopbyhop=$hbh" >> $RESULTS_DIR/$frame.metadata
301   #echo "endtoend=$e2e" >> $RESULTS_DIR/$frame.metadata
302
303   echo " and $RESULTS_DIR/$frame.metadata"
304 done
305
306 # Join frames which need to be reassembled:
307 to_delete=
308 for group in $segmentsGroups
309 do
310   group_array=( $(echo $group | sed 's/,/ /g') )
311   echo "Grouping frames ${group_array[*]} ..."
312   for frame in ${group_array[@]}; do
313     cat $RESULTS_DIR/$frame.hex >> $tmpdir/diam.$group 2>/dev/null
314   done
315   cat $tmpdir/diam.$group | tr -d '\n' > $RESULTS_DIR/$frame.hex
316   # Delete all frames except last one in the group:
317   to_delete="$to_delete  $(echo ${group_array[*]} | awk '{$NF=""; print $0}')"
318 done
319
320 # Delete superfluous metadata:
321 #segments=( $(cat $tmpdir/diameter_frames | awk -F\| '{ if ($16 == "") print $1 }') )
322 segments=( $(echo $to_delete) )
323 echo "Deleting superfluous buffers & metadata (${segments[*]}) ..."
324 for s in ${segments[@]}; do rm -f $RESULTS_DIR/${s}.* ; done
325
326 # Basic checking:
327 ls $RESULTS_DIR/*.metadata >/dev/null 2>/dev/null
328 [ $? -ne 0 ] && { echo "No metadata generated !" ; exit 1 ; }
329
330 # Detecting Session-Id values:
331 grep ^sessionid= $RESULTS_DIR/*.metadata 2>/dev/null | cut -d= -f2- | sort -u > $RESULTS_DIR/session-ids
332 if [ -s $RESULTS_DIR/session-ids ]
333 then
334   count=0
335   while read -r line; do count=$((count+1)) ; echo "Detected Session-Id $count:  $line"; done < $RESULTS_DIR/session-ids
336   rm $RESULTS_DIR/session-ids
337 fi
338
339 # Detecting Origin-Host values:
340 grep ^originhost= $RESULTS_DIR/*.metadata 2>/dev/null | cut -d= -f2- | sort -u > $RESULTS_DIR/origin-hosts
341 if [ -s $RESULTS_DIR/origin-hosts ]
342 then
343   count=0
344   while read -r line; do count=$((count+1)) ; echo "Detected Origin-Host $count: $line"; done < $RESULTS_DIR/origin-hosts
345   #rm $RESULTS_DIR/origin-hosts
346 fi
347
348 # Purge frames with Session-Id not wanted:
349 if [ -n "$SIDS_FILE" ]
350 then
351   grep -l -w -f $SIDS_FILE $RESULTS_DIR/*metadata > $RESULTS_DIR/.wanted
352   grep -l ^sessionid $RESULTS_DIR/*metadata > $RESULTS_DIR/.all
353   for file in `grep -vf $RESULTS_DIR/.wanted $RESULTS_DIR/.all`
354   do
355     frm=$(basename $file | cut -d\. -f1)
356     sid=$(grep ^sessionid= $file | cut -d= -f2-)
357     echo "Purge results for frame $frm (Session-Id: '$sid') ..."
358     rm $RESULTS_DIR/${frm}.*
359   done
360   rm $RESULTS_DIR/.wanted $RESULTS_DIR/.all
361 fi
362
363 # Purge frames with invalid metadata:
364 invalid=( $(grep -lw "^code=$" $RESULTS_DIR/*metadata) )
365 for file in ${invalid[@]}
366 do
367   frm=$(basename $file | cut -d\. -f1)
368   rm $RESULTS_DIR/${frm}.*
369 done
370
371 _exit "Done!" 0
372