计算Internet Checksum,理解其局限

Last Updated: 2023-10-15 12:20:33 Sunday

-- TOC --

Internet Checksum对应RFC1071,许多重要的协议报文(IP,ICMP,TCP,UDP...),都使用此算法,计算并确保报文或报文头的数据一致性(integrity)。

Ethernet Frame使用CRC校验

看看checksum这个词,其实最初就是sum后按某个数取模,以此来判断一致性。但早期的这个简单的sum后取模的算法,很容易出现误判或判断错误的情况,于是科学家发明了复杂一些的算法,但还叫checksum!

计算

这个算法的计算不复杂,但实现必须要尽可能的快!比如路由器要计算每一个收到的IP报文头,转发前更新TTL并重新计算checksum。要彻底研究透这个算法,以及在各种场景下如何计算,好好阅读RFC1071,以及后续的updates!

下面是我写的Python实现:

def inet_cks(bstr):
    """ Return intenet checksum in bytes type """
    length = len(bstr)
    odd = length % 2
    sm = sum([int.from_bytes(bstr[i:i+2],'big')
              for i in range(0,length-odd,2)])
    if odd:
        sm += (bstr[-1]<<8)
    while (h16:=(sm>>16)):
        sm = (sm & 0xFFFF) + h16
    return (~sm&0xFFFF).to_bytes(2,'big')

bstr是按网络序组织的报文内容,计算的中间如果有字节落单,要加到高位!

下面是C版本:

/* Compute Internet Checksum for "count" bytes,
 * beginning at location "addr" which is in big-endian.*/
unsigned short cks(unsigned char *addr, int count) {
    int i, odd;
    unsigned long sum = 0;

    odd = count & 1;
    for (i=0; i<count-odd; i+=2)
        sum += (addr[i]<<8) + addr[i+1];

    if (odd)
        sum += (addr[count-1]<<8);

    while (sum>>16)
        sum = (sum & 0xffff) + (sum >> 16);

    return htons(~sum);
}

局限

Internet Checksum并不够强,它只是提供了最基本的数据一致性检测,用来应对偶然发生的数据错误,只能将其视为最低层次的数据一致性检测手段。

The Internet checksum is a basic algorithm that calculates a checksum value based on the data being transmitted. It is relatively easy to calculate and verify, but it is not intended to provide strong data integrity or protect against deliberate attacks.

The Internet checksum algorithm is a simple and fast mechanism for error detection, but it has some limitations. It can only detect certain types of errors, such as single-bit errors or some two-bit errors. It is not effective in detecting all possible errors or intentional attacks. Therefore, it should not be solely relied upon for ensuring data integrity or security.

在对数据一致性要求很高的场景下,一定需要配合其它检测手段。

本文链接:https://cs.pynote.net/ag/202112171/

-- EOF --

-- MORE --