Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Conversation

niklaskb
Copy link
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
Contributor

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

@niklaskb
Copy link
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
1 check passed
@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.

None yet

2 participants