View/Open - Sacramento

advertisement
NETWORK SNIFFER
Anuj Shah
B.E., K. J. Somaiya College of Engineering, 2008
PROJECT
Submitted in partial satisfaction of
the requirements for the degree of
MASTER OF SCIENCE
in
COMPUTER SCIENCE
at
CALIFORNIA STATE UNIVERSITY, SACRAMENTO
SPRING
2011
NETWORK SNIFFER
A Project
by
Anuj Shah
Approved by:
__________________________________, Committee Chair
Chung-E Wang, Ph.D.
__________________________________, Second Reader
Senad Busovaca, Ph.D.
____________________________
Date
ii
Student: Anuj Shah
I certify that this student has met the requirements for format contained in the University
format manual, and that this project is suitable for shelving in the Library and credit is to
be awarded for the Project.
__________________________, Graduate Coordinator
Nik Faroughi, Ph.D.
Department of Computer Science
iii
________________
Date
Abstract
of
NETWORK SNIFFER
by
Anuj Shah
This is the age of computers, where the world has come so close to each other and no
place in this planet is far anymore. However, few years back the name computer
implies to a machine that could transform information in a purposeful way. It was
supposed to be meant for Scientists, or professors for their research works and
complex calculations. Nevertheless, the definition of computers have been revised and
used as a tool for communication, calculation, processing, designing and much more.
The ability of computers to communicate with each other has made many of the
impossible concepts like networking, data sharing possible but, with the mentioned
advantages, they also come with some disadvantages or threats like data integrity loss,
virus attacks and many more.
In these circumstances, it is highly important to monitor the network for the suspicious
activities to prevent any kind of data attack. Sniffing is a technique of monitoring and
capturing packets across the network. A sniffer can be a software or a hardware that
iv
can monitor the network traffic coming in and out of the Network Interface Card of a
machine where the tool has been installed. Further, it can analyze more about the
packets, and disclose much needed information like the source addresses, by which we
can track the source of various network anomalies.
In this project, we built a system that will allow a user to monitor the data flowing
across a network and parse packets like TCP, IP, DNS, ARP and many more. It can
capture packets on the network and analyze them further with respect to the source
addresses, destination addresses, payload etc. Some of the key features would be the
ability to capture both IPV4 and IPV6 packets, ability to capture packets from both the
wired and wireless networks. The captured information can be decoded from raw
digital form into a human-readable format that permits users of the tool to easily
review data information.
_______________________, Committee Chair
Chung-E Wang, Ph.D.
_______________________
Date
v
ACKNOWLEDGEMENTS
I take this opportunity to express my gratitude towards my guide Prof. Chung-E Wang of
the Computer Science Department, California State University, Sacramento for his
constant encouragement and guidance.
Actually, his enthusiasm in the progress and development of my software constantly kept
me on the go, and encouraged me to put in my best efforts. There were moments when I
felt like things could not have been worse, and there seemed to be no ray of hope
anywhere! I felt like giving up. But there was just one force that kept me going, and that
was the “NEVER SAY DIE” attitude that he gave me.
Lastly, I also express my gratitude towards the teaching & non-teaching staff of the
Computer Science Department, California State University, Sacramento who directly &
indirectly contributed their efforts & helped me for making this project a grand success.
vi
TABLE OF CONTENTS
Page
Acknowledgments....................................................................................................... vi
List of Tables .............................................................................................................. ix
List of Figures ............................................................................................................... x
Chapter
1. INTRODUCTION …………..…………………………………….…………….. 1
1.1 Project Objective ............................................................................................. 2
1.2 Project Implementation ................................................................................... 2
1.3 Project Study.................................................................................................... 3
2. BACKGROUND OF THE STUDY ....................................................................... 4
2.1 Review of Research ......................................................................................... 4
3. OVERVIEW OF THE TECHNOLOGIES USED ................................................. 8
3.1 .NET Framework ……………………………………………………………. 8
3.1.1 Introduction to .NET Framework …..................................................... 8
3.1.2 Features ………………………………………………………………. 9
3.1.3 Architecture …………………………………………………………. 11
3.2 WinPcap Library …………………………………………………………… 12
3.2.1 Introduction to WinPcap Library ……………………………………. 12
3.2.2 Features ……………………………………………………………… 13
3.3 SharpPcap Library ………………………………………………………….. 15
3.3.1 Introduction to SharpPcap Library ....................................................... 15
3.3.2 Features ……………………………………………………………… 15
4. OVERVIEW OF DATA STRUCTURES AND CONCEPTS............................... 16
4.1 Sockets ……………………………………………………………………… 16
4.2 Protocol Suite and Packet Formats …………………………………………. 19
4.2.1 Internet Protocol Suite .....................................................................….. 19
4.2.2 Packet Formats ……………………………………………………….. 21
vii
4.2.2.1 Internet Protocol Version 4 (IPV4) ………………………….. 22
4.2.2.2 Internet Protocol Version 6 (IPV6) ………………………….. 31
4.2.2.3 Transmission Control Protocol (TCP) ………………………. 34
4.2.2.4 User Datagram Protocol (UDP) ……………………………... 38
5.
PROJECT IMPLEMENTATION ………………………………………………. 41
5.1 Application Functions ………………………………………………………. 42
5.1.1 Start the packet capture ……………………………………………….. 42
5.1.1.1 Select the interface for the packet capture ………………….. 42
5.1.1.2 Start the packet capture ……………………………………... 44
5.1.2 Stop the packet capture ……………………………………………….. 45
5.1.3 Save the current capture results in a file ……………………………… 45
5.1.4 Load the previous capture results …………………………………….. 47
5.1.5 Clear the Screen ………………………………………………………. 48
5.1.6 Exit the Application ………………………………………...………… 48
6.
CONCLUSION AND FUTURE WORK …………………………………….… 49
References ……………………..…………………………………………………….. 50
Appendix …………………………..………………………………………………… 52
viii
LIST OF TABLES
Page
1.
Table 2.1 Comparison of available Packet Analyzer .…………..……………….. 6
2.
Table 4.1 IPV4 Options within the header ………………………………......... 30
3.
Table 4.2 List of protocols …………………………………………………….. 31
ix
LIST OF FIGURES
Page
1.
Figure 1.1 Computer Network ………….………………………………………. 1
2.
Figure 2.1 WireShark Network Analyzer …………..…………………………... 7
3.
Figure 3.1 .NET Architecture ……….…………………………………………. 11
4.
Figure 4.1 Socket Communication Cycle ……………………………………… 16
5.
Figure 4.2 Internet Protocol Suite ……………………………………………… 19
6.
Figure 4.3 IPV4 Packet Format ………………………………………………... 23
7.
Figure 4.4 IPV6 Packet Format ………………………………………………... 32
8.
Figure 4.5 TCP Packet Format ………………………………………………… 34
9.
Figure 4.6 UDP Packet Format ………………………………………………... 38
10.
Figure 5.1 Home Screen ……………………………………………………….. 41
11.
Figure 5.2 Interface Selection Screen ………………………………………….. 43
12.
Figure 5.3 Packet Capture Screen ……………………………………………… 44
13.
Figure 5.4 Save Capture Results Screen ……………………………………….. 46
14.
Figure 5.5 Load Previous Capture Results Screen ……………………………... 47
x
1
Chapter 1
INTRODUCTION
A Network sniffer can be defined as a computer software or a hardware that can intercept
and log the traffic flowing over a digital network. As the data flows over the network, the
sniffer can capture packets and analyze them on different grounds.
Depending on the network, we can capture packets from the entire network or from
certain parts of the network. The basic components in a network are computers, switches,
hubs, firewall etc. Capturing of just certain
packets from the whole network can be achieved
with the help of hubs or switches, which can
separate different networks from each other. [17]
Figure 1.1 Computer Network
Some of the privileges that a network sniffer can provide are: [17]

