MBUF to Wireshark: A journey

MBUF to Wireshark: A journey

It was an unusual Friday afternoon at my desk. Surprisingly quiet. That was when I got a popup on the messaging app. The notification said, "There is a crash on ...".

I thought to myself, "Yeah, that's more like a Friday. Was wondering why there wasn't any till now".

Fired up the gdb and the backtrace showed me the function that was added in the last release. The prima-facie showed that the crash was due to an incoming packet from the network. A quick code inspection did not yield anything unusual.

Could be a special header or field in the packet I thought. Dumped the packet memory to see if I can figure it out.

Doing this on a black and white terminal was going to take time. Let me begin by opening the packet with Wireshark I thought. I vaguely remembered a tool available to do just that, so I googled text to pcap. That got me text2pcap. Wow! Such an apt name!

I dumped the memory in the hex format x/100xb <mbuf-address>, copied it over, added an artificial offset to make it look like the format that text2pcap understands. And then ran text2pcap in.txt out.pcap to finally see the packet with Wireshark, such a relief.

This got me thinking. Instead of doing all this manually, can I just do all this from the GDB itself?

I explored a few options and finally wrote a simple native GDB script without any dependency on python, etc.

The script is simple. You just provide it with the mbuf address. It figures out the rest. It walks through the chain, reads the correct lengths, and dumps the data into a hex-dump that can be easily imported into Wireshark.

#Usage mbuf2hex <mbuf>
define mbuf2hex
    set $_mb = $arg0
    shell rm -f /tmp/mbuf-pktdump.bin
    while ($_mb != 0)
        append binary memory /tmp/mbuf-pktdump.bin $_mb->mh_data $_mb->mh_data+$_mb->mh_len
        set $_mb = $_mb->mh_next
    end
    shell xxd -g1 /tmp/mbuf-pktdump.bin
    shell rm -f /tmp/mbuf-pktdump.bin
end

I have put the script on github.

PS: This is my first blog post. Thanks to Catalin Pit for the inspiration.