How to calculate TCP checksum

10,507

Solution 1

To re-calculate the checksum, you better calculate an incremental checksum - just modify the existing checksum based on the fields you've changed, rather than reading the entire packet.

This must be done while you're changing the packet, when you know both the old values and the new values you store.

The basic idea is tcp->check += (new_val - old_val).
It's a bit more complicated than this, becuase:
1. old_val and new_val need to be 16-bit values, which are aligned on 2 bytes (e.g. changing a port number).
2. The checksum uses ones complement arithmetic, so you need to do "carry feedback". This basically means, that if tcp->check + new_val - old_val is negative, you need to subtract 1 from the result.

Solution 2

Here is an example which combine netfilter API + checksum for TCP (not IP):

http://www.linuxvirtualserver.org/software/tcpsp/index.html

Look into the file called tcpsp_core.c.

    th->check = 0;
    th->check = csum_tcpudp_magic(iph->saddr, iph->daddr,
                                  datalen, iph->protocol,
                                  csum_partial((char *)th, datalen, 0));
    skb->ip_summed = CHECKSUM_UNNECESSARY;

(notice it is assigned zero first, checksum calculated, then IP checksum indicated as not needed).

Depends on which netfilter module u load (there are many!!!) they will work at different layer, eg, iptable working at IP layer is shown below (image):

http://ars.sciencedirect.com/content/image/1-s2.0-S1389128608004040-gr3.jpg

Solution 3

@ugoren's answer is not precise. According to RFC1624 https://www.rfc-editor.org/rfc/rfc1624, this will sometimes produce -0 (0xFFFF), which is not allowed.

The correct way to compute checksum should be: new_tcp_check = ~(~old_tcp_check + ~old_val + new_val)

Share:
10,507
Fingolfin
Author by

Fingolfin

Updated on June 09, 2022

Comments

  • Fingolfin
    Fingolfin almost 2 years

    I am writing a Kernel Module that uses Netfilter hooks to modify some of the TCP header information and obviously, before sending, I want to re-calculate the checksum.
    I also edit the header at the receiving side, so I need to re-calculate it there too.

    Searching online, I found some people saying I can simply set it to 0 and it'll be calculated for me, apparently that didn't work.
    I've also found this function

    tcp_v4_send_check(struct sock *sk, struct sk_buff *skb);
    

    Though no one explained how this is used, and whether I can actually use it at the receiving/sending the same way.
    My own attempt was to set checksum to 0 then call this function passing the skb I have and the skb->sk I have, still nothing.

    So please, what is a straightforward way to calculate the checksum of TCP datagrams?