Implement Snifer with Raw Socket

zhaozj2021-02-11  176

First. Summary

Raw Socket: Original Socket

It can be used to send and receive raw packets above the IP layer, such as ICMP, TCP, UDP ...

Int suckraw = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);

This way we created a Raw Socket

Sniffer: sniffer

I think most people may know most of the principles.

1. Place the network card in a mixed mode;

2. Capture the packet;

3. Analyze the packet.

But the specific realization knows is not so much. Ok, let us use the Raw Socket to make a self-Sniffer.

2. Place the network card in a mixed mode

In normal case, a network interface should only respond to two data frames:

One is a data frame that matches its hardware address

One is a broadcast data frame that is sent to all machines

If you want the NIC to receive all the data through it, no matter whether it is sent to it, you must put the network card in a mixed mode. That is to say

Its thinking is chaotic, not working in normal ways. The code is implemented with the RAW Socket is as follows:

Setsockopt (SOCK, IPPROTO_IP, IP_HDRINCL, (Char *) & flag, sizeof (flag); // Setting IP header operation options

Bind (SockRaw, (psockaddr) & addrlocal, sizeof (addrlocal); // Bind SockRaw to your local network card

IOCTLSOCKET (SockRaw, Sio_rcvall, & DWValue); // Let SockRaw accept all data

The FLAG flag is used to set the IP header operation, that is, to proceed to handle IP headers: BOOL flag = Ture;

Addrlocal is a local address: SockAddr_in Addrlocal;

DWValue is executed for the input and output parameters, and the cancellation is canceled at 1: DWORD DWVALUE = 1;

Didn't think so simple?

III. Capture the packet

Your SockRaw is now working, you can use the Sniffer detection tool to detect on the local area network, see you

Whether the NIC is in a mixed mode (such as the Arpkiller of DigitalBrain).

Can't let him waste resources, catch your bag!

Recv (SockRaw, Recvbuf, Buffer_Size, 0); // Accept any packet

#define buffer_size 65535

Char recvbuf [buffer_size];

More and more discovered that Sniffer is so simple, such a function has completed the task of grasping the packet.

IV. Analyze the data package

This round-caught bag and usually acceptable bags accepted by Socket can be just a matter, including original information such as IP, TCP. To analyze it

First you know these structures.

The overall structure of the packet:

----------------------------------------------

| ip header | TCP Header | Data |

----------------------------------------------

IP header structure:

4 8 16 32 Bit

| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------ |

| Ver | IHL | TYPE OF Service | Total Length |

| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------ |

| Identification | Flags | Fragment Offset || ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------

| TIME TO LIVE | Protocol | Header Checksum |

| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------ |

Source Address |

| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------ |

| Destination Address |

| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------ |

| OPTION PADDING |

| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------ |

| Data |

| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------ |

TCP Header Structure:

16 32 Bit

| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------- |

Source Port | Destination Port |

| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------- |

| Sequence Number |

| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------- |

| ACKNOWLEDGEMENT NUMBER |

| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------- |

| Offset | RESRVD | U | A | P | r | s | f | window |

| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------- |

CHECKSUM | Urgent Pointer |

| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------- |

| OPTION PADDING |

| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------- |

| Data |

| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------- |

5. Implement SNIFFER

OK!

It's clear now, what are you waiting for?

Here is the code I have written in BCB6, for reference only.

(Need to join WS2_32.lib this file in the project file)

// ******************************************************** ************************ //

// * CPP file: wmain.cpp

// * Simple Sniffer by ShadowStar

// * http://shadowstar.126.com/

// ******************************************************** ************************ //

#include

#pragma HDRSTOP

#include

#include

#include

#include

#include "wmain.h"

/ / -------------------------------------------------------------------------------------------- ---------------------------

#pragma package (smart_init)

#pragma resource "* .dfm"

TMAINFORM * MainForm;

/ / -------------------------------------------------------------------------------------------- ---------------------------

__fastcall Tmainform :: TMAINFORM (Tcomponent * Owner)

: TFORM (OWNER)

{

Wsadata wsadata;

Bool flag = true;

INT ntimeout = 1000;

Char localname [16];

Struct Hostent * Phost;

/ / Check the Winsock version number

IF (WSAStartup (MakeWord (2, 2), & WSADATA)! = 0)

Throw Exception ("WSAStartup Error!");

// Initialization Raw Socket

IF ((SOCK = Socket (AF_INET, SOCK_RAW, IPPROTO_RAW) == Invalid_socket)

Throw Exception ("Socket Setup Error!");

/ / Set the IP header operation option

IF (setsockopt (sock, ipproto_ip, ip_hdrincl, (char *) & flag, sizeof (flash) == Socket_ERROR)

Throw Exception ("SetsockOpt IP_HDRINCL ERROR!");

// Get this name

IF (GethOstName ((char *) localname, sizeof (localname) -1) == Socket_ERROR)

Throw Exception ("gethostname Error!"); // Get local IP addresses

IF ((phost = gethostbyname) == null)

Throw Exception ("GethostByName Error!");

Addr_in.sin_addr = * (in_addr *) Phost-> h_addr_list [0]; // ip

Addr_in.sin_family = af_INet;

Addr_in.sin_port = htons (57274);

// Bind the SOCK to the local address

IF (Bind (psockaddr) & addr_in, sizeof (addr_in)) == Socket_ERROR)

Throw Exception ("Bind Error!");

ISortDirection = 1;

}

/ / -------------------------------------------------------------------------------------------- ---------------------------

__fastcall tMainform :: ~ tMAINFORM ()

{

WSACLEANUP ();

}

/ / -------------------------------------------------------------------------------------------- ---------------------------

Void __fastcall tMainform :: btnctrlclick (Tobject * Sender)

{

TLISTITEM * ITEM;

DWORD DWVALUE;

INT NINDEX = 0;

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

{

DWValue = 1;

/ / Set SOCK_RAW to SiO_RCVALL to receive all IP packets

IOCTLSocket (Sock, Sio_rcvall, & DWValue)! = 0)

Throw Exception ("IOCTLSOCKET SIO_RCVALL ERROR!");

BSTOP = false;

Btnctrl-> Caption = "& stop";

LSVPACKET-> Items-> Clear ();

}

Else

{

Dwvalue = 0;

BSTOP = TRUE;

Btnctrl-> CAPTION = "& start";

/ / Set SOCK_RAW to SiO_RCVALL, stop receiving

IOCTLSocket (Sock, Sio_rcvall, & DWValue)! = 0)

Throw Exception ("WSAIOCTL SIO_RCVALL ERROR!");

}

While (! BSTOP)

{

IF (RECV (Sock, Recvbuf, Buffer_Size, 0)> 0)

{

NINDEX ;

IP = * (ip *) Recvbuf;

TCP = * (TCP *) (Recvbuf (IP.HDRLEN & IP_HDRLEN_MASK);

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

Item-> CAPTION = NINDEX;

Item-> Subitems-> Add (getProtocoltxt (IP.Protocol);

Item-> Subitems-> add (inet_ntoa (* (in_addr *) & ip.srcaddr)); item-> subs-> add (inet_ntoa (* (in_addr *) & ip.dstaddr));

Item-> Subitems-> Add (tcp.srcport);

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

Item-> Subitems-> Add (ntoHs (ip.totallen);

}

Application-> ProcessMess ();

}

}

/ / -------------------------------------------------------------------------------------------- ---------------------------

ANSISTRING __FASTCALL TMAINFORM :: 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_unknown_txt;

}

}

/ / -------------------------------------------------------------------------------------------- ---------------------------

// ******************************************************** ************************ //

// * Header file: wmain.h for wmain.cpp Class Tmainform

// ******************************************************** ************************ //

/ / -------------------------------------------------------------------------------------------- ---------------------------

#ifndef wmainh

#define WMAINHHH

/ / -------------------------------------------------------------------------------------------- ---------------------------

#define buffer_size 65535

#include

#include

#include

#include

#include

#include

#include

#include "netmon.h"

/ / -------------------------------------------------------------------------------------------- ---------------------------

Class Tmainform: Public TFORM

{

__published: // Ide-management Components

TPANEL * PANEL1; TBUTTON * BTNCTRL;

TLISTVIEW * LSVPAVPACKET;

TLABEL * Label1;

Void __fastcall btnctrlclick (TOBJECT * Sender);

Void __fastcall lsvpacketColumnClick (Tobject * Sender,

TListColumn * column);

Void __fastcall lsvpacketcompare (Tobject * Sender, TLISTITEM * ITEM1,

TLISTITEM * ITEM2, INT DATA, INT & COMPARE

Void __fastcall label1click (TOBJECT * Sender);

PRIVATE: // user declarations

Ansistring __fastcall getProtocoltxt (int protocol);

Public: // user declarations

Socket sock;

SockAddr_in addr_in;

IP IP;

TCP TCP;

PSUHDR PSDHEADER;

Char recvbuf [buffer_size];

Bool bstop;

Int isortdiRection;

Int iColumnTosort;

__fastCall Tmainform (Tcomponent * Owner);

__fastcall ~ tMAINFORM ();

}

/ / -------------------------------------------------------------------------------------------- ---------------------------

Extern package tMainform * mainform;

/ / -------------------------------------------------------------------------------------------- ---------------------------

#ENDIF

Stealing a lazy, IP, TCP head, and some macro definitions with Netmon.h's head, this file can be found in the BCB6's INCLUDE directory.

At that, the related content related to this procedure is as follows:

// ******************************************************** ************************ //

// * Header file: netmon.h

// ******************************************************** ************************ //

//

// ip packet structure

//

Typedef struct _ip

{

union

{

Byte Version;

Byte HDRLEN;

}

BYTE ServiceType;

Word Totallen;

Word ID;

union

{

Word flagg;

Word fragoff;

}

BYTE TIMETOLIVE;

BYTE Protocol;

Word hdrchksum;

DWORD SRCADDR;

DWORD DSTADDR;

BYTE OPTION [0];

} IP;

TYPIDEF IP * LPIP;

TypeDef IP UNALIGNED * ULPIP;

//

// TCP Packet Structure

//

Typedef struct_tcp

{

Word Srcport;

Word dstport;

DWORD seqnum;

DWORD ACKNUM;

BYTE DATAOFF;

BYTE flags;

Word window;

Word chksum;

Word urgptr;} TCP;

TypeDef TCP * LPTCP;

Typedef TCP UNALIGNED * ULPTCP;

// Upper Protocols

#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"

This file also claimed to be not claimed.

// ******************************************************** ************************ //

// * Header file: mstcpip.h

// ******************************************************** ************************ //

// Copyright (c) Microsoft Corporation. All Rights Reserved.

#iF _MSC_VER> 1000

#pragma overce

#ENDIF

/ * Argument structure for SiO_keepalive_vals * /

Struct TCP_Keepalive {

u_long onoff;

U_long KeepaliveTime;

U_long KeepaliveInterVal;

}

// new WSAIOCTL OPTIONS

#define sio_rcvall_wsaiow (IOC_VENDOR, 1)

#define sio_rcvall_mcast_Wsaiow (IOC_VENDOR, 2)

#define sio_rcvall_igmpmcast_wsaiow (IOC_VENDOR, 3)

#define SiO_keepalive_vals_wsaiow (IOC_VENDOR, 4)

#define SiO_Absorb_rtralert_wsaiow (IOC_VENDOR, 5)

#define SiO_UCAST_IF_WSAIOW (IOC_VENDOR, 6)

#define sio_limit_broadcasts_wsaiow (IOC_VENDOR, 7)

#define SiO_index_bind_wsaiow (IOC_VENDOR, 8)

#define sio_index_mcastif_wsaiow (IOC_VENDOR, 9)

#define sio_index_add_mcast_wsaiow (IOC_VENDOR, 10)

#define sio_index_del_mcast_wsaiow (IOC_VENDOR, 11)

// Values ​​for use with sio_rcvall * Options

#define rcvall_off 0

#define rcvall_on 1

#define rcvall_socketlevelonly 2

Now our self-Sniffer is done, run, start ... wow, so many of them are issued from this machine,

What is it doing? The original Adminstrator password is empty, and the Nimda virus!

Sixth.

Advantages: Simple implementation, do not need to do drivers to achieve capture. Disadvantages: Data Package does not include frame information, can not receive other packets with IP, such as ARP, RARP ...

The procedures provided here are only an example of a Sniffer, and there is no further analysis of the packet. The purpose of writing this article is to be familiar

Raw Socket Programming Method, Understanding the TCP / IP Protocol Structure Principle and the relationship between the various protocols.

The author is limited, and the deficiencies should be criticized.

http://shadowstar.126.com/

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

New Post(0)