VC ++ programming to implement network sniffer

xiaoxiao2021-03-06  53

VC programming to implement network sniffer

China Electric Wave Communication Institute Qingdao Branch Lang Rui

introduction

Engaged in network security technicians and quite quasi-hackers (referring to those who use ready-made hackers to attack rather than writing code to write code) Whether it is a very important role in terms of network security or in hacker attacks. By using the network sniffer, the NIC can set the network card to a mixed mode, and the capture and analysis of packets transmitted on the network can be realized. This analysis results are available for network security analysis, but such as a hacker can also provide a valuable information for further attacks. It can be seen that the sniffer is actually a double-edged sword. Although network sniffer technology will constitute a certain threat to network security after hacker, the hazard of the sniffer itself is not very large, mainly to provide network information for other hackers software, and true attacks are mainly from others. Black soft is done. In terms of network security, the network sniffing means can effectively detect packet information transmitted on the network, by analyzing the analysis of this information helps network security maintenance. Weigh the pros and cons, it is necessary to introduce the principles of the realization of the network sniffer.

Sniffer design principle

The sniffer acts as a network communication program, which is also a network communication, and the network card is programmed is also performed using the usual socket. However, the usual socket program can only respond to the data frames that have been issued in accordance with their hardware addresses or to other forms of data frames, such as reaching the network interface, but are not issued to this address, The network interface will not cause a response after verifying the delivery address is not your own address, which means that the application cannot receive the data packet. The purpose of the network sniffer is precisely from receiving all its data packets from the NIC, which can be sent to elsewhere. Obviously, to reach this, you cannot let the NIC will work according to the usual normal mode, but it must be set to a mixed mode.

Specific to program implementation, this setting of the NIC is implemented by the raw socket, which is also different from the data stream sleeve and data sets of data that are often commonly used. After creating the original socket, you need to set the IP header operation option via the setSockopt () function, and then bind the original socket to the local network card via the bind () function. In order to allow the original socket to accept all the data, it is also necessary to set by IOCTLSocket (), and you can also specify whether to processes the IP header person. At this point, it can be done to sniff the network packet, which is completed by the RECV () function as a stream socket or data report set of packets. However, it is different from the other two sockets that the original socket captured the packet at this time is not just a simple data information, but includes the most original data information of the IP header, TCP head, etc. This information 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. The following is given first. The overall structure of the packet:

data pack

IP header

TCP header (or other information head)

data

Data When the transfer layer is reached from the application layer, the TCP data segment head is added, or the UDP data segment head is added. The UDP data segment head is relatively simple, consists of an 8-byte head and data part, and the specific format is as follows:

16-bit

16-bit

Source port

Destination port

UDP length

UDP checksum

The TCP data is more complicated, starting with 20 fixed bytes, and there can be some lengths of unfixed options after the fixed head, and the format consisting of TCP data segments is given:

16-bit

16-bit

Source port

Destination port

Sequence number

Confirmation Number

TCP head length

(Reserved) 7-bit URG

ACK

PSH

RST

SYN

FIN

Window size

Check and verify

Emergency pointer

Options (0 or more 32-bit words)

Data (optional)

The analysis of this TCP data segment header can be defined by the data structure_tcp in the programming implementation:

