1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _NF_TABLES_IPV4_H_
3 #define _NF_TABLES_IPV4_H_
4 
5 #include <net/netfilter/nf_tables.h>
6 #include <net/ip.h>
7 
8 static inline void nft_set_pktinfo_ipv4(struct nft_pktinfo *pkt)
9 {
10 	struct iphdr *ip;
11 
12 	ip = ip_hdr(pkt->skb);
13 	pkt->flags = NFT_PKTINFO_L4PROTO;
14 	pkt->tprot = ip->protocol;
15 	pkt->thoff = ip_hdrlen(pkt->skb);
16 	pkt->fragoff = ntohs(ip->frag_off) & IP_OFFSET;
17 }
18 
19 static inline int __nft_set_pktinfo_ipv4_validate(struct nft_pktinfo *pkt)
20 {
21 	struct iphdr *iph, _iph;
22 	u32 len, thoff;
23 
24 	iph = skb_header_pointer(pkt->skb, skb_network_offset(pkt->skb),
25 				 sizeof(*iph), &_iph);
26 	if (!iph)
27 		return -1;
28 
29 	if (iph->ihl < 5 || iph->version != 4)
30 		return -1;
31 
32 	len = ntohs(iph->tot_len);
33 	thoff = iph->ihl * 4;
34 	if (pkt->skb->len < len)
35 		return -1;
36 	else if (len < thoff)
37 		return -1;
38 	else if (thoff < sizeof(*iph))
39 		return -1;
40 
41 	pkt->flags = NFT_PKTINFO_L4PROTO;
42 	pkt->tprot = iph->protocol;
43 	pkt->thoff = thoff;
44 	pkt->fragoff = ntohs(iph->frag_off) & IP_OFFSET;
45 
46 	return 0;
47 }
48 
49 static inline void nft_set_pktinfo_ipv4_validate(struct nft_pktinfo *pkt)
50 {
51 	if (__nft_set_pktinfo_ipv4_validate(pkt) < 0)
52 		nft_set_pktinfo_unspec(pkt);
53 }
54 
55 static inline int nft_set_pktinfo_ipv4_ingress(struct nft_pktinfo *pkt)
56 {
57 	struct iphdr *iph;
58 	u32 len, thoff;
59 
60 	if (!pskb_may_pull(pkt->skb, sizeof(*iph)))
61 		return -1;
62 
63 	iph = ip_hdr(pkt->skb);
64 	if (iph->ihl < 5 || iph->version != 4)
65 		goto inhdr_error;
66 
67 	len = ntohs(iph->tot_len);
68 	thoff = iph->ihl * 4;
69 	if (pkt->skb->len < len) {
70 		__IP_INC_STATS(nft_net(pkt), IPSTATS_MIB_INTRUNCATEDPKTS);
71 		return -1;
72 	} else if (len < thoff) {
73 		goto inhdr_error;
74 	} else if (thoff < sizeof(*iph)) {
75 		return -1;
76 	}
77 
78 	pkt->flags = NFT_PKTINFO_L4PROTO;
79 	pkt->tprot = iph->protocol;
80 	pkt->thoff = thoff;
81 	pkt->fragoff = ntohs(iph->frag_off) & IP_OFFSET;
82 
83 	return 0;
84 
85 inhdr_error:
86 	__IP_INC_STATS(nft_net(pkt), IPSTATS_MIB_INHDRERRORS);
87 	return -1;
88 }
89 
90 #endif
91