-
Notifications
You must be signed in to change notification settings - Fork 40
/
captcp.py
executable file
·6056 lines (4661 loc) · 221 KB
/
captcp.py
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/env python2
#
# Email: Hagen Paul Pfeifer <hagen@jauu.net>
# URL: http://research.protocollabs.com/captcp/
# Captcp 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.
#
# Captcp 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 Captcp. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import sys
import os
import logging
import optparse
import dpkt
import socket
import struct
import inspect
import math
import pprint
import time
import datetime
import subprocess
import select
import re
import shutil
import distutils.dir_util
import string
# optional packages
try:
import GeoIP
except ImportError:
GeoIP = None
try:
import cairo
except ImportError:
cairo = None
try:
import numpy
except ImportError:
numpy = None
try:
import wave
except ImportError:
wave = None
pp = pprint.PrettyPrinter(indent=4)
# Required debian packages:
# python-dpkt
# Suggested debian packages:
# python-cairo
# Optional debian packages:
# python-geoip
# python-numpy
__programm__ = "captcp"
__author__ = "Hagen Paul Pfeifer"
__version__ = "1.8"
__license__ = "GPLv3"
# custom exceptions
class ArgumentException(Exception): pass
class InternalSequenceException(Exception): pass
class InternalException(Exception): pass
class SequenceContainerException(InternalException): pass
class NotImplementedException(InternalException): pass
class SkipProcessStepException(Exception): pass
class PacketNotSupportedException(Exception): pass
class UnitException(Exception): pass
# IP flag constants
IP_TOS_ECT = dpkt.ip.IP_TOS_ECT
IP_TOS_CE = dpkt.ip.IP_TOS_CE
# TCP flag constants
TH_URG = dpkt.tcp.TH_URG
TH_ACK = dpkt.tcp.TH_ACK
TH_PSH = dpkt.tcp.TH_PUSH
TH_RST = dpkt.tcp.TH_RST
TH_SYN = dpkt.tcp.TH_SYN
TH_FIN = dpkt.tcp.TH_FIN
TH_ECE = dpkt.tcp.TH_ECE
TH_CWR = dpkt.tcp.TH_CWR
# "Robust Explicit Congestion Notification (ECN)
# Signaling with Nonces" (RFC 3540) specifies an
# additional ECN Flag: NS which is out of the 8 bit
# flags section, shared with header length field. I
# emailed Jon Oberheide to get some valuable solutions.
#
# See http://tools.ietf.org/html/rfc3540#section-9
# Protocols
TCP = dpkt.tcp.TCP
UDP = dpkt.udp.UDP
# Units (bit):
# kilobit (kbit) 10^3 - kibibit (Kibit) 2^10
# megabit (Mbit) 10^6 - mebibit (Mibit) 2^20
# gigabit (Gbit) 10^9 - gibibit (Gibit) 2^30
#
# Units (byte):
# kilobyte (kB) 10^3 - kibibyte (KiB) 2^10
# megabyte (MB) 10^6 - mebibyte (MiB) 2^20
# gigabyte (GB) 10^9 - gibibyte (GiB) 2^30
class ExitCodes:
EXIT_SUCCESS = 0
EXIT_ERROR = 1
EXIT_CMD_LINE = 2
EXIT_ENVIRONMENT = 3
EXIT_PLATFORM = 4
class Info:
ETHERNET_HEADER_LEN = 14
class SequenceContainer:
class Container: pass
def __init__(self):
self.sequnce_list = list()
if not numpy:
self.logger.error("Python numpy module not installed - but required")
sys.exit(ExitCodes.EXIT_CMD_LINE)
def __len__(self):
return len(self.sequnce_list)
def print_list(self):
for i in self.sequnce_list:
sys.stdout.write(str(i.left_edge) + "-" +
str(i.right_edge) + "\n" )
@staticmethod
def uint32_add(num, summand):
""" the caller (Module) must make sure that module is available """
s1 = numpy.array(num, dtype=numpy.dtype('uint32'))
s2 = numpy.array(summand, dtype=numpy.dtype('uint32'))
return int(numpy.array((s1 + s2), dtype=numpy.dtype('uint32')))
@staticmethod
def uint32_sub(num, summand):
""" the caller (Module) must make sure that module is available """
s1 = numpy.array(num, dtype=numpy.dtype('uint32'))
s2 = numpy.array(summand, dtype=numpy.dtype('uint32'))
return int(numpy.array((s1 - s2), dtype=numpy.dtype('uint32')))
def before(self, seq1, seq2):
s1 = numpy.array(seq1, dtype=numpy.dtype('uint32'))
s2 = numpy.array(seq2, dtype=numpy.dtype('uint32'))
res = numpy.array((s1 - s2), dtype=numpy.dtype('int32'))
if res < 0:
return True
else:
return False
def after(self, seq1, seq2):
return self.before(seq2, seq1)
# is s2 <= s1 <= s3
def between(self, seq1, seq2, seq3):
s1 = numpy.array(seq1, dtype=numpy.dtype('uint32'))
s2 = numpy.array(seq2, dtype=numpy.dtype('uint32'))
s3 = numpy.array(seq3, dtype=numpy.dtype('uint32'))
if s3 - s2 >= s1 - s2:
return True
else:
return False
def add_sequence(self, array):
if len(array) != 2:
raise ArgumentException("array must contain excatly 2 members")
new = SequenceContainer.Container()
new.left_edge = array[0]
new.right_edge = array[1]
if len(self.sequnce_list) <= 0:
self.sequnce_list.append(new)
return
# if new element is the direct neighbour we merge
if new.left_edge == self.sequnce_list[-1].right_edge + 1:
self.sequnce_list[-1].right_edge = new.right_edge
del new
return
# if new element is far right we add it instantly
if self.sequnce_list[-1].right_edge < new.left_edge + 1:
self.sequnce_list.append(new)
return
# check
if not new.left_edge <= self.sequnce_list[-1].right_edge:
raise SequenceContainerException("internal error")
reverse_enumerate = lambda l: \
itertools.izip(xrange(len(l)-1, -1, -1), reversed(l))
it = reverse_enumerate(self.sequnce_list)
# ok, the new packet is within the packets
while True:
try:
(i, old) = it.next()
# match the segment exactply?
if (old.left_edge - 1 == new.right_edge and
self.sequnce_list[i - 1].right_edge + 1 == new.left_edge):
self.sequnce_list.remove(old)
self.sequnce_list[i - 1].right_edge = old.right_edge
return
# check if the new packet match between a gap
if (old.left_edge > new.right_edge and
self.sequnce_list[i - 1].right_edge < new.left_edge):
self.sequnce_list.insert(i, new)
return
# can we merge one one side at least? (one end close, one new gap)
if old.left_edge - 1 == new.right_edge:
if len(self.sequnce_list) <= 1:
old.left_edge = new.left_edge
del new
return
elif self.sequnce_list[i - 1].right_edge < new.left_edge:
old.left_edge = new.left_edge
del new
return
except:
break
class U:
""" Utility module, to collect usefull functionality
needed by several other classes. We name it U to make it short
and non bloated"""
@staticmethod
def byte_to_unit(byte, unit):
byte = float(byte)
if unit == "byte" or unit == "Byte":
return byte
if unit == "bit" or unit == "Bit":
return byte * 8
if unit == "kB" or unit == "kilobyte":
return byte / 1000
if unit == "MB" or unit == "megabyte":
return byte / (1000 * 1000)
if unit == "GB" or unit == "gigabyte":
return byte / (1000 * 1000 * 1000)
if unit == "KiB" or unit == "kibibyte":
return byte / 1024
if unit == "MiB" or unit == "mebibyte":
return byte / (1024 * 1024)
if unit == "GiB" or unit == "gibibyte":
return byte / (1024 * 1024 * 1024)
if unit == "kbit" or unit == "kilobit":
return byte * 8 / 1000
if unit == "Mbit" or unit == "megabit":
return byte * 8 / (1000 * 1000)
if unit == "Gbit" or unit == "gigabit":
return byte * 8 / (1000 * 1000 * 1000)
if unit == "KiBit" or unit == "kibibit":
return byte * 8 / 1024
if unit == "MiBit" or unit == "mebibit":
return byte * 8 / (1024 * 1024)
if unit == "GiBit" or unit == "gibibit":
return byte * 8 / (1024 * 1024 * 1024)
raise UnitException("unit %s not known" % (unit))
@staticmethod
def best_match(byte):
last_unit = "bit"
last_val = float(byte) * 8
units = ("kbit", "Mbit", "Gbit")
for unit in units:
val = U.byte_to_unit(byte, unit)
if val < 1.0:
return "%.2f %s" % (last_val, last_unit)
last_unit = unit
last_val = val
return "%.2f %s" % (U.byte_to_unit(byte, "Gbit"), "Gbit")
@staticmethod
def percent(a, b):
if b == 0: return 0.0
return float(a) / b * 100
@staticmethod
def copytree(src, dst, symlinks=False, ignore=None):
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
os.makedirs(dst)
errors = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, ignore)
else:
copy2(srcname, dstname)
except (IOError, os.error) as why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error as err:
errors.extend(err.args[0])
try:
copystat(src, dst)
except WindowsError:
# can't copy file access times on Windows
pass
except OSError as why:
errors.extend((src, dst, str(why)))
if errors:
raise Error(errors)
class RainbowColor:
ANSI = 0
ANSI256 = 1
HEX = 2
DISABLE = 3
def __init__(self, mode=ANSI256):
if mode == RainbowColor.ANSI:
self.init_color_ansi()
elif mode == RainbowColor.ANSI256:
self.init_color_ansi256()
elif mode == RainbowColor.HEX:
self.init_color_hex()
elif mode == RainbowColor.DISABLE:
self.init_color_none()
else:
raise Exception()
# this color should not be printed
self.skip_list = ['red', 'end']
def __getitem__(self, key):
return self.color_palette[key]
def init_color_none(self):
self.color_palette = {'red':'', 'green':'', 'end':'' }
def init_color_hex(self):
self.color_palette = {'red':'#ff0000', 'green':'#00ff00', 'end':''}
def init_color_ansi256(self):
self.color_palette = dict()
for i in range(255):
self.color_palette[i + 1] = '\033[38;5;%dm' % (i + 1)
self.color_palette['end'] = '\033[0m'
self.color_palette['red'] = '\033[91m'
del self.color_palette[1]
del self.color_palette[9]
del self.color_palette[52]
del self.color_palette[88]
del self.color_palette[89]
del self.color_palette[124]
del self.color_palette[125]
del self.color_palette[126]
del self.color_palette[127]
del self.color_palette[160]
del self.color_palette[161]
del self.color_palette[162]
del self.color_palette[163]
del self.color_palette[196]
del self.color_palette[197]
del self.color_palette[198]
del self.color_palette[199]
del self.color_palette[200]
def init_color_ansi(self):
self.color_palette = {
'yellow':'\033[0;33;40m',
'real-yellow':'\033[93m',
'red':'\033[91m',
'green':'\033[92m',
'blue':'\033[94m',
'magenta':'\033[0;95;40m',
'cyan':'\033[0;96;40m',
'end':'\033[0m'
}
def next(self):
if self.color_palette_pos >= len(self.color_palette_flat):
raise StopIteration
retdata = self.color_palette_flat[self.color_palette_pos]
self.color_palette_pos += 1
return retdata
def infinite_next(self):
while True:
found = True
retdata = self.color_palette_flat[self.color_palette_pos % \
(len(self.color_palette_flat))]
self.color_palette_pos += 1
for i in self.skip_list:
if i in self.color_palette and self.color_palette[i] == retdata:
found = False
break
if found:
return retdata
def __iter__(self):
self.color_palette_pos = 0
self.color_palette_flat = self.color_palette.values()
return self
class Utils:
@staticmethod
def ts_tofloat(ts):
return float(ts.seconds) + ts.microseconds / 1E6 + ts.days * 86400
class Converter:
def dotted_quad_num(ip):
"convert decimal dotted quad string to long integer"
return struct.unpack('I', socket.inet_aton(ip))[0]
dotted_quad_num = staticmethod(dotted_quad_num)
def num_to_dotted_quad(n):
"convert long int to dotted quad string"
return socket.inet_ntoa(struct.pack('I', n))
num_to_dotted_quad = staticmethod(num_to_dotted_quad)
def make_mask(n):
"return a mask of n bits as a long integer"
return (1L << n)-1
make_mask = staticmethod(make_mask)
def dpkt_addr_to_string(addr):
if len(addr) == 16:
# IPv6
# FIXME: inet_ntop is UNIX only according to the python doc
return socket.inet_ntop(socket.AF_INET6, addr)
else:
# IPv4
iaddr = int(struct.unpack('I', addr)[0])
return Converter.num_to_dotted_quad(iaddr)
dpkt_addr_to_string = staticmethod(dpkt_addr_to_string)
def ip_to_net_host(ip, maskbits):
"returns tuple (network, host) dotted-quad addresses given IP and mask size"
n = Converter.dotted_quad_num(ip)
m = Converter.makeMask(maskbits)
host = n & m
net = n - host
return Converter.num_to_dotted_quad(net), Converter.num_to_dotted_quad(host)
ip_to_net_host = staticmethod(ip_to_net_host)
class PcapParser:
def __init__(self, pcap_file_path, pcap_filter):
self.logger = logging.getLogger()
self.pcap_file = False
try:
self.pcap_file = open(pcap_file_path)
except IOError:
self.logger.error("Cannot open pcap file: %s" % (pcap_file_path))
sys.exit(ExitCodes.EXIT_ERROR)
self.pc = dpkt.pcap.Reader(self.pcap_file)
try:
self.decode = {
dpkt.pcap.DLT_LOOP: dpkt.loopback.Loopback,
dpkt.pcap.DLT_NULL: dpkt.loopback.Loopback,
dpkt.pcap.DLT_EN10MB: dpkt.ethernet.Ethernet,
dpkt.pcap.DLT_IEEE802: dpkt.ethernet.Ethernet,
dpkt.pcap.DLT_PPP: dpkt.ppp.PPP,
dpkt.pcap.DLT_LINUX_SLL: dpkt.sll.SLL
}[self.pc.datalink()]
except KeyError:
self.logger.error("Packet link type not know (%d)! "
"Interpret at Ethernet now - but be carefull!" % (
self.pc.datalink()))
self.decode = dpkt.ethernet.Ethernet
if pcap_filter:
self.pc.setfilter(pcap_filter)
def __del__(self):
if self.pcap_file:
self.pcap_file.close()
def register_callback(self, callback):
self.callback = callback
def packet_len_error(self, snaplen, packet_len):
self.logger.critical("Captured data was too short (packet: %d, snaplen: %d)"
" - please recapture with snaplen of 0: infinity" %
(packet_len, snaplen))
def run(self):
try:
for ts, pkt in self.pc:
if self.pc.snaplen < len(pkt):
self.packet_len_error(self.pc.snaplen, len(pkt))
sys.exit(1)
packet = self.decode(pkt)
dt = datetime.datetime.fromtimestamp(ts)
self.callback(dt, packet.data)
except SkipProcessStepException:
self.logger.debug("skip processing step")
class PacketInfo:
@staticmethod
def is_tcp(packet):
if type(packet) != dpkt.ip.IP and type(packet) != dpkt.ip6.IP6:
return False
if type(packet.data) == TCP:
return True
return False
@staticmethod
def is_udp(packet):
if type(packet) != dpkt.ip.IP and type(packet) != dpkt.ip6.IP6:
return False
if type(packet.data) == UDP:
return True
return False
class IpPacketInfo(PacketInfo):
def __init__(self, packet, module=None):
self.tcp = packet.data
if type(self.tcp) != TCP:
raise InternalException("Only TCP packets are allowed")
if module != None and not isinstance(module, Mod):
raise InternalException(
"Argument module must be a subclass of module (not %s)" %
(type(module)))
if type(packet) == dpkt.ip.IP:
self.sip = Converter.dpkt_addr_to_string(packet.src)
self.dip = Converter.dpkt_addr_to_string(packet.dst)
self.ipversion = "IP "
elif type(packet) == dpkt.ip6.IP6:
self.sip = socket.inet_ntop(socket.AF_INET6, packet.src)
self.dip = socket.inet_ntop(socket.AF_INET6, packet.dst)
self.ipversion = "IP6"
else:
raise InternalException("unknown protocol")
self.sport = int(self.tcp.sport)
self.dport = int(self.tcp.dport)
self.seq = int(self.tcp.seq)
self.ack = int(self.tcp.ack)
self.win = int(self.tcp.win)
self.urp = int(self.tcp.urp)
self.sum = int(self.tcp.sum)
class TcpPacketInfo(PacketInfo):
class TcpOptions:
def __init__(self):
self.data = dict()
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, val):
self.data[key] = val
def __init__(self, packet, module=None):
self.tcp = packet.data
if type(self.tcp) != TCP:
raise InternalException("Only TCP packets are allowed")
if module != None and not isinstance(module, Mod):
raise InternalException(
"Argument module must be a subclass of module (not %s)" %
(type(module)))
if type(packet) == dpkt.ip.IP:
self.sip = Converter.dpkt_addr_to_string(packet.src)
self.dip = Converter.dpkt_addr_to_string(packet.dst)
self.ipversion = "IP "
elif type(packet) == dpkt.ip6.IP6:
self.sip = socket.inet_ntop(socket.AF_INET6, packet.src)
self.dip = socket.inet_ntop(socket.AF_INET6, packet.dst)
self.ipversion = "IP6"
else:
raise InternalException("unknown protocol")
self.sport = int(self.tcp.sport)
self.dport = int(self.tcp.dport)
self.seq = int(self.tcp.seq)
self.ack = int(self.tcp.ack)
self.win = int(self.tcp.win)
self.urp = int(self.tcp.urp)
self.sum = int(self.tcp.sum)
self.parse_tcp_options()
def caller(self):
stack = inspect.stack()
sys.stderr.write("%s" % (stack))
frame = stack[2][0]
caller = frame.f_locals.get('self', None)
return caller
def is_ack_flag(self):
return self.tcp.flags & TH_ACK
def is_syn_flag(self):
return self.tcp.flags & TH_SYN
def is_urg_flag(self):
return self.tcp.flags & TH_URG
def is_psh_flag(self):
return self.tcp.flags & TH_PSH
def is_fin_flag(self):
return self.tcp.flags & TH_FIN
def is_rst_flag(self):
return self.tcp.flags & TH_RST
def is_ece_flag(self):
return self.tcp.flags & TH_ECE
def is_cwr_flag(self):
return self.tcp.flags & TH_CWR
def create_flag_brakets(self):
s = "["
if self.is_cwr_flag():
s += "C"
if self.is_ece_flag():
s += "E"
if self.is_urg_flag():
s += "U"
if self.is_ack_flag():
s += "A"
if self.is_psh_flag():
s += "P"
if self.is_rst_flag():
s += "R"
if self.is_syn_flag():
s += "S"
if self.is_fin_flag():
s += "F"
s += "]"
return s
def construct_tcp_options_label(self):
ret = ""
if self.options['mss']:
ret += "mss: %d" % (self.options['mss'])
if self.options['wsc']:
ret += "wsc: %d" % (self.options['wsc'])
if self.options['tsval'] and self.options['tsecr']:
ret += "ts: %d:%d" % (self.options['tsval'], self.options['tsecr'])
if self.options['sackok']:
ret += "sackok"
def linear_sackblocks_array(self, liste):
retlist = list()
i = len(liste) / 2
while i > 0:
r = list()
r.append(liste.pop(-1))
r.append(liste.pop(-1))
retlist.append(r)
i -= 1
return retlist
def parse_tcp_options(self):
self.options = TcpPacketInfo.TcpOptions()
self.options['mss'] = False
self.options['wsc'] = False
self.options['tsval'] = False
self.options['tsecr'] = False
self.options['sackok'] = False
self.options['sackblocks'] = False
opts = []
for opt in dpkt.tcp.parse_opts(self.tcp.opts):
try:
o, d = opt
if len(d) > 32: raise TypeError
except TypeError:
break
if o == dpkt.tcp.TCP_OPT_MSS:
self.options['mss'] = struct.unpack('>H', d)[0]
elif o == dpkt.tcp.TCP_OPT_WSCALE:
self.options['wsc'] = ord(d)
elif o == dpkt.tcp.TCP_OPT_SACKOK:
self.options['sackok'] = True
elif o == dpkt.tcp.TCP_OPT_SACK:
ofmt="!%sI" % int(len(d) / 4)
self.options['sackblocks'] = self.linear_sackblocks_array(list(struct.unpack(ofmt, d)))
elif o == dpkt.tcp.TCP_OPT_TIMESTAMP:
(self.options['tsval'], self.options['tsecr']) = struct.unpack('>II', d)
opts.append(o)
class CaptureLevel:
LINK_LAYER = 0
NETWORK_LAYER = 1
TRANSPORT_LAYER = 2
class Mod:
def register_captcp(self, captcp):
self.captcp = captcp
def __init__(self):
self.captcp = None
self.cc = ConnectionContainer()
self.capture_level = CaptureLevel.NETWORK_LAYER
self.logger = logging.getLogger()
def internal_pre_process_packet(self, ts, packet):
""" this is a hidden preprocessing function, called for every packet"""
assert(self.captcp != None)
self.cc.update(ts, packet)
self.pre_process_packet(ts, packet)
def initialize(self):
""" called at the very beginning of module lifetime"""
pass
def pre_process_packet(self, ts, packet):
""" final packet round"""
# We simple cannot skip this processing step because it
# is internally required for accounting. The worst case
# scenario imagineable where pre_process_packet() is skipped
# and later in process_packet the connection is required - which
# in turn was never initialized. So we always pre_process_packet
# here.
# There ARE solutions to optimize this case - sure. But I skipped
# this because I never run into performance problems.
pass
def pre_process_final(self):
""" single call between pre_process_packet and process_packet to do some calc"""
pass
def process_packet(self, ts, packet):
""" final packet round"""
raise SkipProcessStepException()
def process_final(self):
""" called at the end of packet processing"""
pass
def set_opts_logevel(self):
if not self.opts:
raise InternalException("Cannot call set_opts_logevel() if no " +
"options parsing was done")
if not self.opts.loglevel:
""" this is legitim: no loglevel specified"""
return
if self.opts.loglevel == "debug":
self.logger.setLevel(logging.DEBUG)
elif self.opts.loglevel == "info":
self.logger.setLevel(logging.INFO)
elif self.opts.loglevel == "warning":
self.logger.setLevel(logging.WARNING)
elif self.opts.loglevel == "error":
self.logger.setLevel(logging.ERROR)
else:
raise ArgumentException("loglevel \"%s\" not supported" % self.opts.loglevel)
class Geoip(Mod):
def initialize(self):
self.parse_local_options()
def parse_local_options(self):
parser = optparse.OptionParser()
parser.usage = "geoip"
parser.add_option( "-v", "--loglevel", dest="loglevel", default=None,
type="string", help="show verbose")
self.opts, args = parser.parse_args(sys.argv[0:])
self.set_opts_logevel()
if len(args) < 3:
self.logger.error("no IP address argument given, exiting")
sys.exit(ExitCodes.EXIT_CMD_LINE)
self.captcp.print_welcome()
self.ip_address = args[2]
self.logger.info("# ip address: \"%s\"" % self.ip_address)
def process_final(self):
if not GeoIP:
self.logger.info("GeoIP package not installed on system, exiting")
sys.exit(ExitCodes.EXIT_CMD_LINE)
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
sys.stdout.write("Country Code: " + gi.country_code_by_addr(self.ip_address) + "\n")
class PayloadTimePortMod(Mod):
PORT_START = 0
PORT_END = 65535
DEFAULT_VAL = 0.0
def initialize(self):
self.parse_local_options()
self.data = dict()
self.trace_start = None
def parse_local_options(self):
parser = optparse.OptionParser()
parser.add_option( "-v", "--verbose", dest="loglevel", default=None,
type="string", help="set the loglevel (info, debug, warning, error)")
parser.add_option( "-f", "--format", dest="format", default="3ddata",
type="string", help="the data format for gnuplot")
parser.add_option( "-p", "--port", dest="port", default="sport",
type="string", help="sport or dport")
parser.add_option( "-s", "--sampling", dest="sampling", default=50,
type="int", help="sampling rate (default: 5 seconds)")
parser.add_option( "-o", "--outfile", dest="outfile", default="payload-time-port.data",
type="string", help="name of the output file (default: payload-time-port.data)")
self.opts, args = parser.parse_args(sys.argv[0:])
self.set_opts_logevel()
if len(args) < 3:
sys.stderr.write("no pcap file argument given, exiting\n")
sys.exit(ExitCodes.EXIT_CMD_LINE)
self.captcp.print_welcome()
self.captcp.pcap_file_path = args[2]
self.logger.info("pcap file: %s" % (self.captcp.pcap_file_path))
def process_packet(self, ts, packet):
try:
ip = packet
tcp = packet.data
except AttributeError:
self.logger.warning("Packet at %s could not be parsed, skipping" % ts)
return
if type(tcp) != TCP:
return
time = Utils.ts_tofloat(ts - self.cc.capture_time_start)
if self.trace_start == None:
self.trace_start = time
self.time_offset = time
self.next_sampling_boundary = time + float(self.opts.sampling)
if time > self.next_sampling_boundary:
self.next_sampling_boundary = time + float(self.opts.sampling)
if self.next_sampling_boundary - self.time_offset not in self.data:
self.data[self.next_sampling_boundary - self.time_offset] = dict()
dport = int(tcp.dport)
sport = int(tcp.sport)
if dport not in self.data[self.next_sampling_boundary - self.time_offset]:
self.data[self.next_sampling_boundary - self.time_offset][dport] = dict()
self.data[self.next_sampling_boundary - self.time_offset][dport]["cnt"] = 0
self.data[self.next_sampling_boundary - self.time_offset][dport]["sum"] = 0
self.data[self.next_sampling_boundary - self.time_offset][dport]["sum"] += len(packet)
self.data[self.next_sampling_boundary - self.time_offset][dport]["cnt"] += 1
if sport not in self.data[self.next_sampling_boundary - self.time_offset]:
self.data[self.next_sampling_boundary - self.time_offset][sport] = dict()
self.data[self.next_sampling_boundary - self.time_offset][sport]["cnt"] = 0
self.data[self.next_sampling_boundary - self.time_offset][sport]["sum"] = 0
self.data[self.next_sampling_boundary - self.time_offset][sport]["sum"] += len(packet)
self.data[self.next_sampling_boundary - self.time_offset][sport]["cnt"] += 1
def print_data(self):
for timesortedtupel in sorted(self.data.iteritems(), key = lambda (k,v): float(k)):
time = timesortedtupel[0]
for port in range(PayloadTimePortMod.PORT_END + 1):
if port in timesortedtupel[1]:
avg = float(timesortedtupel[1][port]["sum"]) / float(timesortedtupel[1][port]["cnt"])
sys.stdout.write(str(time) + " " + str(port) + " " + str(avg) + "\n")
else:
pass
sys.stdout.write(str(time) + " " + str(port) + " " + str(PayloadTimePortMod.DEFAULT_VAL) + "\n")
sys.stdout.write("\n")
def process_final(self):