Filter the harmful data from network.

Analyze network problem.

Detect network attacks.

Monitor bandwidth utilization.

Log the network traffic.
2
1.1 Project Objective
As discussed above, network sniffer is used to protect the network and log the packet
information if needed. The objective of the project was to retrieve the information of the
packets flowing on to the network. The current version of network sniffer can parse
through TCP, IP, UDP and DNS packets to retrieve different information as the source
addresses, destination addresses, the header length, the version, fragmentation offset etc.
1.2 Project Implementation
1. I researched about the current scenario and the specifications that are provided by
the current system. Requirements were also analyzed for the desired system.
2. Also studied and implemented concepts like socket programming, .NET API,
Packet formats etc.
3. Implemented the system for one protocol type, tested it for efficiency and
correctness. After evaluating, completed the needful revisions required and then
continued with implementing other protocols.
3
1.3 Project Study
1. I understood the basics of a packet-capturing tool. Studied the principles on which
the tool works.
2. Also understood the .NET concepts such as Delegates, Asynchronous calls etc…
3. Understood the class libraries of PacketDotNet and SharpPcap.
4. Studied how the sockets talk with each other, understood how they listen to the
network and also implement some basic socket programs to get the basics right.
5. I implemented the system for one protocol type and tested the system for its
throughput.
6. Integrated this system with all the other protocols and performed the integration
testing and the user testing.
4
Chapter 2
BACKGROUND OF THE STUDY
2.1 Review of Research
We are in the age of computers where computers are not just being used as machines,
which can perform complex calculations; instead, they are now the pillars for students
who learn and enhance their skills working on them, for industries who completely
depend on these machines to calculate their daily expenses, their daily data, for the
scientists who carried out different researches and have reached the moon. We can safely
say that computers are the necessity for any individual to survive, to excel and to learn in
their day-to-day life.
However, every invention has its advantages and disadvantages and computers are no
exception to it. With the rise of computer usage and networks there has been a significant
rise in cybercrime, hacking, spoofing, Virus bombing and many more. Cybercrime,
hacking, spoofing is a state when an individual or a group of individuals try to intercept
or disturb a computer network for several reasons like to get important and confidential
information about others, tries to steal a person's identity or even attempts to disrupt
operations with malicious programs.[2]
5
In this situation, it is highly recommended and required to have a system, which can
protect you and your networks from such unwanted entities. I was inspired to built such a
system to protect ourselves. There are many similar systems providing with different
advantages and configurations like Microsoft Network Monitor, Ether Ape, Packet View
Pro and many more but, one of the most inspiring factors for me choosing this project
definition was the company known as ‘WireShark’. WireShark is the company, which
develops software like network protocol analyzer. Their immense contribution in this
field from last 12 years has motivated me to develop such an application. [2]
Some of the features provided by WireShark are: [3]

Live capture and offline analysis

Standard three-pane packet browser

Multi-platform: Runs on Windows, Linux, OS X, Solaris, FreeBSD, NetBSD, and
many others

Captured network data can be browsed via a GUI, or via the TTY-mode TShark
utility

The most powerful display filters in the industry

Rich VoIP analysis

Capture files compressed with gzip can be decompressed on the fly

