Preliminary packet analysis program design (reproduced)

xiaoxiao2021-03-06  107

Preliminary packet analysis program design

Author: maigan

From: The 8th Army - Information Security Group (

http://www.cnhacking.com/

http://www.juntuan.org/)

Mail: maigan@maigan.com

Warning: Reprinted this article, please indicate the author and the source

All day I turned online, I also saw a lot of good articles, but I found that most articles were either still staying in theory, or too high. There are very few introduction to questions detailed analysis. Today, I want to discuss the relevant issues of the network programming with the packet analysis program, I am also a newbie, I can't do it, I hope everyone will not finger.

Through the analysis of the data packet, we can judge the operating system, network information traffic, and the size of the data package, and the content, etc. of the data packet. For those who like to network security, mastering this knowledge is quite important. Now the network communication, most of the data are not encrypted, we can easily extract account numbers, passwords and the like from the data we are concerned packet. When you look at this article if difficult, can first read the computer network and C Programming also has a book for protocol analysis. Below I will be divided into TCP / IP protocol structure, program partial function and data structure description, and the case program analyzes three parts to learn the design method of the packet analysis program.

I. TCP / IP protocol structure

Before you say TCP / IP, let's meet the Ethernet, because we are in touch with the most empty, and the research packet is inseparable from the frame of the Ethernet. In the Ethernet, the data is exchanged in units of data structures called frames. The protocols commonly used in Ethernet are CSMA / CD (Carrier Sense Multiple Access With Collision Detection), that is, the carrier monte to listen to multiple points of access / collision detection, where we are concerned about the format of the frame. There are two standards in the format of common Ethernet frames, one is the DIX Ethernet V2 standard, and the other is the 802.3 standard of IEEE. The most commonly used MAC frame is now V2 format, which is also the format we have to study, as for 802.3 frames. We no longer discuss. The format of the Ethernet V2 frame is as follows:

(Inserted 8 bytes) destination address (6 bytes) -> source address (6 bytes) -> Type (2 bytes) -> Data (46-1500) -> FCS (4 bytes)

The address of the Ethernet is represented by a binary of 48-bit, that is, the MAC address and hardware address we often say. There are 8-bytes of preamble and frame start delimitations in the MAC frame, and then the address and other header information. After the receiving end and the address of the sender are the 2-byte type field, the upper layer protocol type of the transferred data is stored, and the RFC1700 document specifies these, as follows:

Ether Types (hex) Protocols

800 IP

806 ARP

8035 Revese ARP

809B Apple Talk

8137/8138 Novel

814C SNMP

The data portion of the frame is 46-1500 bytes, and when less than 46, an integer byte padding field is added later. FCS (FRAME CHECK SEQUENCE) is used in Ethernet common cycling ministries (CRC: Cyclic RedAndancy Check).

The IP protocol is a network layer protocol, and the data structure of the network layer is called an IP datagram. IP address and domain names These two concepts we don't say, let's take a look at the structure of the IP datagram:

Member name byte number

Version 1/2 IP version, now IPv4

IHL (submission length) 1/2 is most commonly used 20, take 5-15 value, maximum 60 bytes

TYPE OF Service 1 Numerical Value of Preferred and Reliability Services

Full length Identification 2 identifying the number of IP datagrams for Total LENTH 2 IP Date

Flags 3/8 1 bit is 0 indicates a broken block, and 2 bits are 0 indicates the last broken block, and 1 is indicated in reception.

FRAGMENT OFFSET 13/8 slice in the original group

TTL 1 Data Life, the recommended value is 32 seconds

Protocol 1 Upper Protocol

HEADERCHECKSUM 2 Header Inspection Code

Source Address 4 Send IP Address

Destination Address 4 Receive IP Address

Options and padding 4 options and filling locations

Where the value of the protocol field is very important to our analytical packets, here is listed to you:

Value agreement

1 ICMP Internet Control Message Protocol

6 TCP TRANFER Control Protocol

8 EGP EXTERG GATEWAY Protocol

9 IGP Interior Gateway Protocol

17 UDP User DataGram Protocol

The value of these protocols we can see in the latter program, please pay attention. Then we introduce the address resolution protocol (ARP / RARP):

Member name byte number

Hardware Address 2 Hardware Type, Ethernet is 1

Protocol Address 2 Upper Protocol Type, IP 800

BYTE Length of Each Hardware 1 Query the byte length of the physical address, Ethernet is 6

Byte Length of Each Protocol Address 1 Query the byte length of the upper protocol, IPv4 is 4

OpCode 2 1 is an ARP request, 2 is a response; 3 is RARP request, 4 is a response

Hardware Address of Sender of this Packet 6 Send Delivery Hardware Address

Protocol Address of Sender of this Packet 4 Send IP Address

Hardware Address of Target of this Packet 6 Query Object Hardware Address

Protocol Address of Target Of this Packet 4 Query Object IP Address

The ARP / RARP protocol is used to query the hardware address corresponding to the IP or in turn query the IP address, which will also see when we analyze the packets. The ICMP protocol is described below. Our commonly used ping commands are used by this protocol. This protocol is relatively simple, from type (1 bytes), code (1 bytes), inspection and (2 bytes), and four bytes related to types. Variable partial and data composition.

The packet has two important protocols in the transportation layer, namely TCP / UDP, TCP / UDP, using port concepts to distinguish between different programs on your computer. Let's take a look at the head of TCP datagram:

Member name byte number

Source Port 2 Send end slogan

Destination Port 2 Receive end slogan

Sequence NO 4 serial number of the first byte sent by this newspaper section

Ack Number 4 expects the serial number of the next message segment

Data Offset 1/2 Length Length

Reserved 3/4 keeps the future

Contol Bits 3/4 Control Bits

Window 2 Sliding window size

Checksum 2 inspection and

Urgent Pointer 2 Emergency Pointer

Options and Padding 4 optional, true charge

TCP is used in a network application that spans the router, such as WWW, email, news, ftp, etc. UDP is the concept of the port on the IP, and its structure is simple. Only eight bytes are as follows: Source port (2 bytes) -> destination port (2 bytes) -> length (2 bytes) ) -> Inspection and (2 bytes)

