1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * 'raw' table, which is the very first hooked in at PRE_ROUTING and LOCAL_OUT .
4 *
5 * Copyright (C) 2003 Jozsef Kadlecsik <kadlec@netfilter.org>
6 */
7#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
8#include <linux/module.h>
9#include <linux/netfilter_ipv4/ip_tables.h>
10#include <linux/slab.h>
11#include <net/ip.h>
12
13#define RAW_VALID_HOOKS ((1 << NF_INET_PRE_ROUTING) | (1 << NF_INET_LOCAL_OUT))
14
15static bool raw_before_defrag __read_mostly;
16MODULE_PARM_DESC(raw_before_defrag, "Enable raw table before defrag");
17module_param(raw_before_defrag, bool, 0000);
18
19static const struct xt_table packet_raw = {
20	.name = "raw",
21	.valid_hooks =  RAW_VALID_HOOKS,
22	.me = THIS_MODULE,
23	.af = NFPROTO_IPV4,
24	.priority = NF_IP_PRI_RAW,
25};
26
27static const struct xt_table packet_raw_before_defrag = {
28	.name = "raw",
29	.valid_hooks =  RAW_VALID_HOOKS,
30	.me = THIS_MODULE,
31	.af = NFPROTO_IPV4,
32	.priority = NF_IP_PRI_RAW_BEFORE_DEFRAG,
33};
34
35static struct nf_hook_ops *rawtable_ops __read_mostly;
36
37static int iptable_raw_table_init(struct net *net)
38{
39	struct ipt_replace *repl;
40	const struct xt_table *table = &packet_raw;
41	int ret;
42
43	if (raw_before_defrag)
44		table = &packet_raw_before_defrag;
45
46	repl = ipt_alloc_initial_table(table);
47	if (repl == NULL)
48		return -ENOMEM;
49	ret = ipt_register_table(net, table, repl, rawtable_ops);
50	kfree(repl);
51	return ret;
52}
53
54static void __net_exit iptable_raw_net_pre_exit(struct net *net)
55{
56	ipt_unregister_table_pre_exit(net, "raw");
57}
58
59static void __net_exit iptable_raw_net_exit(struct net *net)
60{
61	ipt_unregister_table_exit(net, "raw");
62}
63
64static struct pernet_operations iptable_raw_net_ops = {
65	.pre_exit = iptable_raw_net_pre_exit,
66	.exit = iptable_raw_net_exit,
67};
68
69static int __init iptable_raw_init(void)
70{
71	int ret;
72	const struct xt_table *table = &packet_raw;
73
74	if (raw_before_defrag) {
75		table = &packet_raw_before_defrag;
76
77		pr_info("Enabling raw table before defrag\n");
78	}
79
80	ret = xt_register_template(table,
81				   iptable_raw_table_init);
82	if (ret < 0)
83		return ret;
84
85	rawtable_ops = xt_hook_ops_alloc(table, ipt_do_table);
86	if (IS_ERR(rawtable_ops)) {
87		xt_unregister_template(table);
88		return PTR_ERR(rawtable_ops);
89	}
90
91	ret = register_pernet_subsys(&iptable_raw_net_ops);
92	if (ret < 0) {
93		xt_unregister_template(table);
94		kfree(rawtable_ops);
95		return ret;
96	}
97
98	return ret;
99}
100
101static void __exit iptable_raw_fini(void)
102{
103	unregister_pernet_subsys(&iptable_raw_net_ops);
104	kfree(rawtable_ops);
105	xt_unregister_template(&packet_raw);
106}
107
108module_init(iptable_raw_init);
109module_exit(iptable_raw_fini);
110MODULE_LICENSE("GPL");
111MODULE_DESCRIPTION("iptables legacy raw table");
112