Sniffer implementation 2 - use WinPCap SNIFFER

zhaozj2021-02-11  256

Second of the Sniffer - Implement Sniffer ○ with WinPCAP, and this article is written 1 year ago, because some reasons did not complete it. Today, Shadowstar's Home is found, and this endless article was accidentally found. Although it is something before, but now there is still no time, friends who want to know about Sniffer should help. Dad said that there is a matter of ending. Today is the Dragon Boat Festival, I would like to give a heart to a loved ones in this article. I. Introduction The last time introduced the method of implementing Snifer with Raw Socket, it is relatively simple, but there is a disadvantage that the package of the IP layer can only be intercepted, the data clamp is not included. It is not satisfied with some special requirements, and it is important to handle the ARP package. The use of NDIS drivers can achieve interception of the entire Ethernet package, but complex drivers make a lot of people. It doesn't matter, why is there a ready-made thing? Provide a packet example in Microsoft's DDK, packet.sys can operate any operation, packete32.dll provides a convenient interface to the application, and complex internal operations related to the driver communication is completed by the DLL, Programmers facing the application layer do not need to understand these details. Unfortunately, I step by step by step, but I can't get the result of the desired, I can't move it. It seems that it doesn't want to give me a work: (still don't want to write driver ... lucky is a set of WinPcap's stuff, specifically used to capture in the Win32 platform, can be in http: //winpcap.polito Decremen. And the interface is basically the same as Microsoft's Packet. Haha, this is good, the original code can be used, try to go to the spirit! Let's use WinPCAP to operate directly and The received data is analyzed. Second, a network communication structure in a Windows system 1. Network communication structure in the Windows system Figure 1 The upper application of the upper application of IE, Outlook, etc. Network-based software, network driver protocol? TCP / IP, NetBeui, other Windows supported network layers, transport layer protocols, NDIS is a key part of Windows operating system network function drivers, which are introduced below. 2. Dis and its characteristics NDIS (NetWork Driver Interface Specification) is Microsoft Network driver specifications developed with 3COM companies, and provide a large number of operational functions. It provides services for the upper protocol driver, shielding the difference in various network cards in the lower layer. NDIS supports multiple network protocols, such as TCP / IP, NWLINK IPX / SPX, NetBeui, etc., supports multiple network cards produced by different manufacturers. Disan also supports multiple working modes, support multiprocessors, providing a complete NDIS library (library). But the various functions provided in the library Is working in core mode, users should not do direct operation, this is required to find additional interfaces. Third, WinPCAP Introduction 1. Winpcap Figure 2. WinPCAP includes three parts

The first module NPF (NETGROUP Packet Filter) is a virtual device driver file. Its function is to filter packets and pass these packets to the user module. This process includes some operating system-specific code. The second module packet.dll provides a public interface for the Win32 platform. Different versions of Windows systems have their own kernel modules and user layer modules. Packet.dll is used to solve these differences. Calling packet.dll can run on a different version of Windows platform without recompilation. The third module WPCAP.DLL is not dependent on the operating system. It provides a higher level, abstract function. 3. Packet.dll and wpcap.dllpacket.dll are directly mapped to the kernel calls. WPCap.dll provides a more friendly and more powerful function call. 4. Advantages of WinPCAP

A standard grip interface is provided, compatible with LibPCAP, which enables network analysis tools under many UNIX platforms to easily develop various network analysis tools to fully consider various performance and efficiency, including for NPF kernels. Level Filters Support Support Nuclear Statistical Mode provides the ability to send packets, Packet.dll's Home: http://winpcap.polito.it/ You can download it here, DLLS And develop bag. Here is just a simple introduction to WinPCAP to do Sniffer, do not do in-depth research. You just need to install the driver downloaded to your computer, and use your program to call packet.dll. Packet.dll will be copied to your system directory when installing, or you can use WinRAR to open the installation package, you can see the file inside, and extract the packet.dll you want directly. Packet.dll provides a complete set of powerful APIs, which is basically consistent with the Packet32.dll provided by Microsoft DDK. People who have developed Windows applications will not be Mo Sheng, if you don't know how to use the DLL, please refer to the relevant book, not talking here. Newly built a DLL project is named SNIFFER2, saved to the hard disk. Copy the include, lib directory in the development package to the project directory. If you use Visual C , you can use the introduction library inside LIB directly. Shadowstar uses C Builder, you need to generate a lib file for packet.dll with the Implib tool provided by C Builder. The command line is as follows: IMPLIB -A Packet.lib Packet.dll 5. Simple SHADOWSTAR C Builder wrote a simple demo, only the code of the main part is given here, and the complete code can be downloaded at http://shadowstar.126.com/. Void __fastcall tMainform :: btnctrlclick (Tobject * Sender)

{

// define a Pointer to an adapter structure

LPADAPTER LPADAPTER = 0;

// define a Pointer to a packet structure

LPPACKET LPPACKET;

INT I;

DWORD DWERRORCODE;

DWORD DWVERSION;

DWORD DWINDOWSMAJORVERSON;

// Unicode Strings (WinNT)

Wchar adaptername [8192]; // String That Contains a list of the network adapters

Wchar * Temp, * Temp1; // ASCII STRINGS (Win95)

CHAR Adapternamea [8192]; // String That Contains a list of the network adapters

Char * tempa, * temp1a;

Int adapternum = 0, open;

Ulong adapterLength;

Char buffer [256000]; // Buffer to Hold The Data Coming from The Driver

Struct BPF_STAT Stat;

// Obtain the name of the adapters installed on this machine

AdapterLength = 4096;

ShowMessage ("Packet.dll Test Application. Library Version:") PacketGetVersion ());

ShowMessage ("Adapters Installed:");

i = 0;

// The data returned by packetagetapternames is different in win95 and in winnt.

// we have to check the OS on which we are running

DWVersion = getVersion ();

DWINDOWSMAJORVERSION = (DWORD)));

