Use Sniffer to intercept IP packets flowing through the local Nic

Source: Internet
Author: User

Technical staff engaged in network security and a considerable number of quasi-hackers (those who use off-the-shelf hacker software for attacks rather than writing their own code as needed) will certainly not use the network sniffer (sniffer) the network sniffer plays an important role in both network security and hacker attacks.

The network sniffer can be used to set the NIC to the hybrid mode and capture and analyze the packets transmitted over the network. This analysis result can be used for network security analysis. However, if used by hackers, it can also provide valuable information for further attacks. It can be seen that the sniffer is actually a double-edged sword. Although the network sniffer technology is exploited by hackers to pose a certain threat to network security, the sniffer itself is not very harmful, mainly used to provide network intelligence for other hacker software, the real attacks are mainly completed by other black softwares. In terms of network security, network sniffing can effectively detect the packet information transmitted over the network. The analysis and utilization of this information helps to maintain network security. Weigh the pros and cons, it is necessary to introduce the implementation principle of network sniffer.

Design Principle of sniffer

As a network communication program, the sniffer program implements network communication through programming the network card. The programming of the network card also uses the common socket method. However, normally, a socket program can only respond to data frames that match its own hardware address or are sent in broadcast form, for other data frames that have reached the network interface but are not sent to this address, the network interface will not respond after verifying that the delivery address is not its own address, that is to say, the application cannot receive incoming packets. The purpose of the network sniffer is to receive all packets passing through it from the network adapter. These packets can be sent to or from other places. Obviously, to achieve this goal, you must set the network adapter to the hybrid mode instead of the normal mode.

Specifically, in programming implementation, this set of NIC hybrid mode is implemented through the raw socket, which is different from the commonly used data stream socket and datagram socket. After creating the original socket, you need to use the setsockopt () function to set the IP header operation options, and then bind the original socket to the local Nic through the bind () function. To enable the original socket to accept all the data, you also need to use ioctlsocket () to set and specify whether to process the IP header in person. So far, we can start to sniff network data packets, and the data packet is still obtained through the recv () function like the stream socket or datagram socket. However, unlike the other two sockets, the data packets captured by the original socket are not just data information, instead, it contains the most primitive data information with an IP header and a TCP header, which retains its original appearance during network transmission. By analyzing the original information transmitted at the lower layer, we can obtain some information about the network. As the data is packaged at the network layer and transport layer, data packets need to be analyzed based on the additional frame header. The following describes the structure of the data packet:

Data Packets

IP header TCP Header (or other information headers) data

When the data arrives at the transport layer from the application layer, the TCP Data Segment header or the UDP data segment header will be added. The UDP data segment header is relatively simple and consists of an 8-byte header and data part. The specific format is as follows:

16-bit 16-bit
Source Port destination port
UDP length UDP checksum

The TCP Data header is complex. It starts with 20 fixed bytes. Some unfixed length options can be added after the Fixed Header. The format composition of the TCP Data Segment header is given below:

16-bit 16-bit
Source Port destination port
Sequence Number
Confirmation Number
TCP Header Length (retained) 7-bit urg ack psh rst syn fin window size
Checksum and emergency pointer
Optional (0 or more 32-bit characters)
Data (optional)

The analysis of this TCP Data Segment header can be defined by Data Structure _ TCP in programming implementation:

Typedef struct _ TCP {WORD SrcPort; // Source Port
WORD DstPort; // the destination port.
DWORD SeqNum; // sequence number
DWORD AckNum; // confirmation number
BYTE DataOff; // TCP Header Length
BYTE Flags; // flag (URG, ACK, etc)
WORD Window; // Window size
WORD Chksum; // checksum
WORD UrgPtr; // emergency pointer
} TCP;
Typedef TCP * LPTCP;
Typedef tcp unaligned * ULPTCP;

At the network layer, you must add an IP data segment header to the TCP data packet to form an IP data packet. The IP data header is transmitted in the order of an advanced terminal machine, from left to right, and the high-byte value of the version field is transmitted first (using a large-scale terminal machine as the IP address data header and using a Pentium as a small terminal machine ). If it is a small endpoint machine, it must be converted before transmission. The IP data segment Header Format is as follows:

16-bit 16-bit
Total length of IHL service types
Marker segment offset
Life-cycle protocol header checksum
Source Address
Destination Address
Option (0 or more)

Similarly, in actual programming, you also need to use a Data Structure to represent the IP address data segment header. The following describes the definition of this data structure:

