LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 09-22-2010, 02:19 AM   #1
moby@root
LQ Newbie
 
Registered: Sep 2010
Posts: 21

Rep: Reputation: 0
How can I calculate the right TCP checksum?


Hi,
I'm trying to send a TCP packet with IP_HDRINCL option.I used almost every TCP checksum function I could find to send a RAW packet with correct TCP checksum but the problem still remains. This is the code I'm working on. As you can see I've defined my own IP and TCP structures cause I got a lot of compile time errors with 'ip' and 'tcphdr' structs.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <errno.h>
#define PACKET_SIZE 2048
#define SRC_ADDR "192.168.0.2"
#define DST_ADDR "192.168.0.1"
unsigned short int ip_checksum(unsigned char *,int);
unsigned short tcp_sum_calc(unsigned short len_tcp, unsigned short src_addr[],unsigned short dest_addr[], unsigned short buff[]);

 // structures are created for big endian values.
 // all assigned values to the fields must be in  
 // big endian byte order.network byte order is  
 // big endian.x86 machines use little endian and  
 // network byte order is "always" big endian. 
 // to convert little endian to big endian use 
 // htons(2Byte),htol(4Byte),inet_addr(strIPaddr) 
 // for the fields which are at least two bytes.

 struct ipheader
 {
  unsigned char ver_len;
  unsigned char tos;
  unsigned short int packet_len;
  unsigned short int id;
  unsigned short int flags3_fragmentoffset13;
  unsigned char ttl;
  unsigned char protocol;
  unsigned short int checksum;
  unsigned int srcaddr;
  unsigned int destaddr;
 };

 struct tcpheader
 {
  unsigned short int srcport;
  unsigned short int destport;
  unsigned int seqnum;
  unsigned int acknum;
  unsigned short int offset4_reserved3_ecn3_controlbits6;
  unsigned short int window;
  unsigned short int checksum;
  unsigned short int urgent_pointer;
 };


 int main(void)
 {
  int result,recv_bytes;
  const int optval=1;
  int rawsocket;
  struct ipheader *ip_header;
  struct tcpheader *tcp_header;
  struct sockaddr_in remotehost;
  unsigned char packet[PACKET_SIZE];


   // create a raw socket      
   rawsocket = socket(AF_INET,SOCK_RAW,IPPROTO_TCP);
   if(rawsocket < 0) {
    printf("Unable to create a raw socket.%s\n",strerror(errno));
    exit(0x01);
   }

   // set IP_HDRINCL option
   result = setsockopt(rawsocket, IPPROTO_IP, IP_HDRINCL, &optval, sizeof(const int));
   if(result < 0) {
    printf("Unable to set IP_HDRINCL option.%s\n",strerror(errno));
    exit(0x02);
   }

   // prepare the packet
   memset((unsigned char *) packet, 0, PACKET_SIZE); 
   ip_header = (struct ipheader *) packet;
   tcp_header = (struct tcpheader *) (packet + sizeof(struct ipheader)); 

   remotehost.sin_family = AF_INET;
   remotehost.sin_addr.s_addr = inet_addr(DST_ADDR);
   remotehost.sin_port = htons(5555);
   
   ip_header->ver_len = (4 << 4) | 5;
   ip_header->tos = 0;
   ip_header->packet_len = htons(sizeof(struct ipheader) + sizeof(struct tcpheader));
   ip_header->id = htonl(5); // must be a unique id number for each connection
   ip_header->flags3_fragmentoffset13 = 0;
   ip_header->ttl = 64;
   ip_header->protocol = 6;  // TCP, Transmission Control Protocol
   ip_header->checksum = 0;
   ip_header->srcaddr = inet_addr(SRC_ADDR);
   ip_header->destaddr = inet_addr(DST_ADDR);

   ip_header->checksum = ip_checksum(packet, sizeof(struct ipheader));
   
   
   tcp_header->srcport = htons(1234);
   tcp_header->destport = htons(5555);
   tcp_header->seqnum = htonl(0);
   tcp_header->acknum = htonl(0); 
   tcp_header->offset4_reserved3_ecn3_controlbits6 = htons(0x5002); // binary: 0101 000 000 000010
   tcp_header->window = htons(1234);
   tcp_header->checksum = 0;
   tcp_header->urgent_pointer = htons(0);

   tcp_header->checksum = (unsigned short int) tcp_sum_calc((unsigned short) sizeof(struct tcpheader), (unsigned short *) &ip_header->srcaddr, (unsigned short *) &ip_header->destaddr, (unsigned short *) &tcp_header);


   printf("IP checksum: %x , TCP checksum: %x\n",ip_header->checksum,tcp_header->checksum);


   if(sendto(rawsocket, packet, sizeof(struct ipheader)+sizeof(struct tcpheader), 0, (struct sockaddr *)&remotehost, sizeof(struct sockaddr_in)) < 0)
    printf("Unable to send the packet.\n");
   else
    printf("Sent Successfully.\n");


   close(rawsocket);

  return 0;
 }


 unsigned short int ip_checksum(unsigned char *buff,int bytes)
 {
  unsigned int i;
  unsigned long csum;

   for(i=0; i<bytes ;i+=2)
    csum += * (unsigned short int *) &buff[i];

   csum = (csum >> 16) + (csum & 0xffff);
   csum += csum >> 16;
   csum = ~csum;

  return csum;
 }


 unsigned short tcp_sum_calc(unsigned short len_tcp, unsigned short *src_addr, unsigned short *dest_addr, unsigned short *buff)
 {     
  unsigned short prot_tcp = 6;
  long sum;
  int i;
  sum = 0;
	
   /* Check if the tcp length is even or odd.  Add padding if odd. */
   if((len_tcp % 2) == 1){
    buff[len_tcp] = 0;  // Empty space in the ip buffer should be 0 anyway.
    len_tcp += 1; // incrase length to make even.
   }
	
   /* add the pseudo header */   
   sum += ntohs(src_addr[0]);
   sum += ntohs(src_addr[1]);
   sum += ntohs(dest_addr[0]);
   sum += ntohs(dest_addr[1]);
   sum += len_tcp; // already in host format.
   sum += prot_tcp; // already in host format.
      
   /* 
     calculate the checksum for the tcp header and payload
     len_tcp represents number of 8-bit bytes, 
     we are working with 16-bit words so divide len_tcp by 2. 
   */
   for(i=0;i<(len_tcp/2);i++){
      sum += ntohs(buff[i]);
   }
    
   // keep only the last 16 bits of the 32 bit calculated sum and add the carries
   sum = (sum & 0xFFFF) + (sum >> 16);
   sum += (sum >> 16);
   
   // Take the bitwise complement of sum
   sum = ~sum;

  return htons(((unsigned short) sum));
 }