IF (! (dwversion> = 0x80000000 && dwwindowsmajorversion> = 4))

{// Windows NT

IF (PacketGetAdapternames (PTSTR) Adaptername, & AdapterLength) == FALSE)

{

ShowMessage ("Unable to Retrieve The List of the Adapters! / N");

Return;

}

Temp = adaptername;

Temp1 = adaptername;

While (* Temp! = '/ 0') || (* (TEMP-1)! = '/ 0'))

{

IF (* temp == '/ 0')

{

Memcpy (AdapterList [i], TEMP1, (TEMP-TEMP1) * 2);

TEMP1 = TEMP 1;

i ;

}

TEMP ;

}

Adapternum = i;

For (i = 0; i

SHOWMESSAGE (Format (L "/ N% D-% S / N", ArrayOfconst ((i 1, AdapterList [i]))))))))))))))))

}

Else // Windows 95

{

IF (PacketGetAdapternames ((PTSTR) Adapternamea, & AdapterLength) == false)

{

ShowMessage ("Unable to Retrieve The List of the Adapters! / N");

Return;

}

Tempa = adapternamea;

Temp1a = adaptername;

While (* Tempa! = '/ 0') || (* (TEMPA-1)! = '/ 0')) {

IF (* tempa == '/ 0')

{

Memcpy (AdapterList [i], TEMP1A, TEMPA-TEMP1A);

TEMP1A = TEMPA 1;

i ;

}

TEMPA ;

}

Adapternum = i;

For (i = 0; i

ShowMessage (Format ("/ N% D-% S / N", ArrayOfconst ((i 1, AdapterList [i]))))))))))))

}

LPADAPTER = PacketopenAdapter (AdapterList [0]);

IF (! lpadapter || (lpadapter-> hfile == invalid_handle_value)))

{

Dwerrorcode = getLastError ();

ShowMessage ("Unable to open the adapter, error code:% lx / n",

ArrayOfconst ((int) dwerrorcode)))))))))))))))

Return;

}

// set the network adapter in Promiscuous Mode

