From 4565c89b5994aae4b34d42a606c733a995e6a5c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juhani=20Krekel=C3=A4?= Date: Thu, 4 Jul 2019 01:16:12 +0300 Subject: [PATCH] Do broken CRC32 --- ethertype-dump.c | 53 +++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 5 deletions(-) diff --git a/ethertype-dump.c b/ethertype-dump.c index 07b0b0f..402e5a9 100644 --- a/ethertype-dump.c +++ b/ethertype-dump.c @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -14,6 +15,34 @@ #include #include +uint32_t crc32_table[256]; + +void precompute_crc32_table(void) { + for (size_t index = 0; index < 256; index++) { + uint32_t value = index; + + for (size_t i = 0; i < 8; i++) { + uint32_t low_bit = value & 1; + value = value >> 1; + if (low_bit) { + value ^= 0xEDB88320; + } + } + + crc32_table[index] = value; + } +} + +uint32_t crc32(unsigned char *buf, size_t len) { + uint32_t value = 0xffffffff; + + for (size_t index = 0; index < len; index++) { + value = crc32_table[(value & 0xff) ^ buf[index]] ^ (value >> 8); + } + + return value ^ 0xffffffff; +} + char hexify(int nybble) { assert(0 <= nybble && nybble <= 16); return "0123456789abcdef"[nybble]; @@ -35,6 +64,9 @@ int main(int argc, char **argv) { exit(1); } + // Set up CRC32 + precompute_crc32_table(); + // Create a packet socket errno = 0; int packet_socket = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); @@ -63,6 +95,10 @@ int main(int argc, char **argv) { for(;;) { unsigned char frame[1522]; // 1522 is the largest a 802.3 frame can be + if (fflush(stdout) == -1) { + err(1, "fflush"); + } + errno = 0; ssize_t frame_length = recv(packet_socket, frame, sizeof(frame), MSG_TRUNC); if (frame_length == -1) { @@ -77,6 +113,17 @@ int main(int argc, char **argv) { continue; } + // Compute the CRC32 of the frame + uint32_t crc32_residue = crc32(frame, frame_length); + + if (crc32_residue != 0xc704dd7b) { + errno = 0; + if (printf("CRC failed (%04"PRIx32")\n", crc32_residue) == -1) { + err(1, "printf"); + } + continue; + } + // Extract the MACs // 012345 012345 // dest source @@ -104,7 +151,7 @@ int main(int argc, char **argv) { } errno = 0; - if(printf("%s -> %s ethertype: %02x%02x", source_mac, destination_mac, ethertype >> 8, ethertype & 0xff) == -1) { + if(printf("%s -> %s ethertype: %04" PRIx16, source_mac, destination_mac, ethertype) == -1) { err(1, "printf"); } @@ -118,10 +165,6 @@ int main(int argc, char **argv) { err(1, "printf"); } } - - if (fflush(stdout) == -1) { - err(1, "fflush"); - } } return 0;