Capture network data in the original socket

zhaozj2021-02-12  155

A post on 9CBS: Technician and a considerable part of the technical personnel engaged in network security (refer to those who use the ready-made hacker software to attack instead of going to write code as needed), must not be odors (SNIFFER) ) Is unfamiliar, and the network sniffer plays 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.

The sniffer design principle sniffer as a network communication program, but also through network communication programming, the network card program is also performed using the usual socket mode. 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 structure is given below. The overall structure of the packet: Packet IP header TCP header (or other information header) data data will add TCP data segment head, or the UDP data segment header when the transport layer is reached from the application layer. The UDP data segment head is relatively simple, consists of an 8-byte head and data part, 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 may be some lengths of unfixed options after the fixed head, and the format of the TCP data segment header is given: 16-bit 16-bit source port destination port Sequence number confirmation number TCP header (reservation) 7-bit URG ACK PSH RST SYN FIN Window Size Checks and Emergency Pointer Options (0 or more 32-bit words) Data (optional) Analysis of this TCP Data Section Define by data structure_tcp in 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, etc.) 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 head format is as follows: 16-bit 16-bit version of the IHL service type Total length Identifier Sign Segment Offset Life Protocol Summary Check and Source Address Destination Address Options (0 or more)

Similarly, in the actual programming, it is also necessary to represent this IP data segment header through a data structure, which gives the definition of this data structure: typedef struct _ip {union {byte version; // version byte hdrlen; // hl}; byte ServiceType; // Service Type Word Totallen; // Growler Word ID; // Logo Union {Word Flags; // Sign Word Fragoff; // Segment Offset}; Byte TimeTolive; // Life Byte Protocol; // Protocol Word HDRCHKSUM; // header checks and dword srcaddr; // source address DWORD DSTADDR; // destination address BYTE OPTIONS; // Option} IP; typedef ip * lpip; typedef ip unaligned * ULPIP; in clarity After the composition of the segment head, the captured packet can be analyzed.

The specific implementation of the sniffer according to the previous design idea, 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 can analyze Out of the agreement, 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 article is relatively simple in the method of the original socket method, especially if you do not need to write a VXD virtual device driver, make it very easy to write the process, 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-7154.html

New Post(0)