Typedef struct _tcp {word srcport; // Source port word dstport; // destination port dword seqnum; // sequence number DWORD ACKNUM; // confirmation number byte Dataoff; // TCP head length Byte Flags; // Sign (URG, ACK Word Window; // Window Size Word Chksum; // Check and Word Urgptr; // Emergency Pointer} TCP; TypeDef TCP * LPTCP; TYPEDEF TCP UNALIGNED * ULPTCP;

At the network layer, add an IP data segment header to the TCP packet to form an IP datagram. The IP data header is transmitted in large end order, from left to right, version of the high byte (SPARC is a big end point; Pentium is a small endpoint machine). If it is a small end point, you will switch before sending and receiving and then transferring. The IP data segment format is as follows:

16-bit

16-bit

version

IHL

Service type

Total length

Logo

Sign

Segmentation offset

Life period

protocol

Head checksum

source address

Destination address

Options (0 or more)

Similarly, in actual programming, it is also necessary to represent this IP data segment header through a data structure, and the definition of this data structure is given:

TYPEDEF STRUCT_IP {union {byte version; // version byte hdrlen; // hth}; BYTE ServiceTYPE; // Service Type Word Totallen; // Great Word ID; // Logo Union {Word Flags; // Sign Word Fragoff; // segmentation offset}; Byte TimeTolive; // Life Byte Protocol; // Protocol Word HDRCHKSUM; // Header Auto and DWORD SRCADDR; // Source Address DWORD DSTADDR; // Destination Address Byte Options; // Option } Ip; typedef ip * lpip; typedef ip UNALIGNED * ULPIP;

After clarifying the components of the above data segments, the captured packets can be analyzed.

Snifier specific implementation

According to the previous design ideas, it is not difficult to write the realization code of the network sniffer. The following is given a simple example, which can capture all the local network cards, and analyze the protocol, IP source address , IP target address, TCP source port number, TCP target port number, and packet length. Since the program's design process has been clearly described, it will not be described here, and the specific implementation of the program is explained in conjunction with the annotation of the procedure, while the error check and other protective code. . The main code implementation list is:

/ / Check the Winsock version number, WSADATA is WSADATA structure object WSAStartup (Makeword (2, 2), & WSADATA); // Create original socket SOCK = Socket (AF_INET, SOCK_RAW, IPPROTO_RAW)); // Set IP header operation option Where Flag is set to TURE, processes the IP header to process setsockopt (SOCK, IPPROTO_IP, IP_HDRINCL, (CHAR *) & flag, sizeof (flag)); // Get this name gethostname ((char *) localname, sizeof (localname ) -1); // Get local IP address phost = gethostByName ((char *) localname))); // Plug SockAddr_in structure addr_in.sin_addr = * (in_addr *) phost-> h_addr_list [0]; //ipaddr_in.sin_family = AF_INET; addr_in.sin_port = htons (57274); // Bind the original socket SOCK to the local network card address BIND (SOCK, (PSOCKADDR) & addr_in, sizeof (addr_in)); // dWValue is the input output parameter, When executed at 1, cancel DWORD DWVALUE = 1; // Sets SOCK_RAW to SiO_RCVALL to receive all IP packets. The definition of sio_rcvall // is: #define sio_rcvall _wsaiow (IOC_vendor, 1) ioctlsocket (SOCK, SIO_RCVALL, & DWVALUE); the previous work is basically setting up the original socket, and the original socket is set, When it is possible to operate according to the intended purpose, you can receive data from the NIC from the NIC, and the received raw packet is placed in cache RECVBUF [], and the buffer length buffer_size is defined as 65535. The captured data packet can then be analyzed according to the front side of the front side, the structure of the IP data segment, the TCP data segment header is described.

While (True) {// Receive the original packet information int RET = Recv (Sock, Recvbuf, Buffer_SIZE, 0); if (RET> 0) {// Analysis of the packet, and outputs the analysis result IP = * (IP *) RECVBUF; TCP = * (TCP *); Trace ("Protocol:% S / R / N", getProtocoltxt (IP.Protocol); Trace ("IP source address:% s / R / N ", INET_NTOA (* (in_addr *) & ip.srcaddr); Trace (IP Target Address:% S / R / N", INET_NTOA (* (In_ADDR *) & ip.dstaddr); Trace ("TCP Source port number:% d / r / n ", tcp.srcport); Trace (" TCP target port number:% d / r / n ", tcp.dstport); Trace (" Package length:% D / R / N / R / N / R / N ", NTOHS (ip.totallen));}}

Among them, the GetProtocoltxt () function is used when performing protocol analysis, which is responsible for converting protocols in the IP package into text output, which is implemented as follows:

#define PROTOCOL_STRING_ICMP_TXT "ICMP" #define PROTOCOL_STRING_TCP_TXT "TCP" #define PROTOCOL_STRING_UDP_TXT "UDP" #define PROTOCOL_STRING_SPX_TXT "SPX" #define PROTOCOL_STRING_NCP_TXT "NCP" #define PROTOCOL_STRING_UNKNOW_TXT "UNKNOW" ...... CString CSnifferDlg :: GetProtocolTxt (int Protocol) {switch ( Protocol) {case IPPROTO_ICMP: // 1 / * control message protocol * / return PROTOCOL_STRING_ICMP_TXT; case IPPROTO_TCP: // 6 / * tcp * / return PROTOCOL_STRING_TCP_TXT; case IPPROTO_UDP: // 17 / * user datagram protocol * / return PROTOCOL_STRING_UDP_TXT; default : Return protocol_string_unknow_txt;} Finally, in order to make the program successfully compile, you need to include header file Winsock2.h and WS2TCPIP.H. In this example, the analysis results are output with the trace () macro, running in the debug state, and one of the analyzes obtained is as follows:

Agreement: UDPIP source address: 172.168.1.5IP destination address: 172.168.1.255TCP source port number: 16707TCP target port number: 19522 Package length: 78 ... Protocol: TCPIP source address: 172.168.171IP target Address: 172.168.1.1 TCP source port number: 19714TCP target port number: 10 Package length: 200 ... From the analysis result, this program fully has the basic functions of the data capture of the sniffer and the analysis of the analysis of the packet.

summary

This paper introduces the method of capturing network data in the original socket, especially if you do not need to write a VXD virtual device driver, you can implement the captain, making it very easy to write, but due to capture The data packet header does not include frame information, so other packets, such as ARP packets, RARP packets, and the like cannot be received. The safety factor is taken into account in the sample program given in the previous example, and there is no further analysis of the packet, but only the analysis method of general information is given. Through this paper, there is a basic understanding of the use of the original socket and the principle of TCP / IP protocol structure. The code described herein is compiled by Microsoft Visual C 6.0 under Windows 2000.

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

New Post(0)