Live data can be read from Ethernet, IEEE 802.11, PPP/HDLC, ATM, Bluetooth,
USB, Token Ring, Frame Relay, FDDI, and others
6
Table 2.1 Comparison of available Packet Analyzers [6]
Creator
GUI /
Console
Cost
(USD)
Software
license
ACE Analyst
OPNET Technologies
GUI
Unknown
Proprietary
EULA
Cain and Abel
Massimiliano Montoro
GUI
Free
Freeware
Capsa Network Analyzer
Colasoft
GUI
Free
Proprietary
EULA
Carnivore
Federal Bureau of
Investigation
?
N/A
N/A
Clarified Analyzer
Clarified Networks
GUI
300€ and
up
Proprietary
EULA
dSniff
Dug Song
Console
Free
BSD License
EtherApe
Juan Toledo
GUI
Free
GNU GPL
Ettercap
ALoR and NaGA
Both
Free
GNU GPL
I/O Ninja
Tibbo Technology Inc.
GUI
$30
Proprietary
EULA
Kismet
Mike Kershaw
(dragorn)
Console
Free
GNU GPL
LANMeter
Fluke Corporation
handheld
?
?
netsniff-ng
Daniel Borkmann
Console
Free
GNU GPL
ngrep
Jordan Ritter
Console
Free
Other
Microsoft Network Monitor
Microsoft
GUI
Free
Proprietary
EULA
Observer
Network Instruments
GUI
?
Proprietary
EULA
OmniPeek (formerly AiroPeek,
EtherPeek)
WildPackets
GUI
$1,194.00
and up
Proprietary
EULA
PacketView Pro
Klos Technologies, Inc.
Console
$1,299.00
Proprietary
EULA
pt360 Tool Suite
Packet Trap
?
$99
?
snoop
Sun Microsystems
Console
Free
CDDL
tcpdump
The Tcpdump team
Console
Free
BSD License
Wireshark (formerly Ethereal)
The Wireshark team
Both
Free
GNU GPL
Xplico
The Xplico team
Both
Free
GNU GPL
7
Figure 2.1 WireShark Network Analyzer
8
Chapter 3
OVERVIEW OF THE TECHNOLOGIES USED
In this chapter, the technologies used to implement the project are discussed in detail.
Packet sniffer is a windows based application. The application has been written in C#, on
the Microsoft .NET framework. Windows Packet Capture Library (WinPcap) is used for
the standard methods and functions for the packet capture. Additional to the WinPcap,
the application makes use of SharpPcap, which is a framework for the .NET environment.
The purpose of this library is to provide API for the capturing, analyzing building packets
using the .NET language.
3.1 .NET Framework: [18]
3.1.1 Introduction to .NET Framework:
Microsoft .NET is a software framework for windows operating systems. It has huge set
of classes that supports many programming languages. These classes are available to all
the programming languages that .NET supports as they are interoperable with each other.
9
3.1.2
Features:
Interoperability:
A computer system has to communicate with different programming platforms and
versions. Interoperability is one of the most important features of .NET framework,
which allows the applications to communicate with each other even if they are written in
different language or if the versions are different.
Common Language Runtime Engine:
The heart of .NET processing is the Common Language Runtime (CLR), which acts as an
execution engine. All .NET applications are executed under the supervision of CLR that
ensures execution of certain properties and behaviors of memory management, security
and exception handling.
Language Independence:
Common Type System (CTS) introduces language independence in .NET framework. It
consists of all possible data types and data structures that are supported by CLR and how
they may or may not interact with each other conforming to the specifications defined by
Common Language Infrastructure (CLI). This enables the exchange of different types and
objects instances between applications written in any .NET language.
10
Base Class Library:
The Base Class Library (BCL) is the part of Framework Class Library (FCL), is the
library of functionality available to all .NET languages. BCL incorporates different
classes that include number of common functions, including file reading and writing,
graphics, database interaction and so on.
Simplified Deployment:
.NET framework includes design features and tools that help manage the software
installations and any conflicts with the previous installations and ensure the proper
security.
Security:
Buffer overflow is one of the most common vulnerabilities that have been exposed by the
malicious software. .NET provides a common security model for all applications.
Portability:
Portability ensures that the program, which is used to write the framework, should run
without any changes on any type of system that implements the same framework. The
design of .NET framework allows the application to be almost cross platform compatible.
Class libraries, Common Type System and Common Intermediate Language are the
specifications, which Microsoft submitted to both the ECMA and ISO, making them open
standards.
11
3.1.3
Architecture:
Figure 3.1 .NET Architecture
Common Language Infrastructure:
The Common Language Infrastructure provides language independent platform for
application development and execution. CLI also ensures that the core aspects of .NET
framework are not limited to a single language, but are available across all languages
supported by the framework. The implementation of Common Language Infrastructure is
known as the Common Language Runtime.
12
3.2
WinPcap Library: [4] [5] [19]
3.2.1
Introduction to WinPcap Library:
WinPcap is the industry-standard tool for link-layer network access in Windows
environments: it allows applications to capture and transmit network packets bypassing
the protocol stack, and has additional useful features, including kernel-level packet
filtering, a network statistics engine and support for remote packet capture.
WinPcap consists of a driver that extends the operating system to provide low-level
network access, and a library that is used to easily access the low-level network layers.
This library also contains the Windows version of the well-known libpcap Unix API.
Thanks to its set of features, WinPcap is the packet capture and filtering engine of many
open source and commercial network tools, including protocol analyzers, network
monitors, network intrusion detection systems, sniffers, traffic generators and network
testers. Some of these tools, like Wireshark, Nmap, Snort, ntop are known and used
throughout the networking community.
13
3.2.2
Features:
Free. WinPcap is released under the BSD open source license. This means that you have
total freedom to modify and use it with your application, even if it is commercial. The
binary and source code are available.
High performance. WinPcap implements all of the classic optimizations described in the
packet capture literature (e.g., kernel-level filtering and buffering, context switch
mitigation, partial packet copy), plus some original ones, like JIT filter compilation and
kernel-level statistic processing. For these reasons, WinPcap outperforms other
comparable approaches.
Popular. WinPcap is used as the network interface by many tools -- both free and
commercial including protocol analyzers, network monitors, network intrusion detection
systems, sniffers, traffic generators, network testers, etc. Some of these tools,
like Wireshark, Nmap, Snort, WinDump, ntop are very well known in the networking
community. WinPcap is downloaded thousands of times every day.
Tested and Reliable. Many users have contributed over the years in testing WinPcap on
a wide range of platforms, and in finding the most subtle bugs. WinPcap developers are
experienced Windows driver writers, and their approach to software development
emphasizes rock-solid stability. Remember: a buggy driver means blue screens.
14
Easy to use for the final user. WinPcap is distributed as a single small executable that
runs on every supported operating system. You launch the executable, and from that
moment Windows is able to capture and send raw network traffic. It couldn't be easier.
Easy to use for the programmer. Every version of WinPcap comes with a developer's
pack that includes documentation, libraries and includes files needed to immediately start
with your own new application. The developer's pack contains a set of sample programs
ready to be compiled both with Visual Studio and Cygnus, and are available as excellent
starting points.
Multi-platform. WinPcap is actively maintained on Windows NT, Windows 2000,
Windows XP and Windows Server 2003. WinPcap can also work on Windows 95,
Windows 98 and Windows ME, but these OSes are not maintained any longer. Windows
Vista has a preliminary support, with some features disabled.
Portable. WinPcap is completely compatible with libpcap. This means that you can use it
to port your existing Unix or Linux tools to Windows. This also means that your
Windows applications will be easily portable to Unix.
15
3.3
SharpPcap Library: [12] [13]
3.3.1
Introduction to SharpPcap Library:
SharpPcap is a packet capture framework for the .NET environment, based on the
famous WinPcap component. The purpose of this library is to provide an API for
capturing, injecting, analyzing and building packets using any .NET language such as C#
and VB.NET.
3.3.2
Features:
Enumerating and showing details about physical network interface on a
Windows machine.
Capturing low-level network packets going through a given interface.
Analyzing
and
parsing
the
following
protocols: Ethernet, ARP, IP,
TCP, UDP, ICMP, IGMP.
Injecting low-level network packets on a given interface.
Handling (reading and writing) offline packet capture files.
Injecting packets using Send Queues.
Collecting network statistics on a given network interface.
16
Chapter 4
OVERVIEW OF DATA STRUCTURE AND CONCEPTS
The system uses many data structures as sockets, delegates, tree structures, packet
formats and many more but I will try to explain the two main data structures or concepts
used in my system.
4.1 Sockets: [1]
Sockets can be defined as an endpoint of a bidirectional communication flow across an
Internet Protocol based computer network. One of the simplest examples would be
internet. Sockets can deliver incoming packets to the appropriate application process. It
does this with the help of the local and remote IP addresses. Sockets can communicate
with operating system with the help of threads or application processes.
Here is an example of socket and its communication cycle:
Figure 4.1 Socket Communication Cycle
17
These following functions or methods are used in my system:
1. Socket()
2. Bind()
3. SetSocketOption()
4. IOControl()
5. BeginReceive()
6. Close()
1. Socket(): The Socket method creates a new socket of a particular type and also
allocates system resources for the same. An integer number uniquely identifies it. A
common practice to define a socket is using Socket(AddressFamily, SocketType,
ProtocolType).
The method parameters are defined by the name itself:

The AddressFamily define the family of the socket, which it belongs to.
Example: IPX, AppleTalk, FireFox

The SocketType defines the type of the socket. Example: Stream, Raw

The ProtocolType option indicates the socket type. Example: IPV4, IPV6, TCP
2. Bind(): The Bind method usually binds the socket to a specified protocol or a socket
address structure.
18
3. SetSocketOption(): This method sets the socket options to the specified Boolean
value. Most common method declaration is SetSocketOption(SocketOptionLevel,
SocketOptionName, Boolean)
The method parameters are defined as:
 SocketOptionLevel defines the socket type as IP, TCP.
 SocketOptionName defines the configuration option names
 Boolean decides the values of the above parameter to be true or false.