Second, the program part function and data structure

In this section we will introduce some of the partial functions and data structures used in the subsequent program. In the program we use the PCAP library, you can

ftp://ftp.ee.lbl.gov/libpcap.tar.z Download. We are mainly tested under the Redhat Linux, which briefly introduces the installation method of the library, and other environments please solve themselves. My purpose is to write a packet analysis program to provide ideas. As for the implementation of utilities, the third part given is not practical. To demonstrate, there are more features implemented in the program. Not detailed enough, please pay properly when writing a utility and add the features you need. The installation method of the PCAP library is as follows:

1, unzip file

2, enter the file directory execution ./configure and make

3, use the make command, set the manual and the include file (if there is root permission), do the following command:

Make install -man

make install -incl

4. If there is an incline and include / net directory, create this directory and re-execute make install -incl

5. Check the / usr / include / netinet / directory whether there is a protocols.h file, and there is no copy. The library is complete.

The partial function and data structure that appears in the program below:

1, PCAP_T * PD;

This type of data is called a packet capture descriptor.

2, PCAP_OPEN_LIVE (Argv [1], Defaut_SNALEN, 1, 1000, EBUF)

This function initializes the PCAP library and returns a pointer to PCAP_T data, and its parameter list is as follows:

Char * Specify network interface

INT acquired the maximum number of bytes of data

INT specifies the network interface card, generally 1

INT reads a pause time

CHAR * error message buffer

3, PCAP_LOOP (PD, -1, Packet_Proce, NULL)

The core, repeated execution of this function program, uses PCAP to get packets, returned to the number of read packets, returns -1 when the error is wrong, and its parameter list is as follows:

PCAP_T * Specifies the packet capture descriptor obtained by obtaining a packet

INT gets the number of packets, -1 is infinite

Returns a function of pointer to the function to specify the function of the packet processing

U_char * pointing to the pointer assigned to the packet processing function string

4, Struct Ether_Header * Eth

This structure stores Ethernet header information, and its members are as follows:

Ether_DHOST [6] The MAC address of the receiver

Ether_SHOST [6] sending the MAC address

Ether_type Type of Super Protocol

5, fflush (stdout)

This function is completed is forced output, parameter stdout, forcibly standard output.

6, Noths ((Struct ether_header * p) -> ether_type))

This function converts short integer network bytes into host byte sequence. Such functions are:

NTOHL long integer functions

Htons Short Integer Converts Host Byte Sequence into Network byte Sequence

Htons long integrity

7, struct ip * iPh

The IP structure is defined in the iPh file, and its member and the IP datagram structure talked from the first part correspond to the following:

Member name

IP_HL 4-bit unsigned integer header length IP_V is the same as the upper version, now 4

IP_tos 8-bit unsigned integers Type of Service

IP_LEN 16-bit unsigned integer data report length

IP_ID identifies

IP_off offset and flags on the same data block

IP_TTL 8-bit unsigned integer TTL value

IP_P is the same as upper level agreement

IP_SUM 16-bit unsigned integer inspection and

IP_SRC IN_ADDR Structure Send IP

IP_DST is the same on the upper receiver IP

8, Struct Ether_arp * arph

The Ether_arp structure member is as follows:

Member name

Part of the address of the EA_HDR ARPHDR structure

ARP_SHA 8-bit unsigned integer array sender MAC address

ARP_SPA is the same as the sender IP address

ARP_THA is the same as the target MAC address

ARP_TPA is the same as the target IP address

9, Struct ICMphDR * ICMP

The ICMPHDR structure contains the common nature in accordance with the different nature depending on the type of datagram, which is no longer listed, only three members that can be universal.

Member name

TYPE type field

CODE code

Checksum test and

Third, the case process analysis

//example.c

// How to use: EXAMPLE >

//, for example: eXample etho> Temp.txe

// End method: Ctrl C

// Program start, read the header file

#include

#include

#include

#include

#include

#include

#include

#include // PCAP library

#include // DNS retrieval

#define maxStringsize 256 // String length

#define maxSize 1024 // Maximum number of records in the host cache

#Fefine default_snaplen 68 / packet data length

Typedef struct

{

Unsigned long int ipaddr; // ip address

Char Hostname [MaxStringsize]; // host name

} DNSTABLE; / / Cache data structure

Typedef struct

{

DNSTABLE TABLE [MAXSIZE];

INT FRONT;

IntR;

} sequeue;

Sequeue * SQ; / / Define Cache Queue

SQ-> REAR = SQ-> front = 0; // Initialization queue

/ / Output MAC address function

Void Print_hwadd (u_char * hwadd)

{

For (int i = 0, i <5; i)

Printf ("% 2x:", hwadd [i]);

Printf ("% 2X", hwadd [i]);

}

/ / Output IP address function

Void Print_IpAdd (u_char * ipadd)

{

For (int i = 0; i <3; i)

Printf ("% d.", ipadd [i]);

Printf ("% d", ipadd [i]);

}

// Query port functions

Void getportname (int portno, char portna [], char * proto)

