xref: /linux/net/netfilter/ipset/ip_set_core.c (revision 896d8946da97332d4dc80fa1937d8dd6b1c35ad4)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (C) 2000-2002 Joakim Axelsson <gozem@linux.nu>
3  *                         Patrick Schaaf <bof@bof.de>
4  * Copyright (C) 2003-2013 Jozsef Kadlecsik <kadlec@netfilter.org>
5  */
6 
7 /* Kernel module for IP set management */
8 
9 #include <linux/init.h>
10 #include <linux/module.h>
11 #include <linux/moduleparam.h>
12 #include <linux/ip.h>
13 #include <linux/skbuff.h>
14 #include <linux/spinlock.h>
15 #include <linux/rculist.h>
16 #include <net/netlink.h>
17 #include <net/net_namespace.h>
18 #include <net/netns/generic.h>
19 
20 #include <linux/netfilter.h>
21 #include <linux/netfilter/x_tables.h>
22 #include <linux/netfilter/nfnetlink.h>
23 #include <linux/netfilter/ipset/ip_set.h>
24 
25 static LIST_HEAD(ip_set_type_list);		/* all registered set types */
26 static DEFINE_MUTEX(ip_set_type_mutex);		/* protects ip_set_type_list */
27 static DEFINE_RWLOCK(ip_set_ref_lock);		/* protects the set refs */
28 
29 struct ip_set_net {
30 	struct ip_set * __rcu *ip_set_list;	/* all individual sets */
31 	ip_set_id_t	ip_set_max;	/* max number of sets */
32 	bool		is_deleted;	/* deleted by ip_set_net_exit */
33 	bool		is_destroyed;	/* all sets are destroyed */
34 };
35 
36 static unsigned int ip_set_net_id __read_mostly;
37 
ip_set_pernet(struct net * net)38 static struct ip_set_net *ip_set_pernet(struct net *net)
39 {
40 	return net_generic(net, ip_set_net_id);
41 }
42 
43 #define IP_SET_INC	64
44 #define STRNCMP(a, b)	(strncmp(a, b, IPSET_MAXNAMELEN) == 0)
45 
46 static unsigned int max_sets;
47 
48 module_param(max_sets, int, 0600);
49 MODULE_PARM_DESC(max_sets, "maximal number of sets");
50 MODULE_LICENSE("GPL");
51 MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@netfilter.org>");
52 MODULE_DESCRIPTION("core IP set support");
53 MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_IPSET);
54 
55 /* When the nfnl mutex or ip_set_ref_lock is held: */
56 #define ip_set_dereference(inst)	\
57 	rcu_dereference_protected((inst)->ip_set_list,	\
58 		lockdep_nfnl_is_held(NFNL_SUBSYS_IPSET) || \
59 		lockdep_is_held(&ip_set_ref_lock) || \
60 		(inst)->is_deleted)
61 #define ip_set(inst, id)		\
62 	ip_set_dereference(inst)[id]
63 #define ip_set_ref_netlink(inst,id)	\
64 	rcu_dereference_raw((inst)->ip_set_list)[id]
65 #define ip_set_dereference_nfnl(p)	\
66 	rcu_dereference_check(p, lockdep_nfnl_is_held(NFNL_SUBSYS_IPSET))
67 
68 /* The set types are implemented in modules and registered set types
69  * can be found in ip_set_type_list. Adding/deleting types is
70  * serialized by ip_set_type_mutex.
71  */
72 
73 static void
ip_set_type_lock(void)74 ip_set_type_lock(void)
75 {
76 	mutex_lock(&ip_set_type_mutex);
77 }
78 
79 static void
ip_set_type_unlock(void)80 ip_set_type_unlock(void)
81 {
82 	mutex_unlock(&ip_set_type_mutex);
83 }
84 
85 /* Register and deregister settype */
86 
87 static struct ip_set_type *
find_set_type(const char * name,u8 family,u8 revision)88 find_set_type(const char *name, u8 family, u8 revision)
89 {
90 	struct ip_set_type *type;
91 
92 	list_for_each_entry_rcu(type, &ip_set_type_list, list,
93 				lockdep_is_held(&ip_set_type_mutex))
94 		if (STRNCMP(type->name, name) &&
95 		    (type->family == family ||
96 		     type->family == NFPROTO_UNSPEC) &&
97 		    revision >= type->revision_min &&
98 		    revision <= type->revision_max)
99 			return type;
100 	return NULL;
101 }
102 
103 /* Unlock, try to load a set type module and lock again */
104 static bool
load_settype(const char * name)105 load_settype(const char *name)
106 {
107 	if (!try_module_get(THIS_MODULE))
108 		return false;
109 
110 	nfnl_unlock(NFNL_SUBSYS_IPSET);
111 	pr_debug("try to load ip_set_%s\n", name);
112 	if (request_module("ip_set_%s", name) < 0) {
113 		pr_warn("Can't find ip_set type %s\n", name);
114 		nfnl_lock(NFNL_SUBSYS_IPSET);
115 		module_put(THIS_MODULE);
116 		return false;
117 	}
118 	nfnl_lock(NFNL_SUBSYS_IPSET);
119 	module_put(THIS_MODULE);
120 	return true;
121 }
122 
123 /* Find a set type and reference it */
124 #define find_set_type_get(name, family, revision, found)	\
125 	__find_set_type_get(name, family, revision, found, false)
126 
127 static int
__find_set_type_get(const char * name,u8 family,u8 revision,struct ip_set_type ** found,bool retry)128 __find_set_type_get(const char *name, u8 family, u8 revision,
129 		    struct ip_set_type **found, bool retry)
130 {
131 	struct ip_set_type *type;
132 	int err;
133 
134 	if (retry && !load_settype(name))
135 		return -IPSET_ERR_FIND_TYPE;
136 
137 	rcu_read_lock();
138 	*found = find_set_type(name, family, revision);
139 	if (*found) {
140 		err = !try_module_get((*found)->me) ? -EFAULT : 0;
141 		goto unlock;
142 	}
143 	/* Make sure the type is already loaded
144 	 * but we don't support the revision
145 	 */
146 	list_for_each_entry_rcu(type, &ip_set_type_list, list)
147 		if (STRNCMP(type->name, name)) {
148 			err = -IPSET_ERR_FIND_TYPE;
149 			goto unlock;
150 		}
151 	rcu_read_unlock();
152 
153 	return retry ? -IPSET_ERR_FIND_TYPE :
154 		__find_set_type_get(name, family, revision, found, true);
155 
156 unlock:
157 	rcu_read_unlock();
158 	return err;
159 }
160 
161 /* Find a given set type by name and family.
162  * If we succeeded, the supported minimal and maximum revisions are
163  * filled out.
164  */
165 #define find_set_type_minmax(name, family, min, max) \
166 	__find_set_type_minmax(name, family, min, max, false)
167 
168 static int
__find_set_type_minmax(const char * name,u8 family,u8 * min,u8 * max,bool retry)169 __find_set_type_minmax(const char *name, u8 family, u8 *min, u8 *max,
170 		       bool retry)
171 {
172 	struct ip_set_type *type;
173 	bool found = false;
174 
175 	if (retry && !load_settype(name))
176 		return -IPSET_ERR_FIND_TYPE;
177 
178 	*min = 255; *max = 0;
179 	rcu_read_lock();
180 	list_for_each_entry_rcu(type, &ip_set_type_list, list)
181 		if (STRNCMP(type->name, name) &&
182 		    (type->family == family ||
183 		     type->family == NFPROTO_UNSPEC)) {
184 			found = true;
185 			if (type->revision_min < *min)
186 				*min = type->revision_min;
187 			if (type->revision_max > *max)
188 				*max = type->revision_max;
189 		}
190 	rcu_read_unlock();
191 	if (found)
192 		return 0;
193 
194 	return retry ? -IPSET_ERR_FIND_TYPE :
195 		__find_set_type_minmax(name, family, min, max, true);
196 }
197 
198 #define family_name(f)	((f) == NFPROTO_IPV4 ? "inet" : \
199 			 (f) == NFPROTO_IPV6 ? "inet6" : "any")
200 
201 /* Register a set type structure. The type is identified by
202  * the unique triple of name, family and revision.
203  */
204 int
ip_set_type_register(struct ip_set_type * type)205 ip_set_type_register(struct ip_set_type *type)
206 {
207 	int ret = 0;
208 
209 	if (type->protocol != IPSET_PROTOCOL) {
210 		pr_warn("ip_set type %s, family %s, revision %u:%u uses wrong protocol version %u (want %u)\n",
211 			type->name, family_name(type->family),
212 			type->revision_min, type->revision_max,
213 			type->protocol, IPSET_PROTOCOL);
214 		return -EINVAL;
215 	}
216 
217 	ip_set_type_lock();
218 	if (find_set_type(type->name, type->family, type->revision_min)) {
219 		/* Duplicate! */
220 		pr_warn("ip_set type %s, family %s with revision min %u already registered!\n",
221 			type->name, family_name(type->family),
222 			type->revision_min);
223 		ip_set_type_unlock();
224 		return -EINVAL;
225 	}
226 	list_add_rcu(&type->list, &ip_set_type_list);
227 	pr_debug("type %s, family %s, revision %u:%u registered.\n",
228 		 type->name, family_name(type->family),
229 		 type->revision_min, type->revision_max);
230 	ip_set_type_unlock();
231 
232 	return ret;
233 }
234 EXPORT_SYMBOL_GPL(ip_set_type_register);
235 
236 /* Unregister a set type. There's a small race with ip_set_create */
237 void
ip_set_type_unregister(struct ip_set_type * type)238 ip_set_type_unregister(struct ip_set_type *type)
239 {
240 	ip_set_type_lock();
241 	if (!find_set_type(type->name, type->family, type->revision_min)) {
242 		pr_warn("ip_set type %s, family %s with revision min %u not registered\n",
243 			type->name, family_name(type->family),
244 			type->revision_min);
245 		ip_set_type_unlock();
246 		return;
247 	}
248 	list_del_rcu(&type->list);
249 	pr_debug("type %s, family %s with revision min %u unregistered.\n",
250 		 type->name, family_name(type->family), type->revision_min);
251 	ip_set_type_unlock();
252 
253 	synchronize_rcu();
254 }
255 EXPORT_SYMBOL_GPL(ip_set_type_unregister);
256 
257 /* Utility functions */
258 void *
ip_set_alloc(size_t size)259 ip_set_alloc(size_t size)
260 {
261 	return kvzalloc(size, GFP_KERNEL_ACCOUNT);
262 }
263 EXPORT_SYMBOL_GPL(ip_set_alloc);
264 
265 void
ip_set_free(void * members)266 ip_set_free(void *members)
267 {
268 	pr_debug("%p: free with %s\n", members,
269 		 is_vmalloc_addr(members) ? "vfree" : "kfree");
270 	kvfree(members);
271 }
272 EXPORT_SYMBOL_GPL(ip_set_free);
273 
274 static bool
flag_nested(const struct nlattr * nla)275 flag_nested(const struct nlattr *nla)
276 {
277 	return nla->nla_type & NLA_F_NESTED;
278 }
279 
280 static const struct nla_policy ipaddr_policy[IPSET_ATTR_IPADDR_MAX + 1] = {
281 	[IPSET_ATTR_IPADDR_IPV4]	= { .type = NLA_U32 },
282 	[IPSET_ATTR_IPADDR_IPV6]	= NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)),
283 };
284 
285 int
ip_set_get_ipaddr4(struct nlattr * nla,__be32 * ipaddr)286 ip_set_get_ipaddr4(struct nlattr *nla,  __be32 *ipaddr)
287 {
288 	struct nlattr *tb[IPSET_ATTR_IPADDR_MAX + 1];
289 
290 	if (unlikely(!flag_nested(nla)))
291 		return -IPSET_ERR_PROTOCOL;
292 	if (nla_parse_nested(tb, IPSET_ATTR_IPADDR_MAX, nla,
293 			     ipaddr_policy, NULL))
294 		return -IPSET_ERR_PROTOCOL;
295 	if (unlikely(!ip_set_attr_netorder(tb, IPSET_ATTR_IPADDR_IPV4)))
296 		return -IPSET_ERR_PROTOCOL;
297 
298 	*ipaddr = nla_get_be32(tb[IPSET_ATTR_IPADDR_IPV4]);
299 	return 0;
300 }
301 EXPORT_SYMBOL_GPL(ip_set_get_ipaddr4);
302 
303 int
ip_set_get_ipaddr6(struct nlattr * nla,union nf_inet_addr * ipaddr)304 ip_set_get_ipaddr6(struct nlattr *nla, union nf_inet_addr *ipaddr)
305 {
306 	struct nlattr *tb[IPSET_ATTR_IPADDR_MAX + 1];
307 
308 	if (unlikely(!flag_nested(nla)))
309 		return -IPSET_ERR_PROTOCOL;
310 
311 	if (nla_parse_nested(tb, IPSET_ATTR_IPADDR_MAX, nla,
312 			     ipaddr_policy, NULL))
313 		return -IPSET_ERR_PROTOCOL;
314 	if (unlikely(!ip_set_attr_netorder(tb, IPSET_ATTR_IPADDR_IPV6)))
315 		return -IPSET_ERR_PROTOCOL;
316 
317 	memcpy(ipaddr, nla_data(tb[IPSET_ATTR_IPADDR_IPV6]),
318 	       sizeof(struct in6_addr));
319 	return 0;
320 }
321 EXPORT_SYMBOL_GPL(ip_set_get_ipaddr6);
322 
323 static u32
ip_set_timeout_get(const unsigned long * timeout)324 ip_set_timeout_get(const unsigned long *timeout)
325 {
326 	u32 t;
327 
328 	if (*timeout == IPSET_ELEM_PERMANENT)
329 		return 0;
330 
331 	t = jiffies_to_msecs(*timeout - jiffies) / MSEC_PER_SEC;
332 	/* Zero value in userspace means no timeout */
333 	return t == 0 ? 1 : t;
334 }
335 
336 static char *
ip_set_comment_uget(struct nlattr * tb)337 ip_set_comment_uget(struct nlattr *tb)
338 {
339 	return nla_data(tb);
340 }
341 
342 /* Called from uadd only, protected by the set spinlock.
343  * The kadt functions don't use the comment extensions in any way.
344  */
345 void
ip_set_init_comment(struct ip_set * set,struct ip_set_comment * comment,const struct ip_set_ext * ext)346 ip_set_init_comment(struct ip_set *set, struct ip_set_comment *comment,
347 		    const struct ip_set_ext *ext)
348 {
349 	struct ip_set_comment_rcu *c = rcu_dereference_protected(comment->c, 1);
350 	size_t len = ext->comment ? strlen(ext->comment) : 0;
351 
352 	if (unlikely(c)) {
353 		set->ext_size -= sizeof(*c) + strlen(c->str) + 1;
354 		kfree_rcu(c, rcu);
355 		rcu_assign_pointer(comment->c, NULL);
356 	}
357 	if (!len)
358 		return;
359 	if (unlikely(len > IPSET_MAX_COMMENT_SIZE))
360 		len = IPSET_MAX_COMMENT_SIZE;
361 	c = kmalloc(sizeof(*c) + len + 1, GFP_ATOMIC);
362 	if (unlikely(!c))
363 		return;
364 	strscpy(c->str, ext->comment, len + 1);
365 	set->ext_size += sizeof(*c) + strlen(c->str) + 1;
366 	rcu_assign_pointer(comment->c, c);
367 }
368 EXPORT_SYMBOL_GPL(ip_set_init_comment);
369 
370 /* Used only when dumping a set, protected by rcu_read_lock() */
371 static int
ip_set_put_comment(struct sk_buff * skb,const struct ip_set_comment * comment)372 ip_set_put_comment(struct sk_buff *skb, const struct ip_set_comment *comment)
373 {
374 	struct ip_set_comment_rcu *c = rcu_dereference(comment->c);
375 
376 	if (!c)
377 		return 0;
378 	return nla_put_string(skb, IPSET_ATTR_COMMENT, c->str);
379 }
380 
381 /* Called from uadd/udel, flush or the garbage collectors protected
382  * by the set spinlock.
383  * Called when the set is destroyed and when there can't be any user
384  * of the set data anymore.
385  */
386 static void
ip_set_comment_free(struct ip_set * set,void * ptr)387 ip_set_comment_free(struct ip_set *set, void *ptr)
388 {
389 	struct ip_set_comment *comment = ptr;
390 	struct ip_set_comment_rcu *c;
391 
392 	c = rcu_dereference_protected(comment->c, 1);
393 	if (unlikely(!c))
394 		return;
395 	set->ext_size -= sizeof(*c) + strlen(c->str) + 1;
396 	kfree_rcu(c, rcu);
397 	rcu_assign_pointer(comment->c, NULL);
398 }
399 
400 typedef void (*destroyer)(struct ip_set *, void *);
401 /* ipset data extension types, in size order */
402 
403 const struct ip_set_ext_type ip_set_extensions[] = {
404 	[IPSET_EXT_ID_COUNTER] = {
405 		.type	= IPSET_EXT_COUNTER,
406 		.flag	= IPSET_FLAG_WITH_COUNTERS,
407 		.len	= sizeof(struct ip_set_counter),
408 		.align	= __alignof__(struct ip_set_counter),
409 	},
410 	[IPSET_EXT_ID_TIMEOUT] = {
411 		.type	= IPSET_EXT_TIMEOUT,
412 		.len	= sizeof(unsigned long),
413 		.align	= __alignof__(unsigned long),
414 	},
415 	[IPSET_EXT_ID_SKBINFO] = {
416 		.type	= IPSET_EXT_SKBINFO,
417 		.flag	= IPSET_FLAG_WITH_SKBINFO,
418 		.len	= sizeof(struct ip_set_skbinfo),
419 		.align	= __alignof__(struct ip_set_skbinfo),
420 	},
421 	[IPSET_EXT_ID_COMMENT] = {
422 		.type	 = IPSET_EXT_COMMENT | IPSET_EXT_DESTROY,
423 		.flag	 = IPSET_FLAG_WITH_COMMENT,
424 		.len	 = sizeof(struct ip_set_comment),
425 		.align	 = __alignof__(struct ip_set_comment),
426 		.destroy = ip_set_comment_free,
427 	},
428 };
429 EXPORT_SYMBOL_GPL(ip_set_extensions);
430 
431 static bool
add_extension(enum ip_set_ext_id id,u32 flags,struct nlattr * tb[])432 add_extension(enum ip_set_ext_id id, u32 flags, struct nlattr *tb[])
433 {
434 	return ip_set_extensions[id].flag ?
435 		(flags & ip_set_extensions[id].flag) :
436 		!!tb[IPSET_ATTR_TIMEOUT];
437 }
438 
439 size_t
ip_set_elem_len(struct ip_set * set,struct nlattr * tb[],size_t len,size_t align)440 ip_set_elem_len(struct ip_set *set, struct nlattr *tb[], size_t len,
441 		size_t align)
442 {
443 	enum ip_set_ext_id id;
444 	u32 cadt_flags = 0;
445 
446 	if (tb[IPSET_ATTR_CADT_FLAGS])
447 		cadt_flags = ip_set_get_h32(tb[IPSET_ATTR_CADT_FLAGS]);
448 	if (cadt_flags & IPSET_FLAG_WITH_FORCEADD)
449 		set->flags |= IPSET_CREATE_FLAG_FORCEADD;
450 	if (!align)
451 		align = 1;
452 	for (id = 0; id < IPSET_EXT_ID_MAX; id++) {
453 		if (!add_extension(id, cadt_flags, tb))
454 			continue;
455 		if (align < ip_set_extensions[id].align)
456 			align = ip_set_extensions[id].align;
457 		len = ALIGN(len, ip_set_extensions[id].align);
458 		set->offset[id] = len;
459 		set->extensions |= ip_set_extensions[id].type;
460 		len += ip_set_extensions[id].len;
461 	}
462 	return ALIGN(len, align);
463 }
464 EXPORT_SYMBOL_GPL(ip_set_elem_len);
465 
466 int
ip_set_get_extensions(struct ip_set * set,struct nlattr * tb[],struct ip_set_ext * ext)467 ip_set_get_extensions(struct ip_set *set, struct nlattr *tb[],
468 		      struct ip_set_ext *ext)
469 {
470 	u64 fullmark;
471 
472 	if (unlikely(!ip_set_optattr_netorder(tb, IPSET_ATTR_TIMEOUT) ||
473 		     !ip_set_optattr_netorder(tb, IPSET_ATTR_PACKETS) ||
474 		     !ip_set_optattr_netorder(tb, IPSET_ATTR_BYTES) ||
475 		     !ip_set_optattr_netorder(tb, IPSET_ATTR_SKBMARK) ||
476 		     !ip_set_optattr_netorder(tb, IPSET_ATTR_SKBPRIO) ||
477 		     !ip_set_optattr_netorder(tb, IPSET_ATTR_SKBQUEUE)))
478 		return -IPSET_ERR_PROTOCOL;
479 
480 	if (tb[IPSET_ATTR_TIMEOUT]) {
481 		if (!SET_WITH_TIMEOUT(set))
482 			return -IPSET_ERR_TIMEOUT;
483 		ext->timeout = ip_set_timeout_uget(tb[IPSET_ATTR_TIMEOUT]);
484 	}
485 	if (tb[IPSET_ATTR_BYTES] || tb[IPSET_ATTR_PACKETS]) {
486 		if (!SET_WITH_COUNTER(set))
487 			return -IPSET_ERR_COUNTER;
488 		if (tb[IPSET_ATTR_BYTES])
489 			ext->bytes = be64_to_cpu(nla_get_be64(
490 						 tb[IPSET_ATTR_BYTES]));
491 		if (tb[IPSET_ATTR_PACKETS])
492 			ext->packets = be64_to_cpu(nla_get_be64(
493 						   tb[IPSET_ATTR_PACKETS]));
494 	}
495 	if (tb[IPSET_ATTR_COMMENT]) {
496 		if (!SET_WITH_COMMENT(set))
497 			return -IPSET_ERR_COMMENT;
498 		ext->comment = ip_set_comment_uget(tb[IPSET_ATTR_COMMENT]);
499 	}
500 	if (tb[IPSET_ATTR_SKBMARK]) {
501 		if (!SET_WITH_SKBINFO(set))
502 			return -IPSET_ERR_SKBINFO;
503 		fullmark = be64_to_cpu(nla_get_be64(tb[IPSET_ATTR_SKBMARK]));
504 		ext->skbinfo.skbmark = fullmark >> 32;
505 		ext->skbinfo.skbmarkmask = fullmark & 0xffffffff;
506 	}
507 	if (tb[IPSET_ATTR_SKBPRIO]) {
508 		if (!SET_WITH_SKBINFO(set))
509 			return -IPSET_ERR_SKBINFO;
510 		ext->skbinfo.skbprio =
511 			be32_to_cpu(nla_get_be32(tb[IPSET_ATTR_SKBPRIO]));
512 	}
513 	if (tb[IPSET_ATTR_SKBQUEUE]) {
514 		if (!SET_WITH_SKBINFO(set))
515 			return -IPSET_ERR_SKBINFO;
516 		ext->skbinfo.skbqueue =
517 			be16_to_cpu(nla_get_be16(tb[IPSET_ATTR_SKBQUEUE]));
518 	}
519 	return 0;
520 }
521 EXPORT_SYMBOL_GPL(ip_set_get_extensions);
522 
523 static u64
ip_set_get_bytes(const struct ip_set_counter * counter)524 ip_set_get_bytes(const struct ip_set_counter *counter)
525 {
526 	return (u64)atomic64_read(&(counter)->bytes);
527 }
528 
529 static u64
ip_set_get_packets(const struct ip_set_counter * counter)530 ip_set_get_packets(const struct ip_set_counter *counter)
531 {
532 	return (u64)atomic64_read(&(counter)->packets);
533 }
534 
535 static bool
ip_set_put_counter(struct sk_buff * skb,const struct ip_set_counter * counter)536 ip_set_put_counter(struct sk_buff *skb, const struct ip_set_counter *counter)
537 {
538 	return nla_put_net64(skb, IPSET_ATTR_BYTES,
539 			     cpu_to_be64(ip_set_get_bytes(counter)),
540 			     IPSET_ATTR_PAD) ||
541 	       nla_put_net64(skb, IPSET_ATTR_PACKETS,
542 			     cpu_to_be64(ip_set_get_packets(counter)),
543 			     IPSET_ATTR_PAD);
544 }
545 
546 static bool
ip_set_put_skbinfo(struct sk_buff * skb,const struct ip_set_skbinfo * skbinfo)547 ip_set_put_skbinfo(struct sk_buff *skb, const struct ip_set_skbinfo *skbinfo)
548 {
549 	/* Send nonzero parameters only */
550 	return ((skbinfo->skbmark || skbinfo->skbmarkmask) &&
551 		nla_put_net64(skb, IPSET_ATTR_SKBMARK,
552 			      cpu_to_be64((u64)skbinfo->skbmark << 32 |
553 					  skbinfo->skbmarkmask),
554 			      IPSET_ATTR_PAD)) ||
555 	       (skbinfo->skbprio &&
556 		nla_put_net32(skb, IPSET_ATTR_SKBPRIO,
557 			      cpu_to_be32(skbinfo->skbprio))) ||
558 	       (skbinfo->skbqueue &&
559 		nla_put_net16(skb, IPSET_ATTR_SKBQUEUE,
560 			      cpu_to_be16(skbinfo->skbqueue)));
561 }
562 
563 int
ip_set_put_extensions(struct sk_buff * skb,const struct ip_set * set,const void * e,bool active)564 ip_set_put_extensions(struct sk_buff *skb, const struct ip_set *set,
565 		      const void *e, bool active)
566 {
567 	if (SET_WITH_TIMEOUT(set)) {
568 		unsigned long *timeout = ext_timeout(e, set);
569 
570 		if (nla_put_net32(skb, IPSET_ATTR_TIMEOUT,
571 			htonl(active ? ip_set_timeout_get(timeout)
572 				: *timeout)))
573 			return -EMSGSIZE;
574 	}
575 	if (SET_WITH_COUNTER(set) &&
576 	    ip_set_put_counter(skb, ext_counter(e, set)))
577 		return -EMSGSIZE;
578 	if (SET_WITH_COMMENT(set) &&
579 	    ip_set_put_comment(skb, ext_comment(e, set)))
580 		return -EMSGSIZE;
581 	if (SET_WITH_SKBINFO(set) &&
582 	    ip_set_put_skbinfo(skb, ext_skbinfo(e, set)))
583 		return -EMSGSIZE;
584 	return 0;
585 }
586 EXPORT_SYMBOL_GPL(ip_set_put_extensions);
587 
588 static bool
ip_set_match_counter(u64 counter,u64 match,u8 op)589 ip_set_match_counter(u64 counter, u64 match, u8 op)
590 {
591 	switch (op) {
592 	case IPSET_COUNTER_NONE:
593 		return true;
594 	case IPSET_COUNTER_EQ:
595 		return counter == match;
596 	case IPSET_COUNTER_NE:
597 		return counter != match;
598 	case IPSET_COUNTER_LT:
599 		return counter < match;
600 	case IPSET_COUNTER_GT:
601 		return counter > match;
602 	}
603 	return false;
604 }
605 
606 static void
ip_set_add_bytes(u64 bytes,struct ip_set_counter * counter)607 ip_set_add_bytes(u64 bytes, struct ip_set_counter *counter)
608 {
609 	atomic64_add((long long)bytes, &(counter)->bytes);
610 }
611 
612 static void
ip_set_add_packets(u64 packets,struct ip_set_counter * counter)613 ip_set_add_packets(u64 packets, struct ip_set_counter *counter)
614 {
615 	atomic64_add((long long)packets, &(counter)->packets);
616 }
617 
618 static void
ip_set_update_counter(struct ip_set_counter * counter,const struct ip_set_ext * ext,u32 flags)619 ip_set_update_counter(struct ip_set_counter *counter,
620 		      const struct ip_set_ext *ext, u32 flags)
621 {
622 	if (ext->packets != ULLONG_MAX &&
623 	    !(flags & IPSET_FLAG_SKIP_COUNTER_UPDATE)) {
624 		ip_set_add_bytes(ext->bytes, counter);
625 		ip_set_add_packets(ext->packets, counter);
626 	}
627 }
628 
629 static void
ip_set_get_skbinfo(struct ip_set_skbinfo * skbinfo,const struct ip_set_ext * ext,struct ip_set_ext * mext,u32 flags)630 ip_set_get_skbinfo(struct ip_set_skbinfo *skbinfo,
631 		   const struct ip_set_ext *ext,
632 		   struct ip_set_ext *mext, u32 flags)
633 {
634 	mext->skbinfo = *skbinfo;
635 }
636 
637 bool
ip_set_match_extensions(struct ip_set * set,const struct ip_set_ext * ext,struct ip_set_ext * mext,u32 flags,void * data)638 ip_set_match_extensions(struct ip_set *set, const struct ip_set_ext *ext,
639 			struct ip_set_ext *mext, u32 flags, void *data)
640 {
641 	if (SET_WITH_TIMEOUT(set) &&
642 	    ip_set_timeout_expired(ext_timeout(data, set)))
643 		return false;
644 	if (SET_WITH_COUNTER(set)) {
645 		struct ip_set_counter *counter = ext_counter(data, set);
646 
647 		ip_set_update_counter(counter, ext, flags);
648 
649 		if (flags & IPSET_FLAG_MATCH_COUNTERS &&
650 		    !(ip_set_match_counter(ip_set_get_packets(counter),
651 				mext->packets, mext->packets_op) &&
652 		      ip_set_match_counter(ip_set_get_bytes(counter),
653 				mext->bytes, mext->bytes_op)))
654 			return false;
655 	}
656 	if (SET_WITH_SKBINFO(set))
657 		ip_set_get_skbinfo(ext_skbinfo(data, set),
658 				   ext, mext, flags);
659 	return true;
660 }
661 EXPORT_SYMBOL_GPL(ip_set_match_extensions);
662 
663 /* Creating/destroying/renaming/swapping affect the existence and
664  * the properties of a set. All of these can be executed from userspace
665  * only and serialized by the nfnl mutex indirectly from nfnetlink.
666  *
667  * Sets are identified by their index in ip_set_list and the index
668  * is used by the external references (set/SET netfilter modules).
669  *
670  * The set behind an index may change by swapping only, from userspace.
671  */
672 
673 static void
__ip_set_get(struct ip_set * set)674 __ip_set_get(struct ip_set *set)
675 {
676 	write_lock_bh(&ip_set_ref_lock);
677 	set->ref++;
678 	write_unlock_bh(&ip_set_ref_lock);
679 }
680 
681 static void
__ip_set_put(struct ip_set * set)682 __ip_set_put(struct ip_set *set)
683 {
684 	write_lock_bh(&ip_set_ref_lock);
685 	BUG_ON(set->ref == 0);
686 	set->ref--;
687 	write_unlock_bh(&ip_set_ref_lock);
688 }
689 
690 /* set->ref can be swapped out by ip_set_swap, netlink events (like dump) need
691  * a separate reference counter
692  */
693 static void
__ip_set_get_netlink(struct ip_set * set)694 __ip_set_get_netlink(struct ip_set *set)
695 {
696 	write_lock_bh(&ip_set_ref_lock);
697 	set->ref_netlink++;
698 	write_unlock_bh(&ip_set_ref_lock);
699 }
700 
701 static void
__ip_set_put_netlink(struct ip_set * set)702 __ip_set_put_netlink(struct ip_set *set)
703 {
704 	write_lock_bh(&ip_set_ref_lock);
705 	BUG_ON(set->ref_netlink == 0);
706 	set->ref_netlink--;
707 	write_unlock_bh(&ip_set_ref_lock);
708 }
709 
710 /* Add, del and test set entries from kernel.
711  *
712  * The set behind the index must exist and must be referenced
713  * so it can't be destroyed (or changed) under our foot.
714  */
715 
716 static struct ip_set *
ip_set_rcu_get(struct net * net,ip_set_id_t index)717 ip_set_rcu_get(struct net *net, ip_set_id_t index)
718 {
719 	struct ip_set_net *inst = ip_set_pernet(net);
720 
721 	/* ip_set_list and the set pointer need to be protected */
722 	return ip_set_dereference_nfnl(inst->ip_set_list)[index];
723 }
724 
725 static inline void
ip_set_lock(struct ip_set * set)726 ip_set_lock(struct ip_set *set)
727 {
728 	if (!set->variant->region_lock)
729 		spin_lock_bh(&set->lock);
730 }
731 
732 static inline void
ip_set_unlock(struct ip_set * set)733 ip_set_unlock(struct ip_set *set)
734 {
735 	if (!set->variant->region_lock)
736 		spin_unlock_bh(&set->lock);
737 }
738 
739 int
ip_set_test(ip_set_id_t index,const struct sk_buff * skb,const struct xt_action_param * par,struct ip_set_adt_opt * opt)740 ip_set_test(ip_set_id_t index, const struct sk_buff *skb,
741 	    const struct xt_action_param *par, struct ip_set_adt_opt *opt)
742 {
743 	struct ip_set *set = ip_set_rcu_get(xt_net(par), index);
744 	int ret = 0;
745 
746 	BUG_ON(!set);
747 	pr_debug("set %s, index %u\n", set->name, index);
748 
749 	if (opt->dim < set->type->dimension ||
750 	    !(opt->family == set->family || set->family == NFPROTO_UNSPEC))
751 		return 0;
752 
753 	ret = set->variant->kadt(set, skb, par, IPSET_TEST, opt);
754 
755 	if (ret == -EAGAIN) {
756 		/* Type requests element to be completed */
757 		pr_debug("element must be completed, ADD is triggered\n");
758 		ip_set_lock(set);
759 		set->variant->kadt(set, skb, par, IPSET_ADD, opt);
760 		ip_set_unlock(set);
761 		ret = 1;
762 	} else {
763 		/* --return-nomatch: invert matched element */
764 		if ((opt->cmdflags & IPSET_FLAG_RETURN_NOMATCH) &&
765 		    (set->type->features & IPSET_TYPE_NOMATCH) &&
766 		    (ret > 0 || ret == -ENOTEMPTY))
767 			ret = -ret;
768 	}
769 
770 	/* Convert error codes to nomatch */
771 	return (ret < 0 ? 0 : ret);
772 }
773 EXPORT_SYMBOL_GPL(ip_set_test);
774 
775 int
ip_set_add(ip_set_id_t index,const struct sk_buff * skb,const struct xt_action_param * par,struct ip_set_adt_opt * opt)776 ip_set_add(ip_set_id_t index, const struct sk_buff *skb,
777 	   const struct xt_action_param *par, struct ip_set_adt_opt *opt)
778 {
779 	struct ip_set *set = ip_set_rcu_get(xt_net(par), index);
780 	int ret;
781 
782 	BUG_ON(!set);
783 	pr_debug("set %s, index %u\n", set->name, index);
784 
785 	if (opt->dim < set->type->dimension ||
786 	    !(opt->family == set->family || set->family == NFPROTO_UNSPEC))
787 		return -IPSET_ERR_TYPE_MISMATCH;
788 
789 	ip_set_lock(set);
790 	ret = set->variant->kadt(set, skb, par, IPSET_ADD, opt);
791 	ip_set_unlock(set);
792 
793 	return ret;
794 }
795 EXPORT_SYMBOL_GPL(ip_set_add);
796 
797 int
ip_set_del(ip_set_id_t index,const struct sk_buff * skb,const struct xt_action_param * par,struct ip_set_adt_opt * opt)798 ip_set_del(ip_set_id_t index, const struct sk_buff *skb,
799 	   const struct xt_action_param *par, struct ip_set_adt_opt *opt)
800 {
801 	struct ip_set *set = ip_set_rcu_get(xt_net(par), index);
802 	int ret = 0;
803 
804 	BUG_ON(!set);
805 	pr_debug("set %s, index %u\n", set->name, index);
806 
807 	if (opt->dim < set->type->dimension ||
808 	    !(opt->family == set->family || set->family == NFPROTO_UNSPEC))
809 		return -IPSET_ERR_TYPE_MISMATCH;
810 
811 	ip_set_lock(set);
812 	ret = set->variant->kadt(set, skb, par, IPSET_DEL, opt);
813 	ip_set_unlock(set);
814 
815 	return ret;
816 }
817 EXPORT_SYMBOL_GPL(ip_set_del);
818 
819 /* Find set by name, reference it once. The reference makes sure the
820  * thing pointed to, does not go away under our feet.
821  *
822  */
823 ip_set_id_t
ip_set_get_byname(struct net * net,const char * name,struct ip_set ** set)824 ip_set_get_byname(struct net *net, const char *name, struct ip_set **set)
825 {
826 	ip_set_id_t i, index = IPSET_INVALID_ID;
827 	struct ip_set *s;
828 	struct ip_set_net *inst = ip_set_pernet(net);
829 
830 	rcu_read_lock();
831 	for (i = 0; i < inst->ip_set_max; i++) {
832 		s = rcu_dereference(inst->ip_set_list)[i];
833 		if (s && STRNCMP(s->name, name)) {
834 			__ip_set_get(s);
835 			index = i;
836 			*set = s;
837 			break;
838 		}
839 	}
840 	rcu_read_unlock();
841 
842 	return index;
843 }
844 EXPORT_SYMBOL_GPL(ip_set_get_byname);
845 
846 /* If the given set pointer points to a valid set, decrement
847  * reference count by 1. The caller shall not assume the index
848  * to be valid, after calling this function.
849  *
850  */
851 
852 static void
__ip_set_put_byindex(struct ip_set_net * inst,ip_set_id_t index)853 __ip_set_put_byindex(struct ip_set_net *inst, ip_set_id_t index)
854 {
855 	struct ip_set *set;
856 
857 	rcu_read_lock();
858 	set = rcu_dereference(inst->ip_set_list)[index];
859 	if (set)
860 		__ip_set_put(set);
861 	rcu_read_unlock();
862 }
863 
864 void
ip_set_put_byindex(struct net * net,ip_set_id_t index)865 ip_set_put_byindex(struct net *net, ip_set_id_t index)
866 {
867 	struct ip_set_net *inst = ip_set_pernet(net);
868 
869 	__ip_set_put_byindex(inst, index);
870 }
871 EXPORT_SYMBOL_GPL(ip_set_put_byindex);
872 
873 /* Get the name of a set behind a set index.
874  * Set itself is protected by RCU, but its name isn't: to protect against
875  * renaming, grab ip_set_ref_lock as reader (see ip_set_rename()) and copy the
876  * name.
877  */
878 void
ip_set_name_byindex(struct net * net,ip_set_id_t index,char * name)879 ip_set_name_byindex(struct net *net, ip_set_id_t index, char *name)
880 {
881 	struct ip_set *set = ip_set_rcu_get(net, index);
882 
883 	BUG_ON(!set);
884 
885 	read_lock_bh(&ip_set_ref_lock);
886 	strscpy_pad(name, set->name, IPSET_MAXNAMELEN);
887 	read_unlock_bh(&ip_set_ref_lock);
888 }
889 EXPORT_SYMBOL_GPL(ip_set_name_byindex);
890 
891 /* Routines to call by external subsystems, which do not
892  * call nfnl_lock for us.
893  */
894 
895 /* Find set by index, reference it once. The reference makes sure the
896  * thing pointed to, does not go away under our feet.
897  *
898  * The nfnl mutex is used in the function.
899  */
900 ip_set_id_t
ip_set_nfnl_get_byindex(struct net * net,ip_set_id_t index)901 ip_set_nfnl_get_byindex(struct net *net, ip_set_id_t index)
902 {
903 	struct ip_set *set;
904 	struct ip_set_net *inst = ip_set_pernet(net);
905 
906 	if (index >= inst->ip_set_max)
907 		return IPSET_INVALID_ID;
908 
909 	nfnl_lock(NFNL_SUBSYS_IPSET);
910 	set = ip_set(inst, index);
911 	if (set)
912 		__ip_set_get(set);
913 	else
914 		index = IPSET_INVALID_ID;
915 	nfnl_unlock(NFNL_SUBSYS_IPSET);
916 
917 	return index;
918 }
919 EXPORT_SYMBOL_GPL(ip_set_nfnl_get_byindex);
920 
921 /* If the given set pointer points to a valid set, decrement
922  * reference count by 1. The caller shall not assume the index
923  * to be valid, after calling this function.
924  *
925  * The nfnl mutex is used in the function.
926  */
927 void
ip_set_nfnl_put(struct net * net,ip_set_id_t index)928 ip_set_nfnl_put(struct net *net, ip_set_id_t index)
929 {
930 	struct ip_set *set;
931 	struct ip_set_net *inst = ip_set_pernet(net);
932 
933 	nfnl_lock(NFNL_SUBSYS_IPSET);
934 	if (!inst->is_deleted) { /* already deleted from ip_set_net_exit() */
935 		set = ip_set(inst, index);
936 		if (set)
937 			__ip_set_put(set);
938 	}
939 	nfnl_unlock(NFNL_SUBSYS_IPSET);
940 }
941 EXPORT_SYMBOL_GPL(ip_set_nfnl_put);
942 
943 /* Communication protocol with userspace over netlink.
944  *
945  * The commands are serialized by the nfnl mutex.
946  */
947 
protocol(const struct nlattr * const tb[])948 static inline u8 protocol(const struct nlattr * const tb[])
949 {
950 	return nla_get_u8(tb[IPSET_ATTR_PROTOCOL]);
951 }
952 
953 static inline bool
protocol_failed(const struct nlattr * const tb[])954 protocol_failed(const struct nlattr * const tb[])
955 {
956 	return !tb[IPSET_ATTR_PROTOCOL] || protocol(tb) != IPSET_PROTOCOL;
957 }
958 
959 static inline bool
protocol_min_failed(const struct nlattr * const tb[])960 protocol_min_failed(const struct nlattr * const tb[])
961 {
962 	return !tb[IPSET_ATTR_PROTOCOL] || protocol(tb) < IPSET_PROTOCOL_MIN;
963 }
964 
965 static inline u32
flag_exist(const struct nlmsghdr * nlh)966 flag_exist(const struct nlmsghdr *nlh)
967 {
968 	return nlh->nlmsg_flags & NLM_F_EXCL ? 0 : IPSET_FLAG_EXIST;
969 }
970 
971 static struct nlmsghdr *
start_msg(struct sk_buff * skb,u32 portid,u32 seq,unsigned int flags,enum ipset_cmd cmd)972 start_msg(struct sk_buff *skb, u32 portid, u32 seq, unsigned int flags,
973 	  enum ipset_cmd cmd)
974 {
975 	return nfnl_msg_put(skb, portid, seq,
976 			    nfnl_msg_type(NFNL_SUBSYS_IPSET, cmd), flags,
977 			    NFPROTO_IPV4, NFNETLINK_V0, 0);
978 }
979 
980 /* Create a set */
981 
982 static const struct nla_policy ip_set_create_policy[IPSET_ATTR_CMD_MAX + 1] = {
983 	[IPSET_ATTR_PROTOCOL]	= { .type = NLA_U8 },
984 	[IPSET_ATTR_SETNAME]	= { .type = NLA_NUL_STRING,
985 				    .len = IPSET_MAXNAMELEN - 1 },
986 	[IPSET_ATTR_TYPENAME]	= { .type = NLA_NUL_STRING,
987 				    .len = IPSET_MAXNAMELEN - 1},
988 	[IPSET_ATTR_REVISION]	= { .type = NLA_U8 },
989 	[IPSET_ATTR_FAMILY]	= { .type = NLA_U8 },
990 	[IPSET_ATTR_DATA]	= { .type = NLA_NESTED },
991 };
992 
993 static struct ip_set *
find_set_and_id(struct ip_set_net * inst,const char * name,ip_set_id_t * id)994 find_set_and_id(struct ip_set_net *inst, const char *name, ip_set_id_t *id)
995 {
996 	struct ip_set *set = NULL;
997 	ip_set_id_t i;
998 
999 	*id = IPSET_INVALID_ID;
1000 	for (i = 0; i < inst->ip_set_max; i++) {
1001 		set = ip_set(inst, i);
1002 		if (set && STRNCMP(set->name, name)) {
1003 			*id = i;
1004 			break;
1005 		}
1006 	}
1007 	return (*id == IPSET_INVALID_ID ? NULL : set);
1008 }
1009 
1010 static inline struct ip_set *
find_set(struct ip_set_net * inst,const char * name)1011 find_set(struct ip_set_net *inst, const char *name)
1012 {
1013 	ip_set_id_t id;
1014 
1015 	return find_set_and_id(inst, name, &id);
1016 }
1017 
1018 static int
find_free_id(struct ip_set_net * inst,const char * name,ip_set_id_t * index,struct ip_set ** set)1019 find_free_id(struct ip_set_net *inst, const char *name, ip_set_id_t *index,
1020 	     struct ip_set **set)
1021 {
1022 	struct ip_set *s;
1023 	ip_set_id_t i;
1024 
1025 	*index = IPSET_INVALID_ID;
1026 	for (i = 0;  i < inst->ip_set_max; i++) {
1027 		s = ip_set(inst, i);
1028 		if (!s) {
1029 			if (*index == IPSET_INVALID_ID)
1030 				*index = i;
1031 		} else if (STRNCMP(name, s->name)) {
1032 			/* Name clash */
1033 			*set = s;
1034 			return -EEXIST;
1035 		}
1036 	}
1037 	if (*index == IPSET_INVALID_ID)
1038 		/* No free slot remained */
1039 		return -IPSET_ERR_MAX_SETS;
1040 	return 0;
1041 }
1042 
ip_set_none(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])1043 static int ip_set_none(struct sk_buff *skb, const struct nfnl_info *info,
1044 		       const struct nlattr * const attr[])
1045 {
1046 	return -EOPNOTSUPP;
1047 }
1048 
ip_set_create(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])1049 static int ip_set_create(struct sk_buff *skb, const struct nfnl_info *info,
1050 			 const struct nlattr * const attr[])
1051 {
1052 	struct ip_set_net *inst = ip_set_pernet(info->net);
1053 	struct ip_set *set, *clash = NULL;
1054 	ip_set_id_t index = IPSET_INVALID_ID;
1055 	struct nlattr *tb[IPSET_ATTR_CREATE_MAX + 1] = {};
1056 	const char *name, *typename;
1057 	u8 family, revision;
1058 	u32 flags = flag_exist(info->nlh);
1059 	int ret = 0;
1060 
1061 	if (unlikely(protocol_min_failed(attr) ||
1062 		     !attr[IPSET_ATTR_SETNAME] ||
1063 		     !attr[IPSET_ATTR_TYPENAME] ||
1064 		     !attr[IPSET_ATTR_REVISION] ||
1065 		     !attr[IPSET_ATTR_FAMILY] ||
1066 		     (attr[IPSET_ATTR_DATA] &&
1067 		      !flag_nested(attr[IPSET_ATTR_DATA]))))
1068 		return -IPSET_ERR_PROTOCOL;
1069 
1070 	name = nla_data(attr[IPSET_ATTR_SETNAME]);
1071 	typename = nla_data(attr[IPSET_ATTR_TYPENAME]);
1072 	family = nla_get_u8(attr[IPSET_ATTR_FAMILY]);
1073 	revision = nla_get_u8(attr[IPSET_ATTR_REVISION]);
1074 	pr_debug("setname: %s, typename: %s, family: %s, revision: %u\n",
1075 		 name, typename, family_name(family), revision);
1076 
1077 	/* First, and without any locks, allocate and initialize
1078 	 * a normal base set structure.
1079 	 */
1080 	set = kzalloc(sizeof(*set), GFP_KERNEL);
1081 	if (!set)
1082 		return -ENOMEM;
1083 	spin_lock_init(&set->lock);
1084 	strscpy(set->name, name, IPSET_MAXNAMELEN);
1085 	set->family = family;
1086 	set->revision = revision;
1087 
1088 	/* Next, check that we know the type, and take
1089 	 * a reference on the type, to make sure it stays available
1090 	 * while constructing our new set.
1091 	 *
1092 	 * After referencing the type, we try to create the type
1093 	 * specific part of the set without holding any locks.
1094 	 */
1095 	ret = find_set_type_get(typename, family, revision, &set->type);
1096 	if (ret)
1097 		goto out;
1098 
1099 	/* Without holding any locks, create private part. */
1100 	if (attr[IPSET_ATTR_DATA] &&
1101 	    nla_parse_nested(tb, IPSET_ATTR_CREATE_MAX, attr[IPSET_ATTR_DATA],
1102 			     set->type->create_policy, NULL)) {
1103 		ret = -IPSET_ERR_PROTOCOL;
1104 		goto put_out;
1105 	}
1106 	/* Set create flags depending on the type revision */
1107 	set->flags |= set->type->create_flags[revision];
1108 
1109 	ret = set->type->create(info->net, set, tb, flags);
1110 	if (ret != 0)
1111 		goto put_out;
1112 
1113 	/* BTW, ret==0 here. */
1114 
1115 	/* Here, we have a valid, constructed set and we are protected
1116 	 * by the nfnl mutex. Find the first free index in ip_set_list
1117 	 * and check clashing.
1118 	 */
1119 	ret = find_free_id(inst, set->name, &index, &clash);
1120 	if (ret == -EEXIST) {
1121 		/* If this is the same set and requested, ignore error */
1122 		if ((flags & IPSET_FLAG_EXIST) &&
1123 		    STRNCMP(set->type->name, clash->type->name) &&
1124 		    set->type->family == clash->type->family &&
1125 		    set->type->revision_min == clash->type->revision_min &&
1126 		    set->type->revision_max == clash->type->revision_max &&
1127 		    set->variant->same_set(set, clash))
1128 			ret = 0;
1129 		goto cleanup;
1130 	} else if (ret == -IPSET_ERR_MAX_SETS) {
1131 		struct ip_set **list, **tmp;
1132 		ip_set_id_t i = inst->ip_set_max + IP_SET_INC;
1133 
1134 		if (i < inst->ip_set_max || i == IPSET_INVALID_ID)
1135 			/* Wraparound */
1136 			goto cleanup;
1137 
1138 		list = kvcalloc(i, sizeof(struct ip_set *), GFP_KERNEL);
1139 		if (!list)
1140 			goto cleanup;
1141 		/* nfnl mutex is held, both lists are valid */
1142 		tmp = ip_set_dereference(inst);
1143 		memcpy(list, tmp, sizeof(struct ip_set *) * inst->ip_set_max);
1144 		rcu_assign_pointer(inst->ip_set_list, list);
1145 		/* Make sure all current packets have passed through */
1146 		synchronize_net();
1147 		/* Use new list */
1148 		index = inst->ip_set_max;
1149 		inst->ip_set_max = i;
1150 		kvfree(tmp);
1151 		ret = 0;
1152 	} else if (ret) {
1153 		goto cleanup;
1154 	}
1155 
1156 	/* Finally! Add our shiny new set to the list, and be done. */
1157 	pr_debug("create: '%s' created with index %u!\n", set->name, index);
1158 	ip_set(inst, index) = set;
1159 
1160 	return ret;
1161 
1162 cleanup:
1163 	set->variant->cancel_gc(set);
1164 	set->variant->destroy(set);
1165 put_out:
1166 	module_put(set->type->me);
1167 out:
1168 	kfree(set);
1169 	return ret;
1170 }
1171 
1172 /* Destroy sets */
1173 
1174 static const struct nla_policy
1175 ip_set_setname_policy[IPSET_ATTR_CMD_MAX + 1] = {
1176 	[IPSET_ATTR_PROTOCOL]	= { .type = NLA_U8 },
1177 	[IPSET_ATTR_SETNAME]	= { .type = NLA_NUL_STRING,
1178 				    .len = IPSET_MAXNAMELEN - 1 },
1179 };
1180 
1181 /* In order to return quickly when destroying a single set, it is split
1182  * into two stages:
1183  * - Cancel garbage collector
1184  * - Destroy the set itself via call_rcu()
1185  */
1186 
1187 static void
ip_set_destroy_set_rcu(struct rcu_head * head)1188 ip_set_destroy_set_rcu(struct rcu_head *head)
1189 {
1190 	struct ip_set *set = container_of(head, struct ip_set, rcu);
1191 
1192 	set->variant->destroy(set);
1193 	module_put(set->type->me);
1194 	kfree(set);
1195 }
1196 
1197 static void
_destroy_all_sets(struct ip_set_net * inst)1198 _destroy_all_sets(struct ip_set_net *inst)
1199 {
1200 	struct ip_set *set;
1201 	ip_set_id_t i;
1202 	bool need_wait = false;
1203 
1204 	/* First cancel gc's: set:list sets are flushed as well */
1205 	for (i = 0; i < inst->ip_set_max; i++) {
1206 		set = ip_set(inst, i);
1207 		if (set) {
1208 			set->variant->cancel_gc(set);
1209 			if (set->type->features & IPSET_TYPE_NAME)
1210 				need_wait = true;
1211 		}
1212 	}
1213 	/* Must wait for flush to be really finished  */
1214 	if (need_wait)
1215 		rcu_barrier();
1216 	for (i = 0; i < inst->ip_set_max; i++) {
1217 		set = ip_set(inst, i);
1218 		if (set) {
1219 			ip_set(inst, i) = NULL;
1220 			set->variant->destroy(set);
1221 			module_put(set->type->me);
1222 			kfree(set);
1223 		}
1224 	}
1225 }
1226 
ip_set_destroy(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])1227 static int ip_set_destroy(struct sk_buff *skb, const struct nfnl_info *info,
1228 			  const struct nlattr * const attr[])
1229 {
1230 	struct ip_set_net *inst = ip_set_pernet(info->net);
1231 	struct ip_set *s;
1232 	ip_set_id_t i;
1233 	int ret = 0;
1234 
1235 	if (unlikely(protocol_min_failed(attr)))
1236 		return -IPSET_ERR_PROTOCOL;
1237 
1238 	/* Commands are serialized and references are
1239 	 * protected by the ip_set_ref_lock.
1240 	 * External systems (i.e. xt_set) must call
1241 	 * ip_set_nfnl_get_* functions, that way we
1242 	 * can safely check references here.
1243 	 *
1244 	 * list:set timer can only decrement the reference
1245 	 * counter, so if it's already zero, we can proceed
1246 	 * without holding the lock.
1247 	 */
1248 	if (!attr[IPSET_ATTR_SETNAME]) {
1249 		read_lock_bh(&ip_set_ref_lock);
1250 		for (i = 0; i < inst->ip_set_max; i++) {
1251 			s = ip_set(inst, i);
1252 			if (s && (s->ref || s->ref_netlink)) {
1253 				ret = -IPSET_ERR_BUSY;
1254 				goto out;
1255 			}
1256 		}
1257 		inst->is_destroyed = true;
1258 		read_unlock_bh(&ip_set_ref_lock);
1259 		_destroy_all_sets(inst);
1260 		/* Modified by ip_set_destroy() only, which is serialized */
1261 		inst->is_destroyed = false;
1262 	} else {
1263 		u32 flags = flag_exist(info->nlh);
1264 		u16 features = 0;
1265 
1266 		read_lock_bh(&ip_set_ref_lock);
1267 		s = find_set_and_id(inst, nla_data(attr[IPSET_ATTR_SETNAME]),
1268 				    &i);
1269 		if (!s) {
1270 			if (!(flags & IPSET_FLAG_EXIST))
1271 				ret = -ENOENT;
1272 			goto out;
1273 		} else if (s->ref || s->ref_netlink) {
1274 			ret = -IPSET_ERR_BUSY;
1275 			goto out;
1276 		}
1277 		features = s->type->features;
1278 		ip_set(inst, i) = NULL;
1279 		read_unlock_bh(&ip_set_ref_lock);
1280 		/* Must cancel garbage collectors */
1281 		s->variant->cancel_gc(s);
1282 		if (features & IPSET_TYPE_NAME) {
1283 			/* Must wait for flush to be really finished  */
1284 			rcu_barrier();
1285 		}
1286 		call_rcu(&s->rcu, ip_set_destroy_set_rcu);
1287 	}
1288 	return 0;
1289 out:
1290 	read_unlock_bh(&ip_set_ref_lock);
1291 	return ret;
1292 }
1293 
1294 /* Flush sets */
1295 
1296 static void
ip_set_flush_set(struct ip_set * set)1297 ip_set_flush_set(struct ip_set *set)
1298 {
1299 	pr_debug("set: %s\n",  set->name);
1300 
1301 	ip_set_lock(set);
1302 	set->variant->flush(set);
1303 	ip_set_unlock(set);
1304 }
1305 
ip_set_flush(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])1306 static int ip_set_flush(struct sk_buff *skb, const struct nfnl_info *info,
1307 			const struct nlattr * const attr[])
1308 {
1309 	struct ip_set_net *inst = ip_set_pernet(info->net);
1310 	struct ip_set *s;
1311 	ip_set_id_t i;
1312 
1313 	if (unlikely(protocol_min_failed(attr)))
1314 		return -IPSET_ERR_PROTOCOL;
1315 
1316 	if (!attr[IPSET_ATTR_SETNAME]) {
1317 		for (i = 0; i < inst->ip_set_max; i++) {
1318 			s = ip_set(inst, i);
1319 			if (s)
1320 				ip_set_flush_set(s);
1321 		}
1322 	} else {
1323 		s = find_set(inst, nla_data(attr[IPSET_ATTR_SETNAME]));
1324 		if (!s)
1325 			return -ENOENT;
1326 
1327 		ip_set_flush_set(s);
1328 	}
1329 
1330 	return 0;
1331 }
1332 
1333 /* Rename a set */
1334 
1335 static const struct nla_policy
1336 ip_set_setname2_policy[IPSET_ATTR_CMD_MAX + 1] = {
1337 	[IPSET_ATTR_PROTOCOL]	= { .type = NLA_U8 },
1338 	[IPSET_ATTR_SETNAME]	= { .type = NLA_NUL_STRING,
1339 				    .len = IPSET_MAXNAMELEN - 1 },
1340 	[IPSET_ATTR_SETNAME2]	= { .type = NLA_NUL_STRING,
1341 				    .len = IPSET_MAXNAMELEN - 1 },
1342 };
1343 
ip_set_rename(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])1344 static int ip_set_rename(struct sk_buff *skb, const struct nfnl_info *info,
1345 			 const struct nlattr * const attr[])
1346 {
1347 	struct ip_set_net *inst = ip_set_pernet(info->net);
1348 	struct ip_set *set, *s;
1349 	const char *name2;
1350 	ip_set_id_t i;
1351 	int ret = 0;
1352 
1353 	if (unlikely(protocol_min_failed(attr) ||
1354 		     !attr[IPSET_ATTR_SETNAME] ||
1355 		     !attr[IPSET_ATTR_SETNAME2]))
1356 		return -IPSET_ERR_PROTOCOL;
1357 
1358 	set = find_set(inst, nla_data(attr[IPSET_ATTR_SETNAME]));
1359 	if (!set)
1360 		return -ENOENT;
1361 
1362 	write_lock_bh(&ip_set_ref_lock);
1363 	if (set->ref != 0 || set->ref_netlink != 0) {
1364 		ret = -IPSET_ERR_REFERENCED;
1365 		goto out;
1366 	}
1367 
1368 	name2 = nla_data(attr[IPSET_ATTR_SETNAME2]);
1369 	for (i = 0; i < inst->ip_set_max; i++) {
1370 		s = ip_set(inst, i);
1371 		if (s && STRNCMP(s->name, name2)) {
1372 			ret = -IPSET_ERR_EXIST_SETNAME2;
1373 			goto out;
1374 		}
1375 	}
1376 	strscpy_pad(set->name, name2, IPSET_MAXNAMELEN);
1377 
1378 out:
1379 	write_unlock_bh(&ip_set_ref_lock);
1380 	return ret;
1381 }
1382 
1383 /* Swap two sets so that name/index points to the other.
1384  * References and set names are also swapped.
1385  *
1386  * The commands are serialized by the nfnl mutex and references are
1387  * protected by the ip_set_ref_lock. The kernel interfaces
1388  * do not hold the mutex but the pointer settings are atomic
1389  * so the ip_set_list always contains valid pointers to the sets.
1390  */
1391 
ip_set_swap(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])1392 static int ip_set_swap(struct sk_buff *skb, const struct nfnl_info *info,
1393 		       const struct nlattr * const attr[])
1394 {
1395 	struct ip_set_net *inst = ip_set_pernet(info->net);
1396 	struct ip_set *from, *to;
1397 	ip_set_id_t from_id, to_id;
1398 	char from_name[IPSET_MAXNAMELEN];
1399 
1400 	if (unlikely(protocol_min_failed(attr) ||
1401 		     !attr[IPSET_ATTR_SETNAME] ||
1402 		     !attr[IPSET_ATTR_SETNAME2]))
1403 		return -IPSET_ERR_PROTOCOL;
1404 
1405 	from = find_set_and_id(inst, nla_data(attr[IPSET_ATTR_SETNAME]),
1406 			       &from_id);
1407 	if (!from)
1408 		return -ENOENT;
1409 
1410 	to = find_set_and_id(inst, nla_data(attr[IPSET_ATTR_SETNAME2]),
1411 			     &to_id);
1412 	if (!to)
1413 		return -IPSET_ERR_EXIST_SETNAME2;
1414 
1415 	/* Features must not change.
1416 	 * Not an artifical restriction anymore, as we must prevent
1417 	 * possible loops created by swapping in setlist type of sets.
1418 	 */
1419 	if (!(from->type->features == to->type->features &&
1420 	      from->family == to->family))
1421 		return -IPSET_ERR_TYPE_MISMATCH;
1422 
1423 	write_lock_bh(&ip_set_ref_lock);
1424 
1425 	if (from->ref_netlink || to->ref_netlink) {
1426 		write_unlock_bh(&ip_set_ref_lock);
1427 		return -EBUSY;
1428 	}
1429 
1430 	strscpy_pad(from_name, from->name, IPSET_MAXNAMELEN);
1431 	strscpy_pad(from->name, to->name, IPSET_MAXNAMELEN);
1432 	strscpy_pad(to->name, from_name, IPSET_MAXNAMELEN);
1433 
1434 	swap(from->ref, to->ref);
1435 	ip_set(inst, from_id) = to;
1436 	ip_set(inst, to_id) = from;
1437 	write_unlock_bh(&ip_set_ref_lock);
1438 
1439 	return 0;
1440 }
1441 
1442 /* List/save set data */
1443 
1444 #define DUMP_INIT	0
1445 #define DUMP_ALL	1
1446 #define DUMP_ONE	2
1447 #define DUMP_LAST	3
1448 
1449 #define DUMP_TYPE(arg)		(((u32)(arg)) & 0x0000FFFF)
1450 #define DUMP_FLAGS(arg)		(((u32)(arg)) >> 16)
1451 
1452 int
ip_set_put_flags(struct sk_buff * skb,struct ip_set * set)1453 ip_set_put_flags(struct sk_buff *skb, struct ip_set *set)
1454 {
1455 	u32 cadt_flags = 0;
1456 
1457 	if (SET_WITH_TIMEOUT(set))
1458 		if (unlikely(nla_put_net32(skb, IPSET_ATTR_TIMEOUT,
1459 					   htonl(set->timeout))))
1460 			return -EMSGSIZE;
1461 	if (SET_WITH_COUNTER(set))
1462 		cadt_flags |= IPSET_FLAG_WITH_COUNTERS;
1463 	if (SET_WITH_COMMENT(set))
1464 		cadt_flags |= IPSET_FLAG_WITH_COMMENT;
1465 	if (SET_WITH_SKBINFO(set))
1466 		cadt_flags |= IPSET_FLAG_WITH_SKBINFO;
1467 	if (SET_WITH_FORCEADD(set))
1468 		cadt_flags |= IPSET_FLAG_WITH_FORCEADD;
1469 
1470 	if (!cadt_flags)
1471 		return 0;
1472 	return nla_put_net32(skb, IPSET_ATTR_CADT_FLAGS, htonl(cadt_flags));
1473 }
1474 EXPORT_SYMBOL_GPL(ip_set_put_flags);
1475 
1476 static int
ip_set_dump_done(struct netlink_callback * cb)1477 ip_set_dump_done(struct netlink_callback *cb)
1478 {
1479 	if (cb->args[IPSET_CB_ARG0]) {
1480 		struct ip_set_net *inst =
1481 			(struct ip_set_net *)cb->args[IPSET_CB_NET];
1482 		ip_set_id_t index = (ip_set_id_t)cb->args[IPSET_CB_INDEX];
1483 		struct ip_set *set = ip_set_ref_netlink(inst, index);
1484 
1485 		if (set->variant->uref)
1486 			set->variant->uref(set, cb, false);
1487 		pr_debug("release set %s\n", set->name);
1488 		__ip_set_put_netlink(set);
1489 	}
1490 	return 0;
1491 }
1492 
1493 static inline void
dump_attrs(struct nlmsghdr * nlh)1494 dump_attrs(struct nlmsghdr *nlh)
1495 {
1496 	const struct nlattr *attr;
1497 	int rem;
1498 
1499 	pr_debug("dump nlmsg\n");
1500 	nlmsg_for_each_attr(attr, nlh, sizeof(struct nfgenmsg), rem) {
1501 		pr_debug("type: %u, len %u\n", nla_type(attr), attr->nla_len);
1502 	}
1503 }
1504 
1505 static const struct nla_policy
1506 ip_set_dump_policy[IPSET_ATTR_CMD_MAX + 1] = {
1507 	[IPSET_ATTR_PROTOCOL]	= { .type = NLA_U8 },
1508 	[IPSET_ATTR_SETNAME]	= { .type = NLA_NUL_STRING,
1509 				    .len = IPSET_MAXNAMELEN - 1 },
1510 	[IPSET_ATTR_FLAGS]	= { .type = NLA_U32 },
1511 };
1512 
1513 static int
ip_set_dump_start(struct netlink_callback * cb)1514 ip_set_dump_start(struct netlink_callback *cb)
1515 {
1516 	struct nlmsghdr *nlh = nlmsg_hdr(cb->skb);
1517 	int min_len = nlmsg_total_size(sizeof(struct nfgenmsg));
1518 	struct nlattr *cda[IPSET_ATTR_CMD_MAX + 1];
1519 	struct nlattr *attr = (void *)nlh + min_len;
1520 	struct sk_buff *skb = cb->skb;
1521 	struct ip_set_net *inst = ip_set_pernet(sock_net(skb->sk));
1522 	u32 dump_type;
1523 	int ret;
1524 
1525 	ret = nla_parse(cda, IPSET_ATTR_CMD_MAX, attr,
1526 			nlh->nlmsg_len - min_len,
1527 			ip_set_dump_policy, NULL);
1528 	if (ret)
1529 		goto error;
1530 
1531 	cb->args[IPSET_CB_PROTO] = nla_get_u8(cda[IPSET_ATTR_PROTOCOL]);
1532 	if (cda[IPSET_ATTR_SETNAME]) {
1533 		ip_set_id_t index;
1534 		struct ip_set *set;
1535 
1536 		set = find_set_and_id(inst, nla_data(cda[IPSET_ATTR_SETNAME]),
1537 				      &index);
1538 		if (!set) {
1539 			ret = -ENOENT;
1540 			goto error;
1541 		}
1542 		dump_type = DUMP_ONE;
1543 		cb->args[IPSET_CB_INDEX] = index;
1544 	} else {
1545 		dump_type = DUMP_ALL;
1546 	}
1547 
1548 	if (cda[IPSET_ATTR_FLAGS]) {
1549 		u32 f = ip_set_get_h32(cda[IPSET_ATTR_FLAGS]);
1550 
1551 		dump_type |= (f << 16);
1552 	}
1553 	cb->args[IPSET_CB_NET] = (unsigned long)inst;
1554 	cb->args[IPSET_CB_DUMP] = dump_type;
1555 
1556 	return 0;
1557 
1558 error:
1559 	/* We have to create and send the error message manually :-( */
1560 	if (nlh->nlmsg_flags & NLM_F_ACK) {
1561 		netlink_ack(cb->skb, nlh, ret, NULL);
1562 	}
1563 	return ret;
1564 }
1565 
1566 static int
ip_set_dump_do(struct sk_buff * skb,struct netlink_callback * cb)1567 ip_set_dump_do(struct sk_buff *skb, struct netlink_callback *cb)
1568 {
1569 	ip_set_id_t index = IPSET_INVALID_ID, max;
1570 	struct ip_set *set = NULL;
1571 	struct nlmsghdr *nlh = NULL;
1572 	unsigned int flags = NETLINK_CB(cb->skb).portid ? NLM_F_MULTI : 0;
1573 	struct ip_set_net *inst = ip_set_pernet(sock_net(skb->sk));
1574 	u32 dump_type, dump_flags;
1575 	bool is_destroyed;
1576 	int ret = 0;
1577 
1578 	if (!cb->args[IPSET_CB_DUMP])
1579 		return -EINVAL;
1580 
1581 	if (cb->args[IPSET_CB_INDEX] >= inst->ip_set_max)
1582 		goto out;
1583 
1584 	dump_type = DUMP_TYPE(cb->args[IPSET_CB_DUMP]);
1585 	dump_flags = DUMP_FLAGS(cb->args[IPSET_CB_DUMP]);
1586 	max = dump_type == DUMP_ONE ? cb->args[IPSET_CB_INDEX] + 1
1587 				    : inst->ip_set_max;
1588 dump_last:
1589 	pr_debug("dump type, flag: %u %u index: %ld\n",
1590 		 dump_type, dump_flags, cb->args[IPSET_CB_INDEX]);
1591 	for (; cb->args[IPSET_CB_INDEX] < max; cb->args[IPSET_CB_INDEX]++) {
1592 		index = (ip_set_id_t)cb->args[IPSET_CB_INDEX];
1593 		write_lock_bh(&ip_set_ref_lock);
1594 		set = ip_set(inst, index);
1595 		is_destroyed = inst->is_destroyed;
1596 		if (!set || is_destroyed) {
1597 			write_unlock_bh(&ip_set_ref_lock);
1598 			if (dump_type == DUMP_ONE) {
1599 				ret = -ENOENT;
1600 				goto out;
1601 			}
1602 			if (is_destroyed) {
1603 				/* All sets are just being destroyed */
1604 				ret = 0;
1605 				goto out;
1606 			}
1607 			continue;
1608 		}
1609 		/* When dumping all sets, we must dump "sorted"
1610 		 * so that lists (unions of sets) are dumped last.
1611 		 */
1612 		if (dump_type != DUMP_ONE &&
1613 		    ((dump_type == DUMP_ALL) ==
1614 		     !!(set->type->features & IPSET_DUMP_LAST))) {
1615 			write_unlock_bh(&ip_set_ref_lock);
1616 			continue;
1617 		}
1618 		pr_debug("List set: %s\n", set->name);
1619 		if (!cb->args[IPSET_CB_ARG0]) {
1620 			/* Start listing: make sure set won't be destroyed */
1621 			pr_debug("reference set\n");
1622 			set->ref_netlink++;
1623 		}
1624 		write_unlock_bh(&ip_set_ref_lock);
1625 		nlh = start_msg(skb, NETLINK_CB(cb->skb).portid,
1626 				cb->nlh->nlmsg_seq, flags,
1627 				IPSET_CMD_LIST);
1628 		if (!nlh) {
1629 			ret = -EMSGSIZE;
1630 			goto release_refcount;
1631 		}
1632 		if (nla_put_u8(skb, IPSET_ATTR_PROTOCOL,
1633 			       cb->args[IPSET_CB_PROTO]) ||
1634 		    nla_put_string(skb, IPSET_ATTR_SETNAME, set->name))
1635 			goto nla_put_failure;
1636 		if (dump_flags & IPSET_FLAG_LIST_SETNAME)
1637 			goto next_set;
1638 		switch (cb->args[IPSET_CB_ARG0]) {
1639 		case 0:
1640 			/* Core header data */
1641 			if (nla_put_string(skb, IPSET_ATTR_TYPENAME,
1642 					   set->type->name) ||
1643 			    nla_put_u8(skb, IPSET_ATTR_FAMILY,
1644 				       set->family) ||
1645 			    nla_put_u8(skb, IPSET_ATTR_REVISION,
1646 				       set->revision))
1647 				goto nla_put_failure;
1648 			if (cb->args[IPSET_CB_PROTO] > IPSET_PROTOCOL_MIN &&
1649 			    nla_put_net16(skb, IPSET_ATTR_INDEX, htons(index)))
1650 				goto nla_put_failure;
1651 			ret = set->variant->head(set, skb);
1652 			if (ret < 0)
1653 				goto release_refcount;
1654 			if (dump_flags & IPSET_FLAG_LIST_HEADER)
1655 				goto next_set;
1656 			if (set->variant->uref)
1657 				set->variant->uref(set, cb, true);
1658 			fallthrough;
1659 		default:
1660 			ret = set->variant->list(set, skb, cb);
1661 			if (!cb->args[IPSET_CB_ARG0])
1662 				/* Set is done, proceed with next one */
1663 				goto next_set;
1664 			goto release_refcount;
1665 		}
1666 	}
1667 	/* If we dump all sets, continue with dumping last ones */
1668 	if (dump_type == DUMP_ALL) {
1669 		dump_type = DUMP_LAST;
1670 		cb->args[IPSET_CB_DUMP] = dump_type | (dump_flags << 16);
1671 		cb->args[IPSET_CB_INDEX] = 0;
1672 		if (set && set->variant->uref)
1673 			set->variant->uref(set, cb, false);
1674 		goto dump_last;
1675 	}
1676 	goto out;
1677 
1678 nla_put_failure:
1679 	ret = -EFAULT;
1680 next_set:
1681 	if (dump_type == DUMP_ONE)
1682 		cb->args[IPSET_CB_INDEX] = IPSET_INVALID_ID;
1683 	else
1684 		cb->args[IPSET_CB_INDEX]++;
1685 release_refcount:
1686 	/* If there was an error or set is done, release set */
1687 	if (ret || !cb->args[IPSET_CB_ARG0]) {
1688 		set = ip_set_ref_netlink(inst, index);
1689 		if (set->variant->uref)
1690 			set->variant->uref(set, cb, false);
1691 		pr_debug("release set %s\n", set->name);
1692 		__ip_set_put_netlink(set);
1693 		cb->args[IPSET_CB_ARG0] = 0;
1694 	}
1695 out:
1696 	if (nlh) {
1697 		nlmsg_end(skb, nlh);
1698 		pr_debug("nlmsg_len: %u\n", nlh->nlmsg_len);
1699 		dump_attrs(nlh);
1700 	}
1701 
1702 	return ret < 0 ? ret : skb->len;
1703 }
1704 
ip_set_dump(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])1705 static int ip_set_dump(struct sk_buff *skb, const struct nfnl_info *info,
1706 		       const struct nlattr * const attr[])
1707 {
1708 	if (unlikely(protocol_min_failed(attr)))
1709 		return -IPSET_ERR_PROTOCOL;
1710 
1711 	{
1712 		struct netlink_dump_control c = {
1713 			.start = ip_set_dump_start,
1714 			.dump = ip_set_dump_do,
1715 			.done = ip_set_dump_done,
1716 		};
1717 		return netlink_dump_start(info->sk, skb, info->nlh, &c);
1718 	}
1719 }
1720 
1721 /* Add, del and test */
1722 
1723 static const struct nla_policy ip_set_adt_policy[IPSET_ATTR_CMD_MAX + 1] = {
1724 	[IPSET_ATTR_PROTOCOL]	= { .type = NLA_U8 },
1725 	[IPSET_ATTR_SETNAME]	= { .type = NLA_NUL_STRING,
1726 				    .len = IPSET_MAXNAMELEN - 1 },
1727 	[IPSET_ATTR_LINENO]	= { .type = NLA_U32 },
1728 	[IPSET_ATTR_DATA]	= { .type = NLA_NESTED },
1729 	[IPSET_ATTR_ADT]	= { .type = NLA_NESTED },
1730 };
1731 
1732 static int
call_ad(struct net * net,struct sock * ctnl,struct sk_buff * skb,struct ip_set * set,struct nlattr * tb[],enum ipset_adt adt,u32 flags,bool use_lineno)1733 call_ad(struct net *net, struct sock *ctnl, struct sk_buff *skb,
1734 	struct ip_set *set, struct nlattr *tb[], enum ipset_adt adt,
1735 	u32 flags, bool use_lineno)
1736 {
1737 	int ret;
1738 	u32 lineno = 0;
1739 	bool eexist = flags & IPSET_FLAG_EXIST, retried = false;
1740 
1741 	do {
1742 		if (retried) {
1743 			__ip_set_get_netlink(set);
1744 			nfnl_unlock(NFNL_SUBSYS_IPSET);
1745 			cond_resched();
1746 			nfnl_lock(NFNL_SUBSYS_IPSET);
1747 			__ip_set_put_netlink(set);
1748 		}
1749 
1750 		ip_set_lock(set);
1751 		ret = set->variant->uadt(set, tb, adt, &lineno, flags, retried);
1752 		ip_set_unlock(set);
1753 		retried = true;
1754 	} while (ret == -ERANGE ||
1755 		 (ret == -EAGAIN &&
1756 		  set->variant->resize &&
1757 		  (ret = set->variant->resize(set, retried)) == 0));
1758 
1759 	if (!ret || (ret == -IPSET_ERR_EXIST && eexist))
1760 		return 0;
1761 	if (lineno && use_lineno) {
1762 		/* Error in restore/batch mode: send back lineno */
1763 		struct nlmsghdr *rep, *nlh = nlmsg_hdr(skb);
1764 		struct sk_buff *skb2;
1765 		struct nlmsgerr *errmsg;
1766 		size_t payload = min(SIZE_MAX,
1767 				     sizeof(*errmsg) + nlmsg_len(nlh));
1768 		int min_len = nlmsg_total_size(sizeof(struct nfgenmsg));
1769 		struct nlattr *cda[IPSET_ATTR_CMD_MAX + 1];
1770 		struct nlattr *cmdattr;
1771 		u32 *errline;
1772 
1773 		skb2 = nlmsg_new(payload, GFP_KERNEL);
1774 		if (!skb2)
1775 			return -ENOMEM;
1776 		rep = nlmsg_put(skb2, NETLINK_CB(skb).portid,
1777 				nlh->nlmsg_seq, NLMSG_ERROR, payload, 0);
1778 		errmsg = nlmsg_data(rep);
1779 		errmsg->error = ret;
1780 		unsafe_memcpy(&errmsg->msg, nlh, nlh->nlmsg_len,
1781 			      /* Bounds checked by the skb layer. */);
1782 
1783 		cmdattr = (void *)&errmsg->msg + min_len;
1784 
1785 		ret = nla_parse(cda, IPSET_ATTR_CMD_MAX, cmdattr,
1786 				nlh->nlmsg_len - min_len, ip_set_adt_policy,
1787 				NULL);
1788 
1789 		if (ret) {
1790 			nlmsg_free(skb2);
1791 			return ret;
1792 		}
1793 		errline = nla_data(cda[IPSET_ATTR_LINENO]);
1794 
1795 		*errline = lineno;
1796 
1797 		nfnetlink_unicast(skb2, net, NETLINK_CB(skb).portid);
1798 		/* Signal netlink not to send its ACK/errmsg.  */
1799 		return -EINTR;
1800 	}
1801 
1802 	return ret;
1803 }
1804 
ip_set_ad(struct net * net,struct sock * ctnl,struct sk_buff * skb,enum ipset_adt adt,const struct nlmsghdr * nlh,const struct nlattr * const attr[],struct netlink_ext_ack * extack)1805 static int ip_set_ad(struct net *net, struct sock *ctnl,
1806 		     struct sk_buff *skb,
1807 		     enum ipset_adt adt,
1808 		     const struct nlmsghdr *nlh,
1809 		     const struct nlattr * const attr[],
1810 		     struct netlink_ext_ack *extack)
1811 {
1812 	struct ip_set_net *inst = ip_set_pernet(net);
1813 	struct ip_set *set;
1814 	struct nlattr *tb[IPSET_ATTR_ADT_MAX + 1] = {};
1815 	const struct nlattr *nla;
1816 	u32 flags = flag_exist(nlh);
1817 	bool use_lineno;
1818 	int ret = 0;
1819 
1820 	if (unlikely(protocol_min_failed(attr) ||
1821 		     !attr[IPSET_ATTR_SETNAME] ||
1822 		     !((attr[IPSET_ATTR_DATA] != NULL) ^
1823 		       (attr[IPSET_ATTR_ADT] != NULL)) ||
1824 		     (attr[IPSET_ATTR_DATA] &&
1825 		      !flag_nested(attr[IPSET_ATTR_DATA])) ||
1826 		     (attr[IPSET_ATTR_ADT] &&
1827 		      (!flag_nested(attr[IPSET_ATTR_ADT]) ||
1828 		       !attr[IPSET_ATTR_LINENO]))))
1829 		return -IPSET_ERR_PROTOCOL;
1830 
1831 	set = find_set(inst, nla_data(attr[IPSET_ATTR_SETNAME]));
1832 	if (!set)
1833 		return -ENOENT;
1834 
1835 	use_lineno = !!attr[IPSET_ATTR_LINENO];
1836 	if (attr[IPSET_ATTR_DATA]) {
1837 		if (nla_parse_nested(tb, IPSET_ATTR_ADT_MAX,
1838 				     attr[IPSET_ATTR_DATA],
1839 				     set->type->adt_policy, NULL))
1840 			return -IPSET_ERR_PROTOCOL;
1841 		ret = call_ad(net, ctnl, skb, set, tb, adt, flags,
1842 			      use_lineno);
1843 	} else {
1844 		int nla_rem;
1845 
1846 		nla_for_each_nested(nla, attr[IPSET_ATTR_ADT], nla_rem) {
1847 			if (nla_type(nla) != IPSET_ATTR_DATA ||
1848 			    !flag_nested(nla) ||
1849 			    nla_parse_nested(tb, IPSET_ATTR_ADT_MAX, nla,
1850 					     set->type->adt_policy, NULL))
1851 				return -IPSET_ERR_PROTOCOL;
1852 			ret = call_ad(net, ctnl, skb, set, tb, adt,
1853 				      flags, use_lineno);
1854 			if (ret < 0)
1855 				return ret;
1856 		}
1857 	}
1858 	return ret;
1859 }
1860 
ip_set_uadd(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])1861 static int ip_set_uadd(struct sk_buff *skb, const struct nfnl_info *info,
1862 		       const struct nlattr * const attr[])
1863 {
1864 	return ip_set_ad(info->net, info->sk, skb,
1865 			 IPSET_ADD, info->nlh, attr, info->extack);
1866 }
1867 
ip_set_udel(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])1868 static int ip_set_udel(struct sk_buff *skb, const struct nfnl_info *info,
1869 		       const struct nlattr * const attr[])
1870 {
1871 	return ip_set_ad(info->net, info->sk, skb,
1872 			 IPSET_DEL, info->nlh, attr, info->extack);
1873 }
1874 
ip_set_utest(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])1875 static int ip_set_utest(struct sk_buff *skb, const struct nfnl_info *info,
1876 			const struct nlattr * const attr[])
1877 {
1878 	struct ip_set_net *inst = ip_set_pernet(info->net);
1879 	struct ip_set *set;
1880 	struct nlattr *tb[IPSET_ATTR_ADT_MAX + 1] = {};
1881 	int ret = 0;
1882 	u32 lineno;
1883 
1884 	if (unlikely(protocol_min_failed(attr) ||
1885 		     !attr[IPSET_ATTR_SETNAME] ||
1886 		     !attr[IPSET_ATTR_DATA] ||
1887 		     !flag_nested(attr[IPSET_ATTR_DATA])))
1888 		return -IPSET_ERR_PROTOCOL;
1889 
1890 	set = find_set(inst, nla_data(attr[IPSET_ATTR_SETNAME]));
1891 	if (!set)
1892 		return -ENOENT;
1893 
1894 	if (nla_parse_nested(tb, IPSET_ATTR_ADT_MAX, attr[IPSET_ATTR_DATA],
1895 			     set->type->adt_policy, NULL))
1896 		return -IPSET_ERR_PROTOCOL;
1897 
1898 	rcu_read_lock_bh();
1899 	ret = set->variant->uadt(set, tb, IPSET_TEST, &lineno, 0, 0);
1900 	rcu_read_unlock_bh();
1901 	/* Userspace can't trigger element to be re-added */
1902 	if (ret == -EAGAIN)
1903 		ret = 1;
1904 
1905 	return ret > 0 ? 0 : -IPSET_ERR_EXIST;
1906 }
1907 
1908 /* Get headed data of a set */
1909 
ip_set_header(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])1910 static int ip_set_header(struct sk_buff *skb, const struct nfnl_info *info,
1911 			 const struct nlattr * const attr[])
1912 {
1913 	struct ip_set_net *inst = ip_set_pernet(info->net);
1914 	const struct ip_set *set;
1915 	struct sk_buff *skb2;
1916 	struct nlmsghdr *nlh2;
1917 
1918 	if (unlikely(protocol_min_failed(attr) ||
1919 		     !attr[IPSET_ATTR_SETNAME]))
1920 		return -IPSET_ERR_PROTOCOL;
1921 
1922 	set = find_set(inst, nla_data(attr[IPSET_ATTR_SETNAME]));
1923 	if (!set)
1924 		return -ENOENT;
1925 
1926 	skb2 = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1927 	if (!skb2)
1928 		return -ENOMEM;
1929 
1930 	nlh2 = start_msg(skb2, NETLINK_CB(skb).portid, info->nlh->nlmsg_seq, 0,
1931 			 IPSET_CMD_HEADER);
1932 	if (!nlh2)
1933 		goto nlmsg_failure;
1934 	if (nla_put_u8(skb2, IPSET_ATTR_PROTOCOL, protocol(attr)) ||
1935 	    nla_put_string(skb2, IPSET_ATTR_SETNAME, set->name) ||
1936 	    nla_put_string(skb2, IPSET_ATTR_TYPENAME, set->type->name) ||
1937 	    nla_put_u8(skb2, IPSET_ATTR_FAMILY, set->family) ||
1938 	    nla_put_u8(skb2, IPSET_ATTR_REVISION, set->revision))
1939 		goto nla_put_failure;
1940 	nlmsg_end(skb2, nlh2);
1941 
1942 	return nfnetlink_unicast(skb2, info->net, NETLINK_CB(skb).portid);
1943 
1944 nla_put_failure:
1945 	nlmsg_cancel(skb2, nlh2);
1946 nlmsg_failure:
1947 	kfree_skb(skb2);
1948 	return -EMSGSIZE;
1949 }
1950 
1951 /* Get type data */
1952 
1953 static const struct nla_policy ip_set_type_policy[IPSET_ATTR_CMD_MAX + 1] = {
1954 	[IPSET_ATTR_PROTOCOL]	= { .type = NLA_U8 },
1955 	[IPSET_ATTR_TYPENAME]	= { .type = NLA_NUL_STRING,
1956 				    .len = IPSET_MAXNAMELEN - 1 },
1957 	[IPSET_ATTR_FAMILY]	= { .type = NLA_U8 },
1958 };
1959 
ip_set_type(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])1960 static int ip_set_type(struct sk_buff *skb, const struct nfnl_info *info,
1961 		       const struct nlattr * const attr[])
1962 {
1963 	struct sk_buff *skb2;
1964 	struct nlmsghdr *nlh2;
1965 	u8 family, min, max;
1966 	const char *typename;
1967 	int ret = 0;
1968 
1969 	if (unlikely(protocol_min_failed(attr) ||
1970 		     !attr[IPSET_ATTR_TYPENAME] ||
1971 		     !attr[IPSET_ATTR_FAMILY]))
1972 		return -IPSET_ERR_PROTOCOL;
1973 
1974 	family = nla_get_u8(attr[IPSET_ATTR_FAMILY]);
1975 	typename = nla_data(attr[IPSET_ATTR_TYPENAME]);
1976 	ret = find_set_type_minmax(typename, family, &min, &max);
1977 	if (ret)
1978 		return ret;
1979 
1980 	skb2 = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1981 	if (!skb2)
1982 		return -ENOMEM;
1983 
1984 	nlh2 = start_msg(skb2, NETLINK_CB(skb).portid, info->nlh->nlmsg_seq, 0,
1985 			 IPSET_CMD_TYPE);
1986 	if (!nlh2)
1987 		goto nlmsg_failure;
1988 	if (nla_put_u8(skb2, IPSET_ATTR_PROTOCOL, protocol(attr)) ||
1989 	    nla_put_string(skb2, IPSET_ATTR_TYPENAME, typename) ||
1990 	    nla_put_u8(skb2, IPSET_ATTR_FAMILY, family) ||
1991 	    nla_put_u8(skb2, IPSET_ATTR_REVISION, max) ||
1992 	    nla_put_u8(skb2, IPSET_ATTR_REVISION_MIN, min))
1993 		goto nla_put_failure;
1994 	nlmsg_end(skb2, nlh2);
1995 
1996 	pr_debug("Send TYPE, nlmsg_len: %u\n", nlh2->nlmsg_len);
1997 	return nfnetlink_unicast(skb2, info->net, NETLINK_CB(skb).portid);
1998 
1999 nla_put_failure:
2000 	nlmsg_cancel(skb2, nlh2);
2001 nlmsg_failure:
2002 	kfree_skb(skb2);
2003 	return -EMSGSIZE;
2004 }
2005 
2006 /* Get protocol version */
2007 
2008 static const struct nla_policy
2009 ip_set_protocol_policy[IPSET_ATTR_CMD_MAX + 1] = {
2010 	[IPSET_ATTR_PROTOCOL]	= { .type = NLA_U8 },
2011 };
2012 
ip_set_protocol(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])2013 static int ip_set_protocol(struct sk_buff *skb, const struct nfnl_info *info,
2014 			   const struct nlattr * const attr[])
2015 {
2016 	struct sk_buff *skb2;
2017 	struct nlmsghdr *nlh2;
2018 
2019 	if (unlikely(!attr[IPSET_ATTR_PROTOCOL]))
2020 		return -IPSET_ERR_PROTOCOL;
2021 
2022 	skb2 = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
2023 	if (!skb2)
2024 		return -ENOMEM;
2025 
2026 	nlh2 = start_msg(skb2, NETLINK_CB(skb).portid, info->nlh->nlmsg_seq, 0,
2027 			 IPSET_CMD_PROTOCOL);
2028 	if (!nlh2)
2029 		goto nlmsg_failure;
2030 	if (nla_put_u8(skb2, IPSET_ATTR_PROTOCOL, IPSET_PROTOCOL))
2031 		goto nla_put_failure;
2032 	if (nla_put_u8(skb2, IPSET_ATTR_PROTOCOL_MIN, IPSET_PROTOCOL_MIN))
2033 		goto nla_put_failure;
2034 	nlmsg_end(skb2, nlh2);
2035 
2036 	return nfnetlink_unicast(skb2, info->net, NETLINK_CB(skb).portid);
2037 
2038 nla_put_failure:
2039 	nlmsg_cancel(skb2, nlh2);
2040 nlmsg_failure:
2041 	kfree_skb(skb2);
2042 	return -EMSGSIZE;
2043 }
2044 
2045 /* Get set by name or index, from userspace */
2046 
ip_set_byname(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])2047 static int ip_set_byname(struct sk_buff *skb, const struct nfnl_info *info,
2048 			 const struct nlattr * const attr[])
2049 {
2050 	struct ip_set_net *inst = ip_set_pernet(info->net);
2051 	struct sk_buff *skb2;
2052 	struct nlmsghdr *nlh2;
2053 	ip_set_id_t id = IPSET_INVALID_ID;
2054 	const struct ip_set *set;
2055 
2056 	if (unlikely(protocol_failed(attr) ||
2057 		     !attr[IPSET_ATTR_SETNAME]))
2058 		return -IPSET_ERR_PROTOCOL;
2059 
2060 	set = find_set_and_id(inst, nla_data(attr[IPSET_ATTR_SETNAME]), &id);
2061 	if (id == IPSET_INVALID_ID)
2062 		return -ENOENT;
2063 
2064 	skb2 = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
2065 	if (!skb2)
2066 		return -ENOMEM;
2067 
2068 	nlh2 = start_msg(skb2, NETLINK_CB(skb).portid, info->nlh->nlmsg_seq, 0,
2069 			 IPSET_CMD_GET_BYNAME);
2070 	if (!nlh2)
2071 		goto nlmsg_failure;
2072 	if (nla_put_u8(skb2, IPSET_ATTR_PROTOCOL, protocol(attr)) ||
2073 	    nla_put_u8(skb2, IPSET_ATTR_FAMILY, set->family) ||
2074 	    nla_put_net16(skb2, IPSET_ATTR_INDEX, htons(id)))
2075 		goto nla_put_failure;
2076 	nlmsg_end(skb2, nlh2);
2077 
2078 	return nfnetlink_unicast(skb2, info->net, NETLINK_CB(skb).portid);
2079 
2080 nla_put_failure:
2081 	nlmsg_cancel(skb2, nlh2);
2082 nlmsg_failure:
2083 	kfree_skb(skb2);
2084 	return -EMSGSIZE;
2085 }
2086 
2087 static const struct nla_policy ip_set_index_policy[IPSET_ATTR_CMD_MAX + 1] = {
2088 	[IPSET_ATTR_PROTOCOL]	= { .type = NLA_U8 },
2089 	[IPSET_ATTR_INDEX]	= { .type = NLA_U16 },
2090 };
2091 
ip_set_byindex(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const attr[])2092 static int ip_set_byindex(struct sk_buff *skb, const struct nfnl_info *info,
2093 			  const struct nlattr * const attr[])
2094 {
2095 	struct ip_set_net *inst = ip_set_pernet(info->net);
2096 	struct sk_buff *skb2;
2097 	struct nlmsghdr *nlh2;
2098 	ip_set_id_t id = IPSET_INVALID_ID;
2099 	const struct ip_set *set;
2100 
2101 	if (unlikely(protocol_failed(attr) ||
2102 		     !attr[IPSET_ATTR_INDEX]))
2103 		return -IPSET_ERR_PROTOCOL;
2104 
2105 	id = ip_set_get_h16(attr[IPSET_ATTR_INDEX]);
2106 	if (id >= inst->ip_set_max)
2107 		return -ENOENT;
2108 	set = ip_set(inst, id);
2109 	if (set == NULL)
2110 		return -ENOENT;
2111 
2112 	skb2 = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
2113 	if (!skb2)
2114 		return -ENOMEM;
2115 
2116 	nlh2 = start_msg(skb2, NETLINK_CB(skb).portid, info->nlh->nlmsg_seq, 0,
2117 			 IPSET_CMD_GET_BYINDEX);
2118 	if (!nlh2)
2119 		goto nlmsg_failure;
2120 	if (nla_put_u8(skb2, IPSET_ATTR_PROTOCOL, protocol(attr)) ||
2121 	    nla_put_string(skb2, IPSET_ATTR_SETNAME, set->name))
2122 		goto nla_put_failure;
2123 	nlmsg_end(skb2, nlh2);
2124 
2125 	return nfnetlink_unicast(skb2, info->net, NETLINK_CB(skb).portid);
2126 
2127 nla_put_failure:
2128 	nlmsg_cancel(skb2, nlh2);
2129 nlmsg_failure:
2130 	kfree_skb(skb2);
2131 	return -EMSGSIZE;
2132 }
2133 
2134 static const struct nfnl_callback ip_set_netlink_subsys_cb[IPSET_MSG_MAX] = {
2135 	[IPSET_CMD_NONE]	= {
2136 		.call		= ip_set_none,
2137 		.type		= NFNL_CB_MUTEX,
2138 		.attr_count	= IPSET_ATTR_CMD_MAX,
2139 	},
2140 	[IPSET_CMD_CREATE]	= {
2141 		.call		= ip_set_create,
2142 		.type		= NFNL_CB_MUTEX,
2143 		.attr_count	= IPSET_ATTR_CMD_MAX,
2144 		.policy		= ip_set_create_policy,
2145 	},
2146 	[IPSET_CMD_DESTROY]	= {
2147 		.call		= ip_set_destroy,
2148 		.type		= NFNL_CB_MUTEX,
2149 		.attr_count	= IPSET_ATTR_CMD_MAX,
2150 		.policy		= ip_set_setname_policy,
2151 	},
2152 	[IPSET_CMD_FLUSH]	= {
2153 		.call		= ip_set_flush,
2154 		.type		= NFNL_CB_MUTEX,
2155 		.attr_count	= IPSET_ATTR_CMD_MAX,
2156 		.policy		= ip_set_setname_policy,
2157 	},
2158 	[IPSET_CMD_RENAME]	= {
2159 		.call		= ip_set_rename,
2160 		.type		= NFNL_CB_MUTEX,
2161 		.attr_count	= IPSET_ATTR_CMD_MAX,
2162 		.policy		= ip_set_setname2_policy,
2163 	},
2164 	[IPSET_CMD_SWAP]	= {
2165 		.call		= ip_set_swap,
2166 		.type		= NFNL_CB_MUTEX,
2167 		.attr_count	= IPSET_ATTR_CMD_MAX,
2168 		.policy		= ip_set_setname2_policy,
2169 	},
2170 	[IPSET_CMD_LIST]	= {
2171 		.call		= ip_set_dump,
2172 		.type		= NFNL_CB_MUTEX,
2173 		.attr_count	= IPSET_ATTR_CMD_MAX,
2174 		.policy		= ip_set_dump_policy,
2175 	},
2176 	[IPSET_CMD_SAVE]	= {
2177 		.call		= ip_set_dump,
2178 		.type		= NFNL_CB_MUTEX,
2179 		.attr_count	= IPSET_ATTR_CMD_MAX,
2180 		.policy		= ip_set_setname_policy,
2181 	},
2182 	[IPSET_CMD_ADD]	= {
2183 		.call		= ip_set_uadd,
2184 		.type		= NFNL_CB_MUTEX,
2185 		.attr_count	= IPSET_ATTR_CMD_MAX,
2186 		.policy		= ip_set_adt_policy,
2187 	},
2188 	[IPSET_CMD_DEL]	= {
2189 		.call		= ip_set_udel,
2190 		.type		= NFNL_CB_MUTEX,
2191 		.attr_count	= IPSET_ATTR_CMD_MAX,
2192 		.policy		= ip_set_adt_policy,
2193 	},
2194 	[IPSET_CMD_TEST]	= {
2195 		.call		= ip_set_utest,
2196 		.type		= NFNL_CB_MUTEX,
2197 		.attr_count	= IPSET_ATTR_CMD_MAX,
2198 		.policy		= ip_set_adt_policy,
2199 	},
2200 	[IPSET_CMD_HEADER]	= {
2201 		.call		= ip_set_header,
2202 		.type		= NFNL_CB_MUTEX,
2203 		.attr_count	= IPSET_ATTR_CMD_MAX,
2204 		.policy		= ip_set_setname_policy,
2205 	},
2206 	[IPSET_CMD_TYPE]	= {
2207 		.call		= ip_set_type,
2208 		.type		= NFNL_CB_MUTEX,
2209 		.attr_count	= IPSET_ATTR_CMD_MAX,
2210 		.policy		= ip_set_type_policy,
2211 	},
2212 	[IPSET_CMD_PROTOCOL]	= {
2213 		.call		= ip_set_protocol,
2214 		.type		= NFNL_CB_MUTEX,
2215 		.attr_count	= IPSET_ATTR_CMD_MAX,
2216 		.policy		= ip_set_protocol_policy,
2217 	},
2218 	[IPSET_CMD_GET_BYNAME]	= {
2219 		.call		= ip_set_byname,
2220 		.type		= NFNL_CB_MUTEX,
2221 		.attr_count	= IPSET_ATTR_CMD_MAX,
2222 		.policy		= ip_set_setname_policy,
2223 	},
2224 	[IPSET_CMD_GET_BYINDEX]	= {
2225 		.call		= ip_set_byindex,
2226 		.type		= NFNL_CB_MUTEX,
2227 		.attr_count	= IPSET_ATTR_CMD_MAX,
2228 		.policy		= ip_set_index_policy,
2229 	},
2230 };
2231 
2232 static struct nfnetlink_subsystem ip_set_netlink_subsys __read_mostly = {
2233 	.name		= "ip_set",
2234 	.subsys_id	= NFNL_SUBSYS_IPSET,
2235 	.cb_count	= IPSET_MSG_MAX,
2236 	.cb		= ip_set_netlink_subsys_cb,
2237 };
2238 
2239 /* Interface to iptables/ip6tables */
2240 
2241 static int
ip_set_sockfn_get(struct sock * sk,int optval,void __user * user,int * len)2242 ip_set_sockfn_get(struct sock *sk, int optval, void __user *user, int *len)
2243 {
2244 	unsigned int *op;
2245 	void *data;
2246 	int copylen = *len, ret = 0;
2247 	struct net *net = sock_net(sk);
2248 	struct ip_set_net *inst = ip_set_pernet(net);
2249 
2250 	if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2251 		return -EPERM;
2252 	if (optval != SO_IP_SET)
2253 		return -EBADF;
2254 	if (*len < sizeof(unsigned int))
2255 		return -EINVAL;
2256 
2257 	data = vmalloc(*len);
2258 	if (!data)
2259 		return -ENOMEM;
2260 	if (copy_from_user(data, user, *len) != 0) {
2261 		ret = -EFAULT;
2262 		goto done;
2263 	}
2264 	op = data;
2265 
2266 	if (*op < IP_SET_OP_VERSION) {
2267 		/* Check the version at the beginning of operations */
2268 		struct ip_set_req_version *req_version = data;
2269 
2270 		if (*len < sizeof(struct ip_set_req_version)) {
2271 			ret = -EINVAL;
2272 			goto done;
2273 		}
2274 
2275 		if (req_version->version < IPSET_PROTOCOL_MIN) {
2276 			ret = -EPROTO;
2277 			goto done;
2278 		}
2279 	}
2280 
2281 	switch (*op) {
2282 	case IP_SET_OP_VERSION: {
2283 		struct ip_set_req_version *req_version = data;
2284 
2285 		if (*len != sizeof(struct ip_set_req_version)) {
2286 			ret = -EINVAL;
2287 			goto done;
2288 		}
2289 
2290 		req_version->version = IPSET_PROTOCOL;
2291 		if (copy_to_user(user, req_version,
2292 				 sizeof(struct ip_set_req_version)))
2293 			ret = -EFAULT;
2294 		goto done;
2295 	}
2296 	case IP_SET_OP_GET_BYNAME: {
2297 		struct ip_set_req_get_set *req_get = data;
2298 		ip_set_id_t id;
2299 
2300 		if (*len != sizeof(struct ip_set_req_get_set)) {
2301 			ret = -EINVAL;
2302 			goto done;
2303 		}
2304 		req_get->set.name[IPSET_MAXNAMELEN - 1] = '\0';
2305 		nfnl_lock(NFNL_SUBSYS_IPSET);
2306 		find_set_and_id(inst, req_get->set.name, &id);
2307 		req_get->set.index = id;
2308 		nfnl_unlock(NFNL_SUBSYS_IPSET);
2309 		goto copy;
2310 	}
2311 	case IP_SET_OP_GET_FNAME: {
2312 		struct ip_set_req_get_set_family *req_get = data;
2313 		ip_set_id_t id;
2314 
2315 		if (*len != sizeof(struct ip_set_req_get_set_family)) {
2316 			ret = -EINVAL;
2317 			goto done;
2318 		}
2319 		req_get->set.name[IPSET_MAXNAMELEN - 1] = '\0';
2320 		nfnl_lock(NFNL_SUBSYS_IPSET);
2321 		find_set_and_id(inst, req_get->set.name, &id);
2322 		req_get->set.index = id;
2323 		if (id != IPSET_INVALID_ID)
2324 			req_get->family = ip_set(inst, id)->family;
2325 		nfnl_unlock(NFNL_SUBSYS_IPSET);
2326 		goto copy;
2327 	}
2328 	case IP_SET_OP_GET_BYINDEX: {
2329 		struct ip_set_req_get_set *req_get = data;
2330 		struct ip_set *set;
2331 
2332 		if (*len != sizeof(struct ip_set_req_get_set) ||
2333 		    req_get->set.index >= inst->ip_set_max) {
2334 			ret = -EINVAL;
2335 			goto done;
2336 		}
2337 		nfnl_lock(NFNL_SUBSYS_IPSET);
2338 		set = ip_set(inst, req_get->set.index);
2339 		ret = strscpy(req_get->set.name, set ? set->name : "",
2340 			      IPSET_MAXNAMELEN);
2341 		nfnl_unlock(NFNL_SUBSYS_IPSET);
2342 		if (ret < 0)
2343 			goto done;
2344 		goto copy;
2345 	}
2346 	default:
2347 		ret = -EBADMSG;
2348 		goto done;
2349 	}	/* end of switch(op) */
2350 
2351 copy:
2352 	if (copy_to_user(user, data, copylen))
2353 		ret = -EFAULT;
2354 
2355 done:
2356 	vfree(data);
2357 	if (ret > 0)
2358 		ret = 0;
2359 	return ret;
2360 }
2361 
2362 static struct nf_sockopt_ops so_set __read_mostly = {
2363 	.pf		= PF_INET,
2364 	.get_optmin	= SO_IP_SET,
2365 	.get_optmax	= SO_IP_SET + 1,
2366 	.get		= ip_set_sockfn_get,
2367 	.owner		= THIS_MODULE,
2368 };
2369 
2370 static int __net_init
ip_set_net_init(struct net * net)2371 ip_set_net_init(struct net *net)
2372 {
2373 	struct ip_set_net *inst = ip_set_pernet(net);
2374 	struct ip_set **list;
2375 
2376 	inst->ip_set_max = max_sets ? max_sets : CONFIG_IP_SET_MAX;
2377 	if (inst->ip_set_max >= IPSET_INVALID_ID)
2378 		inst->ip_set_max = IPSET_INVALID_ID - 1;
2379 
2380 	list = kvcalloc(inst->ip_set_max, sizeof(struct ip_set *), GFP_KERNEL);
2381 	if (!list)
2382 		return -ENOMEM;
2383 	inst->is_deleted = false;
2384 	inst->is_destroyed = false;
2385 	rcu_assign_pointer(inst->ip_set_list, list);
2386 	return 0;
2387 }
2388 
2389 static void __net_exit
ip_set_net_pre_exit(struct net * net)2390 ip_set_net_pre_exit(struct net *net)
2391 {
2392 	struct ip_set_net *inst = ip_set_pernet(net);
2393 
2394 	inst->is_deleted = true; /* flag for ip_set_nfnl_put */
2395 }
2396 
2397 static void __net_exit
ip_set_net_exit(struct net * net)2398 ip_set_net_exit(struct net *net)
2399 {
2400 	struct ip_set_net *inst = ip_set_pernet(net);
2401 
2402 	_destroy_all_sets(inst);
2403 	kvfree(rcu_dereference_protected(inst->ip_set_list, 1));
2404 }
2405 
2406 static struct pernet_operations ip_set_net_ops = {
2407 	.init	= ip_set_net_init,
2408 	.pre_exit = ip_set_net_pre_exit,
2409 	.exit   = ip_set_net_exit,
2410 	.id	= &ip_set_net_id,
2411 	.size	= sizeof(struct ip_set_net),
2412 };
2413 
2414 static int __init
ip_set_init(void)2415 ip_set_init(void)
2416 {
2417 	int ret = register_pernet_subsys(&ip_set_net_ops);
2418 
2419 	if (ret) {
2420 		pr_err("ip_set: cannot register pernet_subsys.\n");
2421 		return ret;
2422 	}
2423 
2424 	ret = nfnetlink_subsys_register(&ip_set_netlink_subsys);
2425 	if (ret != 0) {
2426 		pr_err("ip_set: cannot register with nfnetlink.\n");
2427 		unregister_pernet_subsys(&ip_set_net_ops);
2428 		return ret;
2429 	}
2430 
2431 	ret = nf_register_sockopt(&so_set);
2432 	if (ret != 0) {
2433 		pr_err("SO_SET registry failed: %d\n", ret);
2434 		nfnetlink_subsys_unregister(&ip_set_netlink_subsys);
2435 		unregister_pernet_subsys(&ip_set_net_ops);
2436 		return ret;
2437 	}
2438 
2439 	return 0;
2440 }
2441 
2442 static void __exit
ip_set_fini(void)2443 ip_set_fini(void)
2444 {
2445 	nf_unregister_sockopt(&so_set);
2446 	nfnetlink_subsys_unregister(&ip_set_netlink_subsys);
2447 	unregister_pernet_subsys(&ip_set_net_ops);
2448 
2449 	/* Wait for call_rcu() in destroy */
2450 	rcu_barrier();
2451 
2452 	pr_debug("these are the famous last words\n");
2453 }
2454 
2455 module_init(ip_set_init);
2456 module_exit(ip_set_fini);
2457 
2458 MODULE_DESCRIPTION("ip_set: protocol " __stringify(IPSET_PROTOCOL));
2459