Adversarial C2 Protocol Implemented in Zig
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Calculate IPv4 checksum header

This was causing an issue because virtual networks were dropping packets
without this being set

+36
+36
src/EthIpUdp.zig
··· 49 49 50 50 pub fn setPayloadLen(self: *@This(), len: usize) void { 51 51 self.ip.len = @intCast(len + (@bitSizeOf(@TypeOf(self.udp)) / 8) + (@bitSizeOf(@TypeOf(self.ip)) / 8)); 52 + 53 + // Zero the checksum field before calculation 54 + self.ip.header_checksum = 0; 55 + 56 + // Serialize IP header to big-endian bytes 57 + var ip_bytes: [@bitSizeOf(@TypeOf(self.ip)) / 8]u8 = undefined; 58 + var w: Writer = .fixed(&ip_bytes); 59 + w.writeStruct(self.ip, .big) catch unreachable; 60 + 61 + // Calculate checksum over serialized bytes 62 + self.ip.header_checksum = onesComplement16(&ip_bytes); 63 + 52 64 self.udp.len = @intCast(len + (@bitSizeOf(@TypeOf(self.udp)) / 8)); 53 65 } 54 66 }; 67 + 68 + fn onesComplement16(data: []const u8) u16 { 69 + var sum: u32 = 0; 70 + 71 + // Process pairs of bytes as 16-bit words 72 + var i: usize = 0; 73 + while (i + 1 < data.len) : (i += 2) { 74 + const word: u16 = (@as(u16, data[i]) << 8) | data[i + 1]; 75 + sum += word; 76 + } 77 + 78 + // Handle odd byte if present 79 + if (data.len % 2 == 1) { 80 + sum += @as(u32, data[data.len - 1]) << 8; 81 + } 82 + 83 + // Fold 32-bit sum to 16 bits 84 + while (sum >> 16 != 0) { 85 + sum = (sum & 0xFFFF) + (sum >> 16); 86 + } 87 + 88 + // Return ones' complement 89 + return ~@as(u16, @truncate(sum)); 90 + } 55 91 56 92 const std = @import("std"); 57 93 const Writer = std.Io.Writer;