How to check potential array out of bound when processing packets on Linux?

zzy Source

I'm doing socket programming and need to parse the packets on Linux. The general framework provided by Linux is to have the buffer (u_char*), cast it into ethernet header (assuming it is ethernet), read the next protocol (eg. IP), move the pointer and cast it into IP header, then move on to the next protocol (eg. TCP).

So my concern is the bold part: how can we ensure moving the pointer is legal? Generally people only check for the protocol and assume the packet is complete. But I doubt whether this could be always true.

For example:

const u_char* packet = ...; // Receive the packet
struct ethhdr* ethHdr = (struct ethhdr*)packet;
if (ntohs(ethHdr->h_proto) == ETH_P_IP) {
  struct ip* ipHdr = (struct ip*)(packet + sizeof(struct ethhdr));
}

Then for the fourth line, why are we confident that such pointer add is safe? Are there any ways to check the length?

Thanks in advance!

linuxpointersipethernetpacket

Answers

comments powered by Disqus