tcp session logger
TRANSCRIPT
-
8/7/2019 TCP Session Logger
1/9
TCP Session Logger
Nertwork sniffer
Dan Huru, Mihaita Catalin Barbu, Metin GemilComputer Science and Engineering Department
University Politehnica of Bucharest
Romania
{Danut.Huru, Mihaita.Barbu,Metin.Gemil}@gmail.com
January 2011
AbstractIn this project we propose a network sniffer that can act
as a detection system and an efficient provider of informatios. The
use of the TCP session logger as a network sniffer is necessary
when there is a need to analyse traffic on the network. TCPSL
makes use of its features to sniff, document and issue alarms for
the incoming and outgoing traffic of the local machine.
Keywords - sniffer, protocol, TCP, monitoring, detetion.
I. INTRODUCTIONThe TCP session logger is a software application that
detects different issues in your tcp traffic by obtaining,manipulating and interpreting data from open tcp sessions.Tcp session logger listens on an interface and tracks all TCPsessions it sees. Normally, only general information iscarried forward (seq#/ack#, negotiated SYN/ACK features,etc). Whenever an anomaly happens - that is a duplicateACK, SACK response, out-of-order segment, retransmissionor others; it captures those packets into a tcpdump file for
later deep inspection. This tool is to be deployed on livehosts and passive monitors to collect reliable condensed dataabout real-world behavior of TCP on the global Internet.
Complexity and heterogeneity are hallmarks of networkservices today, such as switched networks, load-balancedconfigurations, redundant segments, virtual circuits, andtechnology improvements to achieve higher speed deliverytransport, e.g. 10Gigabit Ethernet or OC-48. A solution thatprovides comprehensive support throughout such mixedenvironments, regardless of topology, across the core,distribution, and access areas of the network is essential.
Monitoring solutions must profile traffic in a manner thatreflects not only the physical network but also the logicalflows of applications as they utilize these services.
Best practices in network monitoring must include thefollowing:
Incorporation of multiple intelligent data source types:
Performance data can be retrieved from a wide array of
sources, each offering a different level of granularity (see
Data Sources). Rather than individual management
solutions to handle each data source type, a performance
management solution should incorporate all types, taking
advantage of the strengths of each to provide an overall
picture of the network and its applications. In doing so, a
significant level of investment protection can be achieved
by leveraging existing data sources where available and
adding advanced instrumentation where greater levels of
detail and application visibility are required particularly
for the most costly and highest utilized network segments.
Coverage of a broad range of topologies: Today's globalnetworks are built from diverse network topologies in the
core, distribution, access and storage areas of the network.
To ensure consistent visibility throughout the enterprise, the
performance management solution should support a full
range of topologies, including those in the WAN and LAN,
and those that will be grown into or migrated to, such as
MPLS or 10Gigabit Ethernet.
Visibility into encrypted networks: While technologies
such as VPNs and MPLS are being used for security, among
other purposes, the challenge is that it also obscures the
detailed data most network professionals require for
troubleshooting and traffic engineering. The performance
management product must have a solution for seeing the
details, including the applications that are traversing these
secure links.
Visibility into QoS and other complex network
configurations: Network configurations are becoming
increasingly complex. Deployments such as Quality of
Service implementations, redundant WAN links for fault
tolerance, and Fast EtherChannel and Gigabit EtherChannel
configurations for load balancing have been introduced to
help improve network efficiency. A performance
management solution must transparently measure and report
upon the network activity in aggregate across such
configurations while also retaining the detail of what traffic,
i.e., applications, is flowing across each individual link or
service class.Visibility into virtual networks: Most networks today
use some form of virtual network technology, typically seen
as VLANs in the LAN, PVCs or DLCIs in the WAN, and
subnets or VRFs in MPLS networks. A performance
management solution must quantify traffic by virtual
network and should provide a full set of application and
volume performance statistics for each virtual segment.
mailto:Metin.Gemil%[email protected]:Metin.Gemil%[email protected]:Metin.Gemil%[email protected]:Metin.Gemil%[email protected] -
8/7/2019 TCP Session Logger
2/9
Continuous 24x7 monitoring that supports real-time and
historical analysis: The performance management solution
must continuously monitor, collect, display and store
information in multiple time frames to meet the needs of the
key performance management tasks. Real-time information
is required for status monitoring and troubleshooting, while
longer-term historical metrics are stored for capacity
planning, trend analysis, baselining, and forecasting.
A. Transmission Control ProtocolThe TCP provides the service of exchanging data
directly between two hosts on the same network, whereas IP
handles addressing and routing message across one or more
networks.
A packet is a sequence of octets and consists of a header
followed by a body. The header describes the packet's
destination and, optionally, the routers to use for forwarding
until it arrives at its destination while the body contains the
data IP is transmitting.
Transmission Control Protocol accepts data from a data
stream, into chunks, and adds a TCP header creating a TCP
segment. The segment is then encapsulated into an IP
packet.TCP also uses the notion of port numbers to identify
sending and receiving application end-points on a host, orInternet sockets. Each side of a TCP connection has anassociated 16-bit unsigned port number (0-65535) reservedby the sending or receiving application.
Arriving TCP data packets are identified as belonging to
a specific TCP connection by its sockets, that is, the
combination of source host address, source port, destination
host address, and destination port. This means that a server
computer can provide several clients with several services
simultaneously, as long as a client takes care of initiatingany simultaneous connections to one destination port from
different source ports.
Port numbers are categorized into three basic categories:
well-known, registered, and dynamic or private. The well-
known ports are assigned by the Internet Assigned Numbers
Authority (IANA) and are typically used by system-level or
root processes. Well-known applications running as servers
and passively listening for connections typically use these
ports. Some examples include: FTP (21), SSH (22),
TELNET (23), SMTP (25) and HTTP (80). Registered ports
are typically used by end user applications as ephemeral
source ports when contacting servers, but they can also
identify named services that have been registered by a thirdparty. Dynamic/private ports can also be used by end user
applications, but are less commonly so. Dynamic/private
ports do not contain any meaning outside of any particular
TCP connection.
Due to network congestion, traffic load balancing, or
other unpredictable network behavior, IP packets can be
lost, duplicated, or delivered out of order. TCP detects these
problems, requests retransmission of lost data, rearranges
out-of-order data, and even helps minimize network
congestion to reduce the occurrence of the other problems.
Once the TCP receiver has reassembled the sequence of
octets originally transmitted, it passes them to the
application program.TCP is optimized for accurate delivery rather than timely
delivery, and therefore, TCP sometimes incurs relativelylong delays (in the order of seconds) while waiting for out-of-order messages or retransmissions of lost messages.
B. Packet analyzerA packet analyzer (also known as a network
analyzer, protocol analyzer or sniffer) is a computer
program (or a piece of computer hardware) that can
intercept and log traffic passing over a digital network or
part of a network. As data streams flow across the network,
the sniffer captures each packet and, if needed, decodes and
analyzes its content.
The captured information is decoded from raw
digital form into a human-readable format that permits users
of the protocol analyzer to easily review the exchanged
information.A packet sniffer, which intercepts TCP traffic on a
network link, can be useful in debugging networks, network
stacks and applications that use TCP by showing the user
what packets are passing through a link. Some networking
stacks support the SO_DEBUG socket option, which can be
enabled on the socket using setsockopt. That option dumps
all the packets, TCP states, and events on that socket, which
is helpful in debugging.PCAP (packet capture) consists of an application
programming interface (API) for capturing network traffic.libpcap provide the packet-capture and filtering engines ofmany open source and commercial network tools, includingpacket sniffers (protocol analyzers), network monitors,
network intrusion detection systems, traffic-generators andnetwork-testers.
C. LibpcapLibpcap is an open source library that provides a
high level interface to network packet capture systems. It
was created in 1994 by McCanne, Leres and Jacobson
researchers at the Lawrence Berkeley National Laboratory
from University of California, at Berkeley as part of a
research project to investigate and improve TCP and
internet gateway performance.
Libpcap authors main objective was to create a
platform-independent API to eliminate the need for system
dependent packet capture modules in each aplication, asvirtually evrey OS vendor implements its own capture
mechanisms.
The libpcap API is designed to be used for C and
C++. However, there are many wappers that allow its use
from languages like Pearl, Python, Java, C# or
Ruby.Libpcap runs on most UNIX-like operating systems.
Today, libpcap is maintained by the Tcpdump Group.
libpcap also support saving captured packets to a
file, and reading files containing saved packets; applications
http://en.wikipedia.org/wiki/Internet_Assigned_Numbers_Authorityhttp://en.wikipedia.org/wiki/Internet_Assigned_Numbers_Authorityhttp://en.wikipedia.org/wiki/File_Transfer_Protocolhttp://en.wikipedia.org/wiki/Secure_Shellhttp://en.wikipedia.org/wiki/TELNEThttp://en.wikipedia.org/wiki/SMTPhttp://en.wikipedia.org/wiki/HTTPhttp://en.wikipedia.org/wiki/HTTPhttp://en.wikipedia.org/wiki/SMTPhttp://en.wikipedia.org/wiki/TELNEThttp://en.wikipedia.org/wiki/Secure_Shellhttp://en.wikipedia.org/wiki/File_Transfer_Protocolhttp://en.wikipedia.org/wiki/Internet_Assigned_Numbers_Authorityhttp://en.wikipedia.org/wiki/Internet_Assigned_Numbers_Authority -
8/7/2019 TCP Session Logger
3/9
can be written, using libpcap or WinPcap, to be able to
capture network traffic and analyze it, or to read a saved
capture and analyze it, using the same analysis code. A
capture file saved in the format that libpcap and WinPcap
use can be read by applications that understand that format,
such as tcpdump, Wireshark, CA NetMaster, or Microsoft
Network Monitor 3.x.
II. RELATED WORKPacket sniffing began with the need to obtain raw packets
across the several layers beneath the application protocol.
Normally the packets or data frames are stripped of their
headers and are passed to the upper layers. However in
promiscuous mode raw packets of lower layers can directly
be obtained alongside their headers. These samples are quite
useful to obtain the data flow patterns across the network.
This can also be used for network monitoring and
management.Much of the idea behind packet sniffing began with the
use of BSD packet filters (BPF) . Because network monitorsrun as user-level processes, packets must be copied acrossthe kernel/user-space protection boundary. This copying canbe minimized by deploying a kernel agent called a packetfilter, which discards unwanted packets as early as possible.The BSD Packet Filter (BPF) uses a redesigned, registerbased filter evaluator that can be implemented efficiently ontodays register based RISC CPU. BPF uses a simple, non-shared buffer model made possible by todays larger addressspaces.
There are many types of network sniffers. Thats why Itis necessary to consider the properties of an ideal packetsniffer. These can be summarized as shown below:
View detailed IP or MAC connections statistics: IPaddresses, ports, sessions, etc.
Display TCP sessions. Map packets to the application that is sending or
receiving them.
View application protocols distribution, bandwidthutilization, and network nodes charts and tables.
Ability to monitor traffic in real time as well asanalyze traffic reports offline
Ability to browse captured and decoded packets in realtime.
Ability to search for strings or hex data in capturedpacket contents.
Ability to import and export packets in hex and textformats from other sniffers
Ability to configure alarms that can notify aboutimportant events, such as suspicious packets, high
bandwidth utilization, unknown addresses, etc.
Ability to create custom plug-ins for decoding anyprotocol.
Ability to exchange data with other application overTCP/IP.
This are three of the primary and most useful packet
sniffers are TCPdump, Ngrep and Snoop.
1) TCPdump is the most common network debuggingand packet monitoring tool that runs under the command
line. It allows the user to intercept and display TCP/IP and
other packets being transmitted or received over a network
to which the computer is attached. TCPdump works on most
Unix-like operating systems: Linux, Solaris, BSD, Mac OS
X, HP-UX and AIX among others. In those systems,
tcpdump uses the libpcap library to capture packets. The
user may optionally apply a BPF-based filter to limit the
number of packets seen by tcpdump; this renders the output
more usable on networks with a high volume of traffic.
Tcpdump is frequently used to debug applications that
generate or receive network traffic. It can also be used for
debugging the network setup itself, by determining whether
all necessary routing is occurring properly, allowing the user
to further isolate the source of a problem.
2) Ngrep strives to provide most of GNU grep'scommon features, applying them to the network layer.Ngrep is a pcap-aware tool that will allow you to specify
extended regular or hexadecimal expressions to match
against data payloads of packets. It currently recognizes
IPv4/6, TCP, UDP, ICMPv4/6, IGMP and Raw across
Ethernet, PPP, SLIP, FDDI, Token Ring and null interfaces,
and understands BPF filter logic in the same fashion as
more common packet sniffing tools, such as tcpdump and
snoop.
Ngrep may simply feed the output of libpcap (or
tcpdump) into the regular expression parse, where the
expressions come from a file on the disk. Some even
simpler systems don't even use regular expressions and
simply compare packets with well-known byte patterns.Ngrep has traditionally been used to debug plain text
protocol interactions such as HTTP, SMTP, FTP, etc.
3) Snoop is a very flexible command line packetsniffer included as part of Sun Microsystems' Solaris
Operating System. It is pretty cable sniffer equal or better
then TCPdump.
Snoop displays packets in a single-line summary form or in
verbose multi-line forms. It can display packets as soon as
they are received or saved to a file. When snoop writes to an
intermediate file, packet loss under busy trace conditions is
unlikely. Snoop itself can be used read and interpret the file
e.g - print summary expended summary and full packets
dumps.The only disadvantage being that since it is tightly
integrated within the Solaris kernel, its use is largely limited
to Sun based systems. Though there have been hacks to port
it to other kernels like FreeBSD and Linux, most of them
have been fairly limited by number.
http://en.wikipedia.org/wiki/CA,_Inc.http://en.wikipedia.org/wiki/CA,_Inc. -
8/7/2019 TCP Session Logger
4/9
Fig. 1. Architectural Diagram
III. ARHITECTUREIn this section we provide details of the design and the
implementation of our program. The TCP Session Logger isbasically a C written sniffer that is concentrated on sniffingTCP packets and is capable of taking best practice decisionsbased on what data it has gathered over time.
A. DesignThe main logic of the program can be easily followed on the
graph below (Fig 1):
1) First, we use the packet generator software to insertseveral TCP packets over the Ethernet channel.
This way we can simulate a scenario where the
Linux guest is sustaining multiple connections that
run over the TCP protocol.
2) Meanwhile our sniffer will be in listen mode,which basically means it will constantly monitor
the ethernet channel for any new packets.
The sniffer does not need to know whether the
packets are TCP packets or not because we use thegenerator to send TCP packets only. Of course, if
we would have needed to send other type of
packets we could have introduced an additional
filter inside the sniffer, for reading TCP only. This
implementation would be needed for real scenario
purposes.
3) While cruising the ethernet channel, packets aretaken one by one by the sniffer. Afterwards the
sniffer will read the data inside and will provide the
Layer 2/3 fields necessary for further use.
4) After reading the data filters are applied. Thesefilters have the role to select only the TCP packets
we are really interested in. (e.g. ACK and NACKpackets may be filtered out if they do not
contribute in any way to our desired analysis).
5) Steps 2,3 and 4 are actually basic steps which canbe found in most sniffer implementations. The TCP
Session Logger adds a new block which is
responsible for making several decisions. This
decisions determine two new features, making use
of the best practice actions that can be taken when
dealing with networking.
6) The first one is relatively simple, but may proveitself very useful. TCPSL documents the data that
it sniffs in different formats for future data
analysis. A statistical representation of the network
data may not be very useful to an end-user system,
but it is critical when dealing with different kind of
servers, that need a proficient management of their
connections.7) The second feature consists of several decisions that
are to be taken based on the information the snifferis gathering. One example could be limiting thenumber of connections initiated or accepted by theserver when there is high network load. Also,
introducing several Qos techniques for varioustraffic could be reasonable actions.
Besides taking decisions, TCPSL could also issuedifferent kind of alarms to the administrator (by email, smsor by using monitoring tools). For example, when the snifferreceives a lot of NACK packets it could send a mail to thehuman administrator warning of a possible connectionproblem or too high traffic load.
The ability to identify a network fault and react to it, is a
also function of our aplication. The Tcp session logger
focuses on a more proactive approach to managing faults by
continuously monitoring for conditions that indicate an
emerging problem or degradation. This proactive approach
is essential to reducing mean-time-to-repair and rectifying
potential issues before end users ever notice. To supportbest practices in accelerated fault detection, our solutions
include the following:
-
8/7/2019 TCP Session Logger
5/9
Anomaly detection alarms: its automatically detectabnormal behavior. In addition we have the ability to
diagnose the anomaly to specific traffic types, or KPIs
e.g. response time and availability.
Conditional and evidence-gathering alarms: Thisgathers crucial information for troubleshooting the
problem. Response time and availability alarms: Application
response time alarms, set per application type, notify
when an application is approaching poor performance,
such as a 3 second response time for an application
that typically responds within 800 milliseconds.
Microburst alarms: Traffic microbursts can severelydisrupt the flow time-sensitive applications such as
voice over IP, streaming financial market data, or
trading applications, yet are often hard to detect or
diagnose.
Rising and falling threshold alarms: It sets thresholdsof network activity to identify resources at risk of
failure is key to staying ahead of network problems
and ensuring that networked services continue to run
smoothly. The network alarm and application statistics,
including the following alarming capabilities:
Utilization alarms: Are needed to identify potentialareas of congestion, such as 70% utilization on a
particular segment, or indicate potential failures, such
as the disappearance of traffic on a load-balanced link.
Application alarms: Thresholds on applicationutilization identify undesired traffic patterns (e.g.,
increasing amount of ICMP traffic indicating a
potential denial of service attack) or an undesired
network usage (e.g., AOL traffic).
B. EnvironmentAs a test environment we used an Ubuntu 10 Linux
platform. The main scope was to send packets using a
packet generator from a loopback interface, called loopback
0 in our case, to an ethernet interface which in our case was
ethernet0. Our sniffer would listen on ethernet0 and extract
the necessary data.
The environment design and devices used is shown in
the image below:
Packet Generator:
As mentioned before we used a GUI based packet
generator called packETH, a useful freeware tool. The
application can easily send batches of packets of many typesover the network. However, we were mostly interested in
capturing TCP traffic so we used packETH to produce
different types of TCP packets.
Resources & Programming:
TCP Session Logger is entirely written in C. The
program makes use of the libpcap library which has a
variety of functions and structures. These functions operate
at the lower level of the system and can be used to obtain
valuable functionality for any kind of traffic sniffer or
analyzer.
We also used tools like Eclipse or gcc compiler for normal
debugging of the program.
C. ImplementationSome of the most common functions used within our
program are in the table below:
Function Description
pcap_lookupdev()gets a network device suitable for
use
pcap_open_live()opens the specified network device
for packet capture
pcap_loop()reads and processes packets that are
being captured live
pcap_compile()compiles a char array which is used
as a regex for filtering traffic
pcap_filter() applies various filters to the sniffer
pcap_t
Descriptor of an open capture
instance, used when calling in
libpcap
Table 1
To start with the C program the simple steps would be:
Find all available devices find_alldevs() is the function
which can be used to get a list of all available network
devices or interfaces present on the machine or which can
be opened by pcap_open_live() for sniffing purpose.
The basic implementation of the Main function is shown
here in Fig. 2:
The prototype is as: int pcap_findalldevs(pcap_if_t
**alldevsp, char *errbuf) where alldevsp is a pointer to an
array of pcap_if_t structures and errbuf is a character
pointer and will contain any error message that occurred
during the function call.
Select a device for sniffing data pcap_open_live() is
the function to get a packet capture descriptor or a handle to
a device which has been opened up for sniffing.
The prototype is as follows:
pcap_t *pcap_open_live(const char *device, int
snaplen,int promisc, int to_ms, char *errbuf). The first
argument is the device that we specified in the previoussection. snaplen is an integer which defines the maximum
number of bytes to be captured by pcap. promisc, when set
to true, brings the interface into promiscuous mode
(however, even if it is set to false, it is possible under
specific cases for the interface to be in promiscuous mode,
anyway). to_ms is the read time out in milliseconds (a value
of 0 means no time out; on at least some platforms, this
means that you may wait until a sufficient number of
packets arrive before seeing any packets, so you should use
-
8/7/2019 TCP Session Logger
6/9
int main(int argc, char *argv[] ){
int i=0, count=0;
pcap_t *descr = NULL;
char errbuf[PCAP_ERRBUF_SIZE], *device=NULL;
memset(errbuf,0,PCAP_ERRBUF_SIZE);
if( argc > 1){ // If user supplied interface name, use it.
device = argv[1];
}
else{ // Get the name of the first device suitable for
capture
if ((device = pcap_lookupdev(errbuf)) == NULL){
fprintf(stderr, "ERROR: %s\n", errbuf);
exit(1);
}
}
printf("Opening device %s\n", device);
// Open device in promiscuous mode
if ( (descr = pcap_open_live(device,
MAXBYTES2CAPTURE, 1, 512, errbuf)) == NULL){
fprintf(stderr, "ERROR: %s\n", errbuf);
exit(1);
}
logfile=fopen("log.txt","w");if(logfile==NULL) printf("Unable to create file.");
// Loop forever & call processPacket() for every received
packet
if ( pcap_loop(descr, -1, processPacket, (u_char *)&count)
== -1){
fprintf(stderr, "ERROR: %s\n", pcap_geterr(descr) );
exit(1);
a non-zero timeout). Lastly, ebuf is a string we can store any
error messages within (as we did above with errbuf). The
function returns our session handler.
deviceis the name of the device as obtained from the call
to pcap_findalldevs.snaplen is the maximum amount of data to be captured.
65536 should be sufficient length.
promisc 0 or 1 to indicate whether to open the device in
promiscuous mode.
to_msthe timeout in milliseconds , 0 for no timeout
errbufbuffer to contain any error message
It returns a device handler in the form of the structure
pcap_t which can be used by pcap_loop() to capture data
from.
Start sniffing the device pcap_loop(). Process the
sniffed packet user defined callback method (e.g. void
processPacket(u_char *arg, const struct pcap_pkthdr*
pkthdr, const u_char * packet)).
The prototype for pcap_loop() is: int pcap_loop(pcap_t
*p, int cnt, pcap_handler callback, u_char *user). The first
argument is our session handle. Following that is an integer
that tells pcap_loop() how many packets it should sniff for
before returning (a negative value means it should sniff until
an error occurs). The third argument is the name of the
callback function (just its identifier, no parentheses). The
last argument is useful in some applications, but many times
is simply set as NULL. Suppose we have arguments of our
own that we wish to send to our callback function, in
addition to the arguments that pcap_loop() sends. This is
where we do it. Obviously, you must typecast to a u_char
pointer to ensure the results make it there correctly; as we
will see later, pcap makes use of some very interestingmeans of passing information in the form of a u_char
pointer.
Before we can provide an example of using pcap_loop(),
we must examine the format of our callback function. We
cannot arbitrarily define our callback's prototype; otherwise,
pcap_loop() would not know how to use the function. So we
use this format as the prototype for our callback function:
void got_packet(u_char *args, const struct pcap_pkthdr
*header, const u_char *packet); Let's examine this in more
detail. First, we notice that the function has a void return
type.
This is logical, because pcap_loop() wouldn't know how
to handle a return value anyway. The first argumentcorresponds to the last argument of pcap_loop(). Whatever
value is passed as the last argument to pcap_loop() is passed
to the first argument of our callback function every time the
function is called. The second argument is the pcap header,
which contains information about when the packet was
sniffed, how large it is, etc. The pcap_pkthdr structure is
defined in pcap.h as in Fig. 3:
-
8/7/2019 TCP Session Logger
7/9
struct pcap_pkthdr {
struct timeval ts; /* time stamp */
bpf_u_int32 caplen; /*length of portion present*/
bpf_u_int32 len; /* length this packet (off wire)*/
};Fig. 3
bit
offset03 47 813 14-15
16
181931
0 VersionHeader
Length
Differentiated
Services CodePoint
Explicit
CongestionNotification
Total Length
32 Identification FlagsFragment
Offset
64 Time to Live Protocol Header Checksum
96 Source IP Address
128 Destination IP Address
160 Options ( if Header Length > 5 )
160or
192+
Data
Fig. 4. Ethernet frame
u_char* handle_IP
(u_char *args,const struct pcap_pkthdr* pkthdr,const u_cha
packet){
const struct my_ip* ip;u_int length = pkthdr->len;
u_int hlen,off,version;int i;int len;
/* jump pass the ethernet header */
ip = (struct my_ip*)(packet + sizeof(struct ether_header));length -= sizeof(struct ether_header);
/* check to see we have a packet of valid length */
if (length < sizeof(struct my_ip)){
printf("truncated ip %d",length);return NULL;
}len = ntohs(ip->ip_len);hlen = IP_HL(ip); // header length
version = IP_V(ip);// ip version
// check version
if(version != 4)
{fprintf(stdout,"Unknown version %d\n",version);return NULL;
}
// check header length
if(hlen < 5 )
{fprintf(stdout,"bad-hlen %d \n",hlen);
}
// see if we have as much packet as we should
if(length < len)printf("\ntruncated IP - %d bytes missing\n",len - length);
// Check to see if we have the first fragment
off = ntohs(ip->ip_off);if((off & 0x1fff) == 0 )/* aka no 1's in first 13 bits */
{/* print SOURCE DESTINATION hlen version len offset fprintf(stdout,"IP source: ");fprintf(stdout,"%s ;\n",
inet_ntoa(ip->ip_src));
fprintf(stdout,"IP destination: %s ;\n header lenght: %dversion: %d ;\n lenght: %d ;\n offset: %d\n",
inet_ntoa(ip->ip_dst),hlen,version,len,off);
fprintf(stdout,"Time to Live: %d ;\n", ntohs(ip->ip_ttl)/25fprintf(stdout,"Protocol: %d ;\n", ip->ip_p);fprintf(stdout,"Checksum: %d ;\n", ip->ip_sum);
}return NULL;
}
Fig. 6
struct my_ip
u_int8_t ip_vhl; /* header length, version*/#define IP_V(ip) (((ip)->ip_vhl & 0xf0) >> 4)
#define IP_HL(ip) ((ip)->ip_vhl & 0x0f)u_int8_t ip_tos; /* type of service */u_int16_t ip_len; /* total length */u_int16_t ip_id; /* identification*/
u_int16_t ip_off; /* fragment offset field */#define IP_DF 0x4000 /* dont fragment flag */#define IP_MF 0x2000 /* more fragments flag */#define IP_OFFMASK 0x1fff /* mask for
fragmenting bits */u_int8_t ip_ttl; /* time to live */u_int8_t ip_p; /* protocol */u_int16_t ip_sum; /* checksum */
struct in_addr ip_src,ip_dst; /* source and dest address */
};Fig. 5
These values should be fairly self explanatory. The last
argument is the most interesting of them all, and the most
confusing to the average novice pcap programmer. It is
another pointer to a u_char, and it points to the first byte of
a chunk of data containing the entire packet, as sniffed by
pcap_loop().
A packet contains many attributes, so as you can
imagine, it is not really a string, but actually a collection of
structures (for instance, a TCP/IP packet would have an
Ethernet header, an IP header, a TCP header, and lastly, the
packet's payload). This u_char pointer points to the
serialized version of these structures. To make any use of it,
we must do some interesting typecasting.
Programming to print out the ethernet header, from now
on we take the easy route. Here is a straightforward callback
function to handle ethernet headers, print out the source anddestination addresses and handle the type.
A summary of the contents of the internet header:
We are following the tcpdump method of handling theversion and header length in Fig.5-6.
-
8/7/2019 TCP Session Logger
8/9
Opening device eth0
ethernet header source: 0:c:29:81:29:3c
destination: 0:50:56:fb:e0:d (IP)
IP source: 192.168.79.138 ;
IP destination: 192.168.79.2 ;
header lenght: 5 ;
version: 4 ;
lenght: 77 ;
offset: 16384
Time to Live: 64 ;
Protocol: 17 ;
Checksum: 44446 ;
Grabbed packet of length 91Recieved at ..... Sat Jan 8 16:08:55 2011
Ethernet address length is 14
Ethernet type hex:800 dec:2048 is an IP packet
Destination Address: 0:50:56:fb:e0:d
Source Address: 0:c:29:81:29:3c
ethernet header source: 0:c:29:81:29:3c
destination: 0:50:56:fb:e0:d (IP)
IP source: 192.168.79.138 ;
IP destination: 192.168.79.2 ;
header lenght: 5 ;
version: 4 ;
lenght: 75 ;
offset: 16384Time to Live: 64 ;
Protocol: 17 ;
Checksum: 44958 ;
Grabbed packet of length 89
Recieved at ..... Sat Jan 8 16:08:55 2011
Fig. 7
IV. RESULTSThe results we have with our application are not very
elaborate, and the application still needs some finaldebugging and testing. The results we will present are onlybase test results.
The functionality testing of our sniffer is shown in Fig. 7:
All the information is stored and used by our faultdetection system, which analysis the information and takeaction based on the problems found.
V. CONCLUSIONS AND FUTURE WORKA good implementation of a TCPSL application could be
very useful in the case of servers that suffer of high load,
and their uptime is essential for the business. Additional
servers or load balancing can, of course, be a solution, but
the additional costs may not be always affordable by the
business owner. One efficiently configured TCPSL may
well manage the existing load and may protect the server
from unwanted downtime periods.
Future work may extend the functionality or the concept
of such an application to all kinds of traffic. Also a GUI/CL
interface could be implemented in order to allow the users
to constantly adapt the application's behavior to their own
needs.
By using statistical data, decisions about upgrading or
adding new servers could be made more exact. Also, the
business owner could have a better picture about how much
more traffic can the server sustain in good conditions.
VI. REFERENCES[1] http://elf.cs.pub.ro/so2/
[2] http://elf.cs.pub.ro/so/
[3]http://recursos.aldabaknocking.com/libpcapHakin9LuisM
artinGarcia.pdf
[4]http://www.programmingpcap.aldabaknocking.com/code
samples.html
[5]http://www.tcpdump.org/release/libpcap-1.1.1.tar.gz
[6] http://www.tcpdump.org/#
[7] Vinton G. Cerf, Robert E. Kahn, A Protocol for PacketNetwork Intercommunication, IEEE Transactions on
Communications, Vol. 22, No. 5,May 1974.
[8] Comer, Douglas E. (2006). Internetworking with TCP/
IP:Principles, Protocols, and Architecture. 1 (5th ed.).
[9] http://www.iana.org/assignments/tcp-parameters/
[10]http://citeseer.ist.psu.edu/stone00when.html
[11] http://lwn.net/Articles/92727/
[12] Peterson, Larry (2003). Computer Networks. Morgan
Kaufmann..
[13]Tanenbaum, Andrew S. (2003-03-17). Computer
Networks (Fourth ed.).
[14]http://www.gont.com.ar/talks/hacklu2009/fgont-
hacklu2009-tcp-security.pdf[15] Business Wire (2007-12-06). "Solera Networks
Announces Advanced Deep Packet Inspection and Capture
Solution for Full 10Gbps Speeds".
[16] Erik Hjelmvik (2008). "Passive Network Security
Analysis with NetworkMiner".
[17] Helman, Paul, Liepins, Gunar, and Richards, Wynette,
"Foundations of Intrusion Detection," The IEEE Computer
Security Foundations Workshop V, 1992.
[18] Steven McCanne and Van Jacobso The BSD Packet
Filter: A New Architecture for User-level Packet Capture
Lawrence Berkeley Laboratory 1992.
[19] Ashish Chaurasia Network packet capturing for Linux
, IBM Corp.[20] Naveed Afzal Host Fingerprinting and Firewalking
With hping.
[21] Anderson, Ross (2001). Security Engineering: A Guide
to Building Dependable Distributed Systems. New York:
John Wiley & Sons. pp. 387388.
[22] Anderson, James P., "Computer Security Threat
Monitoring and Surveillance," Washing, PA, James P.
Anderson Co., 1980.
-
8/7/2019 TCP Session Logger
9/9
[23] Denning, Dorothy E., "An Intrusion Detection Model,"
Proceedings of the Seventh IEEE Symposium on Security
and Privacy, May 1986, pages 119131 .
[24] Lunt, Teresa F., "IDES: An Intelligent System for
Detecting Intruders," Proceedings of the Symposium on
Computer Security; Threats, and Countermeasures; Rome,
Italy, November 2223, 1990, pages 110121.
[25] Lunt, Teresa F., "Detecting Intruders in Computer
Systems," 1993 Conference on Auditing and Computer
Technology, SRI International .
[26] Sebring, Michael M., and Whitehurst, R. Alan., "Expert
Systems in Intrusion Detection: A Case Study," The 11th
National Computer Security Conference, October, 1988
[27] Smaha, Stephen E., "Haystack: An Intrusion Detection
System," The Fourth Aerospace Computer Security
Applications Conference, Orlando, FL, December, 1988 .
[28] Vaccaro, H.S., and Liepins, G.E., "Detection of
Anomalous Computer Session Activity," The 1989 IEEE
Symposium on Security and Privacy, May, 1989 .
[29] Teng, Henry S., Chen, Kaihu, and Lu, Stephen C-Y,
"Adaptive Real-time Anomaly Detection Using InductivelyGenerated Sequential Patterns," 1990 IEEE Symposium on
Security and Privacy .
[30] Heberlein, L. Todd, Dias, Gihan V., Levitt, Karl N.,
Mukherjee, Biswanath, Wood, Jeff, and Wolber, David, "A
Network Security Monitor," 1990 Symposium on Research
in Security and Privacy, Oakland, CA, pages 296304
[31] Winkeler, J.R., "A UNIX Prototype for Intrusion and
Anomaly Detection in Secure Networks," The Thirteenth
National Computer Security Conference, Washington, DC.,
pages 115124, 1990.
[32] Dowell, Cheri, and Ramstedt, Paul, "The
ComputerWatch Data Reduction Tool," Proceedings of the
13th National Computer Security Conference, Washington,D.C., 1990 .
[33] Snapp, Steven R, Brentano, James, Dias, Gihan V.,
Goan, Terrance L., Heberlein, L. Todd, Ho, Che-Lin, Levitt,
Karl N., Mukherjee, Biswanath, Smaha, Stephen E., Grance,
Tim, Teal, Daniel M. and Mansur, Doug, "DIDS
(Distributed Intrusion Detection System) -- Motivation,
Architecture, and An Early Prototype," The 14th National
Computer Security Conference, October, 1991, pages 167
176.
[34] Jackson, Kathleen, DuBois, David H., and Stallings,
Cathy A., "A Phased Approach to Network Intrusion
Detection," 14th National Computing Security Conference,
1991 .[35] Paxson, Vern, "Bro: A System for Detecting Network
Intruders in Real-Time," Proceedings of The 7th USENIX
Security Symposium, San Antonio, TX, 1998 .
[36] Amoroso, Edward, "Intrusion Detection: An
Introduction to Internet Surveillance, Correlation, Trace
Back, Traps, and Response," Intrusion.Net Books, Sparta,
New Jersey, 1999.
[37] Kohlenberg, Toby (Ed.), Alder, Raven, Carter, Dr.
Everett F. (Skip), Jr., Esler, Joel., Foster, James C.,
Jonkman Marty, Raffael, and Poor, Mike, "Snort IDS and
IPS Toolkit," Syngress, 2007.