4. IOControl(): This method is used to define the low level operating modes for the
socket. This method can also define the control codes for the socket.
5. BeginReceive(): The BeginReceive method starts receiving asynchronous data from
the connected socket.
6. Close(): The close method closes the socket and releases the system resources.
19
4.2 Protocol Suite and Packet Formats:
4.2.1 Internet Protocol Suite: [11]
Internet
has
many
communication
protocols
commonly known as the Internet Protocol Suite or
TCP/IP. The internet protocol suite consists of four
abstraction layers; from lower to higher is the Link
Layer,
Internet
Layer,
Transport
Layer
and
Application Layer.
The Link Layer is the lowest layer in the protocol
suite. It contains protocols that operate only on the
host’s link. It is the medium to link with the other
Figure 4.2 Internet Protocol Suite
hosts or nodes in the same network and provides standard methods and functions that
operate between nodes on the Local area network. The link layer is often described as the
combination of the Physical and the Data Link Layer of the OSI layer. Some of the few
protocols in this layer are ARP, DSL, ISDN, PPP, OSPF and many more.
20
Next is the Internet Layer who is responsible for the transfer of the packets from the
host machine to the target machine. The target machine is identified by the network
address. The internet layer derives its name from the functionality it provides, which is
internetworking between multiple hosts.
The three basic functions which internet layer provides are:
For outgoing packets, search for the appropriate path for this packet to reach its
destination. In other words, you can say that it has to decide the next hop or the
next address that the packet has to travel to reach the destination.
For incoming packets, capture that packet and pass the packet payload to the
transport layer protocol. Other functions it provides the incoming packet is error
detection and diagnostic capability.
In IPV4, during both the incoming and the transmitting phase, IP is capable of
providing additional fragmentation and defragmentation of packets based on the
Maximum Transmission Unit (MTU) of elements. However, in IPV6, this feature
has been dropped and the internet layer is not responsible for the reliable
transmission as it only provides unreliable transmission and best effort delivery.
The function of providing reliable service is of higher-level protocols, which are
the Transmission Control Protocol (TCP) in the Transportation Layer.
The primary protocols in the Internet Layer are the Internet Protocol (IP), which has two
versions of implementation IPV4 and IPV6.
21
Transport Layer is the next upper level to the Internet Layer. This layer provides endto-end communication services between two applications. Some of the services provided
by the transport layer are connection-oriented data stream, data reliability, flow control
and multiplexing. The most well-known transport protocol is the Transmission Control
Protocol (TCP). Transmission control protocol enables connection-oriented service
between two hosts while Datagram Protocol provides with connectionless service. TCP is
more reliable than UDP but UDP is faster than TCP.
Application Layer is at the highest level of the Internet protocol suite. This layer has a
huge collection of application-oriented protocols. It uses the underlying transport layer
protocols to establish connections between two hosts. Some of the protocols in
application layer are Telnet for Remote Login, FTP and TFTP for File transfer, SMTP for
Electronic Mail services, DNS, RARP, BOOTP and many more for other support
services.
4.2.2 Packet Formats:
As described earlier, packets are the medium through which the data can be transferred
over the network between multiple hosts. These packets can differ from layers to layers,
they differ in structure and the operations. I shall explain you some of the most common
packet formats which are used in internetworking.
22
4.2.2.1 Internet Protocol version 4 (IPV4) [9]
It is the fourth version of the Internet protocol. IPV4 is still the most widely deployed
internet layer protocol. IPV4 is connectionless protocol so it works on the best effort
delivery model. In best effort model, it does not guarantee delivery, nor does it not assure
proper sequencing or any duplicate delivery of the packets. IPV4 uses 32-bit addresses,
which limits the address space to 232 possible unique addresses.
The below is the IPV4 Packet Format:
bit
offset
0–3
4–7
8–13
14-15
0
Version
Header
Length
Differentiated
Services Code
Point
Explicit
Congestion
Notification
Identification
32
64
Time to Live
16–
18
19–31
Total Length
Flags
Protocol
96
Source IP Address
128
Destination IP Address
160
Options ( if Header Length > 5 )
Fragment Offset
Header Checksum
23
160
or
192+
Data
Figure 4.3 IPV4 Packet Format
Version:
The first header field in an IP packet is the four-bit version field. For IPv4, this has a
value of 4 (hence the name IPv4).
Internet Header Length (IHL):
The second field (4 bits) is the Internet Header Length (IHL) telling the number of 32bit words in the header. Since an IPv4 header may contain a variable number of options,
this field specifies the size of the header (this also coincides with the offset to the data).
The minimum value for this field is 5, which is a length of 5×32 = 160 bits = 20 bytes.
Being a 4-bit value, the maximum length is 15 words (15×32 bits) or 480 bits = 60 bytes.
Differentiated Services Code Point (DSCP)
Originally defined as the Type of Service field, this field is now defined
for Differentiated services (DiffServ). New technologies are emerging that requires realtime data streaming and therefore will make use of the DSCP field. An example is Voice
over IP (VoIP) that is used for interactive data voice exchange.
24
Explicit Congestion Notification (ECN)
It allows end-to-end notification of network congestion without dropping packets. ECN is
an optional feature that is only used when both endpoints support it and are willing to use
it. It is only effective when supported by the underlying network.
Total Length
This 16-bit field defines the entire datagram size, including header and data, in bytes. The
minimum-length datagram is 20 bytes (20-byte header + 0 bytes data) and the maximum
is 65,535 bytes — the maximum value of a 16-bit word. The minimum size datagram that
any host is required to be able to handle is 576 bytes, but most modern hosts handle
much larger packets. Sometimes sub networks impose further restrictions on the size, in
which case datagrams must be fragmented. Fragmentation is handled in either the host or
the packet switch in IPv4.
Identification
This field is an identification field and is primarily used for uniquely identifying
fragments of an original IP datagram. Some experimental work has suggested using the
ID field for other purposes, such as for adding packet-tracing information to datagrams in
order to help trace back datagrams with spoofed source addresses.
25
Flags
A three-bit field follows and is used to control or identify fragments. They are (in order,
from high order to low order):

bit 0: Reserved; must be zero.

bit 1: Don't Fragment (DF)

