Use Sniffer to intercept IP packets flowing through the local Nic

Source: Internet
Author: User

Sniffer tool in Win2kSource codeDetailed information <Lan>

Sniffer source in Win2kCode.

[Code nature] complete VC applicationProgramCode
[Code author] ZW
[File size] 130 KB
[Updated on] 19:47:00
[Downloads] 6015
Http://www.vckbase.com/code/downcode.asp? Id = 1692

IP packet listener (for 9x) source code details <Lan>

IP packet listener source code (including VxD source code)

[Code nature] complete VC application code
[Code author] hihint
[File size] 158 KB
[Updated on] 8:48:00
[Downloads] 9047
Http://www.vckbase.com/code/downcode.asp? Id = 1508

 

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 arrived at 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 the wsadata schema object.
wsastartup (makeword (2, 2), & wsadata );
// create the original socket
sock = socket (af_inet, sock_raw, ipproto_raw);
// set the IP header operation option, where flag is set to true, handle the IP 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 so Ckaddr_in structure
records = * (in_addr *) phost-> h_addr_list [0]; // ip
addr_in.sin_family = af_inet;
addr_in.sin_port = htons (57274 );
// bind the original socket sock to the local NIC address
BIND (sock, (psockaddr) & addr_in, sizeof (addr_in ));
// dwvalue is the input and output parameter. If it is set to 1, it is executed. If it is set to 0,
DWORD dwvalue = 1;
// set 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 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 \ 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: % d \ r \ n", TCP. srcport );
Trace ("TCP destination port: % d \ r \ n", TCP. dstport );
Trace ("Packet Length: % d \ r \ n", 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 is very simple. However, because the captured data packet header does not contain frame information, it cannot receive other packets at the same network layer as the IP address, such as ARP packets and RARP packets. Taking into account the security factors in the preceding example program, we did not perform further analysis on data packets, but only provided an analysis method for general information. Through the introduction in this article, you can have a basic understanding of the usage of the original socket and the structure and Principles of the TCP/IP protocol. The code described in this article is compiled and debugged by Microsoft Visual C ++ 2000 in Windows 6.0.

Http://blog.csdn.net/raphyer/archive/2003/10/07/15670.aspx

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.