1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (C) 2003-2011 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
5 /* Get Layer-4 data from the packets */
8 #include <linux/skbuff.h>
9 #include <linux/icmp.h>
10 #include <linux/icmpv6.h>
11 #include <linux/sctp.h>
12 #include <linux/netfilter_ipv6/ip6_tables.h>
16 #include <linux/netfilter/ipset/ip_set_getport.h>
17 #include <linux/export.h>
19 /* We must handle non-linear skbs */
21 get_port(const struct sk_buff *skb, int protocol, unsigned int protooff,
22 bool src, __be16 *port, u8 *proto)
27 const struct tcphdr *th;
29 th = skb_header_pointer(skb, protooff, sizeof(_tcph), &_tcph);
31 /* No choice either */
34 *port = src ? th->source : th->dest;
39 const struct sctphdr *sh;
41 sh = skb_header_pointer(skb, protooff, sizeof(_sh), &_sh);
43 /* No choice either */
46 *port = src ? sh->source : sh->dest;
50 case IPPROTO_UDPLITE: {
52 const struct udphdr *uh;
54 uh = skb_header_pointer(skb, protooff, sizeof(_udph), &_udph);
56 /* No choice either */
59 *port = src ? uh->source : uh->dest;
64 const struct icmphdr *ic;
66 ic = skb_header_pointer(skb, protooff, sizeof(_ich), &_ich);
70 *port = (__force __be16)htons((ic->type << 8) | ic->code);
73 case IPPROTO_ICMPV6: {
75 const struct icmp6hdr *ic;
77 ic = skb_header_pointer(skb, protooff, sizeof(_ich), &_ich);
81 *port = (__force __be16)
82 htons((ic->icmp6_type << 8) | ic->icmp6_code);
94 ip_set_get_ip4_port(const struct sk_buff *skb, bool src,
95 __be16 *port, u8 *proto)
97 const struct iphdr *iph = ip_hdr(skb);
98 unsigned int protooff = skb_network_offset(skb) + ip_hdrlen(skb);
99 int protocol = iph->protocol;
101 /* See comments at tcp_match in ip_tables.c */
105 if (ntohs(iph->frag_off) & IP_OFFSET)
110 case IPPROTO_UDPLITE:
112 /* Port info not available for fragment offset > 0 */
115 /* Other protocols doesn't have ports,
116 * so we can match fragments.
122 return get_port(skb, protocol, protooff, src, port, proto);
124 EXPORT_SYMBOL_GPL(ip_set_get_ip4_port);
126 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
128 ip_set_get_ip6_port(const struct sk_buff *skb, bool src,
129 __be16 *port, u8 *proto)
135 nexthdr = ipv6_hdr(skb)->nexthdr;
136 protoff = ipv6_skip_exthdr(skb,
137 skb_network_offset(skb) +
138 sizeof(struct ipv6hdr), &nexthdr,
140 if (protoff < 0 || (frag_off & htons(~0x7)) != 0)
143 return get_port(skb, nexthdr, protoff, src, port, proto);
145 EXPORT_SYMBOL_GPL(ip_set_get_ip6_port);
149 ip_set_get_ip_port(const struct sk_buff *skb, u8 pf, bool src, __be16 *port)
156 ret = ip_set_get_ip4_port(skb, src, port, &proto);
159 ret = ip_set_get_ip6_port(skb, src, port, &proto);
174 EXPORT_SYMBOL_GPL(ip_set_get_ip_port);