From d15cbb2d6a9f116e47f71458f075529910bcf27f Mon Sep 17 00:00:00 2001 From: Bananymous Date: Mon, 5 Feb 2024 17:31:15 +0200 Subject: [PATCH] Kernel: Fix IPv4 header checksum calculation --- BAN/include/BAN/IPv4.h | 1 + kernel/include/kernel/Networking/IPv4.h | 13 +++++++------ kernel/kernel/Networking/IPv4.cpp | 4 ++-- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/BAN/include/BAN/IPv4.h b/BAN/include/BAN/IPv4.h index 31a6bafc..b72949d6 100644 --- a/BAN/include/BAN/IPv4.h +++ b/BAN/include/BAN/IPv4.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include diff --git a/kernel/include/kernel/Networking/IPv4.h b/kernel/include/kernel/Networking/IPv4.h index f893f53b..610e64d4 100644 --- a/kernel/include/kernel/Networking/IPv4.h +++ b/kernel/include/kernel/Networking/IPv4.h @@ -23,12 +23,13 @@ namespace Kernel constexpr uint16_t calculate_checksum() const { - return 0xFFFF - - (((uint16_t)version_IHL << 8) | DSCP_ECN) - - total_length - - identification - - flags_frament - - (((uint16_t)time_to_live << 8) | protocol); + uint32_t total_sum = 0; + for (size_t i = 0; i < sizeof(IPv4Header) / sizeof(uint16_t); i++) + total_sum += reinterpret_cast*>(this)[i]; + total_sum -= checksum; + while (total_sum >> 16) + total_sum = (total_sum >> 16) + (total_sum & 0xFFFF); + return ~(uint16_t)total_sum; } }; static_assert(sizeof(IPv4Header) == 20); diff --git a/kernel/kernel/Networking/IPv4.cpp b/kernel/kernel/Networking/IPv4.cpp index e9d76a0b..33f9044d 100644 --- a/kernel/kernel/Networking/IPv4.cpp +++ b/kernel/kernel/Networking/IPv4.cpp @@ -8,15 +8,15 @@ namespace Kernel { auto& header = packet.as(); header.version_IHL = 0x45; - header.DSCP_ECN = 0x10; + header.DSCP_ECN = 0x00; header.total_length = packet.size(); header.identification = 1; header.flags_frament = 0x00; header.time_to_live = 0x40; header.protocol = protocol; - header.checksum = header.calculate_checksum(); header.src_address = src_ipv4; header.dst_address = dst_ipv4; + header.checksum = header.calculate_checksum(); } }