Skip to content

Commit

Permalink
fixed IPv4 checksum calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
garmr-ulfr committed Oct 12, 2023
1 parent 16c7b84 commit 9257f73
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
6 changes: 5 additions & 1 deletion actions/tamper_action_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,9 @@ func TestParseTamperAction(t *testing.T) {
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
s := scanner.NewScanner(tt.rule)
got, err := ParseTamperAction(s)
if (err != nil) != tt.wantErr {
Expand Down Expand Up @@ -117,7 +119,7 @@ func TestTamperTCP(t *testing.T) {
},
want: []byte{
0x30, 0x39, 0xd4, 0x31, 0xde, 0xad, 0xbe, 0xef, 0x00, 0x00, 0x00, 0x00, 0x70, 0x02, 0x00,
0x00, 0x82, 0x9c, 0x00, 0x00, 0x02, 0x04, 0x20, 0x00, 0x0e, 0x05, 0xff, 0xff, 0xff, 0x00,
0x00, 0x82, 0x9c, 0x00, 0x00, 0x02, 0x04, 0x20, 0x00, 0x00, 0x0e, 0x05, 0xff, 0xff, 0xff,
0x00, 0x00, 0x00, 0x54, 0x65, 0x73, 0x74,
},
}, {
Expand All @@ -140,7 +142,9 @@ func TestTamperTCP(t *testing.T) {
}

for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
tamperTCP(tt.args.tcp, tt.args.field, tt.args.valueGen)

got := append([]byte{}, tt.args.tcp.Contents...)
Expand Down
21 changes: 10 additions & 11 deletions common/packet.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,28 +25,27 @@ func UpdateTCPChecksum(tcp *layers.TCP) error {

// UpdateIPv4Checksum updates the IPv4 checksum field and the raw bytes for a gopacket IPv4 layer.
func UpdateIPv4Checksum(ip *layers.IPv4) error {
buf := make([]byte, ip.Length)
copy(buf, ip.Contents)
copy(buf[len(ip.Contents):], ip.Payload)

chksum := CalculateIPv4Checksum(buf)
chksum := CalculateIPv4Checksum(ip.Contents)
ip.Checksum = chksum
binary.BigEndian.PutUint16(ip.Contents[10:12], chksum)

return nil
}

// copied directly from gopacket/layers/ip4.go because they didn't export one. for whatever some reason..
// copied from gopacket/layers/ip4.go because they didn't export one. for whatever some reason..
func CalculateIPv4Checksum(bytes []byte) uint16 {
buf := make([]byte, len(bytes))
copy(buf, bytes)

// Clear checksum bytes
bytes[10] = 0
bytes[11] = 0
buf[10] = 0
buf[11] = 0

// Compute checksum
var csum uint32
for i := 0; i < len(bytes); i += 2 {
csum += uint32(bytes[i]) << 8
csum += uint32(bytes[i+1])
for i := 0; i < len(buf); i += 2 {
csum += uint32(buf[i]) << 8
csum += uint32(buf[i+1])
}

for csum > 0xFFFF {
Expand Down

0 comments on commit 9257f73

Please sign in to comment.