IF (PacketSethWFilter (LPADAPTER, NDIS_PACKET_TYPE_PMISCUOS) == false)

{

ShowMessage ("Warning: Unable to set propiscuous mode! / N");

}

// set a 512k buffer in the driver

IF (PacketSetBuff (lPadapter, 512000) == false)

{

ShowMessage ("Unable to set the kernel buffer! / N");

Return;

}

// set a 1 Second Read Timeout

IF (PacketsetReadTimeout (LPADAPTER, 1000) == FALSE)

{

ShowMessage ("Warning: Unable to set the read tiemout! / N");

}

// Allocate and Initialize a packet structure that will be used to

// Receive the packets.

IF ((lppacket = packetallocatepacket ()) == NULL)

{

ShowMessage ("/ Nerror: failed to allocate the lppacket structure.");

Return;

}

PacketinitPacket (LPPACKET, (Char *) Buffer, 256000);

IF (btnctrl-> caption == "& start")

{

BSTOP = false;

Btnctrl-> Caption = "& stop";

}

Else

{

BSTOP = TRUE;

Btnctrl-> CAPTION = "& start";

}

INT NINDEX = 0;

LPIP IP;

LPTCP TCP;

TLISTITEM * ITEM;

Struct BPF_HDR * HDR; int OFF;

BYTE * BUF;

// main capture loop

While (! BSTOP)

{

// Capture the Packets

IF (PacketReceivePacket (LPADAPTER, LPPACKET, TRUE) == false

ShowMessage ("ERROR: PacketReceivePacket Failed";

OFF = 0;

BUF = (Byte *) LPPACKET-> BUFFER;

While (off ulbytesreceived &! bstop)

{

NINDEX ;

HDR = (Struct BPF_HDR *) (BUF OFF);

OFF = HDR-> BH_HDRLEN

IP = (ip *) (BUF OFF Ethernet_Header_Length);

TCP = (TCP *) ((Byte *) IP (IP-> HDRLEN & IP_HDRLEN_MASK);

OFF = packet_wordalign (OFF HDR-> BH_CAPLEN);

Item = lsvpacket-> items-> add ();

Item-> CAPTION = NINDEX;

Item-> Subitems-> Add (GetProtocoltxt (IP-> Protocol);

Item-> SUBITEMS-> Add (inet_ntoa (* (in_addr *) & ip-> srcaddr);

Item-> Subitems-> Add (inet_ntoa (* (in_addr *) & ip-> dstaddr);

Item-> SUBITEMS-> Add (TCP-> SrcPort);

Item-> Subitems-> Add (tcp-> dstport);

Item-> Subitems-> Add (HDR-> BH_DATALEN);

Application-> ProcessMess ();

}

}

// Print the Capture Statistics

IF (PacketGetStats (LPadapter, & Stat) == False)

ShowMessage ("Warning: Unable to get stats from the kernel! / N");

Else

ShowMessage (Format ("/ N / N% D Packets Received./n%D Packets Lost",

ArrayOfconst ((int) stat.bs_recv, (int) stat.bs_drop)))))))))))))))))

PacketFreePacket;

// Close the adapter and exit

PacketCloseadapter (LPADAPTER);

Return;

} 6. Concluding Concluding If intercepted on a busy network, it does not set any filtration, the obtained packet is very much, and thousands of packets may be obtained in one second. If the application does not perform the necessary performance optimization, the packet will be lost, and the following is an optimization scheme for performance. This solution uses multithreading to process packets. Create a public packet buffer pool in the program, this buffer pool is a lilo queue. Use three threads in the program: A thread only capture operation, which will add a packet obtained from the driver to the header of the packet queue; another thread only filter operation, it checks the new to The packet checks whether it satisfies the filter condition. If it is not met, it deletes the queue; the last thread performs a packet processing operation, and the job is made by sending a new packet according to the received packet. In the above three threads, consider that the conditions of the data packets as possible should be the highest priority of the thread that captures the operation. Of course, the specific problem is specifically analyzed, what is the focus of the application. 2003-06-04 08:03