Skip to content

fix(ip4defrag): allow final fragment to be less than 8 octets#35

Merged
mosajjal merged 1 commit intogopacket:masterfrom
niklaskb:fix/allow-final-fragment-to-be-less-than-8-octets
Nov 25, 2023
Merged

fix(ip4defrag): allow final fragment to be less than 8 octets#35
mosajjal merged 1 commit intogopacket:masterfrom
niklaskb:fix/allow-final-fragment-to-be-less-than-8-octets

Conversation

@niklaskb
Copy link
Copy Markdown
Contributor

This PR will fix a bug where the defragmenter fails on pcap files that has a final fragment that is smaller than 8 octets.
The final fragment should be allowed to be less than 8 octets according to the standard.

For reference:
https://packetpushers.net/ip-fragmentation-in-detail/
https://stackoverflow.com/a/7846487/1642369

@mosajjal
Copy link
Copy Markdown
Contributor

hey. can you please provide a code and a sample pcap that triggers the issue.

@niklaskb
Copy link
Copy Markdown
Contributor Author

Sure, here is a pcap file with a fragmented packet: fragmented.tar.gz

And here is a piece of code that would trigger the error when reading the file.

package pcap

import (
	"errors"
	"fmt"
	"github.com/gopacket/gopacket"
	"github.com/gopacket/gopacket/ip4defrag"
	"github.com/gopacket/gopacket/layers"
	"github.com/gopacket/gopacket/pcapgo"
	"io"
	"os"
	"testing"

	"gotest.tools/v3/assert"
)

func Test(t *testing.T) {
	file, err := os.Open("fragmented.pcapng")
	pcapr, err := pcapgo.NewNgReader(file, pcapgo.DefaultNgReaderOptions)
	assert.NilError(t, err)

	defragmenter := ip4defrag.NewIPv4Defragmenter()

	for {
		data, ci, err := pcapr.ZeroCopyReadPacketData()
		if errors.Is(err, io.EOF) {
			fmt.Println("End of file")
			return
		}
		assert.NilError(t, err)

		packet := gopacket.NewPacket(data, pcapr.LinkType(), gopacket.Default)
		if ipv4Layer := packet.Layer(layers.LayerTypeIPv4); ipv4Layer != nil {
			ipv4LayerCasted := ipv4Layer.(*layers.IPv4)
			defragmented, err := defragmenter.DefragIPv4WithTimestamp(ipv4LayerCasted, ci.Timestamp)
			assert.NilError(t, err)
			if defragmented == nil || defragmented.Protocol != layers.IPProtocolUDP {
				continue // packet fragment, we don't have whole packet yet.
			}

			udpPacket := gopacket.NewPacket(defragmented.LayerPayload(), layers.LayerTypeUDP, gopacket.Default)
			if udpLayer := udpPacket.Layer(layers.LayerTypeUDP); udpLayer != nil {
				payload := udpLayer.LayerPayload()
				assert.Equal(t, len(payload) > 0, true)
				fmt.Println("Read payload success")
			}
		}
	}
}

@mosajjal mosajjal merged commit ce9cd50 into gopacket:master Nov 25, 2023
@niklaskb niklaskb deleted the fix/allow-final-fragment-to-be-less-than-8-octets branch November 25, 2023 18:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants