Handle teach you to capture packets [Bi Package Game Series 2] By PiggyXP [Pig]

xiaoxiao2021-03-06  60

Forehead

I often see that the forum asks questions about the interception and analysis of the data package. Fortunately I also know this slightly, I have written a lot of Sniffer, so I want to write a series of articles to explore the data package in detail. knowledge.

I hope that through this series of articles, I can make knowledge about the data packets are popular, so every article in this series, I will have a shallow depth, detailed analysis, and encoding steps, and additionally with detailed The source code of the comment (in order to take care of most friends, I provide the source code of the MFC).

However, since it is also an initiator, he is still looking forward to it.

This article condenses the author's heart, if you want to reprint, please indicate the original author and the source, thank you! ^ _ ^

OK ,. Let's go! Have Fun! ! q ^ _ ^ P

The second hand teaches you to capture the packet

table of Contents:

One. Capture the principle of implementation of packets

two. Capture the programming implementation of the packet:

1. Realization method of Raw Socket

2. WinPCAP implementation method

a. Information on this machine network card

b. Open the corresponding network card and set to mixed mode

c. Intercept packets and save as file

Author:

9CBS VC / MFC Network Programming Master PiggyXP

One. Capture the implementation principle of packets: ----------------------------------------- -------------------------

Under normal circumstances, the socket program of network communication can only respond to the data frames that match the hardware address or in broadcast form, for other forms of data frames, such as the network interface, but is not sent to this address. Data frames, network interfaces will not be in response after verifying delivery addresses, that is, the application cannot charge a packet that is not related to yourself.

So we want to realize all the packets that flow through the network equipment, we have to take a little special means:

Set the NIC to a mixed mode.

In this way, the network card of the host can capture all packets and frames flowing through its network card.

However, pay attention to it, this interception is only a copy of the packet, and it cannot be truncated. If you want to cut off network traffic, you should use some more underlying methods, not within the discussion of this article.

two. Capture the programming implementation of the packet:

1.Raw Socket implementation method ----------------------------------------- -------------------------

Unlike our commonly used data flow sleeve and data sets, after creating the original socket, you need to use the wsaiocTl () function to set it, it is such a definition.

INT WSAIOCTL (

Socket S,

DWORD DWIOCONTROLCODE,

LPVOID LPVINBUFFER,

DWORD CBINBUFFER,

LPVOID LPVOUTBUFFER,

DWORD CBOUTBUFFER,

LPDWORD LPCBBYTESRETURNED,

LPWSAOVERLAPPED LPOVERLAPPED,

LPWSAOVERLAPPED_COMPLETION_ROUTINE LPCOMPLETIONROUTINE

);

Although it is more than the parameters, it is only the second item we care about. What we need to do is to set the second item as SiO_rcvall, say so much, but what is actually doing this, it is very simple. Is it? ^ _ ^

Of course, we can also specify whether it processes the IP header, but this is not necessary.

The complete code is similar to the following, the bold code is where the need to pay attention to usual:

(In order to make the code at a glance, I will remove the wrong hand, the same) #include "winsock2.h"

#define sio_rcvall_wsaiow (IOC_VENDOR, 1)

Socket SnifferSocket

Wsadata wsadata;

iflag = WSAStartup (Makeword (2, 2), & WSADATA); / / Open Winsock.dll

SnifferSocket = WSASOCKET (AF_INET, / / ​​Creating Raw Socket

SOCK_RAW, IPPROTO_IP, NULL, 0, WSA_FLAG_OVERLAPPEDs;

Char far name [128]; // Get this machine IP address

GethostName (Name, Sizeof (Name));

Struct Hostent Far * Phostent;

phostent = gethostByName (Name);

SockAddr_in sa; // Fill the contents of the SockAddr_in structure

sa.sin_family = af_inet;

sa.sin_port = HTONS (6000); // port number can be changed, of course, the system cannot conflict with the system

Memcpy (& (sa.sin_addr), phostent-> h_addr, phostent-> h_length;

Bind (SnifferSocket, (LPSOCKADDR) & sa, sizeof (sa)); // Binding

// Set IOCTL to receive all network data, key steps

DWORD dwbufferlen [10];

DWORD dwbufferinlen = 1;

DWORD DWBYTESRETURNED = 0;

WSAIOCTL (SnifferSocket, IO_RCVALL, & DWBUFFERINLEN, IZEOF (dwbufferinlen),

& dwbufferlen, SizeOf (dwbufferlen), & DWBYTESRETURNED, NULL, NULL

At this point, it can actually start sniffing the network packet, and the reception of the packet is also completed by the RECV () function, because the different Socket model is involved, and the receiving method is very different. Therefore, the received code is not provided here.

2.WinPCap implementation method: ----------------------------------------- ----------------------------

WinPCAP driver package is a good Dongdong, and WinPCAP's main functionality is to send and receive raw datagrams independently of host protocols (such as TCP-IP), mainly to provide us with four functions:

Functions: 1> Capture the original datagram, including the data reported on the shared network, and exchanged data reports; 2> Before the data is reported to the application, according to the custom rules, certain special Datasters are filtered off; 3> Send raw datagram on the network; 4> Collect statistics during network communication

If the environment is allowed (such as what you do is not a Trojan program), I still recommend you to use WinPCAP to intercept the packet because it is more powerful, the work efficiency is higher, the unique shortcomings are before running WinPCAP development, To install the WinPCap's Driver on the host. And we will find it better than the Raw Socket function, and work is more under, the most obvious reason is that the data package captured by Raw Socket is not too old, this is an afterward.

As for how to install use, please refer to this series of "hand-handed people to play in the ARP package", there is a detailed way to load WinPCAP driver ^ _ ^

Not much nonsense, let us transfer to the topic, using WinPcap to intercepting the packets to do some of the following work:

A. Enumerate the information of this machine network card (mainly the name of the NIC)

It is used to use the PCAP_FINDALDALDEVS function, it is defined

/ **************************************************

INT PCAP_FINDALDEVS (PCAP_IF_T ** AlldevSP,

Char * Errbuf

)

Features:

Enumerate information about all network devices

Parameters: alldevsp: It is a pointer to a PCAP_IF_T structure. If the function PCAP_FINDALDEVS function is successful, a list of available NICs will be obtained, while stored is a pointer for the first element.

Errbuf: String of the error message

Return Value: INT: If it returns 0, it is successful, and the error returns -1.

********************************************************* /

We use this function to get the full code of the NIC name as follows:

PCAP_IF_T * ALLDEVS;

PCAP_IF_T * D;

CHAR ERRBUF [PCAP_ERRBUF_SIZE];

PCAP_FINDALDEVS (& alldevs, errbuf); // Get network device pointers

For (d = alldevs; d; d = d-> next) // enumerate the network card then add to ComboBox

{

D-> name; // D-> Name is the network card name string we need, and save it to your corresponding variable according to you //

}

PCAP_FREEALLDEVS (AllDevs); // Release AllDev Resources

Please look forward to the following. . . . . ^ _ ^

B. Open the corresponding NIC and set to mixed mode:

Before you here, you have to have a message to choose a NIC, and get the code of the NIC's name, since it already gains the name of all NICs, this code is temporarily slightly.

We mainly use the PCAP_OPEN_LIVE function, but this function WinPCap's development team has suggests that it is replaced with a PCAP_Open function, but because of my code is PCAP_OPEN_LIVE, it is not convenient to modify, but PCAP_OPEN_LIVE uses no problem The following is a function declaration of PCAP_OPEN_LIVE:

/ **************************************************

PCAP_T * PCAP_OPEN_LIVE (Char * Device,

Int snake,

Int Promisc,

INT to_MS,

Char * ebuf

)

Function: Open the NIC according to the NIC and set to mix mode, then return to its handle

parameter:

Device: It is the name of the NIC we have obtained before.

Snaplen: We get the length of the data from each packet, such as 100, each time we just get 100 lengths of each packet, there is no special needs, set it to 65535 maximum value. a;

Promisc: This parameter is to set whether the network card is set to "Mixed Mode" and set to 1;

TO_MS: Timeout, millisecond, typically set to 1000.

return value:

PCAP_T: Similar to a network card "handle", of course, this parameter is the back intercepted data to be used.

*********************************************************** *************************** /

Although it looks more complicated, it is still very simple, in fact, 1 line is OK:

PCAP_T * ADHANDLE;

CHAR ERRBUF [PCAP_ERRBUF_SIZE];

/ / Open the NIC and set to mixed mode

// pcardName is the NIC name parameter from the previous

Adhandle = PCAP_OPEN_LIVE (PcardName, 65535, 1, 1000, Errbuf);

C. Intercepting the packet and saves the file: -------------------------------------- ----------------

Of course, you don't save the packet as a file, but if you don't save, you can only analyze the moment that intercepted into the packet, and there is no ^ _ ^

So, in order to facilitate the analysis, the master and my individual often analyze the packets slowly analyze.

But pay attention to network traffic, pay attention to the hard disk space when traffic is very large, often have a few megaby things in a few seconds.

Let's first explain in detail below, the WinPCAP function you need to use in this step:

/ ************************************************** ************

PCAP_DUMPER_T * PCAP_DUMP_OPEN (PCAP_T * P,

Const char * fname

)

Features:

Establish or open the file that stores the contents of the packet, and returns its handle

parameter:

PCAP_T * P: Net card handle opened in front;

Const char * fname: The file name to be saved

return value:

PCAP_DUMPER_T *: Save the description of the file, detail, we don't have to care

*********************************************************** ************* /

/ ************************************************** *************

INT PCAP_NEXT_EX (PCAP_T * P,

Struct PCAP_PKTHDR ** PKT_HEADER,

u_char ** pkt_data

)

Features:

Read data content from the NIC or packet file

parameter:

PCAP_T * P: Net card handle

Struct PCAP_PKTHDR ** PKT_HEADER: Not a packet of packets, just a headeru_char ** pkt_data related to packet capture drive: pointing to packet content, including protocol headers

return value:

1: If you successfully read the packet

0: PCAP_OPEN_LIVE () does not read the content within the timeout time

-1: Error

-2: After reading the file, I read it.

*********************************************************** ************* /

/ ************************************************** *************

Void PCAP_DUMP (U_CHAR * User,

Const struct pcap_pkthdr * h,

Const U_CHAR * SP

)

Features:

Write the packet content to the file specified in PCAP_DUMP_OPEN ()

parameter:

u_char * user: Net card handle

Const struct pcap_pkthdr * h: Not a packet of packets, just a header associated with packet capture

Const U_CHAR * SP: Packet Content Pointer

return value:

Void

*********************************************************** ************* /

The code for a complete capture packet is given, which is written in the thread. For the program clear, I have dropped the error handling code and the code exit, the complete code can download the sample source code, old rules, important Steps are marked with bold characters.

We are actually in capturing a packet, and it is best to put the code into another thread.

/ ************************************************** *********

* Process:

* This is the core part of the program and completes the interception of the packet.

* Parameters:

* PPAram: Name of the network card selected to capture data

*********************************************************** ******* /

Uint CaptuRethread (LPVOID PPARAM)

{

Const char * pcardname = (char *) PPARAM; // conversion parameters, get the NIC name

PCAP_T * ADHANDLE;

CHAR ERRBUF [PCAP_ERRBUF_SIZE];

/ / Open the NIC and set to mixed mode

Adhandle = PCAP_Open_Live (PcardName, 65535, 1, 1000, Errbuf); {

PCAP_DUMPER_T * DUMPFILE;

/ / Establish a file that stores intercepted packets

DUMPFILE = PCAP_DUMP_OPEN (Adhandle, "Packet.dat");

Int Re;

PCAP_PKTHDR * HEADER; // HEADER

U_CHAR * PKT_DATA; // Packet Content Pointer

// Do not read packet information from the network card or file

While ((RE = PCAP_NEXT_EX (Adhandle, & Header, (Const U_CHAR **) & PKT_DATA))> = 0)

{

// Subscribe the captured packet into the file

PCAP_DUMP (UNSIGNED Char *) Dumpfile, Header, PKT_DATA);

Return 0;

}

Add a thread to the program started inside. . . Wait, how to start this thread, don't tell me, you can like this code.

:: AfxBeginthread (CaptuRethread, chnic); // chnic is the name of the NIC, Char * Type

After a thread is started (there is an effect in a few seconds), you can see that the packet has been intercepted and stored in the packet.dat file in the program directory.

============================================================================================================================================================================================================= ===

At this point, the interception method of the data package is over, everyone looked at this article, in fact, you must also understand, whether it is Raw Socket method or WinPCap method, it is very simple, really there is something, just Will make people who don't understand the principles look mysterious, isn't it?

Oh, but don't be happy too early, this saved packet file, you can try to open this file with UltraEdit, is it most of it? There is basically no readability because:

The packet captured at this time is not just simple data information, but includes the most original data information of the IP header, TCP head and other information heads, which retains its original appearance when it is transmitted. Some information about the network can be obtained by analyzing these raw information transmitted at low-level information. Since these data have passed the package of the network layer and the transport layer, the packet is required to analyze the packet according to its additional frame header.

Oh, so the road we have to go is still very long, this is just getting started, ^ _ ^

Please look forward to the next series of this series

"Hand teaches you to analyze the packet"

The source code of this article will also be released together in the next article.

-------- Made in dLUT | DIP

-------- Finished AT

2004-06-23

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

New Post(0)