93b29d42e1b160f2a7276628d277edec9685a72b
[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: only TCP datagrams. Allow split diameter messages between frames, but not, several messages into single datagram.
42
43 #############
44 # VARIABLES #
45 #############
46 tmpdir=$(mktemp -d)
47 TSHARK=tshark
48
49 #############
50 # FUNCTIONS #
51 #############
52
53 usage() {
54   echo
55   echo "Usage: $0 [-h|--help] [-o|--other-ports <list>] [-d|--results-dir <dir>] [-s|--sids <file>] <pcap>"
56   echo
57   echo "       -h|--help:                this usage help."
58   echo "       -o|--other-ports <list>:  space-separated list of ports which frames"
59   echo "                                 will be decoded as diameter protocol although"
60   echo "                                 not being standard. For example, we could use"
61   echo "                                 \"13868\" to disect the Ericsson Sy variant."
62   echo "       -d|--results-dir <dir>:   directory where results are stored."
63   echo "                                 By default, pcap dirname."
64   echo "       -s|--sids <file>:         file containing a list of Session-Id values"
65   echo "                                 (one per line) to be taken into account."
66   echo "                                 If missing, all the frames will be extracted."
67   echo
68   echo "       pcap:                     pcap formatted file to be processed."
69   echo
70   echo "       The utility, dumps the extracted hexadecimal content and useful information"
71   echo "       (timestamps, source, destination, etc.) within a metadata file:"
72   echo
73   echo "          <results directory>/<frame sequence>.hex"
74   echo "          <results directory>/<frame sequence>.metadata"
75   echo
76   _exit
77 }
78
79 parse_arguments() {
80   OTHER_PORTS=
81   RESULTS_DIR=
82   SIDS_FILE=
83   PCAP_FILE=
84
85   while [ $# -gt 0 ]; do
86     case $1 in
87       -h|--help)
88         usage
89       ;;
90
91       -o|--other-ports)
92         OTHER_PORTS="$2"
93         [ -z "$OTHER_PORTS" ] && _exit "Missing non-standard ports list"
94         shift
95       ;;
96
97       -d|--results-dir)
98         RESULTS_DIR=$2
99         shift
100       ;;
101
102       -s|--sids)
103         SIDS_FILE=$2
104         shift
105       ;;
106
107       *)
108         first=$(echo $1 | cut -c1)
109         [ "$first" = "-" ] && _exit "Unsupported script option: $1. Type '$SCR_BN -h' (or --help) to print the available options."
110         PCAP_FILE=$1
111       ;;
112     esac
113     shift
114   done
115
116   [ -z "$PCAP_FILE" ] && _exit "Missing pcap file"
117   [ ! -f "$PCAP_FILE" ] && _exit "Cannot found provided pcap file '$PCAP_FILE' !!"
118   [ -z "$RESULTS_DIR" ] && RESULTS_DIR=`dirname $PCAP_FILE`
119   [ ! -d $RESULTS_DIR ] && _exit "The results directory '$RESULTS_DIR' must exists !!"
120   if [ -n "$SIDS_FILE" ]
121   then
122     [ ! -f $SIDS_FILE ] && _exit "The Session-Id list file '$SIDS_FILE' provided, does not exist !!"
123   fi
124 }
125
126 _exit () {
127   echo
128   echo -e $1
129   echo
130
131   # Cleanup
132   rm -rf $tmpdir
133
134   rc=1
135   [ -n "$2" ] && rc=$2
136   exit $rc
137 }
138
139
140 #############
141 # EXECUTION #
142 #############
143
144 echo
145 echo "============================================"
146 echo "Diameter buffer extractor from PCAP raw file"
147 echo "============================================"
148 echo
149
150 # Arguments:
151 [ "$1" = "" -o "$1" = "--help" -o "$1" = "-h" ] && usage
152 parse_arguments "$@"
153
154 # Tshark available:
155 which $TSHARK >/dev/null 2>/dev/null
156 [ $? -ne 0 ] && _exit "Missing 'tshark' tool !!"
157
158 # 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):
159 # 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
160 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"
161 # Disect selectors for non-standard diameter ports:
162 for port in $OTHER_PORTS
163 do
164   echo "Taking tcp port $port to be decoded as diameter protocol"
165   DISECT_SELECTORS="$DISECT_SELECTORS -d tcp.port=$port,diameter"
166 done
167
168 $TSHARK -E separator="|" -r $PCAP_FILE -N mntC -Tfields $FIELDS $DISECT_SELECTORS 2>/dev/null > $tmpdir/all_frames
169 grep -i diameter $tmpdir/all_frames > $tmpdir/diameter_frames
170 #cat $tmpdir/all_frames
171
172 # Example output:
173 #                                                                                         / lengths \
174 # frm timestamp src   dst   code R  App-ID   HopByHop   EndToEnd  Sid OHost Subs SubsType FRM TCP DIA   protocol                              segments    sctp chunk length
175 #   1   2      3       4      5  6    7          8          9     10   11    12     13    14   15  16      17                                    18             19
176 #   1|tt.tt|gt_traf|vcbavipt|272|1|16777238|0x0004e6e6|0x000bd986|xxx|xxxxx|xxxxx|xxxxxxx|fff|432|432|eth:ip:tcp:diameter:diameter:diameter3gpp|
177 #   3|tt.tt|vcbavipt|gt_traf|272|0|16777238|0x0004e6e6|0x000bd986|xxx|xxxxx|xxxxx|xxxxxxx|fff|292|292|eth:ip:tcp:diameter:diameter:diameter3gpp|
178 #   5|tt.tt|gt_traf|vcbavipt||||||ffff|1400||eth:ip:tcp:diameter|
179 #   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
180 #   8|tt.tt|vcbavipt|gt_traf|265|0|16777236|0x000c73c3|0x0004cee4|xxx|xxxxx|xxxxx|xxxxxxx|fff|248|248|eth:ip:tcp:diameter:diameter:diameter3gpp|
181 cat $tmpdir/diameter_frames | cut -d\| -f1 > $tmpdir/frames_num
182 all_frames=( $(cat $tmpdir/frames_num) )
183
184 # Segments groups (TCP or SCTP):
185 segmentsGroups=
186
187 # The case of SCTP is precalculated:
188 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
189 if [ -s $tmpdir/extra_frames_num ]
190 then
191   # Take into account these frames in all_frames array:
192
193   cat $tmpdir/extra_frames_num >> $tmpdir/frames_num
194   all_frames=( $(cat $tmpdir/frames_num | sort -un) )
195
196   # Prepare as groups (1,2 7,8 ...)
197   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')
198 fi
199
200
201 # Reassemble procedure (using frame 1 as example):
202 # (for non segmented frames, it is enough with tcp or diameter length within the frame content itself)
203 # 1) Get the TCP length: 432 bytes. 432*2 = 864 characters per byte in hexadecimal string format
204 # 2) Get the frame length: `wc -c $tmpdir/block.$frame` => 997
205 # 3) Get 864 from the tail: `cat $tmpdir/block.$frame | cut -c133
206
207 # Dump the hex blocks for all the diameter frames:
208 cat $PCAP_FILE | rawshark -s -r - -d proto:diameter -F data 2>/dev/null > $tmpdir/all_hex_data
209 for frame in ${all_frames[@]}; do
210   grep "^$frame " $tmpdir/all_hex_data | cut -d\" -f2 | sed 's/://g' > $tmpdir/block.$frame
211   frame_info=$(grep "^${frame}|" $tmpdir/diameter_frames)
212
213   ##########################################################################################
214   # Get the diameter part:
215   frm_len=$(echo $frame_info | cut -d\| -f14)
216   tcp_len=$(echo $frame_info | cut -d\| -f15)
217   dia_len=$(echo $frame_info | cut -d\| -f16)
218   protocol=$(echo $frame_info | cut -d\| -f17)
219
220   # TCP and SCTP supported:
221   transport=$(echo $protocol | grep -ow tcp)
222   [ -z "$transport" ] && transport=$(echo $protocol | grep -ow sctp)
223   # in case of segmented SCTP frames, protocol won't be sctp ...:
224   if [ -s "$tmpdir/extra_frames_num" -a -z "$transport" ]
225   then
226     grep -qw ^${frame} $tmpdir/extra_frames_num
227     if [ $? -eq 0 ]
228     then
229       transport=sctp
230       frame_info=$(grep "^${frame}|" $tmpdir/all_frames)
231     fi
232   fi
233
234   case $transport in
235     sctp)
236       chunk_length=$(echo $frame_info | cut -d\| -f19)
237       dia_partial_len=$((chunk_length-16))
238       if [ "$dia_len" != "$dia_partial_len" ]
239       then
240         #echo "Segmented SCTP frame $frame; taking partial diameter length = $dia_partial_len"
241         dia_len=$dia_partial_len
242       fi 
243       cut_len=$((2*dia_len))
244       cat $tmpdir/block.$frame | rev | cut -c-${cut_len} | rev > $RESULTS_DIR/$frame.hex
245       ;;
246
247     tcp)
248       cut_len=$((2*(frm_len-tcp_len) + 1))
249       cat $tmpdir/block.$frame | cut -c${cut_len}- > $RESULTS_DIR/$frame.hex
250       cp $tmpdir/block.$frame /tmp/block
251       segments=$(echo $frame_info | cut -d\| -f18)
252       segmentsGroups="$segmentsGroups $segments"
253       ;;
254
255     *) _exit "Only TCP and SCTP transports supported !!"
256       ;;
257   esac
258   ##########################################################################################
259
260   echo -n "Created $RESULTS_DIR/$frame.hex"
261
262   # Metadata:
263   ts=$(echo $frame_info | cut -d\| -f2)
264   date=$(date -d @$ts)
265   src=$(echo $frame_info | cut -d\| -f3)
266   dst=$(echo $frame_info | cut -d\| -f4)
267   code=$(echo $frame_info | cut -d\| -f5)
268   isreq=$(echo $frame_info | cut -d\| -f6)
269   appid=$(echo $frame_info | cut -d\| -f7)
270   sid=$(echo $frame_info | cut -d\| -f10)
271   oh=$(echo $frame_info | cut -d\| -f11)
272   subscriber=$(echo $frame_info | cut -d\| -f12)
273   subscribertype=$(echo $frame_info | cut -d\| -f13)
274   [ "$subscribertype" = "0" ] && subscribertype=msisdn
275   [ "$subscribertype" = "1" ] && subscribertype=imsi
276
277
278   #hbh=$(echo $frame_info | cut -d\| -f8)
279   #e2e=$(echo $frame_info | cut -d\| -f9)
280   # HBH and ETE To decimal:
281   #hbh=$(printf "%d\n" $hbh)
282   #e2e=$(printf "%d\n" $e2e)
283   echo "date=$date" > $RESULTS_DIR/$frame.metadata
284   echo "timestamp=$ts" >> $RESULTS_DIR/$frame.metadata
285   echo "src=$src" >> $RESULTS_DIR/$frame.metadata
286   echo "dst=$dst" >> $RESULTS_DIR/$frame.metadata
287   echo "code=$code" >> $RESULTS_DIR/$frame.metadata
288   echo "isrequest=$isreq" >> $RESULTS_DIR/$frame.metadata
289   echo "applicationid=$appid" >> $RESULTS_DIR/$frame.metadata
290   [ -n "$sid" ] && echo "sessionid=$sid" >> $RESULTS_DIR/$frame.metadata
291   echo "originhost=$oh" >> $RESULTS_DIR/$frame.metadata
292   if [ -n "$subscriber" ]
293   then
294     echo "subscriber=$subscriber" >> $RESULTS_DIR/$frame.metadata
295     echo "subscribertype=$subscribertype" >> $RESULTS_DIR/$frame.metadata
296   fi
297   #echo "hopbyhop=$hbh" >> $RESULTS_DIR/$frame.metadata
298   #echo "endtoend=$e2e" >> $RESULTS_DIR/$frame.metadata
299
300   echo " and $RESULTS_DIR/$frame.metadata"
301 done
302
303 # Join frames which need to be reassembled:
304 to_delete=
305 for group in $segmentsGroups
306 do
307   group_array=( $(echo $group | sed 's/,/ /g') )
308   echo "Grouping frames ${group_array[*]} ..."
309   for frame in ${group_array[@]}; do
310     cat $RESULTS_DIR/$frame.hex >> $tmpdir/diam.$group
311   done
312   cat $tmpdir/diam.$group | tr -d '\n' > $RESULTS_DIR/$frame.hex
313   # Delete all frames except last one in the group:
314   to_delete="$to_delete  $(echo ${group_array[*]} | awk '{$NF=""; print $0}')"
315 done
316
317 # Delete superfluous metadata:
318 #segments=( $(cat $tmpdir/diameter_frames | awk -F\| '{ if ($16 == "") print $1 }') )
319 segments=( $(echo $to_delete) )
320 echo "Deleting superfluous buffers & metadata (${segments[*]}) ..."
321 for s in ${segments[@]}; do rm $RESULTS_DIR/${s}.* ; done
322
323 # Detecting Session-Id values:
324 grep ^sessionid= $RESULTS_DIR/*.metadata 2>/dev/null | cut -d= -f2- | sort -u > $RESULTS_DIR/session-ids
325 if [ -s $RESULTS_DIR/session-ids ]
326 then
327   count=0
328   while read -r line; do count=$((count+1)) ; echo "Detected Session-Id $count:  $line"; done < $RESULTS_DIR/session-ids
329   rm $RESULTS_DIR/session-ids
330 fi
331
332 # Detecting Origin-Host values:
333 grep ^originhost= $RESULTS_DIR/*.metadata 2>/dev/null | cut -d= -f2- | sort -u > $RESULTS_DIR/origin-hosts
334 if [ -s $RESULTS_DIR/origin-hosts ]
335 then
336   count=0
337   while read -r line; do count=$((count+1)) ; echo "Detected Origin-Host $count: $line"; done < $RESULTS_DIR/origin-hosts
338   #rm $RESULTS_DIR/origin-hosts
339 fi
340
341 # Purge frames with Session-Id not wanted:
342 if [ -n "$SIDS_FILE" ]
343 then
344   grep -l -w -f $SIDS_FILE $RESULTS_DIR/*metadata > $RESULTS_DIR/.wanted
345   grep -l ^sessionid $RESULTS_DIR/*metadata > $RESULTS_DIR/.all
346   for file in `grep -vf $RESULTS_DIR/.wanted $RESULTS_DIR/.all`
347   do
348     frm=$(basename $file | cut -d\. -f1)
349     sid=$(grep ^sessionid= $file | cut -d= -f2-)
350     echo "Purge results for frame $frm (Session-Id: '$sid') ..."
351     rm $RESULTS_DIR/${frm}.*
352   done
353   rm $RESULTS_DIR/.wanted $RESULTS_DIR/.all
354 fi
355
356 _exit "Done!" 0
357