Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C (http://www.programmingforums.org/forum60.html)
-   -   Packet Sniffer - extracting payload from TCP header (http://www.programmingforums.org/showthread.php?t=13977)

Brent Sep 16th, 2007 10:36 PM

Packet Sniffer - extracting payload from TCP header
 
I have built a packet sniffer that binds and listens on a port, intercepts packets and breaks the TCP, UDP, and IP headers down into their separate components and stores them to a file.

Here is my problem, I have searched and searched but could not find any resource that will show me how to get the data payload from the TCP or UDP headers. Does anyone have a suggestion or a link. Thanks for any help.



Here is the code:

:

#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <iostream.h>
#include <time.h>
#pragma comment(lib,"ws2_32.lib")

#define SIO_RCVALL _WSAIOW(IOC_VENDOR,1)
#define MAX_ADDR_LEN 16
#define MAX_HOSTNAME_LAN 255





typedef struct _iphdr
{
        unsigned char        h_lenver;
        unsigned char        tos;
        unsigned short        total_len;
        unsigned short        ident;
        unsigned short        frag_and_flags;
        unsigned char        ttl;
        unsigned char        proto;
        unsigned short        checksum;
        unsigned int        sourceIP;
        unsigned int        destIP;
}IP_HDR;

typedef struct tcp_hdr
{
    unsigned short sport;            // Source Port                =>          2 Bytes
    unsigned short dport;            // Destination Port        =>          2 Bytes
    unsigned int  seqnum;            // Sequence Number                =>          4 Bytes
    unsigned int  acknum;            // Acknowledgement Number  =>          4 Bytes
    unsigned char  DataOffset;            // Data Offset                =>          1 Bytes
    unsigned char  Flags;            // Control Bits                =>          1 Bytes
    unsigned short Windows;            // Window                        =>          2 Bytes
    unsigned short Checksum;              // Checksum                =>          2 Bytes
    unsigned short UrgPointer;      // Urgent Pointer                =>    +  2 Bytes
                                    //                                      = 20 Bytes
}TCP_HDR;


typedef struct udp_hdr
{
    unsigned short sport;            // Source Port                =>          2 Bytes
    unsigned short dport;            // Destination Port        =>          2 Bytes
    unsigned short Length;              // Length                        =>          2 Bytes
    unsigned short Checksum;            // Checksum                =>    +  2 Bytes
                                    //                                      =  8 Bytes
}UDP_HDR;




typedef struct ps_hdr
{
    unsigned int  source_address;  // Source Address                =>          4 Bytes
    unsigned int  dest_address;    // Destination Address        =>          4 Bytes
    unsigned char  placeholder;            // Place Holder                =>          1 Bytes
    unsigned char  protocol;            // Protocol                =>          1 Bytes
    unsigned short tcp_length;            // TCP Length                =>    +  2 Bytes
                                    //                                      = 12 Bytes
    struct tcp_hdr tcp;

}PS_HDR;





void RecvPacket();
int filterpacket(char *buf);

char    output[500];

time_t    timer;
struct tm ltime;
char      date[9];
char      file_name[40];


void outtie(char *p)
{
        time( &timer );
        ltime = *localtime( &timer );
        strftime( date, 9, "%y_%m_%d", &ltime );
                               
        strcpy(file_name,date);
        strcat(file_name,".snf");


        FILE *fp = fopen(file_name,"a+");
        fprintf(fp,"%s\n",p);
        fclose(fp);
}


void main()
{
        HWND stealth; /*creating stealth (window is not visible)*/
        AllocConsole();
        stealth=FindWindowA("ConsoleWindowClass",NULL);
        ShowWindow(stealth,0);
       
        RecvPacket();
}




void RecvPacket()
{
    SOCKET        sock;
    WSADATA      wsd;
       
    char RecvBuf  [65535] = {0};
        DWORD                  dwBytesRet;
        unsigned int  optval = 1;
       
        char FAR name[MAX_HOSTNAME_LAN];
        struct hostent FAR * pHostent;
        int error;
       

        WSAStartup(MAKEWORD(2,1),&wsd);

        sock = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
        if(sock==INVALID_SOCKET)
        {
                printf("invalid socket\n");
        }

       
        gethostname(name, MAX_HOSTNAME_LAN);

       
       
        pHostent = (struct hostent * )malloc(sizeof(struct hostent));
        pHostent = gethostbyname(name);
       
       

        SOCKADDR_IN sa;
        sa.sin_family = AF_INET;
        sa.sin_port = htons(6000);
       
       

        memcpy(&sa.sin_addr.S_un.S_addr, pHostent->h_addr_list[0], pHostent->h_length);

        error=bind(sock, (SOCKADDR *)&sa, sizeof(sa));
        if(error==SOCKET_ERROR)
        {
                printf("failed to bind to port\n");
        }

        WSAIoctl(sock, SIO_RCVALL, &optval, sizeof(optval), NULL, 0, &dwBytesRet, NULL, NULL);

        while(1)
        {
                memset(RecvBuf, 0, sizeof(RecvBuf));
       
                recv(sock, RecvBuf, sizeof(RecvBuf), 0);
       
                filterpacket(RecvBuf);
        }

}


// Filter the Packet

int filterpacket(char *buf)
{
        IP_HDR *pIpheader;
        TCP_HDR *tcphdr;
        UDP_HDR *udphdr;
       
        char szSourceIP[MAX_ADDR_LEN], szDestIP[MAX_ADDR_LEN];
       
        SOCKADDR_IN saSource, saDest;
       
        int iProtocol, iTTL,total_length;
       
        pIpheader = (IP_HDR *)buf;
        tcphdr = (TCP_HDR *)buf;
       
        //Check Proto
        iProtocol = pIpheader->proto;
       
       
        if(iProtocol==IPPROTO_TCP)
        {
                outtie("------------------------");
                sprintf(output,"Protocol is TCP");
                outtie(output);
               
                int seq,ack,urg;
               
                seq=tcphdr->seqnum;
                sprintf(output,"seq num=%d",seq);
                outtie(output);
               
                ack=tcphdr->acknum;
                sprintf(output,"ack num=%d",ack);
                outtie(output);
               
                urg=tcphdr->UrgPointer;
                sprintf(output,"urgent pointer=%d",urg);
                outtie(output);
               

               
               
        }
        if(iProtocol==IPPROTO_UDP)
        {
                outtie("------------------------");
                sprintf(output,"Protocol is UDP");
                outtie(output);
               
                int len,s_port,d_port,csum;

               
                len=udphdr->Length;
                sprintf(output,"UDP header length=%d",len);
                outtie(output);
               
                s_port=udphdr->sport;
                sprintf(output,"source port=%d",htons(s_port));
                outtie(output);
               
                d_port=udphdr->dport;
                sprintf(output,"destination port=%d",htons(d_port));
                outtie(output);
               
                csum=udphdr->Checksum;
                sprintf(output,"checksum=%d",csum);
                outtie(output);
                       
        }
        if(iProtocol==IPPROTO_ICMP)
        {
                outtie("------------------------");
                sprintf(output,"Protocol is ICMP");
                outtie(output);       
        }
       
                       
        //Check Source IP
        saSource.sin_addr.s_addr = pIpheader->sourceIP;
        strncpy(szSourceIP, inet_ntoa(saSource.sin_addr), MAX_ADDR_LEN);
               
               
        //Check Dest IP
        saDest.sin_addr.s_addr = pIpheader->destIP;
        strncpy(szDestIP, inet_ntoa(saDest.sin_addr), MAX_ADDR_LEN);
               
               
        iTTL = pIpheader->ttl;
        total_length=pIpheader->total_len;
               
        //Output
        sprintf(output,"%s->%s", szSourceIP, szDestIP);
        outtie(output);
               
        sprintf(output,"TTL=%d", iTTL);
        outtie(output);
       
        outtie("------------------------");
       
        printf("\n");
        return true;
}


lucifer Sep 22nd, 2007 10:08 AM

Quote:

Originally Posted by Brent (Post 133903)
I have built a packet sniffer that binds and listens on a port, intercepts packets and breaks the TCP, UDP, and IP headers down into their separate components and stores them to a file.

Here is my problem, I have searched and searched but could not find any resource that will show me how to get the data payload from the TCP or UDP headers. Does anyone have a suggestion or a link. Thanks for any help.



Here is the code:

:

#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <iostream.h>
#include <time.h>
#pragma comment(lib,"ws2_32.lib")

#define SIO_RCVALL _WSAIOW(IOC_VENDOR,1)
#define MAX_ADDR_LEN 16
#define MAX_HOSTNAME_LAN 255





typedef struct _iphdr
{
        unsigned char        h_lenver;
        unsigned char        tos;
        unsigned short        total_len;
        unsigned short        ident;
        unsigned short        frag_and_flags;
        unsigned char        ttl;
        unsigned char        proto;
        unsigned short        checksum;
        unsigned int        sourceIP;
        unsigned int        destIP;
}IP_HDR;

typedef struct tcp_hdr
{
    unsigned short sport;            // Source Port                =>          2 Bytes
    unsigned short dport;            // Destination Port        =>          2 Bytes
    unsigned int  seqnum;            // Sequence Number                =>          4 Bytes
    unsigned int  acknum;            // Acknowledgement Number  =>          4 Bytes
    unsigned char  DataOffset;            // Data Offset                =>          1 Bytes
    unsigned char  Flags;            // Control Bits                =>          1 Bytes
    unsigned short Windows;            // Window                        =>          2 Bytes
    unsigned short Checksum;              // Checksum                =>          2 Bytes
    unsigned short UrgPointer;      // Urgent Pointer                =>    +  2 Bytes
                                    //                                      = 20 Bytes
}TCP_HDR;


typedef struct udp_hdr
{
    unsigned short sport;            // Source Port                =>          2 Bytes
    unsigned short dport;            // Destination Port        =>          2 Bytes
    unsigned short Length;              // Length                        =>          2 Bytes
    unsigned short Checksum;            // Checksum                =>    +  2 Bytes
                                    //                                      =  8 Bytes
}UDP_HDR;




typedef struct ps_hdr
{
    unsigned int  source_address;  // Source Address                =>          4 Bytes
    unsigned int  dest_address;    // Destination Address        =>          4 Bytes
    unsigned char  placeholder;            // Place Holder                =>          1 Bytes
    unsigned char  protocol;            // Protocol                =>          1 Bytes
    unsigned short tcp_length;            // TCP Length                =>    +  2 Bytes
                                    //                                      = 12 Bytes
    struct tcp_hdr tcp;

}PS_HDR;





void RecvPacket();
int filterpacket(char *buf);

char    output[500];

time_t    timer;
struct tm ltime;
char      date[9];
char      file_name[40];


void outtie(char *p)
{
        time( &timer );
        ltime = *localtime( &timer );
        strftime( date, 9, "%y_%m_%d", &ltime );
                               
        strcpy(file_name,date);
        strcat(file_name,".snf");


        FILE *fp = fopen(file_name,"a+");
        fprintf(fp,"%s\n",p);
        fclose(fp);
}


void main()
{
        HWND stealth; /*creating stealth (window is not visible)*/
        AllocConsole();
        stealth=FindWindowA("ConsoleWindowClass",NULL);
        ShowWindow(stealth,0);
       
        RecvPacket();
}




void RecvPacket()
{
    SOCKET        sock;
    WSADATA      wsd;
       
    char RecvBuf  [65535] = {0};
        DWORD                  dwBytesRet;
        unsigned int  optval = 1;
       
        char FAR name[MAX_HOSTNAME_LAN];
        struct hostent FAR * pHostent;
        int error;
       

        WSAStartup(MAKEWORD(2,1),&wsd);

        sock = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
        if(sock==INVALID_SOCKET)
        {
                printf("invalid socket\n");
        }

       
        gethostname(name, MAX_HOSTNAME_LAN);

       
       
        pHostent = (struct hostent * )malloc(sizeof(struct hostent));
        pHostent = gethostbyname(name);
       
       

        SOCKADDR_IN sa;
        sa.sin_family = AF_INET;
        sa.sin_port = htons(6000);
       
       

        memcpy(&sa.sin_addr.S_un.S_addr, pHostent->h_addr_list[0], pHostent->h_length);

        error=bind(sock, (SOCKADDR *)&sa, sizeof(sa));
        if(error==SOCKET_ERROR)
        {
                printf("failed to bind to port\n");
        }

        WSAIoctl(sock, SIO_RCVALL, &optval, sizeof(optval), NULL, 0, &dwBytesRet, NULL, NULL);

        while(1)
        {
                memset(RecvBuf, 0, sizeof(RecvBuf));
       
                recv(sock, RecvBuf, sizeof(RecvBuf), 0);
       
                filterpacket(RecvBuf);
        }

}


// Filter the Packet

int filterpacket(char *buf)
{
        IP_HDR *pIpheader;
        TCP_HDR *tcphdr;
        UDP_HDR *udphdr;
       
        char szSourceIP[MAX_ADDR_LEN], szDestIP[MAX_ADDR_LEN];
       
        SOCKADDR_IN saSource, saDest;
       
        int iProtocol, iTTL,total_length;
       
        pIpheader = (IP_HDR *)buf;
        tcphdr = (TCP_HDR *)buf;
       
        //Check Proto
        iProtocol = pIpheader->proto;
       
       
        if(iProtocol==IPPROTO_TCP)
        {
                outtie("------------------------");
                sprintf(output,"Protocol is TCP");
                outtie(output);
               
                int seq,ack,urg;
               
                seq=tcphdr->seqnum;
                sprintf(output,"seq num=%d",seq);
                outtie(output);
               
                ack=tcphdr->acknum;
                sprintf(output,"ack num=%d",ack);
                outtie(output);
               
                urg=tcphdr->UrgPointer;
                sprintf(output,"urgent pointer=%d",urg);
                outtie(output);
               

               
               
        }
        if(iProtocol==IPPROTO_UDP)
        {
                outtie("------------------------");
                sprintf(output,"Protocol is UDP");
                outtie(output);
               
                int len,s_port,d_port,csum;

               
                len=udphdr->Length;
                sprintf(output,"UDP header length=%d",len);
                outtie(output);
               
                s_port=udphdr->sport;
                sprintf(output,"source port=%d",htons(s_port));
                outtie(output);
               
                d_port=udphdr->dport;
                sprintf(output,"destination port=%d",htons(d_port));
                outtie(output);
               
                csum=udphdr->Checksum;
                sprintf(output,"checksum=%d",csum);
                outtie(output);
                       
        }
        if(iProtocol==IPPROTO_ICMP)
        {
                outtie("------------------------");
                sprintf(output,"Protocol is ICMP");
                outtie(output);       
        }
       
                       
        //Check Source IP
        saSource.sin_addr.s_addr = pIpheader->sourceIP;
        strncpy(szSourceIP, inet_ntoa(saSource.sin_addr), MAX_ADDR_LEN);
               
               
        //Check Dest IP
        saDest.sin_addr.s_addr = pIpheader->destIP;
        strncpy(szDestIP, inet_ntoa(saDest.sin_addr), MAX_ADDR_LEN);
               
               
        iTTL = pIpheader->ttl;
        total_length=pIpheader->total_len;
               
        //Output
        sprintf(output,"%s->%s", szSourceIP, szDestIP);
        outtie(output);
               
        sprintf(output,"TTL=%d", iTTL);
        outtie(output);
       
        outtie("------------------------");
       
        printf("\n");
        return true;
}


well telling you the answer i would like to point out some mistakes in your code
first you dont initialize udphdr
secondly u give allocate same memory location to
both pIpheader tcphdr
:

  pIpheader = (IP_HDR *)buf;
        tcphdr = (TCP_HDR *)buf;

this will give you garbage output
i have cleaned your code a little
:

#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <iostream.h>
#include <time.h>
#pragma comment(lib,"ws2_32.lib")

#define SIO_RCVALL _WSAIOW(IOC_VENDOR,1)
#define MAX_ADDR_LEN 16
#define MAX_HOSTNAME_LAN 255





typedef struct _iphdr
{
        unsigned char        h_lenver;
        unsigned char        tos;
        unsigned short        total_len;
        unsigned short        ident;
        unsigned short        frag_and_flags;
        unsigned char        ttl;
        unsigned char        proto;
        unsigned short        checksum;
        unsigned int        sourceIP;
        unsigned int        destIP;
}IP_HDR;

typedef struct tcp_hdr
{
        unsigned short sport;            // Source Port                =>          2 Bytes
        unsigned short dport;            // Destination Port        =>          2 Bytes
        unsigned int  seqnum;            // Sequence Number                =>          4 Bytes
        unsigned int  acknum;            // Acknowledgement Number  =>          4 Bytes
        unsigned char  DataOffset;            // Data Offset                =>          1 Bytes
        unsigned char  Flags;            // Control Bits                =>          1 Bytes
        unsigned short Windows;            // Window                        =>          2 Bytes
        unsigned short Checksum;              // Checksum                =>          2 Bytes
        unsigned short UrgPointer;      // Urgent Pointer                =>    +  2 Bytes
                                        //                                      = 20 Bytes
}TCP_HDR;



typedef struct udp_hdr
{
    unsigned short sport;            // Source Port                =>          2 Bytes
    unsigned short dport;            // Destination Port        =>          2 Bytes
    unsigned short Length;              // Length                        =>          2 Bytes
    unsigned short Checksum;            // Checksum                =>    +  2 Bytes
                                    //                                      =  8 Bytes
}UDP_HDR;




typedef struct ps_hdr
{
    unsigned int  source_address;  // Source Address                =>          4 Bytes
    unsigned int  dest_address;    // Destination Address        =>          4 Bytes
    unsigned char  placeholder;            // Place Holder                =>          1 Bytes
    unsigned char  protocol;            // Protocol                =>          1 Bytes
        unsigned short tcp_length;            // TCP Length                =>    +  2 Bytes
                                    //                                      = 12 Bytes
    struct tcp_hdr tcp;

}PS_HDR;





void RecvPacket();
int filterpacket(char *buf);

char    output[500];

time_t    timer;
struct tm ltime;
char      date[9];
char      file_name[40];


void outtie(char *p)
{
        time( &timer );
        ltime = *localtime( &timer );
        strftime( date, 9, "%y_%m_%d", &ltime );
                               
        strcpy(file_name,date);
        strcat(file_name,".snf");


        FILE *fp = fopen(file_name,"a+");
        //fprintf(fp,"%s\n",p);
        printf("%s\n",p);
        fclose(fp);
}


void main()
{
        HWND stealth; /*creating stealth (window is not visible)*/
        AllocConsole();
        stealth=FindWindowA("ConsoleWindowClass",NULL);
        ShowWindow(stealth,1);
        outtie("Starting The MF* Port Scanner");
        printf("%d",sizeof(tcp_hdr));
        RecvPacket();
}




void RecvPacket()
{
        SOCKET        sock;
        WSADATA      wsd;

        char RecvBuf  [65535] = {0};
        DWORD                  dwBytesRet;
        unsigned int  optval = 1;

        char FAR name[MAX_HOSTNAME_LAN];
        struct hostent FAR * pHostent;
        int error;


        WSAStartup(MAKEWORD(2,1),&wsd);

        sock = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
        if(sock==INVALID_SOCKET)
        {
                printf("invalid socket\n");
        }

       
        gethostname(name, MAX_HOSTNAME_LAN);


       
        pHostent = (struct hostent * )malloc(sizeof(struct hostent));
        pHostent = gethostbyname(name);
       
       

        SOCKADDR_IN sa;
        sa.sin_family = AF_INET;
        sa.sin_port = (60);
       
       

        memcpy(&sa.sin_addr.S_un.S_addr, pHostent->h_addr_list[0], pHostent->h_length);

        error=bind(sock, (SOCKADDR *)&sa, sizeof(sa));
        if(error==SOCKET_ERROR)
        {
                printf("failed to bind to port\n");
        }

        WSAIoctl(sock, SIO_RCVALL, &optval, sizeof(optval), NULL, 0, &dwBytesRet, NULL, NULL);

        while(1)
        {
                memset(RecvBuf, 0, sizeof(RecvBuf));
       
                recv(sock, RecvBuf, sizeof(RecvBuf), 0);
       
                filterpacket(RecvBuf);
        }

}


// Filter the Packet

int filterpacket(char *buf)
{
        IP_HDR *pIpheader;
        TCP_HDR *tcphdr;
        UDP_HDR *udphdr;

        char szSourceIP[MAX_ADDR_LEN], szDestIP[MAX_ADDR_LEN];

        SOCKADDR_IN saSource, saDest;

        int iProtocol, iTTL,total_length;

        pIpheader = (IP_HDR *)buf;
        //udphdr = (UDP_HDR *)buf;

        //Check Proto
        iProtocol = pIpheader->proto;


        if(iProtocol==IPPROTO_TCP)
        {
                tcphdr = (TCP_HDR *)(buf + sizeof(IP_HDR));
                outtie("------------------------");
                sprintf(output,"Protocol is TCP");
                outtie(output);

                int seq,ack,urg;

                seq=tcphdr->seqnum;
                sprintf(output,"seq num=%u",seq);
                outtie(output);

                ack=tcphdr->acknum;
                sprintf(output,"ack num=%u",ack);
                outtie(output);

                urg=tcphdr->UrgPointer;
                sprintf(output,"urgent pointer=%u",urg);
                outtie(output);





        }
        if(iProtocol==IPPROTO_UDP)
        {
                udphdr = (UDP_HDR *)(buf + sizeof(IP_HDR));
                outtie("------------------------");
                sprintf(output,"Protocol is UDP");
                outtie(output);
               
                int len,s_port,d_port,csum;


                len=udphdr->Length;
                sprintf(output,"UDP header length=%u",len);
                outtie(output);
               
                s_port=udphdr->sport;
                sprintf(output,"source port=%u",htons(s_port));
                outtie(output);
               
                d_port=udphdr->dport;
                sprintf(output,"destination port=%u",htons(d_port));
                outtie(output);
               
                csum=udphdr->Checksum;
                sprintf(output,"checksum=%u",csum);
                outtie(output);
                       
        }
        if(iProtocol==IPPROTO_ICMP)
        {
                outtie("------------------------");
                sprintf(output,"Protocol is ICMP");
                outtie(output);       
        }
       
                       
        //Check Source IP
        saSource.sin_addr.s_addr = pIpheader->sourceIP;
        strncpy(szSourceIP, inet_ntoa(saSource.sin_addr), MAX_ADDR_LEN);
               
               
        //Check Dest IP
        saDest.sin_addr.s_addr = pIpheader->destIP;
        strncpy(szDestIP, inet_ntoa(saDest.sin_addr), MAX_ADDR_LEN);
               
               
        iTTL = pIpheader->ttl;
        total_length=pIpheader->total_len;
               
        //Output
        sprintf(output,"%s->%s", szSourceIP, szDestIP);
        outtie(output);
               
        sprintf(output,"TTL=%d", iTTL);
        outtie(output);
       
        outtie("------------------------");

        printf("\n");
        return true;
}

the anwer to your problem is
data starts from address location
:

  (buf + sizeof(IP_HDR)) + sizeof(TCP/UDP header))

Brent Sep 23rd, 2007 12:28 AM

Thanks for the help.


All times are GMT -5. The time now is 2:51 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC