Вопрос

When dealing with a sk_buff in kernel modules code, I see many code samples use either

(struct iphdr *)skb_network_header(skb) //skb is an instance of (struct sk_buff*)

or the function ip_hdr() which is really the same (calling skb_network_header and casting). Is this safe? If we don't have any assumptions on where that sk_buff came from, is there a check I can do to make sure the network protocol is indeed IP?

Edit: It may be that by the point there can be an sk_buff the only possible network protocol is IP, but I would still like to see a "proof" or explanation for that. What if I implement my own protocol in the Linux kernel for example and the network protocol header may be something else? How can I make sure the network transport protocol is indeed IP?

Это было полезно?

Решение 2

Answering to myself because at the time I found a fuller answer.

It is possible to make sure the protocol is IP by the 'protocol' field of the sk_buff struct. For example:

if (skb->protocol != htons(ETH_P_IP)) return ERROR_NOT_IP; //ERROR_NOT_IP defined by me

struct iphdr* ip_header = ip_hdr(skb); //Now that we know the protocol we can use ip_hdr()

Другие советы

skb refers to socket buffer, the data structures used to represent and manage packets in the Linux Kernel.
And the implementation of Linux network system is designed to independent of a specific protocol.
Socket buffer in Linux Kernel network system will give you more details.

To your question:
The caller that called skb_network_header() should guarantee he knows the protocal. Proof : you can find out many references to skb_network_header(), including arp_hdr(), ipv6_hdr(), ip_hdr(), etc. The caller that call arp_hdr() to casting network header to aprhdr, will guarantee the protocal is ARP.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top