1 // SPDX-License-Identifier: GPL-2.0-only
7 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
8 #include <linux/module.h>
9 #include <linux/skbuff.h>
10 #include <linux/netdevice.h>
13 #include <net/ip_fib.h>
14 #include <net/route.h>
16 #include <linux/netfilter/xt_rpfilter.h>
17 #include <linux/netfilter/x_tables.h>
19 MODULE_LICENSE("GPL");
21 MODULE_DESCRIPTION("iptables: ipv4 reverse path filter match");
23 /* don't try to find route from mcast/bcast/zeronet */
24 static __be32 rpfilter_get_saddr(__be32 addr)
26 if (ipv4_is_multicast(addr) || ipv4_is_lbcast(addr) ||
27 ipv4_is_zeronet(addr))
32 static bool rpfilter_lookup_reverse(struct net *net, struct flowi4 *fl4,
33 const struct net_device *dev, u8 flags)
35 struct fib_result res;
36 int ret __maybe_unused;
38 if (fib_lookup(net, fl4, &res, FIB_LOOKUP_IGNORE_LINKSTATE))
41 if (res.type != RTN_UNICAST) {
42 if (res.type != RTN_LOCAL || !(flags & XT_RPFILTER_ACCEPT_LOCAL))
45 return fib_info_nh_uses_dev(res.fi, dev) || flags & XT_RPFILTER_LOOSE;
49 rpfilter_is_loopback(const struct sk_buff *skb, const struct net_device *in)
51 return skb->pkt_type == PACKET_LOOPBACK || in->flags & IFF_LOOPBACK;
54 static bool rpfilter_mt(const struct sk_buff *skb, struct xt_action_param *par)
56 const struct xt_rpfilter_info *info;
57 const struct iphdr *iph;
61 info = par->matchinfo;
62 invert = info->flags & XT_RPFILTER_INVERT;
64 if (rpfilter_is_loopback(skb, xt_in(par)))
68 if (ipv4_is_zeronet(iph->saddr)) {
69 if (ipv4_is_lbcast(iph->daddr) ||
70 ipv4_is_local_multicast(iph->daddr))
74 memset(&flow, 0, sizeof(flow));
75 flow.flowi4_iif = LOOPBACK_IFINDEX;
76 flow.daddr = iph->saddr;
77 flow.saddr = rpfilter_get_saddr(iph->daddr);
78 flow.flowi4_mark = info->flags & XT_RPFILTER_VALID_MARK ? skb->mark : 0;
79 flow.flowi4_tos = RT_TOS(iph->tos);
80 flow.flowi4_scope = RT_SCOPE_UNIVERSE;
81 flow.flowi4_oif = l3mdev_master_ifindex_rcu(xt_in(par));
83 return rpfilter_lookup_reverse(xt_net(par), &flow, xt_in(par), info->flags) ^ invert;
86 static int rpfilter_check(const struct xt_mtchk_param *par)
88 const struct xt_rpfilter_info *info = par->matchinfo;
89 unsigned int options = ~XT_RPFILTER_OPTION_MASK;
90 if (info->flags & options) {
91 pr_info_ratelimited("unknown options\n");
95 if (strcmp(par->table, "mangle") != 0 &&
96 strcmp(par->table, "raw") != 0) {
97 pr_info_ratelimited("only valid in \'raw\' or \'mangle\' table, not \'%s\'\n",
105 static struct xt_match rpfilter_mt_reg __read_mostly = {
107 .family = NFPROTO_IPV4,
108 .checkentry = rpfilter_check,
109 .match = rpfilter_mt,
110 .matchsize = sizeof(struct xt_rpfilter_info),
111 .hooks = (1 << NF_INET_PRE_ROUTING),
115 static int __init rpfilter_mt_init(void)
117 return xt_register_match(&rpfilter_mt_reg);
120 static void __exit rpfilter_mt_exit(void)
122 xt_unregister_match(&rpfilter_mt_reg);
125 module_init(rpfilter_mt_init);
126 module_exit(rpfilter_mt_exit);