1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (C) 2003-2011 Jozsef Kadlecsik <kadlec@netfilter.org>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
9 /* Get Layer-4 data from the packets */
12 #include <linux/skbuff.h>
13 #include <linux/icmp.h>
14 #include <linux/icmpv6.h>
15 #include <linux/sctp.h>
16 #include <linux/netfilter_ipv6/ip6_tables.h>
20 #include <linux/netfilter/ipset/ip_set_getport.h>
21 #include <linux/export.h>
23 /* We must handle non-linear skbs */
25 get_port(const struct sk_buff *skb, int protocol, unsigned int protooff,
26 bool src, __be16 *port, u8 *proto)
31 const struct tcphdr *th;
33 th = skb_header_pointer(skb, protooff, sizeof(_tcph), &_tcph);
35 /* No choice either */
38 *port = src ? th->source : th->dest;
43 const struct sctphdr *sh;
45 sh = skb_header_pointer(skb, protooff, sizeof(_sh), &_sh);
47 /* No choice either */
50 *port = src ? sh->source : sh->dest;
54 case IPPROTO_UDPLITE: {
56 const struct udphdr *uh;
58 uh = skb_header_pointer(skb, protooff, sizeof(_udph), &_udph);
60 /* No choice either */
63 *port = src ? uh->source : uh->dest;
68 const struct icmphdr *ic;
70 ic = skb_header_pointer(skb, protooff, sizeof(_ich), &_ich);
74 *port = (__force __be16)htons((ic->type << 8) | ic->code);
77 case IPPROTO_ICMPV6: {
79 const struct icmp6hdr *ic;
81 ic = skb_header_pointer(skb, protooff, sizeof(_ich), &_ich);
85 *port = (__force __be16)
86 htons((ic->icmp6_type << 8) | ic->icmp6_code);
98 ip_set_get_ip4_port(const struct sk_buff *skb, bool src,
99 __be16 *port, u8 *proto)
101 const struct iphdr *iph = ip_hdr(skb);
102 unsigned int protooff = skb_network_offset(skb) + ip_hdrlen(skb);
103 int protocol = iph->protocol;
105 /* See comments at tcp_match in ip_tables.c */
109 if (ntohs(iph->frag_off) & IP_OFFSET)
114 case IPPROTO_UDPLITE:
116 /* Port info not available for fragment offset > 0 */
119 /* Other protocols doesn't have ports,
120 * so we can match fragments.
126 return get_port(skb, protocol, protooff, src, port, proto);
128 EXPORT_SYMBOL_GPL(ip_set_get_ip4_port);
130 #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
132 ip_set_get_ip6_port(const struct sk_buff *skb, bool src,
133 __be16 *port, u8 *proto)
139 nexthdr = ipv6_hdr(skb)->nexthdr;
140 protoff = ipv6_skip_exthdr(skb,
141 skb_network_offset(skb) +
142 sizeof(struct ipv6hdr), &nexthdr,
144 if (protoff < 0 || (frag_off & htons(~0x7)) != 0)
147 return get_port(skb, nexthdr, protoff, src, port, proto);
149 EXPORT_SYMBOL_GPL(ip_set_get_ip6_port);