-
Notifications
You must be signed in to change notification settings - Fork 49
/
chaosreader
executable file
·7597 lines (6667 loc) · 206 KB
/
chaosreader
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
#
# Chaosreader can trace TCP/UDP/... sessions and fetch application data
# from tcpdump or snoop logs. This is like an "any-snarf" program, it will
# fetch telnet sessions, FTP files, HTTP transfers (HTML, GIF, JPEG, ...),
# SMTP emails, etc ... from the captured data inside the network traffic
# logs. It creates a html index file that links to all the session details,
# including realtime replay programs for telnet, rlogin or IRC sessions;
# and reports such as image reports and HTTP GET/POST content reports.
# It also creates replay programs for telnet sessions, so that you can
# play them back in realtime (or even different speeds).
#
# Chaosreader can also run in standalone mode - where it invokes tcpdump or
# snoop (if they are available) to create the log files and then processes
# them.
#
# 15-Jun-2014, ver 0.96 https://github.com/brendangregg/Chaosreader
#
# Chaosreader currently lives in that github location. If 2014 sounds really
# old, you may want to run a web search for "chaosreader" in case it's updated
# somewhere else. Also see http//www.brendangregg.com/chaosreader.html.
#
# Recent versions:
#
# 11-Sep-2011, ver 0.95
# 24-Sep 2011, ver 0.95b
# 04-Jan 2012, ver 0.95c
# 10-Jan 2012, ver 0.95d
# 15-Mar 2013, ver 0.95e
# 15-Apr 2013, ver 0.95f
# 18-Apr 2013, ver 0.95g
# 12-Apr 2014, ver 0.95h
# 14-Apr 2014, ver 0.95i
# 12-jun 2014, ver 0.95.10
#
# QUICK USAGE:
# tcpdump -s9000 -w out1; chaosreader out1; netscape index.html
# or,
# snoop -o out1; chaosreader out1; netscape index.html
# or,
# ethereal (save as "out1"); chaosreader out1; netscape index.html
# or,
# chaosreader -s 5; netscape index.html
#
#
# USAGE: chaosreader [-adehiknqrvxAHIRTUXY] [-D dir]
# [-b port[,...]] [-B port[,...]]
# [-j IPaddr[,...]] [-J IPaddr[,...]]
# [-l port[,...]] [-L port[,...]] [-m bytes[k]]
# [-M bytes[k]] [-o "time"|"size"|"type"|"ip"]
# [-p port[,...]] [-P port[,...]]
# infile [infile2 ...]
#
# chaosreader -s [mins] | -S [mins[,count]]
# [-z] [-f 'filter']
#
# chaosreader # Create application session files, indexes
#
# -a, --application # Create application session files (default)
# -d, --preferdns # Show DNS names instead of IP addresses
# -e, --everything # Create HTML 2-way & hex files for everything
# -h # Print a brief help
# --help # Print verbose help (this) and version
# --help2 # Print massive help
# -i, --info # Create info file
# -q, --quiet # Quiet, no output to screen
# -r, --raw # Create raw files
# -v, --verbose # Verbose - Create ALL files .. (except -e)
# -x, --index # Create index files (default)
# -A, --noapplication # Exclude application session files
# -H, --hex # Include hex dumps (slow)
# -I, --noinfo # Exclude info files
# -R, --noraw # Exclude raw files
# -T, --notcp # Exclude TCP traffic
# -U, --noudp # Exclude UDP traffic
# -Y, --noicmp # Exclude ICMP traffic
# -X, --noindex # Exclude index files
# -k, --keydata # Create extra files for keystroke analysis
# -n, --names # Include hostnames in hyperlinked HTTPlog (HTML)
# -D dir --dir dir # Output all files to this directory
# -b 25,79 --playtcp 25,79 # replay these TCP ports as well (playback)
# -B 36,42 --playudp 36,42 # replay these UDP ports as well (playback)
# -l 7,79 --htmltcp 7,79 # Create HTML for these TCP ports as well
# -L 7,123 --htmludp 7,123 # Create HTML for these UDP ports as well
# -m 1k --min 1k # Min size of connection to save ("k" for Kb)
# -M 1024k --max 1k # Max size of connection to save ("k" for Kb)
# -o size --sort size # sort Order: time/size/type/ip (Default time)
# -p 21,23 --port 21,23 # Only examine these ports (TCP & UDP)
# -P 80,81 --noport 80,81 # Exclude these ports (TCP & UDP)
# -s 5 --runonce 5 # Standalone. Run tcpdump/snoop for 5 mins.
# -S 5,10 --runmany 5,10 # Standalone, many. 10 samples of 5 mins each.
# -S 5 --runmany 5 # Standalone, endless. 5 min samples forever.
# -z --runredo # Standalone, redo. Rereads last run's logs.
# -j 10.1.2.1 --ipaddr 10.1.2.1 # Only examine these IPs
# -J 10.1.2.1 --noipaddr 10.1.2.1 # Exclude these IPs
# -f 'port 7' --filter 'port 7' # With standalone, use this dump filter.
#
# eg1,
# tcpdump -s9000 -w output1 # create tcpdump capture file
# chaosreader output1 # extract recognised sessions, or,
# chaosreader -ve output1 # gimme everything, or,
# chaosreader -p 20,21,23 output1 # only ftp and telnet...
# eg2,
# snoop -o output1 # create snoop capture file instead
# chaosreader output1 # extract recognised sessions...
# eg3,
# chaosreader -S 2,5 # Standalone, sniff network 5 times for 2 mins
# # each. View index.html for progress (or .text)
#
# Output Files: Many will be created, run this in a clean directory.
#
# Short example:
# index.html Html index (full details)
# index.text Text index
# index.file File index for standalone redo mode
# image.html HTML report of images
# getpost.html HTML report of HTTP GET/POST requests
# session_0001.info Info file describing TCP session #1
# session_0001.telnet.html HTML coloured 2-way capture (time sorted)
# session_0001.telnet.raw Raw data 2-way capture (time sorted)
# session_0001.telnet.raw1 Raw 1-way capture (assembeled) server->client
# session_0001.telnet.raw2 Raw 1-way capture (assembeled) client->server
# session_0002.web.html HTML coloured 2-way
# session_0002.part_01.html HTTP portion of the above, a HTML file
# session_0003.web.html HTML coloured 2-way
# session_0003.part_01.jpeg HTTP portion of the above, a JPEG file
# session_0004.web.html HTML coloured 2-way
# session_0004.part_01.gif HTTP portion of the above, a GIF file
# session_0005.part_01.ftp-data.gz An FTP transfer, a gz file.
# ...
#
# The convention is:
# session_* TCP Sessions
# stream_* UDP Streams
# icmp_* ICMP packets
# index.html HTML Index
# index.text Text Index
# index.file File Index for standalone redo mode only
# image.html HTML report of images
# getpost.html HTML report of HTTP GET/POST requests
# *.info Info file describing the Session/Stream
# *.raw Raw data 2-way capture (time sorted)
# *.raw1 Raw 1-way capture (assembeled) server->client
# *.raw2 Raw 1-way capture (assembeled) client->server
# *.replay Session replay program (perl)
# *.partial.* Partial capture (tcpdump/snoop were aware of drops)
# *.hex.html 2-way Hex dump, rendered in coloured HTML
# *.hex.text 2-way Hex dump in plain text
# *.X11.replay X11 replay script (talks X11)
# *.textX11.replay X11 communicated text replay script (text only)
# *.textX11.html 2-way text report, rendered in red/blue HTML
# *.keydata Keystroke delay data file. Used for SSH analysis.
#
# Modes:
# * Normal - eg "chaosreader infile", this is where a tcpdump/snoop file
# was created previously and chaosreader reads and processes it.
# * Standalone, once - eg "chaosreader -s 10", this is where chaosreader
# runs tcpdump/snoop and generates the log file, in this case for 10 i
# minutes, and then processes the result. Some OS's may not have
# tcpdump or snoop available so this will not work (instead you may be
# able to get Ethereal, run it, save to a file, then use normal mode).
# There is a master index.html and the report index.html in a sub dir,
# which is of the format out_YYYYMMDD-hhmm, eg "out_20031003-2221".
# * Standalone, many - eg "chaosreader -S 5,12", this is where chaosreader
# runs tcpdump/snoop and generates many log files, in this case it
# samples 12 times for 5 minutes each. While this is running, the master
# index.html can be viewed to watch progress, which links to minor
# index.html reports in each sub directory.
# * Standalone, redo - eg "chaosreader -ve -z", (the -z), this is where
# a standalone capture was previously performed - and now you would like
# to reprocess the logs - perhaps with different options (in this case,
# "-ve"). It reads index.file to determine which capture logs to read.
# * Standalone, endless - eg "chaosreader -S 5", like standalone many -
# but runs forever (if you ever had the need?). Watch your disk space!
#
# Note: this is a work in progress, some of the code is a little unpolished.
#
# Advice:
# * Run chaosreader in an empty directory.
# * Create small packet dumps. Chaosreader uses around 5x the dump size
# in memory. A 100Mb file could need 500Mb of RAM to process.
# * Your tcpdump may allow "-s0" (entire packet) instead of "-s9000".
# * Beware of using too much disk space, especially standalone mode.
# * If you capture too many small connections giving a huge index.html,
# try using the -m option to ignore small connections. eg "-m 1k".
# * snoop logs may actually work better. Snoop logs are based on RFC1761,
# however there are many varients of tcpdump/libpcap and this program
# cannot read them all. If you have Ethereal you can create snoop logs
# during the "save as" option. On Solaris use "snoop -o logfile".
# * tcpdump logs may not be portable between OSs that use different sized
# timestamps or endian.
# * Logs are best created in a memory filesystem for speed, usually /tmp.
# * For X11 or VNC playbacks, first practise by replaying a recent captured
# session of your own. The biggest problem is colour depth, your screen
# must match the capture. For X11 check authentication (xhost +), for
# VNC check the viewers options (-8bit, "Hextile", ...)
# * SSH analysis can be performed with the "sshkeydata" program as
# demonstrated on http://www.brendangregg.com/sshanalysis.html .
# chaosreader provides the input files (*.keydata) that sshkeydata
# analyses.
#
# Bugs: The following assumptions may cause problems (check for new vers);
# * A lower port number = the service type. Eg with ports 31247 and 23,
# the actual type of session is telnet (23). This may not work for
# some things (eg, VNC).
# * Time based order is more important for 2-way sessions (eg telnet),
# SEQ order is more import for 1-way transfers (eg ftp-data).
# * One particular TCP session isn't active for long enough that the SEQ
# number loops (or even wraps).
#
# WARNING: Please don't use this software for anything illegal. That definition
# differs for every country, please check the law first.
# This is a great network troubleshooting and development tool, not a
# "cracking" or "hacking" tool - a misidentification that could render owning
# this software illegal in some countries.
#
# SEE ALSO: wireshark (GUI packet viewer), dsniff (sniffing toolkit)
#
# COPYRIGHT: Copyright (c) 2003, 2004 Brendan Gregg.
# Copyright (c) 2008 Indian Larry.
# Copyright (c) 2011, 2012, 2013 Jens Lechtenbörger.
# Copyright (c) 2014 Pavel Hančar, Jens Lechtenbörger, Pex pexnet0@gmail.com.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authors: Brendan Gregg [Sydney, Australia]
# Indian Larry [http://refrequelate.blogspot.com/]
# Jens Lechtenbörger [Münster, Germany]
# Pavel Hančar [Brno, Czech Republic]
# Pex [https://github.com/pexnet]
#
# Todo:
# * Rework code to improve structure.
# * Add more application protocol filters. ARP, RARP.
# * Ensure current application filters are robust (more testing).
# * Process captured filenames from FTP, HTTP and NFS transfers.
# * Add more file types (magic numbers/frequency analysis).
# * Process more IPv6 extension headers, ICMP types.
#
# 28-Sep-2003 Brendan Gregg Began writing this.
# 08-Oct-2003 " " Released version 0.7 beta
# 09-Oct-2003 " " Added telnet replays
# 12-Oct-2003 " " Added IRC ports and replays
# 19-Oct-2003 " " Made code more robust on different OSs
# 01-Nov-2003 " " Code cleanup, complex data types, IPv6, ICMP
# 03-Nov-2003 " " Added Standalone mode, standalone redo, ...
# 05-Nov-2003 " " Added Image indexes, GETPOST indexes
# 15-Nov-2003 " " Added HTTP proxy style log, hex dumps
# 27-Jan-2004 " " Released experimental X11 & VNC processing
# 30-Mar-2004 " " 802.11b, sorts, less RAM used, tun packets.
# 01-May-2004 " " CLI enhanced, faster, SSH analysis.
#
# 11-Sep-2011, Jens Lechtenbörger:
# - Switch from GPLv2 to GPLv3
# - Integrate diff from
# http://refrequelate.blogspot.com/2008/07/more-de-chunking-chaosreader-patch.html
# to reassemble chunked HTTP transfers.
# - Parse linux cooked captures, which result from listening on "any"
# interface. (Chaosreader0.94 does not produce any output for such
# pcap files.)
# - Use HTTP content-type to identify file types such as HTML, XML,
# Javascript, CSS; use those types for better file extensions than
# "data".
# - Uncompress gzip'ed data.
# - Add new command line switch to show host names in HTTPlog and to
# create href-links from HTTPlog rows to the corresponding rows in
# the table on index.html.
# - Several minor improvements (see comments with "JL:").
#
# 24-Sep-2011, Jens Lechtenbörger:
# - More systematic Content-Type handling based on MIME types.
# - More image types included in Image Report based on MIME types.
#
# 4-Jan-2012, Jens Lechtenbörger:
# - Parsing of DNS replies to show names instead of IP addresses (new
# command line switch -d) and to save DNS replies as text files.
#
# 10-Feb-2012, Jens Lechtenbörger:
# - Use file magic (again) to detect MIME type if HTTP's Content-Type is
# application/octet-stream. (Some Web servers report images incorrectly.)
#
# 15-Mar-2013, Jens Lechtenbörger:
# - Create additional HTTP log file in text format. That file contains one
# line per GET request, which shows the referrer (if present) and indicates
# whether cookies have been sent in the request or received in the reply.
#
# 15-Apr-2013, Jens Lechtenbörger:
# - Link additional HTTP log file from index.html.
# - Also look for images in plain/text Content-Types (seen in the wild).
# - Extend GET/POST report to include all GETs; not only those including a
# question mark (with parameters).
#
# 18-Apr-2013, Jens Lechtenbörger:
# - Build new "External Image Report" (linked from index.html), where images
# are embedded from their origin servers.
# In contrast, the "Image Report" points to images on the local hard disk.
# The new report may be more suitable for publication on Web pages as it
# does not require to publish (potentially copyright protected) images.
# - Parse CNAME DNS replies to show original host names (which are hopefully
# more familiar than aliases).
# - Show also empty parts on index.html that result from cache hits.
# - Create directory passed after switch "-D".
#
# 12-Apr-2014, Pavel Hančar:
# - Optimized hexadecimal dumps to use less memory.
# - Modified "IP Count" to "IP and MAC Count".
# - Fixed a few bugs concerning output.
#
# 14-Apr-2014, Jens Lechtenbörger:
# - Also create HTML files for ports 8118 (polipo) and 9050 (Tor) and treat
# both as HTTP traffic (quick hack, works for me).
# - Improved handling of TCP streams with same source and destination IP
# address (e.g., from localhost to localhost).
#
# 12 Jun 2014 Pex
# - support for deflate
# Jens frequently calls this program with options "-vden -D <somedir>".
use Getopt::Long;
use Benchmark;
use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
use IO::Uncompress::Inflate qw(inflate $InflateError) ;
use IO::Uncompress::RawInflate qw(rawinflate $RawInflateError) ;
use Net::DNS::Packet;
#####################
# --- Variables ---
#
#
# Some defaults
#
$PERL = "/usr/bin/perl"; # perl path for replay scripts
$integerSize = length(pack('I',0)); # can make a difference for tcpdumps
$the_date = scalar localtime(); # this is printed in the reports
$WRAP = 108; # wordwrap chars
$BM = 0; # benchmark counter
$| = 1; # flush output
#
# The following is needed for old perl5 multiline matching. New perl5 uses
# a "/s" on the RE (which is used in this program as well).
#
#$* = 1; # old perl5
#
# These ports have been selected to be saved as coloured 2-way HTML files
#
@Save_As_HTML_TCP_Ports = (21,23,25,79,80,109,110,119,143,513,514,1080,
3128,4110,5000,5555,6660,6665,6666,6667,6668,7000,8000,8080,8118,9000,9050);
@Save_As_HTML_UDP_Ports = (53);
#
# These ports have been selected to be saved as realtime playback scripts
# (telnet, login, and numerous IRC ports)
#
@Save_As_TCP_Playback_Ports = (23,513,4110,5000,5555,6660,6666,6667,
6668,7000,8000,9000);
@Save_As_UDP_Playback_Ports = (7);
#
# These are the X11 ports to save as X11 playback scripts
#
@Save_As_X11_Playback_Ports = (6000,6001,6002,6003,6004,6005,6006,6007);
#
# These X11 ports will have the text saved as coloured 2-way HTML files
#
@Save_As_HTML_X11_Ports = (6000,6001,6002,6003,6004,6005,6006,6007);
#
# These are the VNC ports to save as VNC playback scripts
#
@Save_As_VNC_Playback_Ports = (5900,5901,5902,5903,5904,5905,5906,5907);
#
# --- Arguments ---
#
&Process_Command_Line_Arguments();
### Record program start
$Bench{++$BM}{mark} = new Benchmark if $Arg{bench};
$Bench{$BM}{text} = "Program Start";
#
# Load some lookup tables for number -> name translations.
#
&Load_Etc_Services();
&Set_IP_Protocols();
&Set_ICMP_Types();
&Set_Result_Names();
&Set_X11_Codes();
&Set_X11_KeyCodes();
&Set_VNC_Codes();
&Set_MIME_Types(); #JL
&Set_DNS(); #JL
###########################
# --- MODE 1 - Normal --- #
###########################
#
# Process log files,
#
if ($Arg{normal}) {
#
# Initial values
#
$frame = 0; $number = 0;
%IP = (); %TCP = (); %UDP = (); %ICMP = (); %Count = (); %Hex = ();
### Print version
&Print_Welcome();
######################################
# --- INPUT - Read Packet Log(s) ---
#
foreach $filename (@{$Arg{infiles}}) {
#
# Check input file type and Open
#
&Open_Input_File($filename);
#
# Read though the entire input file, saving all packet
# data in memory (mainly %TCP and %UDP).
#
&Read_Input_File();
}
#############################################
# --- OUTPUT - Process TCP/UDP Sessions ---
#
### cd to output
&Chdir($Arg{output_dir});
&Print_Header2();
### Determine Session and Stream time order
%Index = (); %Image = (); %ExtImage = (); %GETPOST = ();
&Sort_Index();
#
# Process %TCP and create session* output files, write %Index
#
&Process_TCP_Sessions();
#
# Process %UDP and create session* output files, write %Index
#
&Process_UDP_Streams();
#
# Process %ICMP
#
&Process_ICMP();
#
# Create Index Files from %Index
#
&Create_Index_Files();
&Create_Log_Files();
###############
# --- END ---
#
&Print_Footer1();
}
###############################
# --- MODE 2 - Standalone --- #
###############################
elsif ($Arg{standalone}) {
############################################################
# --- STANDALONE - Create Packet Logs and Process them ---
#
$limit = $Arg{count};
$filenum = 0;
### Check for the sniffer command
&Check_Command();
### cd to output
&Chdir($Arg{output_dir});
### Print welcome
&Print_Welcome();
#
# MAIN LOOP
#
while ($limit != 0) {
#
# Create a meaningful directory and filename
#
@Times = localtime();
$dirname = sprintf("out_%d%02d%02d-%02d%02d",($Times[5]+1900),
$Times[4],$Times[3],$Times[2],$Times[1]);
$filename = "$dirname.log";
#
# Initial values
#
$frame = 0; $number = 0;
%IP = (); %TCP = (); %UDP = (); %ICMP = (); %Count = (); %Hex = ();
#
# Record details in a Master Index
#
$Master[$filenum]{starttime} = scalar localtime();
$Master[$filenum]{duration} = - time(); # will +end time
$Master[$filenum]{dir} = $dirname;
$Master[$filenum]{file} = $filename;
#
# Create and cd to output dir
#
mkdir ("$dirname",0755) || die "ERROR01: Couldn't mkdir (perms?): $!\n";
chdir "$dirname" || die "ERROR02: Couldn't cd $dirname: $!\n";
print "\nCreating log: $dirname/$filename\n" unless $Arg{quiet};
#
# fork, so that one process can exec tcpdump/snoop while the other
# sleeps and then kills it.
#
$pid = fork();
die "ERROR03: Can't fork (resources?): $!\n" if (! defined $pid);
if ($pid == 0) {
###############################
# --- CREATE - Packet Log ---
#
print "Running: $command $filename $Arg{filter}\n"
unless $Arg{quiet};
### exec, so $pid points to sniffer
exec("$command $filename $Arg{filter}") &&
die "ERROR04: couldn't run $command file: $!\n";
} else {
### Wait for logfile to be populated
sleep($Arg{mins} * 60);
### Kill child (TERM, INT)
kill 15, $pid;
kill 2, $pid;
}
exit if $pid == 0; # check for impossibility
### Record end time, duration, size
$Master[$filenum]{endtime} = scalar localtime();
$Master[$filenum]{duration} += time();
# finish writing the log before reading it's size
system("sync") if (($^O eq "linux") || ($^O eq "solaris"));
$Master[$filenum]{size} = -s "$filename";
print "\nProcessing: $dirname/$filename\n" unless $Arg{quiet};
$bak = $Arg{quiet}; $Arg{quiet} = 1;
###############################
# --- INPUT - Process Log ---
#
&Open_Input_File($filename);
### Populate memory (%TCP, %UDP, ...).
&Read_Input_File();
#############################################
# --- OUTPUT - Process TCP/UDP Sessions ---
#
### Determine Session and Stream time order
%Index = (); %Image = (); %ExtImage = (); %GETPOST = ();
&Sort_Index();
### Process %TCP, %UDP, ..., create output fies, write %Index
&Process_TCP_Sessions();
&Process_UDP_Streams();
&Process_ICMP();
### Create Index Files from %Index
&Create_Index_Files();
&Create_Log_Files();
chdir ".." || die "ERROR05: Couldn't cd ..: $!\n";
$Arg{quiet} = $bak;
### Create Master Index from @Master
&Create_Index_Master();
$limit--;
$filenum++;
}
}
##########################
# --- MODE 3 - Redo --- #
##########################
elsif ($Arg{redo}) {
#############################################################
# --- STANDALONE REDO - Redo last run from sniffer logs ---
#
$filenum = 0;
### Read index.file for logs to process
&Load_Index_File();
### Print welcome
&Print_Welcome();
#
# MAIN LOOP
#
for ($index=0; $index <= $#Master; $index++) {
### Get previous run values
$dirname = $Master[$index]{dir};
$filename = $Master[$index]{file};
### Initial values
$frame = 0; $number = 0;
%IP = (); %TCP = (); %UDP = (); %ICMP = (); %Count = (); %Hex = ();
### Create and cd to output dir
chdir "$dirname" || die "ERROR06: Couldn't cd $dirname: $!\n";
print "Processing: $dirname/$filename\n" unless $Arg{quiet};
$bak = $Arg{quiet}; $Arg{quiet} = 1;
###############################
# --- INPUT - Process Log ---
#
&Open_Input_File($filename);
### Populate memory (%TCP, %UDP, ...).
&Read_Input_File();
#############################################
# --- OUTPUT - Process TCP/UDP Sessions ---
#
### Determine Session and Stream time order
%Index = (); %Image = (); %ExtImage = (); %GETPOST = ();
&Sort_Index();
### Process %TCP, %UDP, ..., create output fies, write %Index
&Process_TCP_Sessions();
&Process_UDP_Streams();
&Process_ICMP();
### Create Index Files from %Index
&Create_Index_Files();
&Create_Log_Files();
chdir ".." || die "ERROR07: Couldn't cd ..: $!\n";
$Arg{quiet} = $bak;
$limit--;
$filenum++;
}
### Create Master Index from @Master
&Create_Index_Master();
}
#
# BENCHMARK REPORT
#
if ($Arg{bench}) {
$Bench{++$BM}{mark} = new Benchmark;
$Bench{$BM}{text} = "Program End";
print "\nBenchmarks,\n\n";
for ($bm=1; $bm <= $BM; $bm++) {
$bdiff = timediff($Bench{$bm}{mark},$Bench{1}{mark});
printf(" %-32s %s\n",$Bench{$bm}{text},timestr($bdiff));
}
}
#####################
# --- SUBROUTINES ---
# (Most of these subroutines are used as shortcuts to code, not traditional
# scoped subroutines as with other languages)
# Open_Input_File - open the packet log specified. This checks the header
# of the file to determine whether it is a tcpdump/libpcap or snoop
# log (including several styles of tcpdump/libpcap).
#
sub Open_Input_File {
my $infile = shift;
my ($length,$size);
$Bench{++$BM}{mark} = new Benchmark if $Arg{bench};
$Bench{$BM}{text} = "Open Input File";
print "Opening, $infile\n\n" unless $Arg{quiet};
#
# Open packet log
#
open(INFILE,$infile) || die "Can't open $infile: $!\n";
binmode(INFILE); # for backward OSs
#
# Fetch header
#
$length = read(INFILE,$header,8);
die "ERROR08: Can't read from $infile\n" if $length < 8;
### Print status
print "Reading file contents,\n" unless $Arg{quiet};
$SIZE = -s $infile;
#
# Try to determine if this is a tcpdump or a snoop file
#
($ident) = unpack('a8',$header);
if ($ident =~ /^snoop/) {
$TYPE = "snoop";
$length = read(INFILE,$header,8);
($version,$type) = unpack('NN',$header);
} elsif ($ident =~ /^\241\262\303\324|^\324\303\262\241/ ||
$ident =~ /^\241\262\315\064|^\064\315\262\241/) {
$TYPE = "tcpdump";
$ident = unpack('a4',$header); # try again
# standard/modified defines style, 1/2 defines endian
if ($ident =~ /^\241\262\303\324/) { $STYLE = "standard1"; }
if ($ident =~ /^\324\303\262\241/) { $STYLE = "standard2"; }
if ($ident =~ /^\241\262\315\064/) { $STYLE = "modified1"; }
if ($ident =~ /^\064\315\262\241/) { $STYLE = "modified2"; }
if ($STYLE =~ /1$/) {
# reread in big-endian
($ident,$major,$minor) = unpack('a4nn',$header);
} else {
# reread in little-endian
($ident,$major,$minor) = unpack('a4vv',$header);
}
#
# Check tcpdump header carefully to ensure this is ver 2.4.
#
if ($major != 2 && $minor != 4) {
#
# Die if this is an unknown version. (there could
# be new vers of tcpdump/libpcap in the future).
#
print STDERR "ERROR09: Wrong tcpdump version ";
print STDERR "($version.$type).\n(expected 2.4).\n";
exit 1;
}
#
# Nudge the filehandle past the rest of the header...
#
$length = read(INFILE,$header_rest,16);
} else {
#
# Die - unknown file format
#
print STDERR "ERROR10: Input dosen't look like a tcpdump or ";
print STDERR "snoop output file.\n\tIf it is tcpdump, it ";
print STDERR "may be a wrong or new version.\n";
exit 1;
}
### Record the filename into the global %Arg
$Arg{infile} = $infile;
}
# Read_Input_File - this subroutine loops through the records in the packet
# log, storing all the TCP and UDP data into %TCP and %UDP. (see the end
# of the program for the structure of these data types). %Count is also
# populated with various frequency counts.
#
sub Read_Input_File {
my ($trailers,$pppoe_verNtype,$pppoe_code,$pppoe_id,$pppoe_length,
$ppp_protocol,$wless_fc,$wless_version,$wless_type,$wless_duration,
$wless_subtype,$wless_from,$wless_to,$wless_flag,$wless_WEP,
$wless_bss,$wless_src,$wless_dest,$wless_cksum,$llc_head,$llc_control,
$llc_org,$llc_type,$wless_OK,$bytes,$counter,$packets);
$Bench{++$BM}{mark} = new Benchmark if $Arg{bench};
$Bench{$BM}{text} = "Read Input File - start";
local $packet = 0; # counter
if ($TYPE eq "snoop") {
$bytes = 16;
} else {
$bytes = 24;
}
#
# --- Pass #1, Store IP data in memory (%IP) --
#
while (1) {
#
# --- Read Record from Log ---
#
if ($TYPE eq "snoop") {
&Read_Snoop_Record(); # will "last" on error
$packet_data = $snoop_data;
$packet_time = $snoop_seconds;
$packet_timefull = $snoop_seconds + $snoop_msecs/1000000;
$record_size = $snoop_length_rec;
} else {
&Read_Tcpdump_Record(); # will "last" on error
$packet_data = $tcpdump_data;
$packet_time = $tcpdump_seconds;
$packet_timefull = $tcpdump_seconds + $tcpdump_msecs/1000000;
$record_size = $tcpdump_length + ($integerSize * 2 + 8);
}
### Print status summary
unless ($Arg{quiet}) {
$bytes += $record_size;
if (($packet % 16) == 0) {
printf("%s %2.0f%% (%d/%d)","\b"x24,
(100*$bytes/$SIZE),$bytes,$SIZE);
}
}
#
# --- Parse TCP/IP layers (a little ;) ---
#
#-------------------------------------------------------------------
#
# Wireless, 802.11b
#
$decoded = 0; # this flag is true if wireless was found
# unpack a little first, (efficiency)
($wless_fc) = unpack('H4',$packet_data);
# this matches on possible send or receive wireless traffic, however
# this could also be the start of an 802.3 frame - making this part
# of a MAC address. (The IEEE list on OUIs had these as unassigned).
if ($wless_fc =~ /^080[1256]/) {
# now dig deeper,
# (this is one form of 802.11 - the form we are interested
# in, however note that there is a lot more to 802.11).
($wless_fc,$wless_duration,$wless_bss,$wless_src,
$wless_dest,$wless_cksum,$llc_head,$llc_control,$llc_org,
$llc_type,$ether_data)
= unpack('nnH12H12H12na2CH6H4a*',$packet_data);
$wless_to = $wless_fc & 1;
# Check this is IP and encapsulated Ethernet,
if (($llc_type eq "0800") && ($llc_org eq "000000")) {
### Populate ether variables for use later on
$ether_type = $llc_type;
if ($wless_to) {
$ether_dest = $wless_dest;
$ether_src = $wless_src;
} else {
$ether_dest = $wless_src;
$ether_src = $wless_dest;
}
$decoded = 1; # remember we did this
}
# (else try redecoding this using 802.3)
}
#-------------------------------------------------------------------
#
# Tun device
#
# unpack a little first, (efficiency)
($tun_id) = unpack('H8',$packet_data);
# this checks if the frame looks like a tun device frame
if ($tun_id eq "02000000") {
# now dig deeper,
($tun_id,$ether_data) = unpack('a4a*',$packet_data);
$ether_src = "0";
$ether_dest = "0";
$ether_type = "0800";
$decoded = 1; # remember we did this
}
#-------------------------------------------------------------------
#
# Ethernet, 802.3
#
### Unpack ether data
($ether_dest,$ether_src,$ether_type,$ether_data) =
unpack('H12H12H4a*',$packet_data) unless $decoded;
### Count ether types seen
$Count{EtherType}{$ether_type}++;
$CountMaster{EtherType}{$ether_type}++;
#
# Process extended Ethernet types (wireless, PPPoE, VLAN)
#
### PPPoE
if ($ether_type eq "8864") {
($pppoe_verNtype,$pppoe_code,$pppoe_id,$pppoe_length,
$ppp_protocol,$ether_data) = unpack("CCnnna*",$ether_data);
### Skip anything but data (we just want data - code 0)
next if $pppoe_code != 0;
# (May like to add code here later to process $ppp_protocol,
# eg, to process LCP).
}
### VLAN tagged
elsif ($ether_type eq "8100") {
($vlan_PCP, $orig_ether_type, $ip_rest) = unpack('H4H4a*', $ether_data);
$ether_data = $ip_rest;
}
elsif (($ether_type ne "0800") && ($ether_type ne "86dd")) {
# JL: Try linux cooked capture
($lptype,$lladdr_type,$lladdr_len,
$ether_src,$ll_dummy,$ether_type,$ether_data) =
unpack('nnnH12nH4a*',$packet_data) unless $decoded;
if ($ether_type ne "0800") {
next;
}
}
#-------------------------------------------------------------------
#
# IP
#
### Check for IP ver
($ip_verNihl,$ip_rest) = unpack('Ca*',$ether_data);
$ip_ver = $ip_verNihl & 240;
$ip_ver = $ip_ver >> 4;
if ($ip_ver == 4) {
#-----------------------------------------------------------
#
# IPv4
#
### Unpack IP data
($ip_verNihl,$ip_tos,$ip_length,$ip_ident,$ip_flagNfrag,
$ip_ttl,$ip_protocol,$ip_checksum,@ip_src[0..3],
@ip_dest[0..3],$ip_data) = unpack('CCnnnCCa2CCCCCCCCa*',
$ether_data);
### Get frag and flag data
$ip_frag = $ip_flagNfrag & 8191;
$ip_flag = $ip_flagNfrag & 57344;
$ip_flag = $ip_flag >> 13;
$ip_MF = $ip_flag & 1;
### Strip off IP options if present
$ip_ihl = $ip_verNihl & 15;
$ip_ihl = $ip_ihl << 2;
$ip_options_num = $ip_ihl - 20;