xref: /linux/net/netfilter/xt_esp.c (revision 1b78070aaef63512688aebfbc82365ef9d6660f1)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Kernel module to match ESP parameters. */
3 
4 /* (C) 1999-2000 Yon Uriarte <yon@astaro.de>
5  */
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7 #include <linux/module.h>
8 #include <linux/skbuff.h>
9 #include <linux/in.h>
10 #include <linux/ip.h>
11 
12 #include <linux/netfilter/xt_esp.h>
13 #include <linux/netfilter/x_tables.h>
14 
15 #include <linux/netfilter_ipv4/ip_tables.h>
16 #include <linux/netfilter_ipv6/ip6_tables.h>
17 
18 MODULE_LICENSE("GPL");
19 MODULE_AUTHOR("Yon Uriarte <yon@astaro.de>");
20 MODULE_DESCRIPTION("Xtables: IPsec-ESP packet match");
21 MODULE_ALIAS("ipt_esp");
22 MODULE_ALIAS("ip6t_esp");
23 
24 /* Returns 1 if the spi is matched by the range, 0 otherwise */
25 static inline bool
26 spi_match(u_int32_t min, u_int32_t max, u_int32_t spi, bool invert)
27 {
28 	return (spi >= min && spi <= max) ^ invert;
29 }
30 
31 static bool esp_mt(const struct sk_buff *skb, struct xt_action_param *par)
32 {
33 	const struct ip_esp_hdr *eh;
34 	struct ip_esp_hdr _esp;
35 	const struct xt_esp *espinfo = par->matchinfo;
36 
37 	/* Must not be a fragment. */
38 	if (par->fragoff != 0)
39 		return false;
40 
41 	eh = skb_header_pointer(skb, par->thoff, sizeof(_esp), &_esp);
42 	if (eh == NULL) {
43 		/* We've been asked to examine this packet, and we
44 		 * can't.  Hence, no choice but to drop.
45 		 */
46 		par->hotdrop = true;
47 		return false;
48 	}
49 
50 	return spi_match(espinfo->spis[0], espinfo->spis[1], ntohl(eh->spi),
51 			 !!(espinfo->invflags & XT_ESP_INV_SPI));
52 }
53 
54 static int esp_mt_check(const struct xt_mtchk_param *par)
55 {
56 	const struct xt_esp *espinfo = par->matchinfo;
57 
58 	if (espinfo->invflags & ~XT_ESP_INV_MASK) {
59 		pr_info_ratelimited("unknown flags %X\n", espinfo->invflags);
60 		return -EINVAL;
61 	}
62 
63 	return 0;
64 }
65 
66 static struct xt_match esp_mt_reg[] __read_mostly = {
67 	{
68 		.name		= "esp",
69 		.family		= NFPROTO_IPV4,
70 		.checkentry	= esp_mt_check,
71 		.match		= esp_mt,
72 		.matchsize	= sizeof(struct xt_esp),
73 		.proto		= IPPROTO_ESP,
74 		.me		= THIS_MODULE,
75 	},
76 	{
77 		.name		= "esp",
78 		.family		= NFPROTO_IPV6,
79 		.checkentry	= esp_mt_check,
80 		.match		= esp_mt,
81 		.matchsize	= sizeof(struct xt_esp),
82 		.proto		= IPPROTO_ESP,
83 		.me		= THIS_MODULE,
84 	},
85 };
86 
87 static int __init esp_mt_init(void)
88 {
89 	return xt_register_matches(esp_mt_reg, ARRAY_SIZE(esp_mt_reg));
90 }
91 
92 static void __exit esp_mt_exit(void)
93 {
94 	xt_unregister_matches(esp_mt_reg, ARRAY_SIZE(esp_mt_reg));
95 }
96 
97 module_init(esp_mt_init);
98 module_exit(esp_mt_exit);
99