1 // SPDX-License-Identifier: GPL-2.0-only
3 * This is the 1999 rewrite of IP Firewalling, aiming for kernel 2.3.x.
5 * Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
8 #include <linux/module.h>
9 #include <linux/netfilter_ipv4/ip_tables.h>
10 #include <linux/netdevice.h>
11 #include <linux/skbuff.h>
12 #include <linux/slab.h>
14 #include <net/route.h>
18 MODULE_LICENSE("GPL");
20 MODULE_DESCRIPTION("iptables mangle table");
22 #define MANGLE_VALID_HOOKS ((1 << NF_INET_PRE_ROUTING) | \
23 (1 << NF_INET_LOCAL_IN) | \
24 (1 << NF_INET_FORWARD) | \
25 (1 << NF_INET_LOCAL_OUT) | \
26 (1 << NF_INET_POST_ROUTING))
28 static int __net_init iptable_mangle_table_init(struct net *net);
30 static const struct xt_table packet_mangler = {
32 .valid_hooks = MANGLE_VALID_HOOKS,
35 .priority = NF_IP_PRI_MANGLE,
36 .table_init = iptable_mangle_table_init,
40 ipt_mangle_out(struct sk_buff *skb, const struct nf_hook_state *state)
43 const struct iphdr *iph;
49 /* Save things which could affect route */
56 ret = ipt_do_table(skb, state, state->net->ipv4.iptable_mangle);
57 /* Reroute for ANY change. */
58 if (ret != NF_DROP && ret != NF_STOLEN) {
61 if (iph->saddr != saddr ||
62 iph->daddr != daddr ||
65 err = ip_route_me_harder(state->net, skb, RTN_UNSPEC);
67 ret = NF_DROP_ERR(err);
74 /* The work comes in here from netfilter.c. */
76 iptable_mangle_hook(void *priv,
78 const struct nf_hook_state *state)
80 if (state->hook == NF_INET_LOCAL_OUT)
81 return ipt_mangle_out(skb, state);
82 return ipt_do_table(skb, state, state->net->ipv4.iptable_mangle);
85 static struct nf_hook_ops *mangle_ops __read_mostly;
86 static int __net_init iptable_mangle_table_init(struct net *net)
88 struct ipt_replace *repl;
91 if (net->ipv4.iptable_mangle)
94 repl = ipt_alloc_initial_table(&packet_mangler);
97 ret = ipt_register_table(net, &packet_mangler, repl, mangle_ops,
98 &net->ipv4.iptable_mangle);
103 static void __net_exit iptable_mangle_net_exit(struct net *net)
105 if (!net->ipv4.iptable_mangle)
107 ipt_unregister_table(net, net->ipv4.iptable_mangle, mangle_ops);
108 net->ipv4.iptable_mangle = NULL;
111 static struct pernet_operations iptable_mangle_net_ops = {
112 .exit = iptable_mangle_net_exit,
115 static int __init iptable_mangle_init(void)
119 mangle_ops = xt_hook_ops_alloc(&packet_mangler, iptable_mangle_hook);
120 if (IS_ERR(mangle_ops)) {
121 ret = PTR_ERR(mangle_ops);
125 ret = register_pernet_subsys(&iptable_mangle_net_ops);
131 ret = iptable_mangle_table_init(&init_net);
133 unregister_pernet_subsys(&iptable_mangle_net_ops);
140 static void __exit iptable_mangle_fini(void)
142 unregister_pernet_subsys(&iptable_mangle_net_ops);
146 module_init(iptable_mangle_init);
147 module_exit(iptable_mangle_fini);