bit 2: More Fragments (MF)
If the DF flag is set and fragmentation is required to route the packet then the packet will
be dropped. This can be used when sending packets to a host that does not have sufficient
resources to handle fragmentation. It can also be used for Path MTU Discovery, either
automatically by the host IP software, or manually using diagnostic tools such as ping
or traceroute.
When a packet is fragmented all fragments have the MF flag set except the last fragment,
which does not have the MF flag set. The MF flag is also not set on packets that are not
fragmented — an unfragmented packet is its own last fragment.
Fragment Offset
The fragment offset field, measured in units of eight-byte blocks, is 13 bits longand
specifies the offset of a particular fragment relative to the beginning of the original
26
unfragmented IP datagram. The first fragment has an offset of zero. This allows a
maximum offset of (213 – 1) × 8 = 65,528 bytes which would exceed the maximum IP
packet length of 65,535 bytes with the header length included (65,528 + 20 = 65,548
bytes).
Time To Live (TTL)
An eight-bit time to live field helps prevent datagrams from persisting (e.g. going in
circles) on an internet. This field limits a datagram's lifetime. It is specified in seconds,
but time intervals less than 1 second are rounded up to 1. In latencies typical in practice,
it has come to be a hop count field. Each router that a datagram crosses decrements the
TTL field by one. When the TTL field hits zero, the packet is no longer forwarded by a
packet switch and is discarded. Typically, an ICMP message (specifically the time) is
sent back to the sender to inform it that the packet has been discarded. The reception of
these ICMP messages is at the heart of how traceroute works.
27
Protocol
This field defines the protocol used in the data portion of the IP datagram. The Internet
Assigned Numbers Authority maintains a list of IP protocol numbers.
Header Checksum
The 16-bit checksum field is used for error checking of the header. At each hop, the
checksum of the header must be compared to the value of this field. If a header checksum
is found to be mismatched, then the packet is discarded. Note that errors in the data field
are up to the encapsulated protocol to handle — indeed; both UDP and TCP have
checksum fields.
Since the TTL field is decremented on each hop and fragmentation is possible at each
hop then at each hop the checksum will have to be recomputed. The method used to
compute the checksum.
The checksum field is the 16-bit one's complement of the one's complement sum of all
16-bit words in the header. For purposes of computing the checksum, the value of the
checksum field is zero.
In other words, all 16-bit words are summed together using one's complement (with the
checksum field set to zero). The sum is then one is complemented and this final value is
inserted as the checksum field.
28
For example, use Hex 45000030442240008006442e8c7c19acae241e2b (20 bytes IP
header):
4500 + 0030 + 4422 + 4000 + 8006 + 0000 + 8c7c + 19ac + ae24 + 1e2b = 2BBCF
2 + BBCF = BBD1 = 1011101111010001, the 1'S of sum = 0100010000101110 = 442E
To validate a header's checksum the same algorithm may be used - the checksum of the
header with the checksum field filled in should be a word containing all zeros (value 0).
Source address
An IPv4 address is a group of four octets for a total of 32 bits. The value for this field is
determined by taking the binary value of each octet and concatenating them together to
make a single 32-bit value.
For
example,
the
address
10.9.8.7
would
be
00001010000010010000100000000111.
This address is the address of the sender of the packet. Note that this address may not be
the "true" sender of the packet due to network address translation. Instead, the source
address will be translated by the NATing machine to its own address. Thus, reply packets
sent by the receiver are routed to the NATing machine, which translates the destination
address to the original sender's address.
29
Destination address
Identical to the source address field but indicates the receiver of the packet.
Options
Additional header fields may follow the destination address field, but these are not often
used. Note that the value in the IHL field must include enough extra 32-bit words to hold
all the options (plus any padding needed to ensure that the header contains an integral
number of 32-bit words). The list of options may be terminated with an EOL (End of
Options List, 0x00) option; this is only necessary if the end of the options would not
otherwise coincide with the end of the header. The possible options that can be put in the
header are as follows:
Table 4.1 IPV4 Options within the header
Size
(bits)
Field
Description
Copied
1
Set to 1 if the options need to be copied into all fragments of a
fragmented packet.
Option
Class
2
A general options category. 0 is for "control" options, and 2 is for
"debugging and measurement". 1, and 3 are reserved.
Option
Number
5
Specifies an option.
30
Option
Length
8
Indicates the size of the entire option (including this field). This field
may not exist for simple options.
Option Data Variable Option-specific data. This field may not exist for simple options.
Note: If the Header Length is greater than 5, i.e. it is between 6-15, it means that
the Options field is present and must be considered.
Note: the Copied, Option Class, and Option Number are sometimes referred to as
a single eight-bit field - the Option Type.
The use of the LSRR and SSRR options (Loose and Strict Source and Record Route) is
discouraged because they create security concerns; many routers block packets
containing these options.
Data
The data field is not a part of the header and, consequently, is not included in the
checksum field. The format of the data field is specified in the protocol header field and
can be any one of the transport layer protocols.
Some of the common protocols are listed below including their value used in the protocol
field:
31
Table 4.2 List of protocols
Protocol Number
Protocol Name
Abbreviation
1
Internet Control Message Protocol
ICMP
2
Internet Group Management Protocol
IGMP
6
Transmission Control Protocol
TCP
17
User Datagram Protocol
UDP
41
IPv6 encapsulation
-
89
Open Shortest Path First
OSPF
132
Stream Control Transmission Protocol
SCTP
4.2.2.2 Internet Protocol version 6 (IPV6) [10]
It is the 6th version of the Internet protocol implementation. The internet operated by
transmitting data in the form of small packets which travel from source to destination
host by the help of many communication protocols known as Internet protocol. Each data
packet has two numeric addresses, which resembles the source, and destination addresses.
IPV4 has been widely implemented throughout many years and hence created the need
32
for more numerical addresses. IPV6 has been in the picture for the same picture and
intended to solve the shortage of the internet protocols addresses.
IPV6 uses 128-bit addresses, so the new address space is approximately about 2128 bit
addresses. IPV6 also implements additional features like the address assignment and
network renumbering.
The below is the IPV6 Packet Format:
Figure 4.4 IPV6 Packet Format
33
The IPv6 packet is composed of two parts: the packet header and the payload. The header
consists of a fixed portion with minimal functionality required for all packets and may
contain optional extension to implement special features.
The fixed header occupies the first 40 octets (320 bits) of the IPv6 packet. It contains the
source and destination addresses, traffic classification options, a hop counter, and a
pointer for extension headers if any. The Next Header field, present in each extension as
well, points to the next element in the chain of extensions. The last field points to the
upper-layer protocol that is carried in the packet's payload.
Extension headers carry options that are used for special treatment of a packet in the
network, e.g., for routing, fragmentation, and for security using the IPSec framework.
The payload can have a size of up to 64KiB without special options or larger with a
jumbo payload option in a Hop-By-Hop Options extension header.
Unlike in IPv4, fragmentation is handled only in the end points of a communication
session; routers never fragment a packet, and hosts are expected to use Path MTU
Discovery to select a packet size that can traverse the entire communications path.
34
4.2.2.3 Transmission Control Protocol (TCP) [8]
Many applications rely on the transmission control protocol for the services required by
them. Some of the applications are the World Wide Web, e-mail, file transfer and many
more. TCP is connection oriented and a reliable protocol.
Below is the packet format of transmission control protocol:
TCP Header
Bit
offs
et
1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
Source port
0
Destination port
32
Sequence number
64
Acknowledgment number
96
128
160
...
Data
offset
Reserved
C E U A P R S F
W C R C S S Y I
R E G K H T N N
Checksum
Options (if Data Offset > 5)
...
Figure 4.5 TCP Packet Format
Window Size
Urgent pointer
padding
35
Source port (16 bits) – identifies the sending port
Destination port (16 bits) – identifies the receiving port
Sequence number (32 bits) – has a dual role:
If the SYN flag is set (1), then this is the initial sequence number. The sequence number
of the actual first data byte and the acknowledged number in the corresponding ACK are
then this sequence number plus 1.
If the SYN flag is clear (0), then this is the accumulated sequence number of the first data
byte of this packet for the current session.
Acknowledgment number (32 bits) – if the ACK flag is set then the value of this field is
the next sequence number that the receiver is expecting. This acknowledges receipt of all
prior bytes (if any). The first ACK sent by each end acknowledges the other end's initial
sequence number itself, but no data.
Data offset (4 bits) – specifies the size of the TCP header in 32-bit words. The minimum
size header is 5 words and the maximum is 15 words thus giving the minimum size of 20
bytes and maximum of 60 bytes, allowing for up to 40 bytes of options in the header.
This field gets its name from the fact that it is also the offset from the start of the TCP
segment to the actual data.
36
Reserved (4 bits) – for future use and should be set to zero
Flags (8 bits) – contains 8 1-bit flags
CWR (1 bit) – Congestion Window Reduced (CWR) flag is set by the sending host to
indicate that it received a TCP segment with the ECE flag set and had responded in
congestion control mechanism.
ECE (1 bit) – ECN-Echo indicates
If the SYN flag is set (1), that the TCP peer is ECN capable.
If the SYN flag is clear (0), that a packet with Congestion Experienced flag in IP header
set is received during normal transmission.
URG (1 bit) – indicates that the Urgent pointer field is significant
ACK (1 bit) – indicates that the Acknowledgment field is significant. All packets after
the initial SYN packet sent by the client should have this flag set.
PSH (1 bit) – Push function. Asks to push the buffered data to the receiving application.
RST (1 bit) – Reset the connection
37
SYN (1 bit) – Synchronize sequence numbers. Only the first packet sent from each end
should have this flag set. Some other flags change meaning based on this flag, and some
are only valid for when it is set, and others when it is clear.
FIN (1 bit) – No more data from sender
Window size (16 bits) – the size of the receive window, which specifies the number of
bytes (beyond the sequence number in the acknowledgment field) that the receiver is
currently willing to receive.
Checksum (16 bits) – The 16-bit checksum field is used for error-checking of the header
and data
Urgent pointer (16 bits) – if the URG flag is set, then this 16-bit field is an offset from
the sequence number indicating the last urgent data byte
Options (Variable 0-320 bits, divisible by 32) – The length of this field is determined
by the data offset field. Options 0 and 1 are a single byte (8 bits) in length. The remaining
options indicate the total length of the option (expressed in bytes) in the second byte.
38
Padding – The TCP header padding is used to ensure that the TCP header ends and data
begins on a 32-bit boundary. The padding is composed of zeros.
4.2.2.4 User Datagram Protocol (UDP) [7]
User Datagram protocol is a connectionless protocol compared to transmission control
protocol, but this results in faster delivery than TCP. UDP is used in scenarios where the
prompt delivery is needed rather than security or reliability.
Below is the UDP packet format:
bits
0 – 15
16 – 31
0
Source Port Number
Destination Port Number
32
Length
Checksum
Data
64
Figure 4.6 UDP Packet Format
The UDP header consists of 4 fields, each of which is 2 bytes (16 bits). The use of two of
those is optional in IPv4 (pink background in table). In IPv6, only the source port is
optional.
39
Source port number
This field identifies the sender's port when meaningful and should be assumed to be the
port to reply to if needed. If not used, then it should be zero. If the source host is the
client, the port number is likely to be an ephemeral port number. If the source host is the
server, the port number is likely to be a well-known port number.
Destination port number
This field identifies the receiver's port and is required. Similar to source port number, if
the client is the destination host then the port number will likely be an ephemeral port
number and if the destination host is the server then the port number will likely be a wellknown port number.
Length
A field that specifies the length in bytes of the entire datagram: header and data. The
minimum length is 8 bytes since that is the length of the header. The field size sets a
theoretical limit of 65,535 bytes (8-byte header + 65,527 bytes of data) for a UDP
datagram. The practical limit for the data length which is imposed by the
underlying IPv4 protocol is 65,507 bytes (65,535 − 8 byte UDP header − 20 byte IP
header).
40
Checksum
The checksum field is used for error checking of the header and data. If the transmitter
generates no checksum, the field uses the value all-zeros. This field is not optional for
IPv6.
41
Chapter 5
PROJECT IMPLEMENTATION
This chapter aims to explain all the functions, which are provided by this application.
Every function is explained with a screenshot and a pseudo function or an algorithm,
which allows the users to gauge the functionality of the same. As you know by now that,
this application is used for packet capturing and analyzing them. To use this application,
users have to first install the WinPcap class library to aid the packet capturing.
Below is the home screen of the application.
Figure 5.1 Home Screen
42
5.1 Functions Offered by the Application:
Below are the functions that are offered by the application to the users:
Start the packet capture.
Stop the current packet capturing.
Save the current capture results in a file.
Load the previous capture results.
Clear the screen.
Exit the application.
5.1.1 Start the packet capture:
5.1.1.1 Select the interface for the packet capture:
Before a user clicks the start button, the user has to select the interface from which he
wants the packets to be captured. This application supports both the wired internet
connection and the wireless internet support. The dropdown list just below the start
button populates itself based on the interfaces, which the host machine can support.
Below image shows the options from which user can select one:
43
Figure 5.2 Interface Selection Screen
The above image shows us two options, the first option is the wireless interface and the
second one is the wired interface. For the time being, we will select the first option.
The pseudo for populating the supporting interfaces is:
//Initialize the dropdown list
Clear the existing list
//Populate the list with the available devices
LivePcapDeviceList deviceList = LivePcapDeviceList.Instance;
//Check if the host device is in that deviceList
If Client device matches device in the deviceList
Then add that device in the dropdown List
44
5.1.1.2 Start the packet capture:
A user can now click the start button to start the packet capture. The start functionality
will begin the packet capture from the network and will list the captured packets in the
window below it. The below resultant screen can be observed after the Start functionality
has been initiated:
Figure 5.3 Packet Capture Screen
The pseudo for the packet capture start is:
//Initialize the packet capture window and set the packet count to zero
45
//Check for the network interface match
If the selected interface supports the LivePcapDeviceList
Then Start capturing packets on the currently selected network interface
Else, dump an error message for inappropriate network device
5.1.2 Stop the packet capture:
Stopping the current packet capture is pretty much simple where it stops the capture and
initializes the packet count to zero and does bit of housekeeping work as buttons
handling.
5.1.3 Save the current capture results in a file:
The application has another feature where the user can save their current results for future
use and for network tracking. User has to just choose a location where he wants the user
wants to save the file. The extension of the saved file would be .cap.
46
Figure 5.4 Save Capture Results Screen
For saving the results in a file the application performs these steps:
//Sets the Save file dialog
Opens the save file dialog.
Applies the filter and the extension to .cap file
//Opens the dump file and dumps the data in it.
Opens the file in a generic pcap dump file
For each packet in the current result
Saves that packet in that generic dump file
//Close the generic dump file and save the resultant file
47
5.1.4 Load the previous capture results:
The load functionality is pretty much similar to the save where the user just needs to
select the file which he/she wants to load.
The method that loads the file is:
//Initialize the Open file dialog
Set the filter and the default extension to .cap
//Set the generic offline pcap dump file (OfflinePcapDevice) with the saved file.
Open the created dump file
For every packet in the saved file
Check and add them to the packet buffer
Figure 5.5 Load Previous Capture Results Screen
48
5.1.5 Clear the screen:
Clear functionality just clears all the buffers and windows to the initial position.
5.1.6 Exit the Application:
It is same as the above with one additional step where it closes the window instance to
exit the application.
49
Chapter 6
CONCLUSION AND FUTURE WORK
Introduce new features like port scanning and analyze more on the packets.
Built the software to the next level, which will also act as a firewall and not just sniffer.
Extend the support for other operating systems like Linux, Solaris and many others.
Configure some kind of notification alerts for any abnormal activities.
Add filtering of packets for the display purposes.
50
REFERENCES
[1]
MSDN Library – Sockets [Online].
Available: http://msdn.microsoft.com/en-s/library/system.net.sockets.socket.aspx
[2]
WireShark [Online].
Available: http://www.wireshark.org/
[3]
WireShark [Online].
Available: http://www.wireshark.org/about.html
[4]
WinPcap [Online].
Available: http://www.winpcap.org/default.htm
[5]
WinPcap Features [Online].
Available: http://www.winpcap.org/misc/features.htm
[6]
Comparison of Packet Analyzers [Online].
Available: http://en.wikipedia.org/wiki/Comparison_of_packet_analyzers
[7]
User Datagram Protocol [Online].
Available: http://en.wikipedia.org/wiki/User_Datagram_Protocol
[8]
Transmission Control Protocol [Online].
Available: http://en.wikipedia.org/wiki/Transmission_Control_Protocol
[9]
Internet Protocol Version 4 (IPV4) [Online].
Available: http://en.wikipedia.org/wiki/IPv4
[10]
Internet Protocol Version 6 (IPV6) [Online].
Available: http://en.wikipedia.org/wiki/IPv6
[11]
Internet Protocol Suite [Online].
Available: http://en.wikipedia.org/wiki/Internet_Protocol_Suite
[12]
SharpPcap [Online].
Available: http://www.tamirgal.com/blog/page/SharpPcap.aspx
[13]
SharpPcap [Online].
http://sourceforge.net/apps/mediawiki/sharppcap/index.php?title=Main_Page
51
[14]
Internet Layer of TCP/IP [Online].
Available: http://www.softpanorama.org/Net/Internet_layer/index.shtml
[15]
MSDN Library [Online].
Available: http://msdn.microsoft.com/en-us/library/ms817899.aspx
[16]
IP Address Types [Online].
http://www.softpanorama.org/Net/Internet_layer/index.shtml#IP_Address_Types
[17]
Packet Analyzer [Online].
Available: http://en.wikipedia.org/wiki/Packet_analyzer
[18]
.NET Framework [Online].
Available: http://en.wikipedia.org/wiki/.NET_Framework
[19]
WinPcap [Online].
Available: http://www.winpcap.org/docs/default.htm
[20]
SharPpcap API Calls [Online].
Available: http://sharppcap.sourceforge.net/htmldocs/index.html
[21]
Packet Colors [Online].
Available: http://linuxgazette.net/issue65/padala.html
[22]
SharPpcap [Online].
Available: http://www.tamirgal.com/home/SourceView.aspx?Item=SharpPcap
52
APPENDIX
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SharpPcap;
using System.Collections;
using PacketDotNet;
using System.Reflection;
using PacketDotNet.Utils;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace CaptureApplication
{
public partial class Form1 : Form
{
private ArrayList packets;
private delegate void AsyncUpdateList();
private AsyncUpdateList UpdateList;
private PcapDevice pDev; //
public Form1()
{
InitializeComponent();
RefreshDeviceCombo();
packets = new ArrayList(5000);
UpdateList = new AsyncUpdateList(DoUpdate);
}
private void DoUpdate()
{
if (dgPacketView.InvokeRequired)
{
dgPacketView.Invoke(UpdateList);
return;
}
dgPacketView.RowCount = packets.Count;
if (dgPacketView.RowCount > 0)
53
{
dgPacketView.FirstDisplayedScrollingRowIndex = dgPacketView.RowCount -1 ;
}
}
private void RefreshDeviceCombo()
{
cmbDevices.Items.Clear();
LivePcapDeviceList devList = LivePcapDeviceList.Instance;
foreach (LivePcapDevice dev in devList)
{
cmbDevices.Items.Add(dev.Description);
}
cmbDevices.SelectedIndex = 0;
}
private void dgPacketView_CellValueNeeded(object sender,
DataGridViewCellValueEventArgs e)
{
if (e.RowIndex == -1 || e.ColumnIndex == -1) { e.Value = ""; return; }
if (e.ColumnIndex == colSeqNo.Index)
{
e.Value = e.RowIndex;
return;
}
try
{
Packet p = Packet.ParsePacket((RawPacket)packets[e.RowIndex]);
Color fore = new Color();
Color back = new Color();
if (e.ColumnIndex == colTime.Index)
{
e.Value = p.Timeval.ToString();
return;
}
if (p is EthernetPacket)
{
ShowPacket((EthernetPacket)p, ref e);
}
54
else
{
e.Value = p.ToColoredVerboseString(false);
this.GetColorFromString(ref fore, ref back, p.Color);
dgPacketView.Rows[e.RowIndex].DefaultCellStyle.BackColor = fore;
}
}
catch (Exception ex)
{
lblStatusMain.Text = "Error decoding packet: " + ex.Message;
e.Value = ex.Message;
}
}
private void ShowPacket(EthernetPacket ethernetPacket, ref
DataGridViewCellValueEventArgs e)
{
try
{
Packet pPlain = ethernetPacket;
while (pPlain.PayloadPacket != null)
{
pPlain = pPlain.PayloadPacket;
}
Color fore = new Color();
Color back = new Color();
this.GetColorFromString(ref fore, ref back, pPlain.Color);
dgPacketView.Rows[e.RowIndex].DefaultCellStyle.BackColor = fore;
if (e.ColumnIndex == colProto.Index)
{
PropertyInfo pi = null;
while (pi == null && pPlain!=null)
{
pi = pPlain.GetType().GetProperty("Protocol");
if (pi == null) { pPlain = pPlain.ParentPacket; }
}
if (pi == null)
{
int ix1 = ethernetPacket.ToColoredVerboseString(false).IndexOf("proto=");
if (ix1 == -1)
{
e.Value = ethernetPacket.GetType().Name.ToString();
55
return;
}
ix1 += 6;
int ix2 = ethernetPacket.ToColoredVerboseString(false).IndexOf(" ", ix1);
if (ix2 == -1)
{
e.Value = ethernetPacket.GetType().Name.ToString();
return;
}
e.Value = ethernetPacket.ToColoredVerboseString(false).Substring(ix1, ix2 ix1).ToUpper();
return;
}
e.Value = pi.GetValue(pPlain, null).ToString();
return;
}
if (ethernetPacket.PayloadPacket is IpPacket)
{
IpPacket p = (IpPacket)ethernetPacket.PayloadPacket;
if (e.ColumnIndex == colSrcIP.Index)
{
e.Value = p.SourceAddress.ToString();
return;
}
if (e.ColumnIndex == colDstIP.Index)
{
e.Value = p.DestinationAddress.ToString();
return;
}
if (e.ColumnIndex == colInfo.Index)
{
e.Value = p.ToColoredString(false);
return;
}
}
else
{
if (e.ColumnIndex == colSrcIP.Index)
{
e.Value = ethernetPacket.SourceHwAddress.ToString();
return;
}
56
if (e.ColumnIndex == colDstIP.Index)
{
e.Value = ethernetPacket.DestinationHwAddress.ToString();
return;
}
if (e.ColumnIndex == colInfo.Index)
{
e.Value = ethernetPacket.ToColoredVerboseString(false);
return;
}
}
}
catch (Exception ex)
{
lblStatusMain.Text = ex.Message;
}
}
private void tsButtonCaptureStart_Click(object sender, EventArgs e)
{
dgPacketView.RowCount = 0;
packets.Clear();
DoUpdate();
treePacket.Nodes.Clear();
txtPacketString.Text = "";
string devName = (string) cmbDevices.Items[cmbDevices.SelectedIndex];
LivePcapDeviceList devList = LivePcapDeviceList.Instance;
foreach (LivePcapDevice dev in devList)
{
if (dev.Description == devName)
{
StartCapture(dev);
return;
}
}
MessageBox.Show("No such device", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
private bool GetColorFromString(ref Color ForeGround, ref Color Background, string
escape)
{
ForeGround = Color.Black;
Background = Color.White;
57
while (true)
{
if (escape == AnsiEscapeSequences.Black)
{
ForeGround = Color.Black;
break;
}
if (escape == AnsiEscapeSequences.Blue)
{
ForeGround = Color.Blue;
break;
}
if (escape == AnsiEscapeSequences.Brown)
{
ForeGround = Color.Brown;
break;
}
if (escape == AnsiEscapeSequences.Cyan)
{
ForeGround = Color.Cyan;
break;
}
if (escape == AnsiEscapeSequences.DarkGray)
{
ForeGround = Color.DarkGray;
break;
}
if (escape == AnsiEscapeSequences.Green)
{
ForeGround = Color.Green;
break;
}
if (escape == AnsiEscapeSequences.LightBlue)
{
ForeGround = Color.LightBlue;
break;
}
if (escape == AnsiEscapeSequences.LightCyan)
{
ForeGround = Color.LightCyan;
break;
}
if (escape == AnsiEscapeSequences.LightGray)
{
ForeGround = Color.LightGray;
break;
58
}
if (escape == AnsiEscapeSequences.LightGreen)
{
ForeGround = Color.LightGreen;
break;
}
if (escape == AnsiEscapeSequences.LightPurple)
{
ForeGround = Color.LightSalmon;
break;
}
if (escape == AnsiEscapeSequences.LightRed)
{
ForeGround = Color.LightPink;
break;
}
if (escape == AnsiEscapeSequences.Purple)
{
ForeGround = Color.Purple;
break;
}
if (escape == AnsiEscapeSequences.Red)
{
ForeGround = Color.Red;
break;
}
if (escape == AnsiEscapeSequences.White)
{
ForeGround = Color.White;
break;
}
if (escape == AnsiEscapeSequences.Yellow)
{
ForeGround = Color.Yellow;
break;
}
break;
}
while (true)
{
if (escape == AnsiEscapeSequences.YellowBackground)
{
Background = Color.Yellow;
break;
}
if (escape == AnsiEscapeSequences.RedBackground)
59
{
Background = Color.Red;
break;
}
if (escape == AnsiEscapeSequences.PurpleBackground)
{
Background = Color.Purple;
break;
}
if (escape == AnsiEscapeSequences.LightGrayBackground)
{
Background = Color.LightGray;
break;
}
if (escape == AnsiEscapeSequences.GreenBackground)
{
Background = Color.Green;
break;
}
if (escape == AnsiEscapeSequences.CyanBackground)
{
Background = Color.Cyan;
break;
}
if (escape == AnsiEscapeSequences.BlueBackground)
{
Background = Color.Blue;
break;
}
break;
}
return true;
}
private bool StartCapture(PcapDevice dev)
{
if (dev.Opened)
{
try
{
dev.StopCapture();
dev.Close();
}
catch (Exception ex)
{
60
}
}
dev.OnPacketArrival += new PacketArrivalEventHandler(dev_OnPacketArrival);
dev.OnCaptureStopped += new CaptureStoppedEventHandler(dev_OnCaptureStopped);
dev.OnPcapStatistics += new StatisticsModeEventHandler(dev_OnPcapStatistics);
try
{
tsButtonCaptureStart.Enabled = false;
tsButtonStop.Enabled = true;
dev.Open();
dev.StartCapture();
pDev = dev;
}
catch (Exception ex)
{
MessageBox.Show("Error Starting Capture :" + ex.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
tsButtonCaptureStart.Enabled = true;
tsButtonStop.Enabled = false;
return false;
}
return true;
}
void dev_OnPcapStatistics(object sender, StatisticsModeEventArgs e)
{
}
void dev_OnCaptureStopped(object sender, CaptureStoppedEventStatus status)
{
try
{
lblStatusMain.Text = status.ToString();
tsButtonCaptureStart.Enabled = true;
tsButtonStop.Enabled = false;
pDev.Close();
}
catch (Exception ex)
{
tsButtonCaptureStart.Enabled = true;
tsButtonStop.Enabled = false;
lblStatusMain.Text = ex.Message;
}
61
}
void dev_OnPacketArrival(object sender, CaptureEventArgs e)
{
if (pDev.Equals(e.Device))
{
packets.Add(e.Packet);
UpdateList();
}
}
private void tsButtonStop_Click(object sender, EventArgs e)
{
try
{
tsButtonCaptureStart.Enabled = true;
tsButtonStop.Enabled = false;
pDev.StopCaptureTimeout = new TimeSpan(0, 0, 5);
pDev.StopCapture();
}
catch (Exception ex)
{
tsButtonCaptureStart.Enabled = true;
tsButtonStop.Enabled = false;
pDev.StopCapture();
pDev.Close();
lblStatusMain.Text = ex.Message;
}
pDev.Close();
}
private void dgPacketView_SelectionChanged(object sender, EventArgs e)
{
try
{
if (dgPacketView.SelectedRows.Count <= 0) { return; }
Packet p =
Packet.ParsePacket((RawPacket)packets[dgPacketView.SelectedRows[0].Index]);
string strHex = HexPrinter.GetString(p.Bytes, 0, p.Bytes.Length);
strHex = strHex.Replace('[', ' ');
strHex = strHex.Replace(']', ' ');
strHex = strHex.ToUpper();
txtPacketString.Text = strHex;
62
treePacket.Nodes.Clear();
TreeNode root = new TreeNode();
root.Text = p.GetType().Name;
Type t = p.GetType();
PropertyInfo[] Xpi = t.GetProperties();
foreach (PropertyInfo pi in Xpi)
{
if (pi.CanRead && !pi.PropertyType.IsArray & !pi.PropertyType.IsAbstract)
{
if (pi.Name.Contains("Color") || pi.Name.Contains("BytesHighPerformance"))
{
continue;
}
TreeNode tn = new TreeNode();
root.Nodes.Add(tn);
object o = pi.GetValue(p, null);
if (o != null)
{
tn.Text = pi.Name + ": " + o.ToString();
}
}
}
p = p.PayloadPacket;
TreeNode lastNode = root;
while (p != null)
{
t = p.GetType();
TreeNode tNew = new TreeNode();
tNew.Text = t.Name;
lastNode.Nodes.Add(tNew);
Xpi = t.GetProperties();
foreach (PropertyInfo pi in Xpi)
{
if (pi.CanRead && !pi.PropertyType.IsArray && !pi.PropertyType.IsAbstract)
{
{
if (pi.Name.Contains("Color") || pi.Name.Contains("BytesHighPerformance"))
{
continue;
}
63
TreeNode tn = new TreeNode();
tNew.Nodes.Add(tn);
object o = pi.GetValue(p, null);
if (o != null)
{
tn.Text = pi.Name + ": " + o.ToString();
}
}
}
lastNode = tNew;
p = p.PayloadPacket;
}
treePacket.Nodes.Add(root);
}
catch (Exception ex)
{
lblStatusMain.Text = "Error: " + ex.Message;
}
}
private void dgPacketView_CellContentClick(object sender, DataGridViewCellEventArgs
e)
{
}
private void tsBtnSaveToFile_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = ".cap";
sfd.Filter = "Capture File(*.cap)|*.cap";
sfd.AddExtension = true;
DialogResult dr = sfd.ShowDialog();
bool wasOpen = false;
if (dr == DialogResult.OK)
{
try
{
if (!pDev.Opened)
{
pDev.Open();
}
64
else
{
wasOpen = true;
}
pDev.DumpOpen(sfd.FileName);
foreach (RawPacket p in packets)
{
pDev.Dump(p);
}
pDev.DumpFlush();
pDev.DumpClose();
lblStatusMain.Text = sfd.FileName + " saved";
}
catch (Exception ex)
{
MessageBox.Show("Error saving file: " + ex.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!wasOpen)
{
pDev.Close();
}
}
}
private void btnLoadFromFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.DefaultExt=".cap";
ofd.Filter = "Capture File(*.cap)|*.cap";
DialogResult dr = ofd.ShowDialog();
dgPacketView.RowCount = 0;
packets.Clear();
if(dr == DialogResult.OK)
{
try
{
OfflinePcapDevice opd = new OfflinePcapDevice(ofd.FileName);
opd.Open();
while (true)
{
RawPacket p;
65
opd.GetNextPacket(out p);
if (p == null)
{
break;
}
else
{
packets.Add(p);
}
}
opd.Close();
DoUpdate();
}
catch (Exception ex)
{
MessageBox.Show("Error loading file: " + ex.Message, "Error",
MessageBoxButtons.OK);
return;
}
}
}
private void copySelectedPacketsToolStripMenuItem_Click(object sender, EventArgs e)
{
Clipboard.Clear();
string data="";
foreach (DataGridViewRow r in dgPacketView.SelectedRows)
{
foreach (DataGridViewCell c in r.Cells)
{
data += c.Value.ToString() + " ";
}
data += "\r\n";
}
Clipboard.SetText(data);
}
private void toolStripBtnClear_Click(object sender, EventArgs e)
{
packets.Clear();
UpdateList();
treePacket.Nodes.Clear();
66
txtPacketString.Text = "";
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
try
{
tsButtonCaptureStart.Enabled = true;
tsButtonStop.Enabled = false;
pDev.StopCaptureTimeout = new TimeSpan(0, 0, 5);
pDev.StopCapture();
}
catch (Exception ex)
{
tsButtonCaptureStart.Enabled = true;
tsButtonStop.Enabled = false;
if (pDev != null)
{
pDev.StopCapture();
pDev.Close();
}
lblStatusMain.Text = ex.Message;
}
Application.Exit();
}
}
}
Download