Typedef struct _ IP {
Union {BYTE Version; // Version
BYTE HdrLen; // IHL
};
BYTE ServiceType; // service type
WORD TotalLen; // total length
Word id; // ID
Union {WORD Flags; // flag
WORD FragOff; // segment offset
};
BYTE TimeToLive; // Life Cycle
BYTE Protocol; // Protocol
WORD HdrChksum; // header checksum
DWORD SrcAddr; // Source Address
DWORD DstAddr; // Destination Address
BYTE Options; // Option
} IP;
Typedef IP * LPIP;
Typedef ip unaligned * ULPIP;

After clarifying the structure of the above data segment headers, we can analyze the captured data packets.

Implementation of the sniffer

According to the previous design ideas, it is not difficult to write the implementation code of the network sniffer. The following is a simple example. This example can capture all packets passing through the local Nic, the Protocol, IP Source Address, IP Destination Address, TCP source port number, TCP destination port number, and packet length can be analyzed. As the previous design process of the program has been described clearly, I will not go into details here. The following will explain the specific implementation of the program with annotations, at the same time, Protection Code such as error check is removed for the sake of program flow clarity. The main code implementation list is:

// Check the Winsock version number. WSAData is a WSADATA structure object.
WSAStartup (MAKEWORD (2, 2), & WSAData );
// Create the original socket
Sock = socket (AF_INET, SOCK_RAW, IPPROTO_RAW ));
// Set the IP Address Header operation option, where flag is set to true, and handle the IP Address Header in person
Setsockopt (sock, IPPROTO_IP, IP_HDRINCL, (char *) & flag, sizeof (flag ));
// Obtain the local name
Gethostname (char *) LocalName, sizeof (LocalName)-1 );
// Obtain the local IP Address
PHost = gethostbyname (char *) LocalName ));
// Fill in the SOCKADDR_IN Structure
Addr_in.sin_addr = * (in_addr *) pHost-> h_addr_list [0]; // IP
Addr_in.sin_family = AF_INET;
Addr_in.sin_port = htons (0, 57274 );
// Bind the original socket sock to the local NIC address
Bind (sock, (PSOCKADDR) & addr_in, sizeof (addr_in ));
// DwValue is the input/output parameter. If it is set to 1, it is executed. If it is set to 0, it is canceled.
DWORD dwValue = 1;
// Set SOCK_RAW to SIO_RCVALL to receive all IP packets. Among them, SIO_RCVALL
// The definition is: # define SIO_RCVALL _ WSAIOW (IOC_VENDOR, 1)
Ioctlsocket (sock, SIO_RCVALL, & dwValue );

The previous work is basically to set the original socket. When the original socket is set to work as expected, you can use the recv () function to receive data from the NIC, the received raw data packet is stored in the cache RecvBuf [], and the buffer length BUFFER_SIZE is defined as 65535. Then, we can analyze the captured data packets based on the structure descriptions of the IP data segment header and TCP Data Segment header:

While (true)
{
// Receives the original data packet information
Int ret = recv (sock, RecvBuf, BUFFER_SIZE, 0 );
If (ret> 0)
{
// Analyze the data packets and output the analysis results
Ip = * (IP *) RecvBuf;
Tcp = * (TCP *) (RecvBuf + ip. HdrLen );
TRACE ("Protocol: % s", GetProtocolTxt (ip. Protocol ));
TRACE ("IP Source Address: % s", inet_ntoa (* (in_addr *) & ip. SrcAddr ));
TRACE ("IP target address: % s", inet_ntoa (* (in_addr *) & ip. DstAddr ));
TRACE ("TCP source port: % d", tcp. SrcPort );
TRACE ("TCP destination port: % d", tcp. DstPort );
TRACE ("Packet Length: % d", ntohs (ip. TotalLen ));
}
}

The GetProtocolTxt () function is used for protocol analysis. This function is used to convert the Protocol (Digital identifier) in the IP package into text output. The function 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 datasync protocol */
Return PROTOCOL_STRING_UDP_TXT;
Default:
Return PROTOCOL_STRING_UNKNOW_TXT;
}

Finally, to make the program compile successfully, the header files winsock2.h and ws2tcpip. h must be included. In this example, the analysis results are output using the TRACE () macro and run in the debugging status. The analysis result is as follows:

Protocol: UDP
IP Source Address: 172.161.5
IP Address: 172.161.255
TCP source port: 16707
TCP destination port: 19522
Packet Length: 78
......
Protocol: TCP
IP Source Address: 172.161.17
IP Address: 172.161.1
TCP source port: 19714
TCP destination port: 10
Packet Length: 200
......

From the analysis results, we can see that this program is fully capable of data capture by the sniffer and analysis of data packets.

Summary

This article describes how to capture network data using the original socket method, which is relatively simple. In particular, packet capture can be implemented without writing the VxD Virtual Device Driver, the compilation process becomes very simple,

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.