After sending each packet I check the result in Wireshark. it always says your TCP checksum should be '0x0f38' but the checksum that my code generates always differ from the last one.
I think Linux kernel changes sth in TCP header.I found that it doesn't matter what number I choose for IP Identification field, sth changes this number and calculates IP checksum again. But I couldn't find anything in TCP header.everything seems to be in the right place but the result is 'Bad Checksum'.

I can't find anything wrong in my code, so, could you take a look at it and tell me what is the problem?

Thanks,
Mobin

Last edited by moby@root; 09-22-2010 at 02:30 AM.
 
Old 09-26-2010, 03:29 AM   #2
linux_hy
Member
 
Registered: Oct 2006
Posts: 66

Rep: Reputation: -2
USHORT Checksum(USHORT *buffer, int size)
{
unsigned long cksum=0;

while(size >1)
{
cksum+=*buffer++;
size -=sizeof(USHORT);
}
if(size)
cksum += *(UCHAR*)buffer;
cksum = (cksum >> 16) + (cksum & 0xffff);
cksum += (cksum >>16);
return (USHORT)(~cksum);
}
 
Old 11-11-2010, 12:26 PM   #3
mejohnsn
Member
 
Registered: Sep 2009
Posts: 174

Rep: Reputation: Disabled
Quote:
Originally Posted by moby@root View Post
Hi,
I'm trying to send a TCP packet with IP_HDRINCL option.I used almost every TCP checksum function I could find to send a RAW packet with correct TCP checksum but the problem still remains. This is the code I'm working on. As you can see I've defined my own IP and TCP structures cause I got a lot of compile time errors with 'ip' and 'tcphdr' structs.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <errno.h>
#define PACKET_SIZE 2048
#define SRC_ADDR "192.168.0.2"
#define DST_ADDR "192.168.0.1"
unsigned short int ip_checksum(unsigned char *,int);
unsigned short tcp_sum_calc(unsigned short len_tcp, unsigned short src_addr[],unsigned short dest_addr[], unsigned short buff[]);

 // structures are created for big endian values.
 // all assigned values to the fields must be in  
 // big endian byte order.network byte order is  
 // big endian.x86 machines use little endian and  
 // network byte order is "always" big endian. 
 // to convert little endian to big endian use 
 // htons(2Byte),htol(4Byte),inet_addr(strIPaddr) 
 // for the fields which are at least two bytes.

 struct ipheader
 {
  unsigned char ver_len;
  unsigned char tos;
  unsigned short int packet_len;
  unsigned short int id;
  unsigned short int flags3_fragmentoffset13;
  unsigned char ttl;
  unsigned char protocol;
  unsigned short int checksum;
  unsigned int srcaddr;
  unsigned int destaddr;
 };

 struct tcpheader
 {
  unsigned short int srcport;
  unsigned short int destport;
  unsigned int seqnum;
  unsigned int acknum;
  unsigned short int offset4_reserved3_ecn3_controlbits6;
  unsigned short int window;
  unsigned short int checksum;
  unsigned short int urgent_pointer;
 };


 int main(void)
 {
  int result,recv_bytes;
  const int optval=1;
  int rawsocket;
  struct ipheader *ip_header;
  struct tcpheader *tcp_header;
  struct sockaddr_in remotehost;
  unsigned char packet[PACKET_SIZE];


   // create a raw socket      
   rawsocket = socket(AF_INET,SOCK_RAW,IPPROTO_TCP);
   if(rawsocket < 0) {
    printf("Unable to create a raw socket.%s\n",strerror(errno));
    exit(0x01);
   }

   // set IP_HDRINCL option
   result = setsockopt(rawsocket, IPPROTO_IP, IP_HDRINCL, &optval, sizeof(const int));
   if(result < 0) {
    printf("Unable to set IP_HDRINCL option.%s\n",strerror(errno));
    exit(0x02);
   }

   // prepare the packet
   memset((unsigned char *) packet, 0, PACKET_SIZE); 
   ip_header = (struct ipheader *) packet;
   tcp_header = (struct tcpheader *) (packet + sizeof(struct ipheader)); 

   remotehost.sin_family = AF_INET;
   remotehost.sin_addr.s_addr = inet_addr(DST_ADDR);
   remotehost.sin_port = htons(5555);
   
   ip_header->ver_len = (4 << 4) | 5;
   ip_header->tos = 0;
   ip_header->packet_len = htons(sizeof(struct ipheader) + sizeof(struct tcpheader));
   ip_header->id = htonl(5); // must be a unique id number for each connection
   ip_header->flags3_fragmentoffset13 = 0;
   ip_header->ttl = 64;
   ip_header->protocol = 6;  // TCP, Transmission Control Protocol
   ip_header->checksum = 0;
   ip_header->srcaddr = inet_addr(SRC_ADDR);
   ip_header->destaddr = inet_addr(DST_ADDR);

   ip_header->checksum = ip_checksum(packet, sizeof(struct ipheader));
   
   
   tcp_header->srcport = htons(1234);
   tcp_header->destport = htons(5555);
   tcp_header->seqnum = htonl(0);
   tcp_header->acknum = htonl(0); 
   tcp_header->offset4_reserved3_ecn3_controlbits6 = htons(0x5002); // binary: 0101 000 000 000010
   tcp_header->window = htons(1234);
   tcp_header->checksum = 0;
   tcp_header->urgent_pointer = htons(0);

   tcp_header->checksum = (unsigned short int) tcp_sum_calc((unsigned short) sizeof(struct tcpheader), (unsigned short *) &ip_header->srcaddr, (unsigned short *) &ip_header->destaddr, (unsigned short *) &tcp_header);


   printf("IP checksum: %x , TCP checksum: %x\n",ip_header->checksum,tcp_header->checksum);


   if(sendto(rawsocket, packet, sizeof(struct ipheader)+sizeof(struct tcpheader), 0, (struct sockaddr *)&remotehost, sizeof(struct sockaddr_in)) < 0)
    printf("Unable to send the packet.\n");
   else
    printf("Sent Successfully.\n");


   close(rawsocket);

  return 0;
 }


 unsigned short int ip_checksum(unsigned char *buff,int bytes)
 {
  unsigned int i;
  unsigned long csum;

   for(i=0; i<bytes ;i+=2)
    csum += * (unsigned short int *) &buff[i];

   csum = (csum >> 16) + (csum & 0xffff);
   csum += csum >> 16;
   csum = ~csum;

  return csum;
 }


 unsigned short tcp_sum_calc(unsigned short len_tcp, unsigned short *src_addr, unsigned short *dest_addr, unsigned short *buff)
 {     
  unsigned short prot_tcp = 6;
  long sum;
  int i;
  sum = 0;
	
   /* Check if the tcp length is even or odd.  Add padding if odd. */
   if((len_tcp % 2) == 1){
    buff[len_tcp] = 0;  // Empty space in the ip buffer should be 0 anyway.
    len_tcp += 1; // incrase length to make even.
   }
	
   /* add the pseudo header */   
   sum += ntohs(src_addr[0]);
   sum += ntohs(src_addr[1]);
   sum += ntohs(dest_addr[0]);
   sum += ntohs(dest_addr[1]);
   sum += len_tcp; // already in host format.
   sum += prot_tcp; // already in host format.
      
   /* 
     calculate the checksum for the tcp header and payload
     len_tcp represents number of 8-bit bytes, 
     we are working with 16-bit words so divide len_tcp by 2. 
   */
   for(i=0;i<(len_tcp/2);i++){
      sum += ntohs(buff[i]);
   }
    
   // keep only the last 16 bits of the 32 bit calculated sum and add the carries
   sum = (sum & 0xFFFF) + (sum >> 16);
   sum += (sum >> 16);
   
   // Take the bitwise complement of sum
   sum = ~sum;

  return htons(((unsigned short) sum));
 }

After sending each packet I check the result in Wireshark. it always says your TCP checksum should be '0x0f38' but the checksum that my code generates always differ from the last one.
I think Linux kernel changes sth in TCP header.I found that it doesn't matter what number I choose for IP Identification field, sth changes this number and calculates IP checksum again. But I couldn't find anything in TCP header.everything seems to be in the right place but the result is 'Bad Checksum'.

I can't find anything wrong in my code, so, could you take a look at it and tell me what is the problem?

Thanks,
Mobin
For tcp_len, you should be using the total length of the TCP segment -- data and headers -- not just the length of your TCP header structure.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
[SOLVED] TCP Checksum function yaplej Programming 2 04-22-2010 01:45 PM
[SOLVED] Calculate new tcp checksum yaplej Programming 1 09-25-2009 11:27 AM
TCP checksum doubt arun4will Programming 1 05-17-2007 08:53 AM
TCP checksum error mshenbagaraj Programming 3 05-16-2007 02:43 PM
anyone can help me with the TCP checksum? vaaub Programming 1 02-10-2004 01:32 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 09:46 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration