1 // SPDX-License-Identifier: GPL-2.0-only
2 /* (C) 1999-2001 Paul `Rusty' Russell
3 * (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
4 * (C) 2011 Patrick McHardy <kaber@trash.net>
7 #include <linux/module.h>
8 #include <linux/netfilter.h>
9 #include <linux/netfilter_ipv4.h>
10 #include <linux/netfilter_ipv4/ip_tables.h>
14 #include <net/netfilter/nf_nat.h>
16 static int __net_init iptable_nat_table_init(struct net *net);
18 static const struct xt_table nf_nat_ipv4_table = {
20 .valid_hooks = (1 << NF_INET_PRE_ROUTING) |
21 (1 << NF_INET_POST_ROUTING) |
22 (1 << NF_INET_LOCAL_OUT) |
23 (1 << NF_INET_LOCAL_IN),
26 .table_init = iptable_nat_table_init,
29 static unsigned int iptable_nat_do_chain(void *priv,
31 const struct nf_hook_state *state)
33 return ipt_do_table(skb, state, state->net->ipv4.nat_table);
36 static const struct nf_hook_ops nf_nat_ipv4_ops[] = {
38 .hook = iptable_nat_do_chain,
40 .hooknum = NF_INET_PRE_ROUTING,
41 .priority = NF_IP_PRI_NAT_DST,
44 .hook = iptable_nat_do_chain,
46 .hooknum = NF_INET_POST_ROUTING,
47 .priority = NF_IP_PRI_NAT_SRC,
50 .hook = iptable_nat_do_chain,
52 .hooknum = NF_INET_LOCAL_OUT,
53 .priority = NF_IP_PRI_NAT_DST,
56 .hook = iptable_nat_do_chain,
58 .hooknum = NF_INET_LOCAL_IN,
59 .priority = NF_IP_PRI_NAT_SRC,
63 static int ipt_nat_register_lookups(struct net *net)
67 for (i = 0; i < ARRAY_SIZE(nf_nat_ipv4_ops); i++) {
68 ret = nf_nat_ipv4_register_fn(net, &nf_nat_ipv4_ops[i]);
71 nf_nat_ipv4_unregister_fn(net, &nf_nat_ipv4_ops[--i]);
80 static void ipt_nat_unregister_lookups(struct net *net)
84 for (i = 0; i < ARRAY_SIZE(nf_nat_ipv4_ops); i++)
85 nf_nat_ipv4_unregister_fn(net, &nf_nat_ipv4_ops[i]);
88 static int __net_init iptable_nat_table_init(struct net *net)
90 struct ipt_replace *repl;
93 if (net->ipv4.nat_table)
96 repl = ipt_alloc_initial_table(&nf_nat_ipv4_table);
99 ret = ipt_register_table(net, &nf_nat_ipv4_table, repl,
100 NULL, &net->ipv4.nat_table);
106 ret = ipt_nat_register_lookups(net);
108 ipt_unregister_table(net, net->ipv4.nat_table, NULL);
109 net->ipv4.nat_table = NULL;
116 static void __net_exit iptable_nat_net_exit(struct net *net)
118 if (!net->ipv4.nat_table)
120 ipt_nat_unregister_lookups(net);
121 ipt_unregister_table(net, net->ipv4.nat_table, NULL);
122 net->ipv4.nat_table = NULL;
125 static struct pernet_operations iptable_nat_net_ops = {
126 .exit = iptable_nat_net_exit,
129 static int __init iptable_nat_init(void)
131 int ret = register_pernet_subsys(&iptable_nat_net_ops);
136 ret = iptable_nat_table_init(&init_net);
138 unregister_pernet_subsys(&iptable_nat_net_ops);
142 static void __exit iptable_nat_exit(void)
144 unregister_pernet_subsys(&iptable_nat_net_ops);
147 module_init(iptable_nat_init);
148 module_exit(iptable_nat_exit);
150 MODULE_LICENSE("GPL");