{

IF (GetServByport (Htons (portno, proto)! = null) {

STRCPY (portna, GetServbyport (Htons (portno, proto) -> s_name);

}

Else

Sprintf (portna, "% d", portno;

}

// Translate IP to DNS name

Void iptohost (unsigned long int ipad, char * hostn)

{

Struct Hostent * ShostName;

INT M, N, I;

M = SQ-> REAR;

n = sq-> front;

For (i = n% maxSize; i = m% maxsize; i = ( n)% maxSize)

{

/ / Check if IP has appeared for the first time

IF (SQ-> Table [i] .ipaddr == ipad)

{

STRCPY (Hostn, SQ-> Table [i] .hostname);

Break;

}

}

IF (i = m% maxsize)

{// does not exist, query from the domain name server and put the result into the cache

IF ((SQ-> Rear 1)% maxSize = sq-> front) // sentenced

SQ-> front = (SQ-> Front 1)% maxSize; // out of queue

SQ-> Table [i] .ipaddr = ipad;

Shostname = gethostbyaddr ((char *) & ipad, sizeof (ipad), AF_INET);

IF (ShostName! = NULL)

STRCPY (SQ-> Table [i] .hostname, ShostName-> h_name);

Else

STRCPY (SQ-> Table [i] .hostname, "");

SQ-> REAR = (SQ-> Rear 1)% maxsize;

}

}

Void Print_Hostname (u_char * ipadd)

{

UNSIGNED Long Int iPad;

Char Hostn [MaxStrintsize];

iPad = * ((unsigned long int *) ipadd;

Iptohost (iPad, Hostn)

IF (Strlen> 0)

Printf ("% s", Hostn);

Else

Print_IpAdd (iPadd);

}

// Process the function of the packet

Void packet_proce (u_char * packets, const struct pcap_pkthdr * header, const u_char * pp)

{

Struct Ether_Header * Eth; // Ethernet frame header pointer

Struct Ether_arp * Arth; // ARP header

Struct ip * iph; // ip header

Struct TCPHDR * TCPH;

Struct udphdr * udph;

U_SHORT SRCPORT, DSTPORT; / / Port number

Char protocol [maxStringsize]; // protocol type name

Char srcp [MaxStringsize], DSTP [MaxStringsize]; // Port Name

UNSIGNED INT PTYPE; / / Protocol Type Variable

u_char * data; // packet data pointer

u_char tcpudpdata [maxStringsize]; // packet data

INT I;

Eth = (struct ether_header *) PP;

PTYPE = NTOHS ((Struct Ether_Header *) PP) -> Ether_TYPE); if ((ptype == ethertype_arp) || (ptype == ethertype_rarp))

{

ARPH = (Struct Ether_arp *) (PP SIZEOF (Struct Ether_Header);

IF (ptype == ethertype_arp)

Printf ("ARP");

Else

Printf ("RARP"); // Output Protocol Type

Print_hwadd ((u_char *) & (arph-> arp_sha);

Printf (");

Print_HostName ((u_char *) & (arph-> arp_spa);

PRINTF (") ->");

Print_hwadd ((U_CHAR *) & (ARPH-> ARP_THA);

Printf (");

Print_HostName ((u_char *) & (arph-> arp_tpa));

Printf (") / tpacketlen:% D", header-> len);

}

Else if (ptype == ethertype_ip) // ip Data News

{

IPH = (struct ip *) (PP SIZEOF (Struct Ether_Header);

IF (iPh-> ip_p == 1) // ICMP packet

{

STRCPY (Protocol, "ICMP");

SrcPort = dstport = 0;

}

ELSE IF (iPh-> ip_p == 6) // TCP packet

{

STRCPY (Protocol, "TCP");

TCPH = (struct tcphdr *) (PP SIZEOF (Struct Ether_Header) 4 * iPh-> ip_hl);

Srcport = NTOHS (TCPH-> SOURCE);

Dstport = NTOHS (TCPH-> DEST);

Data = (u_char *) (PP SIZEOF (Struct Ether_Header) 4 * iPh-> ip_hl 4 * TCPH-> DOFF);

For (i = 0; i

{

IF (i> = header-> len-sizeof (struct ether_header) -4 * iPh-> ip_hl-4 * tcph-> doff);

Break;

Else

Tcpudpdata [i] = data [i];

}

} // TCP data processing is completed

ELSE IF (iPh-> ip_p = 17) // UDP packet

{

STRCPY (Protocol, "UDP");

UDPH = (struct udphdr *) (PP SITHER_HEADER 4 * iPh-> ip_hl);

Srcport = NTOHS (UDPH-> Source);

Dstport = NTOHS (UDPH-> DEST);

Data = (u_char *) (PP SIZEOF (Struct Ether_Header) 4 * iPh-> ip_hl 8);

For (i = 0; i

{

IF (i> = header-> len-sizeof (struct ether_header) -4 * iPh-> ip_hl-8); Break;

Else

Tcpudpdata [i] = data [i];

}

}

Tcpudpdata [i] = '/ 0';

GetportName (Srcport, SRCP, Protocol);

GetportName (Dstport, DSTP, Protocol);

Printf ("IP");

Print_hwadd (eth-> ether_shost);

Printf (");

Print_hostname ((u_char *) & (iPh-> ip_src);

Printf (") [% s:% s] ->", protocol, srcp);

Print_hwadd (Eth-> Ether_DHOST);

Printf (");

Print_hostname ((u_char *) & (iPh-> IP_DST));

Printf (") [% s:% s]", protocol, dstp);

Printf ("/ tttl:% d packetlen:% d, iph-> ttl, header-> len);

Printf ("/ n");

Printf ("% s", tcpudpdata);

Printf ("== EndPacket ==");

}

Printf ("/ n");

}

// main function takes packets and initializes the program environment

INT main (int Argc, char ** argv)

{

Char EBUF [PCAP_ERRBUF_SIZE];

PCAP * PD;

IF (argc <= 1) // parameter check

{

Printf ("Usage:% S / N", Argv [0]);

exit (0);

}

/ / Set up PCAP library

IF ((pd = pcap_open_live (argv [1], default_snaplen, 1, 1000, ebuf) = NULL)

{

(void) FPRINTF (stderr, "% s", ebuf);

Exit (1);

}

// Take a data package

// Change the parameter-1 is other value, determine the number of packets, here is infinite

IF (PCAP_LOOP (PD, -1, Packet_Proce, NULL) <0)

{

(void) FPRINTF (stderr, "pcap_loop:% s / n", PCAP_GETERR (PD));

Exit (1);

}

PCAP_COLSE (PD);

exit (0);

}

// End of the program

So far, my article is over, I hope I can give you inspiration and help. Usually, most of the friends who have seen long in the Internet often have no confidence. In fact, I have just like this, but here I want to tell everyone, don't go in and go in and learn, I can't get it. Harvested. No pain no gain.

转载请注明原文地址:https://www.9cbs.com/read-125088.html

New Post(0)