Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def add(self, ts, buf, eth):
'''
ts = dpkt timestamp
buf = original packet data
eth = dpkt.ethernet.Ethernet, whether its real Ethernet or from SLL
'''
#decide based on pkt.data
# if it's IP...
if (isinstance(eth.data, dpkt.ip.IP) or
isinstance(eth.data, dpkt.ip6.IP6)):
ip = eth.data
# if it's TCP
if isinstance(ip.data, dpkt.tcp.TCP):
tcppkt = tcp.Packet(ts, buf, eth, ip, ip.data)
self.tcp.add(tcppkt)
# if it's UDP...
elif isinstance(ip.data, dpkt.udp.UDP):
self.udp.add(ts, ip.data)
tcp_pkts_malformed = 0L
of10_in_pkts_malformed = 0L
of10_out_pkts_malformed = 0L
of13_in_pkts_malformed = 0L
of13_out_pkts_malformed = 0L
try:
for _, pkt in pcap.pcap(name=ifname, immediate=False):
eth = dpkt.ethernet.Ethernet(pkt)
if hasattr(eth.data, 'data'):
tcp = eth.data.data
else:
continue
if type(tcp) != dpkt.tcp.TCP:
tcp_pkts_malformed += 1
continue
# do not further analyze the packet if it does not have any
# OpenFlow payload
payload = tcp.data
nbytes = len(payload)
if nbytes <= 1:
continue
# element 0: packet count
# element 1: total packet bytes
if tcp.dport == int(ofport):
of_in_counts[0] += 1
of_in_counts[1] += nbytes
elif tcp.sport == int(ofport):
for ts, buf in pcap:
eth = dpkt.ethernet.Ethernet(buf)
if eth.type != dpkt.ethernet.ETH_TYPE_IP:
continue
ip = eth.data
if not isinstance(ip, dpkt.ip.IP):
try:
ip = dpkt.ip.IP(ip)
except:
continue
if ip.p != dpkt.ip.IP_PROTO_TCP:
continue
tcp = ip.data
if not isinstance(tcp, dpkt.tcp.TCP):
try:
tcp = dpkt.tcp.TCP(tcp)
except:
continue
tupl = (ip.src, ip.dst, tcp.sport, tcp.dport)
if tupl in streams:
streams[tupl] = streams[tupl] + tcp.data
else:
streams[tupl] = tcp.data
if (tcp.flags & dpkt.tcp.TH_FIN) != 0 and \
(tcp.dport == 80 or tcp.sport == 80) and \
len(streams[tupl]) > 0:
other_tupl = (ip.dst, ip.src, tcp.dport, tcp.sport)
stream1 = streams[tupl]
seg = ip.data
'''
if isinstance(seg, dpkt.tcp.TCP):
try:
seg2 = flow[1].data.data
except IndexError:
return None
if not (seg.flags & dpkt.tcp.TH_SYN and seg2.flags & dpkt.tcp.TH_SYN):
return None
proto = "tcp"
flow = flow[3:] # срезаем tcp handshake
elif isinstance(seg, dpkt.udp.UDP):
proto = "udp"
'''
if isinstance(seg, dpkt.tcp.TCP):
proto = "tcp"
try:
seg2 = flow[1].data.data
except IndexError:
return None
# check if there is SYN flag in first 2 packets:
if (seg.flags & dpkt.tcp.TH_SYN and seg2.flags & dpkt.tcp.TH_SYN):
flow = flow[3:] # cut out the tcp handshake
elif isinstance(seg, dpkt.udp.UDP):
proto = "udp"
else:
raise ValueError("Unknown transport protocol: `{}`".format(
seg.__class__.__name__))
if strip > 0:
def _filter_packets(source):
for timestamp, raw in source:
eth = dpkt.ethernet.Ethernet(raw)
ip = eth.data
if not isinstance(ip, dpkt.ip.IP):
continue
seg = ip.data
if isinstance(seg, (dpkt.tcp.TCP, dpkt.udp.UDP)):
yield timestamp, ip, seg
connection["dst"] = socket.inet_ntoa(ip.dst)
elif isinstance(ip, dpkt.ip6.IP6):
connection["src"] = socket.inet_ntop(socket.AF_INET6,
ip.src)
connection["dst"] = socket.inet_ntop(socket.AF_INET6,
ip.dst)
else:
offset = file.tell()
continue
self._add_hosts(connection)
if ip.p == dpkt.ip.IP_PROTO_TCP:
tcp = ip.data
if not isinstance(tcp, dpkt.tcp.TCP):
tcp = dpkt.tcp.TCP(tcp)
connection["sport"] = tcp.sport
connection["dport"] = tcp.dport
if len(tcp.data) > 0:
self._tcp_dissect(connection, tcp.data)
src, sport, dst, dport = (
connection["src"], connection["sport"], connection["dst"], connection["dport"])
if not ((dst, dport, src, sport) in self.tcp_connections_seen or (
src, sport, dst, dport) in self.tcp_connections_seen):
self.tcp_connections.append((src, sport, dst, dport, offset, ts - first_ts))
self.tcp_connections_seen.add((src, sport, dst, dport))
elif ip.p == dpkt.ip.IP_PROTO_UDP:
udp = ip.data
if not isinstance(udp, dpkt.udp.UDP):
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
"""
Extracts TCP streams with data from the pcap file. TCP segments in
each stream are queued according to their sequence number.
"""
with open(self.filepath) as pcap_file:
pcap_reader = dpkt.pcap.Reader(pcap_file)
for timestamp, buf in pcap_reader:
try:
frame = dpkt.ethernet.Ethernet(buf)
except dpkt.dpkt.UnpackError:
continue
ip_pkt = frame.data
if (not isinstance(ip_pkt, dpkt.ip.IP) and
not isinstance(ip_pkt, dpkt.ip6.IP6)):
continue
if not isinstance(ip_pkt.data, dpkt.tcp.TCP):
continue
ip_ver = socket.AF_INET
if ip_pkt.v == 6:
ip_ver = socket.AF_INET6
tcp_pkt = ip_pkt.data
stream_id = (
socket.inet_ntop(ip_ver, ip_pkt.src),
tcp_pkt.sport,
socket.inet_ntop(ip_ver, ip_pkt.dst),
tcp_pkt.dport
)
if len(tcp_pkt.data) > 0:
timestamp = int(timestamp * 1000) # in ms
self.streams[stream_id].put(
(tcp_pkt.seq, (timestamp, tcp_pkt)))
logging.info("Streams: %d", len(self.streams))
conn["unacked"].append((seq, payload))
conn["seq"] += len(payload)
bflags = tcp_dump_flags(flags)
estimated_ts_val = self.timers[conn["ip_src"]].get_time()
if estimated_ts_val is None or estimated_ts_val == 0:
estimated_ts_val = conn.get("last_ts_val", 0)
ts_val = struct.pack("!I", estimated_ts_val)
ts_ecr = struct.pack("!I", conn.get("ts_ecr", 0))
tcp_opts_list = [
(dpkt.tcp.TCP_OPT_TIMESTAMP, ts_val + ts_ecr)
]
if "S" in flags:
tcp_opts_list += conn["syn_options"].items()
tcp_opts = tcp_dump_opts(tcp_opts_list)
pkt = dpkt.tcp.TCP(
sport=conn["sport"],
dport=conn["dport"],
seq=seq,
ack=ack,
flags=bflags,
win=conn.get("win", dpkt.tcp.TCP_WIN_MAX),
)
pkt.opts = tcp_opts
pkt.off += len(tcp_opts) / 4
if payload is not None:
pkt.data = payload
if self.debug:
self.log("TCP {}{} {:.3f} {}:{:<5}->{}:{:<5} {:<4} seq={:<3} ({:<10}) ack={:<3} ({:<10}) data=[{:<4}]{:8} tsval={} tsecr={}",
"->", "AB"[dst],
time.clock(),
self.name = "SF|SR Probe to Open Port"
self.expect = "detect.output.1"
# Packet 1
payload = TCP(sport=555, dport=80, seq=10000,
flags=dnet.TH_SYN|dnet.TH_RST)
ip = IP(src=dnet.ip_aton("192.0.2.1"),
dst=dnet.ip_aton("192.18.0.10"),
id=5624,
p=dnet.IP_PROTO_TCP)
ip.data = payload
ip.len += len(ip.data)
self.packets.append(ip)
# Packet 2
payload = TCP(sport=556, dport=80, seq=10000,
flags=dnet.TH_SYN|dnet.TH_FIN)
ip = IP(src=dnet.ip_aton("192.0.2.1"),
dst=dnet.ip_aton("192.18.0.10"),
id=5625,
p=dnet.IP_PROTO_TCP)
ip.data = payload
ip.len += len(ip.data)
self.packets.append(ip)