xref: /openbmc/linux/net/netfilter/nf_tables_api.c (revision 164936b2)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2007-2009 Patrick McHardy <kaber@trash.net>
4  *
5  * Development of this code funded by Astaro AG (http://www.astaro.com/)
6  */
7 
8 #include <linux/module.h>
9 #include <linux/init.h>
10 #include <linux/list.h>
11 #include <linux/skbuff.h>
12 #include <linux/netlink.h>
13 #include <linux/vmalloc.h>
14 #include <linux/rhashtable.h>
15 #include <linux/audit.h>
16 #include <linux/netfilter.h>
17 #include <linux/netfilter/nfnetlink.h>
18 #include <linux/netfilter/nf_tables.h>
19 #include <net/netfilter/nf_flow_table.h>
20 #include <net/netfilter/nf_tables_core.h>
21 #include <net/netfilter/nf_tables.h>
22 #include <net/netfilter/nf_tables_offload.h>
23 #include <net/net_namespace.h>
24 #include <net/sock.h>
25 
26 #define NFT_MODULE_AUTOLOAD_LIMIT (MODULE_NAME_LEN - sizeof("nft-expr-255-"))
27 #define NFT_SET_MAX_ANONLEN 16
28 
29 unsigned int nf_tables_net_id __read_mostly;
30 
31 static LIST_HEAD(nf_tables_expressions);
32 static LIST_HEAD(nf_tables_objects);
33 static LIST_HEAD(nf_tables_flowtables);
34 static LIST_HEAD(nf_tables_destroy_list);
35 static LIST_HEAD(nf_tables_gc_list);
36 static DEFINE_SPINLOCK(nf_tables_destroy_list_lock);
37 static DEFINE_SPINLOCK(nf_tables_gc_list_lock);
38 
39 enum {
40 	NFT_VALIDATE_SKIP	= 0,
41 	NFT_VALIDATE_NEED,
42 	NFT_VALIDATE_DO,
43 };
44 
45 static struct rhltable nft_objname_ht;
46 
47 static u32 nft_chain_hash(const void *data, u32 len, u32 seed);
48 static u32 nft_chain_hash_obj(const void *data, u32 len, u32 seed);
49 static int nft_chain_hash_cmp(struct rhashtable_compare_arg *, const void *);
50 
51 static u32 nft_objname_hash(const void *data, u32 len, u32 seed);
52 static u32 nft_objname_hash_obj(const void *data, u32 len, u32 seed);
53 static int nft_objname_hash_cmp(struct rhashtable_compare_arg *, const void *);
54 
55 static const struct rhashtable_params nft_chain_ht_params = {
56 	.head_offset		= offsetof(struct nft_chain, rhlhead),
57 	.key_offset		= offsetof(struct nft_chain, name),
58 	.hashfn			= nft_chain_hash,
59 	.obj_hashfn		= nft_chain_hash_obj,
60 	.obj_cmpfn		= nft_chain_hash_cmp,
61 	.automatic_shrinking	= true,
62 };
63 
64 static const struct rhashtable_params nft_objname_ht_params = {
65 	.head_offset		= offsetof(struct nft_object, rhlhead),
66 	.key_offset		= offsetof(struct nft_object, key),
67 	.hashfn			= nft_objname_hash,
68 	.obj_hashfn		= nft_objname_hash_obj,
69 	.obj_cmpfn		= nft_objname_hash_cmp,
70 	.automatic_shrinking	= true,
71 };
72 
73 struct nft_audit_data {
74 	struct nft_table *table;
75 	int entries;
76 	int op;
77 	struct list_head list;
78 };
79 
80 static const u8 nft2audit_op[NFT_MSG_MAX] = { // enum nf_tables_msg_types
81 	[NFT_MSG_NEWTABLE]	= AUDIT_NFT_OP_TABLE_REGISTER,
82 	[NFT_MSG_GETTABLE]	= AUDIT_NFT_OP_INVALID,
83 	[NFT_MSG_DELTABLE]	= AUDIT_NFT_OP_TABLE_UNREGISTER,
84 	[NFT_MSG_NEWCHAIN]	= AUDIT_NFT_OP_CHAIN_REGISTER,
85 	[NFT_MSG_GETCHAIN]	= AUDIT_NFT_OP_INVALID,
86 	[NFT_MSG_DELCHAIN]	= AUDIT_NFT_OP_CHAIN_UNREGISTER,
87 	[NFT_MSG_NEWRULE]	= AUDIT_NFT_OP_RULE_REGISTER,
88 	[NFT_MSG_GETRULE]	= AUDIT_NFT_OP_INVALID,
89 	[NFT_MSG_DELRULE]	= AUDIT_NFT_OP_RULE_UNREGISTER,
90 	[NFT_MSG_NEWSET]	= AUDIT_NFT_OP_SET_REGISTER,
91 	[NFT_MSG_GETSET]	= AUDIT_NFT_OP_INVALID,
92 	[NFT_MSG_DELSET]	= AUDIT_NFT_OP_SET_UNREGISTER,
93 	[NFT_MSG_NEWSETELEM]	= AUDIT_NFT_OP_SETELEM_REGISTER,
94 	[NFT_MSG_GETSETELEM]	= AUDIT_NFT_OP_INVALID,
95 	[NFT_MSG_DELSETELEM]	= AUDIT_NFT_OP_SETELEM_UNREGISTER,
96 	[NFT_MSG_NEWGEN]	= AUDIT_NFT_OP_GEN_REGISTER,
97 	[NFT_MSG_GETGEN]	= AUDIT_NFT_OP_INVALID,
98 	[NFT_MSG_TRACE]		= AUDIT_NFT_OP_INVALID,
99 	[NFT_MSG_NEWOBJ]	= AUDIT_NFT_OP_OBJ_REGISTER,
100 	[NFT_MSG_GETOBJ]	= AUDIT_NFT_OP_INVALID,
101 	[NFT_MSG_DELOBJ]	= AUDIT_NFT_OP_OBJ_UNREGISTER,
102 	[NFT_MSG_GETOBJ_RESET]	= AUDIT_NFT_OP_OBJ_RESET,
103 	[NFT_MSG_NEWFLOWTABLE]	= AUDIT_NFT_OP_FLOWTABLE_REGISTER,
104 	[NFT_MSG_GETFLOWTABLE]	= AUDIT_NFT_OP_INVALID,
105 	[NFT_MSG_DELFLOWTABLE]	= AUDIT_NFT_OP_FLOWTABLE_UNREGISTER,
106 	[NFT_MSG_GETSETELEM_RESET] = AUDIT_NFT_OP_SETELEM_RESET,
107 };
108 
nft_validate_state_update(struct nft_table * table,u8 new_validate_state)109 static void nft_validate_state_update(struct nft_table *table, u8 new_validate_state)
110 {
111 	switch (table->validate_state) {
112 	case NFT_VALIDATE_SKIP:
113 		WARN_ON_ONCE(new_validate_state == NFT_VALIDATE_DO);
114 		break;
115 	case NFT_VALIDATE_NEED:
116 		break;
117 	case NFT_VALIDATE_DO:
118 		if (new_validate_state == NFT_VALIDATE_NEED)
119 			return;
120 	}
121 
122 	table->validate_state = new_validate_state;
123 }
124 static void nf_tables_trans_destroy_work(struct work_struct *w);
125 static DECLARE_WORK(trans_destroy_work, nf_tables_trans_destroy_work);
126 
127 static void nft_trans_gc_work(struct work_struct *work);
128 static DECLARE_WORK(trans_gc_work, nft_trans_gc_work);
129 
nft_ctx_init(struct nft_ctx * ctx,struct net * net,const struct sk_buff * skb,const struct nlmsghdr * nlh,u8 family,struct nft_table * table,struct nft_chain * chain,const struct nlattr * const * nla)130 static void nft_ctx_init(struct nft_ctx *ctx,
131 			 struct net *net,
132 			 const struct sk_buff *skb,
133 			 const struct nlmsghdr *nlh,
134 			 u8 family,
135 			 struct nft_table *table,
136 			 struct nft_chain *chain,
137 			 const struct nlattr * const *nla)
138 {
139 	ctx->net	= net;
140 	ctx->family	= family;
141 	ctx->level	= 0;
142 	ctx->table	= table;
143 	ctx->chain	= chain;
144 	ctx->nla   	= nla;
145 	ctx->portid	= NETLINK_CB(skb).portid;
146 	ctx->report	= nlmsg_report(nlh);
147 	ctx->flags	= nlh->nlmsg_flags;
148 	ctx->seq	= nlh->nlmsg_seq;
149 }
150 
nft_trans_alloc_gfp(const struct nft_ctx * ctx,int msg_type,u32 size,gfp_t gfp)151 static struct nft_trans *nft_trans_alloc_gfp(const struct nft_ctx *ctx,
152 					     int msg_type, u32 size, gfp_t gfp)
153 {
154 	struct nft_trans *trans;
155 
156 	trans = kzalloc(sizeof(struct nft_trans) + size, gfp);
157 	if (trans == NULL)
158 		return NULL;
159 
160 	INIT_LIST_HEAD(&trans->list);
161 	INIT_LIST_HEAD(&trans->binding_list);
162 	trans->msg_type = msg_type;
163 	trans->ctx	= *ctx;
164 
165 	return trans;
166 }
167 
nft_trans_alloc(const struct nft_ctx * ctx,int msg_type,u32 size)168 static struct nft_trans *nft_trans_alloc(const struct nft_ctx *ctx,
169 					 int msg_type, u32 size)
170 {
171 	return nft_trans_alloc_gfp(ctx, msg_type, size, GFP_KERNEL);
172 }
173 
nft_trans_list_del(struct nft_trans * trans)174 static void nft_trans_list_del(struct nft_trans *trans)
175 {
176 	list_del(&trans->list);
177 	list_del(&trans->binding_list);
178 }
179 
nft_trans_destroy(struct nft_trans * trans)180 static void nft_trans_destroy(struct nft_trans *trans)
181 {
182 	nft_trans_list_del(trans);
183 	kfree(trans);
184 }
185 
__nft_set_trans_bind(const struct nft_ctx * ctx,struct nft_set * set,bool bind)186 static void __nft_set_trans_bind(const struct nft_ctx *ctx, struct nft_set *set,
187 				 bool bind)
188 {
189 	struct nftables_pernet *nft_net;
190 	struct net *net = ctx->net;
191 	struct nft_trans *trans;
192 
193 	if (!nft_set_is_anonymous(set))
194 		return;
195 
196 	nft_net = nft_pernet(net);
197 	list_for_each_entry_reverse(trans, &nft_net->commit_list, list) {
198 		switch (trans->msg_type) {
199 		case NFT_MSG_NEWSET:
200 			if (nft_trans_set(trans) == set)
201 				nft_trans_set_bound(trans) = bind;
202 			break;
203 		case NFT_MSG_NEWSETELEM:
204 			if (nft_trans_elem_set(trans) == set)
205 				nft_trans_elem_set_bound(trans) = bind;
206 			break;
207 		}
208 	}
209 }
210 
nft_set_trans_bind(const struct nft_ctx * ctx,struct nft_set * set)211 static void nft_set_trans_bind(const struct nft_ctx *ctx, struct nft_set *set)
212 {
213 	return __nft_set_trans_bind(ctx, set, true);
214 }
215 
nft_set_trans_unbind(const struct nft_ctx * ctx,struct nft_set * set)216 static void nft_set_trans_unbind(const struct nft_ctx *ctx, struct nft_set *set)
217 {
218 	return __nft_set_trans_bind(ctx, set, false);
219 }
220 
__nft_chain_trans_bind(const struct nft_ctx * ctx,struct nft_chain * chain,bool bind)221 static void __nft_chain_trans_bind(const struct nft_ctx *ctx,
222 				   struct nft_chain *chain, bool bind)
223 {
224 	struct nftables_pernet *nft_net;
225 	struct net *net = ctx->net;
226 	struct nft_trans *trans;
227 
228 	if (!nft_chain_binding(chain))
229 		return;
230 
231 	nft_net = nft_pernet(net);
232 	list_for_each_entry_reverse(trans, &nft_net->commit_list, list) {
233 		switch (trans->msg_type) {
234 		case NFT_MSG_NEWCHAIN:
235 			if (nft_trans_chain(trans) == chain)
236 				nft_trans_chain_bound(trans) = bind;
237 			break;
238 		case NFT_MSG_NEWRULE:
239 			if (trans->ctx.chain == chain)
240 				nft_trans_rule_bound(trans) = bind;
241 			break;
242 		}
243 	}
244 }
245 
nft_chain_trans_bind(const struct nft_ctx * ctx,struct nft_chain * chain)246 static void nft_chain_trans_bind(const struct nft_ctx *ctx,
247 				 struct nft_chain *chain)
248 {
249 	__nft_chain_trans_bind(ctx, chain, true);
250 }
251 
nf_tables_bind_chain(const struct nft_ctx * ctx,struct nft_chain * chain)252 int nf_tables_bind_chain(const struct nft_ctx *ctx, struct nft_chain *chain)
253 {
254 	if (!nft_chain_binding(chain))
255 		return 0;
256 
257 	if (nft_chain_binding(ctx->chain))
258 		return -EOPNOTSUPP;
259 
260 	if (chain->bound)
261 		return -EBUSY;
262 
263 	if (!nft_use_inc(&chain->use))
264 		return -EMFILE;
265 
266 	chain->bound = true;
267 	nft_chain_trans_bind(ctx, chain);
268 
269 	return 0;
270 }
271 
nf_tables_unbind_chain(const struct nft_ctx * ctx,struct nft_chain * chain)272 void nf_tables_unbind_chain(const struct nft_ctx *ctx, struct nft_chain *chain)
273 {
274 	__nft_chain_trans_bind(ctx, chain, false);
275 }
276 
nft_netdev_register_hooks(struct net * net,struct list_head * hook_list)277 static int nft_netdev_register_hooks(struct net *net,
278 				     struct list_head *hook_list)
279 {
280 	struct nft_hook *hook;
281 	int err, j;
282 
283 	j = 0;
284 	list_for_each_entry(hook, hook_list, list) {
285 		err = nf_register_net_hook(net, &hook->ops);
286 		if (err < 0)
287 			goto err_register;
288 
289 		j++;
290 	}
291 	return 0;
292 
293 err_register:
294 	list_for_each_entry(hook, hook_list, list) {
295 		if (j-- <= 0)
296 			break;
297 
298 		nf_unregister_net_hook(net, &hook->ops);
299 	}
300 	return err;
301 }
302 
nft_netdev_unregister_hooks(struct net * net,struct list_head * hook_list,bool release_netdev)303 static void nft_netdev_unregister_hooks(struct net *net,
304 					struct list_head *hook_list,
305 					bool release_netdev)
306 {
307 	struct nft_hook *hook, *next;
308 
309 	list_for_each_entry_safe(hook, next, hook_list, list) {
310 		nf_unregister_net_hook(net, &hook->ops);
311 		if (release_netdev) {
312 			list_del(&hook->list);
313 			kfree_rcu(hook, rcu);
314 		}
315 	}
316 }
317 
nf_tables_register_hook(struct net * net,const struct nft_table * table,struct nft_chain * chain)318 static int nf_tables_register_hook(struct net *net,
319 				   const struct nft_table *table,
320 				   struct nft_chain *chain)
321 {
322 	struct nft_base_chain *basechain;
323 	const struct nf_hook_ops *ops;
324 
325 	if (table->flags & NFT_TABLE_F_DORMANT ||
326 	    !nft_is_base_chain(chain))
327 		return 0;
328 
329 	basechain = nft_base_chain(chain);
330 	ops = &basechain->ops;
331 
332 	if (basechain->type->ops_register)
333 		return basechain->type->ops_register(net, ops);
334 
335 	if (nft_base_chain_netdev(table->family, basechain->ops.hooknum))
336 		return nft_netdev_register_hooks(net, &basechain->hook_list);
337 
338 	return nf_register_net_hook(net, &basechain->ops);
339 }
340 
__nf_tables_unregister_hook(struct net * net,const struct nft_table * table,struct nft_chain * chain,bool release_netdev)341 static void __nf_tables_unregister_hook(struct net *net,
342 					const struct nft_table *table,
343 					struct nft_chain *chain,
344 					bool release_netdev)
345 {
346 	struct nft_base_chain *basechain;
347 	const struct nf_hook_ops *ops;
348 
349 	if (table->flags & NFT_TABLE_F_DORMANT ||
350 	    !nft_is_base_chain(chain))
351 		return;
352 	basechain = nft_base_chain(chain);
353 	ops = &basechain->ops;
354 
355 	if (basechain->type->ops_unregister)
356 		return basechain->type->ops_unregister(net, ops);
357 
358 	if (nft_base_chain_netdev(table->family, basechain->ops.hooknum))
359 		nft_netdev_unregister_hooks(net, &basechain->hook_list,
360 					    release_netdev);
361 	else
362 		nf_unregister_net_hook(net, &basechain->ops);
363 }
364 
nf_tables_unregister_hook(struct net * net,const struct nft_table * table,struct nft_chain * chain)365 static void nf_tables_unregister_hook(struct net *net,
366 				      const struct nft_table *table,
367 				      struct nft_chain *chain)
368 {
369 	return __nf_tables_unregister_hook(net, table, chain, false);
370 }
371 
nft_trans_commit_list_add_tail(struct net * net,struct nft_trans * trans)372 static void nft_trans_commit_list_add_tail(struct net *net, struct nft_trans *trans)
373 {
374 	struct nftables_pernet *nft_net = nft_pernet(net);
375 
376 	switch (trans->msg_type) {
377 	case NFT_MSG_NEWSET:
378 		if (!nft_trans_set_update(trans) &&
379 		    nft_set_is_anonymous(nft_trans_set(trans)))
380 			list_add_tail(&trans->binding_list, &nft_net->binding_list);
381 		break;
382 	case NFT_MSG_NEWCHAIN:
383 		if (!nft_trans_chain_update(trans) &&
384 		    nft_chain_binding(nft_trans_chain(trans)))
385 			list_add_tail(&trans->binding_list, &nft_net->binding_list);
386 		break;
387 	}
388 
389 	list_add_tail(&trans->list, &nft_net->commit_list);
390 }
391 
nft_trans_table_add(struct nft_ctx * ctx,int msg_type)392 static int nft_trans_table_add(struct nft_ctx *ctx, int msg_type)
393 {
394 	struct nft_trans *trans;
395 
396 	trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_table));
397 	if (trans == NULL)
398 		return -ENOMEM;
399 
400 	if (msg_type == NFT_MSG_NEWTABLE)
401 		nft_activate_next(ctx->net, ctx->table);
402 
403 	nft_trans_commit_list_add_tail(ctx->net, trans);
404 	return 0;
405 }
406 
nft_deltable(struct nft_ctx * ctx)407 static int nft_deltable(struct nft_ctx *ctx)
408 {
409 	int err;
410 
411 	err = nft_trans_table_add(ctx, NFT_MSG_DELTABLE);
412 	if (err < 0)
413 		return err;
414 
415 	nft_deactivate_next(ctx->net, ctx->table);
416 	return err;
417 }
418 
nft_trans_chain_add(struct nft_ctx * ctx,int msg_type)419 static struct nft_trans *nft_trans_chain_add(struct nft_ctx *ctx, int msg_type)
420 {
421 	struct nft_trans *trans;
422 
423 	trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_chain));
424 	if (trans == NULL)
425 		return ERR_PTR(-ENOMEM);
426 
427 	if (msg_type == NFT_MSG_NEWCHAIN) {
428 		nft_activate_next(ctx->net, ctx->chain);
429 
430 		if (ctx->nla[NFTA_CHAIN_ID]) {
431 			nft_trans_chain_id(trans) =
432 				ntohl(nla_get_be32(ctx->nla[NFTA_CHAIN_ID]));
433 		}
434 	}
435 	nft_trans_chain(trans) = ctx->chain;
436 	nft_trans_commit_list_add_tail(ctx->net, trans);
437 
438 	return trans;
439 }
440 
nft_delchain(struct nft_ctx * ctx)441 static int nft_delchain(struct nft_ctx *ctx)
442 {
443 	struct nft_trans *trans;
444 
445 	trans = nft_trans_chain_add(ctx, NFT_MSG_DELCHAIN);
446 	if (IS_ERR(trans))
447 		return PTR_ERR(trans);
448 
449 	nft_use_dec(&ctx->table->use);
450 	nft_deactivate_next(ctx->net, ctx->chain);
451 
452 	return 0;
453 }
454 
nft_rule_expr_activate(const struct nft_ctx * ctx,struct nft_rule * rule)455 void nft_rule_expr_activate(const struct nft_ctx *ctx, struct nft_rule *rule)
456 {
457 	struct nft_expr *expr;
458 
459 	expr = nft_expr_first(rule);
460 	while (nft_expr_more(rule, expr)) {
461 		if (expr->ops->activate)
462 			expr->ops->activate(ctx, expr);
463 
464 		expr = nft_expr_next(expr);
465 	}
466 }
467 
nft_rule_expr_deactivate(const struct nft_ctx * ctx,struct nft_rule * rule,enum nft_trans_phase phase)468 void nft_rule_expr_deactivate(const struct nft_ctx *ctx, struct nft_rule *rule,
469 			      enum nft_trans_phase phase)
470 {
471 	struct nft_expr *expr;
472 
473 	expr = nft_expr_first(rule);
474 	while (nft_expr_more(rule, expr)) {
475 		if (expr->ops->deactivate)
476 			expr->ops->deactivate(ctx, expr, phase);
477 
478 		expr = nft_expr_next(expr);
479 	}
480 }
481 
482 static int
nf_tables_delrule_deactivate(struct nft_ctx * ctx,struct nft_rule * rule)483 nf_tables_delrule_deactivate(struct nft_ctx *ctx, struct nft_rule *rule)
484 {
485 	/* You cannot delete the same rule twice */
486 	if (nft_is_active_next(ctx->net, rule)) {
487 		nft_deactivate_next(ctx->net, rule);
488 		nft_use_dec(&ctx->chain->use);
489 		return 0;
490 	}
491 	return -ENOENT;
492 }
493 
nft_trans_rule_add(struct nft_ctx * ctx,int msg_type,struct nft_rule * rule)494 static struct nft_trans *nft_trans_rule_add(struct nft_ctx *ctx, int msg_type,
495 					    struct nft_rule *rule)
496 {
497 	struct nft_trans *trans;
498 
499 	trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_rule));
500 	if (trans == NULL)
501 		return NULL;
502 
503 	if (msg_type == NFT_MSG_NEWRULE && ctx->nla[NFTA_RULE_ID] != NULL) {
504 		nft_trans_rule_id(trans) =
505 			ntohl(nla_get_be32(ctx->nla[NFTA_RULE_ID]));
506 	}
507 	nft_trans_rule(trans) = rule;
508 	nft_trans_commit_list_add_tail(ctx->net, trans);
509 
510 	return trans;
511 }
512 
nft_delrule(struct nft_ctx * ctx,struct nft_rule * rule)513 static int nft_delrule(struct nft_ctx *ctx, struct nft_rule *rule)
514 {
515 	struct nft_flow_rule *flow;
516 	struct nft_trans *trans;
517 	int err;
518 
519 	trans = nft_trans_rule_add(ctx, NFT_MSG_DELRULE, rule);
520 	if (trans == NULL)
521 		return -ENOMEM;
522 
523 	if (ctx->chain->flags & NFT_CHAIN_HW_OFFLOAD) {
524 		flow = nft_flow_rule_create(ctx->net, rule);
525 		if (IS_ERR(flow)) {
526 			nft_trans_destroy(trans);
527 			return PTR_ERR(flow);
528 		}
529 
530 		nft_trans_flow_rule(trans) = flow;
531 	}
532 
533 	err = nf_tables_delrule_deactivate(ctx, rule);
534 	if (err < 0) {
535 		nft_trans_destroy(trans);
536 		return err;
537 	}
538 	nft_rule_expr_deactivate(ctx, rule, NFT_TRANS_PREPARE);
539 
540 	return 0;
541 }
542 
nft_delrule_by_chain(struct nft_ctx * ctx)543 static int nft_delrule_by_chain(struct nft_ctx *ctx)
544 {
545 	struct nft_rule *rule;
546 	int err;
547 
548 	list_for_each_entry(rule, &ctx->chain->rules, list) {
549 		if (!nft_is_active_next(ctx->net, rule))
550 			continue;
551 
552 		err = nft_delrule(ctx, rule);
553 		if (err < 0)
554 			return err;
555 	}
556 	return 0;
557 }
558 
__nft_trans_set_add(const struct nft_ctx * ctx,int msg_type,struct nft_set * set,const struct nft_set_desc * desc)559 static int __nft_trans_set_add(const struct nft_ctx *ctx, int msg_type,
560 			       struct nft_set *set,
561 			       const struct nft_set_desc *desc)
562 {
563 	struct nft_trans *trans;
564 
565 	trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_set));
566 	if (trans == NULL)
567 		return -ENOMEM;
568 
569 	if (msg_type == NFT_MSG_NEWSET && ctx->nla[NFTA_SET_ID] && !desc) {
570 		nft_trans_set_id(trans) =
571 			ntohl(nla_get_be32(ctx->nla[NFTA_SET_ID]));
572 		nft_activate_next(ctx->net, set);
573 	}
574 	nft_trans_set(trans) = set;
575 	if (desc) {
576 		nft_trans_set_update(trans) = true;
577 		nft_trans_set_gc_int(trans) = desc->gc_int;
578 		nft_trans_set_timeout(trans) = desc->timeout;
579 		nft_trans_set_size(trans) = desc->size;
580 	}
581 	nft_trans_commit_list_add_tail(ctx->net, trans);
582 
583 	return 0;
584 }
585 
nft_trans_set_add(const struct nft_ctx * ctx,int msg_type,struct nft_set * set)586 static int nft_trans_set_add(const struct nft_ctx *ctx, int msg_type,
587 			     struct nft_set *set)
588 {
589 	return __nft_trans_set_add(ctx, msg_type, set, NULL);
590 }
591 
nft_mapelem_deactivate(const struct nft_ctx * ctx,struct nft_set * set,const struct nft_set_iter * iter,struct nft_set_elem * elem)592 static int nft_mapelem_deactivate(const struct nft_ctx *ctx,
593 				  struct nft_set *set,
594 				  const struct nft_set_iter *iter,
595 				  struct nft_set_elem *elem)
596 {
597 	struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
598 
599 	if (!nft_set_elem_active(ext, iter->genmask))
600 		return 0;
601 
602 	nft_set_elem_change_active(ctx->net, set, ext);
603 	nft_setelem_data_deactivate(ctx->net, set, elem);
604 
605 	return 0;
606 }
607 
608 struct nft_set_elem_catchall {
609 	struct list_head	list;
610 	struct rcu_head		rcu;
611 	void			*elem;
612 };
613 
nft_map_catchall_deactivate(const struct nft_ctx * ctx,struct nft_set * set)614 static void nft_map_catchall_deactivate(const struct nft_ctx *ctx,
615 					struct nft_set *set)
616 {
617 	u8 genmask = nft_genmask_next(ctx->net);
618 	struct nft_set_elem_catchall *catchall;
619 	struct nft_set_elem elem;
620 	struct nft_set_ext *ext;
621 
622 	list_for_each_entry(catchall, &set->catchall_list, list) {
623 		ext = nft_set_elem_ext(set, catchall->elem);
624 		if (!nft_set_elem_active(ext, genmask))
625 			continue;
626 
627 		elem.priv = catchall->elem;
628 		nft_set_elem_change_active(ctx->net, set, ext);
629 		nft_setelem_data_deactivate(ctx->net, set, &elem);
630 		break;
631 	}
632 }
633 
nft_map_deactivate(const struct nft_ctx * ctx,struct nft_set * set)634 static void nft_map_deactivate(const struct nft_ctx *ctx, struct nft_set *set)
635 {
636 	struct nft_set_iter iter = {
637 		.genmask	= nft_genmask_next(ctx->net),
638 		.type		= NFT_ITER_UPDATE,
639 		.fn		= nft_mapelem_deactivate,
640 	};
641 
642 	set->ops->walk(ctx, set, &iter);
643 	WARN_ON_ONCE(iter.err);
644 
645 	nft_map_catchall_deactivate(ctx, set);
646 }
647 
nft_delset(const struct nft_ctx * ctx,struct nft_set * set)648 static int nft_delset(const struct nft_ctx *ctx, struct nft_set *set)
649 {
650 	int err;
651 
652 	err = nft_trans_set_add(ctx, NFT_MSG_DELSET, set);
653 	if (err < 0)
654 		return err;
655 
656 	if (set->flags & (NFT_SET_MAP | NFT_SET_OBJECT))
657 		nft_map_deactivate(ctx, set);
658 
659 	nft_deactivate_next(ctx->net, set);
660 	nft_use_dec(&ctx->table->use);
661 
662 	return err;
663 }
664 
nft_trans_obj_add(struct nft_ctx * ctx,int msg_type,struct nft_object * obj)665 static int nft_trans_obj_add(struct nft_ctx *ctx, int msg_type,
666 			     struct nft_object *obj)
667 {
668 	struct nft_trans *trans;
669 
670 	trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_obj));
671 	if (trans == NULL)
672 		return -ENOMEM;
673 
674 	if (msg_type == NFT_MSG_NEWOBJ)
675 		nft_activate_next(ctx->net, obj);
676 
677 	nft_trans_obj(trans) = obj;
678 	nft_trans_commit_list_add_tail(ctx->net, trans);
679 
680 	return 0;
681 }
682 
nft_delobj(struct nft_ctx * ctx,struct nft_object * obj)683 static int nft_delobj(struct nft_ctx *ctx, struct nft_object *obj)
684 {
685 	int err;
686 
687 	err = nft_trans_obj_add(ctx, NFT_MSG_DELOBJ, obj);
688 	if (err < 0)
689 		return err;
690 
691 	nft_deactivate_next(ctx->net, obj);
692 	nft_use_dec(&ctx->table->use);
693 
694 	return err;
695 }
696 
697 static struct nft_trans *
nft_trans_flowtable_add(struct nft_ctx * ctx,int msg_type,struct nft_flowtable * flowtable)698 nft_trans_flowtable_add(struct nft_ctx *ctx, int msg_type,
699 		        struct nft_flowtable *flowtable)
700 {
701 	struct nft_trans *trans;
702 
703 	trans = nft_trans_alloc(ctx, msg_type,
704 				sizeof(struct nft_trans_flowtable));
705 	if (trans == NULL)
706 		return ERR_PTR(-ENOMEM);
707 
708 	if (msg_type == NFT_MSG_NEWFLOWTABLE)
709 		nft_activate_next(ctx->net, flowtable);
710 
711 	INIT_LIST_HEAD(&nft_trans_flowtable_hooks(trans));
712 	nft_trans_flowtable(trans) = flowtable;
713 	nft_trans_commit_list_add_tail(ctx->net, trans);
714 
715 	return trans;
716 }
717 
nft_delflowtable(struct nft_ctx * ctx,struct nft_flowtable * flowtable)718 static int nft_delflowtable(struct nft_ctx *ctx,
719 			    struct nft_flowtable *flowtable)
720 {
721 	struct nft_trans *trans;
722 
723 	trans = nft_trans_flowtable_add(ctx, NFT_MSG_DELFLOWTABLE, flowtable);
724 	if (IS_ERR(trans))
725 		return PTR_ERR(trans);
726 
727 	nft_deactivate_next(ctx->net, flowtable);
728 	nft_use_dec(&ctx->table->use);
729 
730 	return 0;
731 }
732 
__nft_reg_track_clobber(struct nft_regs_track * track,u8 dreg)733 static void __nft_reg_track_clobber(struct nft_regs_track *track, u8 dreg)
734 {
735 	int i;
736 
737 	for (i = track->regs[dreg].num_reg; i > 0; i--)
738 		__nft_reg_track_cancel(track, dreg - i);
739 }
740 
__nft_reg_track_update(struct nft_regs_track * track,const struct nft_expr * expr,u8 dreg,u8 num_reg)741 static void __nft_reg_track_update(struct nft_regs_track *track,
742 				   const struct nft_expr *expr,
743 				   u8 dreg, u8 num_reg)
744 {
745 	track->regs[dreg].selector = expr;
746 	track->regs[dreg].bitwise = NULL;
747 	track->regs[dreg].num_reg = num_reg;
748 }
749 
nft_reg_track_update(struct nft_regs_track * track,const struct nft_expr * expr,u8 dreg,u8 len)750 void nft_reg_track_update(struct nft_regs_track *track,
751 			  const struct nft_expr *expr, u8 dreg, u8 len)
752 {
753 	unsigned int regcount;
754 	int i;
755 
756 	__nft_reg_track_clobber(track, dreg);
757 
758 	regcount = DIV_ROUND_UP(len, NFT_REG32_SIZE);
759 	for (i = 0; i < regcount; i++, dreg++)
760 		__nft_reg_track_update(track, expr, dreg, i);
761 }
762 EXPORT_SYMBOL_GPL(nft_reg_track_update);
763 
nft_reg_track_cancel(struct nft_regs_track * track,u8 dreg,u8 len)764 void nft_reg_track_cancel(struct nft_regs_track *track, u8 dreg, u8 len)
765 {
766 	unsigned int regcount;
767 	int i;
768 
769 	__nft_reg_track_clobber(track, dreg);
770 
771 	regcount = DIV_ROUND_UP(len, NFT_REG32_SIZE);
772 	for (i = 0; i < regcount; i++, dreg++)
773 		__nft_reg_track_cancel(track, dreg);
774 }
775 EXPORT_SYMBOL_GPL(nft_reg_track_cancel);
776 
__nft_reg_track_cancel(struct nft_regs_track * track,u8 dreg)777 void __nft_reg_track_cancel(struct nft_regs_track *track, u8 dreg)
778 {
779 	track->regs[dreg].selector = NULL;
780 	track->regs[dreg].bitwise = NULL;
781 	track->regs[dreg].num_reg = 0;
782 }
783 EXPORT_SYMBOL_GPL(__nft_reg_track_cancel);
784 
785 /*
786  * Tables
787  */
788 
nft_table_lookup(const struct net * net,const struct nlattr * nla,u8 family,u8 genmask,u32 nlpid)789 static struct nft_table *nft_table_lookup(const struct net *net,
790 					  const struct nlattr *nla,
791 					  u8 family, u8 genmask, u32 nlpid)
792 {
793 	struct nftables_pernet *nft_net;
794 	struct nft_table *table;
795 
796 	if (nla == NULL)
797 		return ERR_PTR(-EINVAL);
798 
799 	nft_net = nft_pernet(net);
800 	list_for_each_entry_rcu(table, &nft_net->tables, list,
801 				lockdep_is_held(&nft_net->commit_mutex)) {
802 		if (!nla_strcmp(nla, table->name) &&
803 		    table->family == family &&
804 		    nft_active_genmask(table, genmask)) {
805 			if (nft_table_has_owner(table) &&
806 			    nlpid && table->nlpid != nlpid)
807 				return ERR_PTR(-EPERM);
808 
809 			return table;
810 		}
811 	}
812 
813 	return ERR_PTR(-ENOENT);
814 }
815 
nft_table_lookup_byhandle(const struct net * net,const struct nlattr * nla,int family,u8 genmask,u32 nlpid)816 static struct nft_table *nft_table_lookup_byhandle(const struct net *net,
817 						   const struct nlattr *nla,
818 						   int family, u8 genmask, u32 nlpid)
819 {
820 	struct nftables_pernet *nft_net;
821 	struct nft_table *table;
822 
823 	nft_net = nft_pernet(net);
824 	list_for_each_entry(table, &nft_net->tables, list) {
825 		if (be64_to_cpu(nla_get_be64(nla)) == table->handle &&
826 		    table->family == family &&
827 		    nft_active_genmask(table, genmask)) {
828 			if (nft_table_has_owner(table) &&
829 			    nlpid && table->nlpid != nlpid)
830 				return ERR_PTR(-EPERM);
831 
832 			return table;
833 		}
834 	}
835 
836 	return ERR_PTR(-ENOENT);
837 }
838 
nf_tables_alloc_handle(struct nft_table * table)839 static inline u64 nf_tables_alloc_handle(struct nft_table *table)
840 {
841 	return ++table->hgenerator;
842 }
843 
844 static const struct nft_chain_type *chain_type[NFPROTO_NUMPROTO][NFT_CHAIN_T_MAX];
845 
846 static const struct nft_chain_type *
__nft_chain_type_get(u8 family,enum nft_chain_types type)847 __nft_chain_type_get(u8 family, enum nft_chain_types type)
848 {
849 	if (family >= NFPROTO_NUMPROTO ||
850 	    type >= NFT_CHAIN_T_MAX)
851 		return NULL;
852 
853 	return chain_type[family][type];
854 }
855 
856 static const struct nft_chain_type *
__nf_tables_chain_type_lookup(const struct nlattr * nla,u8 family)857 __nf_tables_chain_type_lookup(const struct nlattr *nla, u8 family)
858 {
859 	const struct nft_chain_type *type;
860 	int i;
861 
862 	for (i = 0; i < NFT_CHAIN_T_MAX; i++) {
863 		type = __nft_chain_type_get(family, i);
864 		if (!type)
865 			continue;
866 		if (!nla_strcmp(nla, type->name))
867 			return type;
868 	}
869 	return NULL;
870 }
871 
872 struct nft_module_request {
873 	struct list_head	list;
874 	char			module[MODULE_NAME_LEN];
875 	bool			done;
876 };
877 
878 #ifdef CONFIG_MODULES
nft_request_module(struct net * net,const char * fmt,...)879 __printf(2, 3) int nft_request_module(struct net *net, const char *fmt,
880 				      ...)
881 {
882 	char module_name[MODULE_NAME_LEN];
883 	struct nftables_pernet *nft_net;
884 	struct nft_module_request *req;
885 	va_list args;
886 	int ret;
887 
888 	va_start(args, fmt);
889 	ret = vsnprintf(module_name, MODULE_NAME_LEN, fmt, args);
890 	va_end(args);
891 	if (ret >= MODULE_NAME_LEN)
892 		return 0;
893 
894 	nft_net = nft_pernet(net);
895 	list_for_each_entry(req, &nft_net->module_list, list) {
896 		if (!strcmp(req->module, module_name)) {
897 			if (req->done)
898 				return 0;
899 
900 			/* A request to load this module already exists. */
901 			return -EAGAIN;
902 		}
903 	}
904 
905 	req = kmalloc(sizeof(*req), GFP_KERNEL);
906 	if (!req)
907 		return -ENOMEM;
908 
909 	req->done = false;
910 	strscpy(req->module, module_name, MODULE_NAME_LEN);
911 	list_add_tail(&req->list, &nft_net->module_list);
912 
913 	return -EAGAIN;
914 }
915 EXPORT_SYMBOL_GPL(nft_request_module);
916 #endif
917 
lockdep_nfnl_nft_mutex_not_held(void)918 static void lockdep_nfnl_nft_mutex_not_held(void)
919 {
920 #ifdef CONFIG_PROVE_LOCKING
921 	if (debug_locks)
922 		WARN_ON_ONCE(lockdep_nfnl_is_held(NFNL_SUBSYS_NFTABLES));
923 #endif
924 }
925 
926 static const struct nft_chain_type *
nf_tables_chain_type_lookup(struct net * net,const struct nlattr * nla,u8 family,bool autoload)927 nf_tables_chain_type_lookup(struct net *net, const struct nlattr *nla,
928 			    u8 family, bool autoload)
929 {
930 	const struct nft_chain_type *type;
931 
932 	type = __nf_tables_chain_type_lookup(nla, family);
933 	if (type != NULL)
934 		return type;
935 
936 	lockdep_nfnl_nft_mutex_not_held();
937 #ifdef CONFIG_MODULES
938 	if (autoload) {
939 		if (nft_request_module(net, "nft-chain-%u-%.*s", family,
940 				       nla_len(nla),
941 				       (const char *)nla_data(nla)) == -EAGAIN)
942 			return ERR_PTR(-EAGAIN);
943 	}
944 #endif
945 	return ERR_PTR(-ENOENT);
946 }
947 
nft_base_seq(const struct net * net)948 static __be16 nft_base_seq(const struct net *net)
949 {
950 	struct nftables_pernet *nft_net = nft_pernet(net);
951 
952 	return htons(nft_net->base_seq & 0xffff);
953 }
954 
955 static const struct nla_policy nft_table_policy[NFTA_TABLE_MAX + 1] = {
956 	[NFTA_TABLE_NAME]	= { .type = NLA_STRING,
957 				    .len = NFT_TABLE_MAXNAMELEN - 1 },
958 	[NFTA_TABLE_FLAGS]	= { .type = NLA_U32 },
959 	[NFTA_TABLE_HANDLE]	= { .type = NLA_U64 },
960 	[NFTA_TABLE_USERDATA]	= { .type = NLA_BINARY,
961 				    .len = NFT_USERDATA_MAXLEN }
962 };
963 
nf_tables_fill_table_info(struct sk_buff * skb,struct net * net,u32 portid,u32 seq,int event,u32 flags,int family,const struct nft_table * table)964 static int nf_tables_fill_table_info(struct sk_buff *skb, struct net *net,
965 				     u32 portid, u32 seq, int event, u32 flags,
966 				     int family, const struct nft_table *table)
967 {
968 	struct nlmsghdr *nlh;
969 
970 	event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
971 	nlh = nfnl_msg_put(skb, portid, seq, event, flags, family,
972 			   NFNETLINK_V0, nft_base_seq(net));
973 	if (!nlh)
974 		goto nla_put_failure;
975 
976 	if (nla_put_string(skb, NFTA_TABLE_NAME, table->name) ||
977 	    nla_put_be32(skb, NFTA_TABLE_USE, htonl(table->use)) ||
978 	    nla_put_be64(skb, NFTA_TABLE_HANDLE, cpu_to_be64(table->handle),
979 			 NFTA_TABLE_PAD))
980 		goto nla_put_failure;
981 
982 	if (event == NFT_MSG_DELTABLE) {
983 		nlmsg_end(skb, nlh);
984 		return 0;
985 	}
986 
987 	if (nla_put_be32(skb, NFTA_TABLE_FLAGS,
988 			 htonl(table->flags & NFT_TABLE_F_MASK)))
989 		goto nla_put_failure;
990 
991 	if (nft_table_has_owner(table) &&
992 	    nla_put_be32(skb, NFTA_TABLE_OWNER, htonl(table->nlpid)))
993 		goto nla_put_failure;
994 
995 	if (table->udata) {
996 		if (nla_put(skb, NFTA_TABLE_USERDATA, table->udlen, table->udata))
997 			goto nla_put_failure;
998 	}
999 
1000 	nlmsg_end(skb, nlh);
1001 	return 0;
1002 
1003 nla_put_failure:
1004 	nlmsg_trim(skb, nlh);
1005 	return -1;
1006 }
1007 
1008 struct nftnl_skb_parms {
1009 	bool report;
1010 };
1011 #define NFT_CB(skb)	(*(struct nftnl_skb_parms*)&((skb)->cb))
1012 
nft_notify_enqueue(struct sk_buff * skb,bool report,struct list_head * notify_list)1013 static void nft_notify_enqueue(struct sk_buff *skb, bool report,
1014 			       struct list_head *notify_list)
1015 {
1016 	NFT_CB(skb).report = report;
1017 	list_add_tail(&skb->list, notify_list);
1018 }
1019 
nf_tables_table_notify(const struct nft_ctx * ctx,int event)1020 static void nf_tables_table_notify(const struct nft_ctx *ctx, int event)
1021 {
1022 	struct nftables_pernet *nft_net;
1023 	struct sk_buff *skb;
1024 	u16 flags = 0;
1025 	int err;
1026 
1027 	if (!ctx->report &&
1028 	    !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
1029 		return;
1030 
1031 	skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
1032 	if (skb == NULL)
1033 		goto err;
1034 
1035 	if (ctx->flags & (NLM_F_CREATE | NLM_F_EXCL))
1036 		flags |= ctx->flags & (NLM_F_CREATE | NLM_F_EXCL);
1037 
1038 	err = nf_tables_fill_table_info(skb, ctx->net, ctx->portid, ctx->seq,
1039 					event, flags, ctx->family, ctx->table);
1040 	if (err < 0) {
1041 		kfree_skb(skb);
1042 		goto err;
1043 	}
1044 
1045 	nft_net = nft_pernet(ctx->net);
1046 	nft_notify_enqueue(skb, ctx->report, &nft_net->notify_list);
1047 	return;
1048 err:
1049 	nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
1050 }
1051 
nf_tables_dump_tables(struct sk_buff * skb,struct netlink_callback * cb)1052 static int nf_tables_dump_tables(struct sk_buff *skb,
1053 				 struct netlink_callback *cb)
1054 {
1055 	const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
1056 	struct nftables_pernet *nft_net;
1057 	const struct nft_table *table;
1058 	unsigned int idx = 0, s_idx = cb->args[0];
1059 	struct net *net = sock_net(skb->sk);
1060 	int family = nfmsg->nfgen_family;
1061 
1062 	rcu_read_lock();
1063 	nft_net = nft_pernet(net);
1064 	cb->seq = READ_ONCE(nft_net->base_seq);
1065 
1066 	list_for_each_entry_rcu(table, &nft_net->tables, list) {
1067 		if (family != NFPROTO_UNSPEC && family != table->family)
1068 			continue;
1069 
1070 		if (idx < s_idx)
1071 			goto cont;
1072 		if (idx > s_idx)
1073 			memset(&cb->args[1], 0,
1074 			       sizeof(cb->args) - sizeof(cb->args[0]));
1075 		if (!nft_is_active(net, table))
1076 			continue;
1077 		if (nf_tables_fill_table_info(skb, net,
1078 					      NETLINK_CB(cb->skb).portid,
1079 					      cb->nlh->nlmsg_seq,
1080 					      NFT_MSG_NEWTABLE, NLM_F_MULTI,
1081 					      table->family, table) < 0)
1082 			goto done;
1083 
1084 		nl_dump_check_consistent(cb, nlmsg_hdr(skb));
1085 cont:
1086 		idx++;
1087 	}
1088 done:
1089 	rcu_read_unlock();
1090 	cb->args[0] = idx;
1091 	return skb->len;
1092 }
1093 
nft_netlink_dump_start_rcu(struct sock * nlsk,struct sk_buff * skb,const struct nlmsghdr * nlh,struct netlink_dump_control * c)1094 static int nft_netlink_dump_start_rcu(struct sock *nlsk, struct sk_buff *skb,
1095 				      const struct nlmsghdr *nlh,
1096 				      struct netlink_dump_control *c)
1097 {
1098 	int err;
1099 
1100 	if (!try_module_get(THIS_MODULE))
1101 		return -EINVAL;
1102 
1103 	rcu_read_unlock();
1104 	err = netlink_dump_start(nlsk, skb, nlh, c);
1105 	rcu_read_lock();
1106 	module_put(THIS_MODULE);
1107 
1108 	return err;
1109 }
1110 
1111 /* called with rcu_read_lock held */
nf_tables_gettable(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])1112 static int nf_tables_gettable(struct sk_buff *skb, const struct nfnl_info *info,
1113 			      const struct nlattr * const nla[])
1114 {
1115 	struct netlink_ext_ack *extack = info->extack;
1116 	u8 genmask = nft_genmask_cur(info->net);
1117 	u8 family = info->nfmsg->nfgen_family;
1118 	const struct nft_table *table;
1119 	struct net *net = info->net;
1120 	struct sk_buff *skb2;
1121 	int err;
1122 
1123 	if (info->nlh->nlmsg_flags & NLM_F_DUMP) {
1124 		struct netlink_dump_control c = {
1125 			.dump = nf_tables_dump_tables,
1126 			.module = THIS_MODULE,
1127 		};
1128 
1129 		return nft_netlink_dump_start_rcu(info->sk, skb, info->nlh, &c);
1130 	}
1131 
1132 	table = nft_table_lookup(net, nla[NFTA_TABLE_NAME], family, genmask, 0);
1133 	if (IS_ERR(table)) {
1134 		NL_SET_BAD_ATTR(extack, nla[NFTA_TABLE_NAME]);
1135 		return PTR_ERR(table);
1136 	}
1137 
1138 	skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
1139 	if (!skb2)
1140 		return -ENOMEM;
1141 
1142 	err = nf_tables_fill_table_info(skb2, net, NETLINK_CB(skb).portid,
1143 					info->nlh->nlmsg_seq, NFT_MSG_NEWTABLE,
1144 					0, family, table);
1145 	if (err < 0)
1146 		goto err_fill_table_info;
1147 
1148 	return nfnetlink_unicast(skb2, net, NETLINK_CB(skb).portid);
1149 
1150 err_fill_table_info:
1151 	kfree_skb(skb2);
1152 	return err;
1153 }
1154 
nft_table_disable(struct net * net,struct nft_table * table,u32 cnt)1155 static void nft_table_disable(struct net *net, struct nft_table *table, u32 cnt)
1156 {
1157 	struct nft_chain *chain;
1158 	u32 i = 0;
1159 
1160 	list_for_each_entry(chain, &table->chains, list) {
1161 		if (!nft_is_active_next(net, chain))
1162 			continue;
1163 		if (!nft_is_base_chain(chain))
1164 			continue;
1165 
1166 		if (cnt && i++ == cnt)
1167 			break;
1168 
1169 		nf_tables_unregister_hook(net, table, chain);
1170 	}
1171 }
1172 
nf_tables_table_enable(struct net * net,struct nft_table * table)1173 static int nf_tables_table_enable(struct net *net, struct nft_table *table)
1174 {
1175 	struct nft_chain *chain;
1176 	int err, i = 0;
1177 
1178 	list_for_each_entry(chain, &table->chains, list) {
1179 		if (!nft_is_active_next(net, chain))
1180 			continue;
1181 		if (!nft_is_base_chain(chain))
1182 			continue;
1183 
1184 		err = nf_tables_register_hook(net, table, chain);
1185 		if (err < 0)
1186 			goto err_register_hooks;
1187 
1188 		i++;
1189 	}
1190 	return 0;
1191 
1192 err_register_hooks:
1193 	if (i)
1194 		nft_table_disable(net, table, i);
1195 	return err;
1196 }
1197 
nf_tables_table_disable(struct net * net,struct nft_table * table)1198 static void nf_tables_table_disable(struct net *net, struct nft_table *table)
1199 {
1200 	table->flags &= ~NFT_TABLE_F_DORMANT;
1201 	nft_table_disable(net, table, 0);
1202 	table->flags |= NFT_TABLE_F_DORMANT;
1203 }
1204 
1205 #define __NFT_TABLE_F_INTERNAL		(NFT_TABLE_F_MASK + 1)
1206 #define __NFT_TABLE_F_WAS_DORMANT	(__NFT_TABLE_F_INTERNAL << 0)
1207 #define __NFT_TABLE_F_WAS_AWAKEN	(__NFT_TABLE_F_INTERNAL << 1)
1208 #define __NFT_TABLE_F_UPDATE		(__NFT_TABLE_F_WAS_DORMANT | \
1209 					 __NFT_TABLE_F_WAS_AWAKEN)
1210 
nft_table_pending_update(const struct nft_ctx * ctx)1211 static bool nft_table_pending_update(const struct nft_ctx *ctx)
1212 {
1213 	struct nftables_pernet *nft_net = nft_pernet(ctx->net);
1214 	struct nft_trans *trans;
1215 
1216 	if (ctx->table->flags & __NFT_TABLE_F_UPDATE)
1217 		return true;
1218 
1219 	list_for_each_entry(trans, &nft_net->commit_list, list) {
1220 		if (trans->ctx.table == ctx->table &&
1221 		    ((trans->msg_type == NFT_MSG_NEWCHAIN &&
1222 		      nft_trans_chain_update(trans)) ||
1223 		     (trans->msg_type == NFT_MSG_DELCHAIN &&
1224 		      nft_is_base_chain(trans->ctx.chain))))
1225 			return true;
1226 	}
1227 
1228 	return false;
1229 }
1230 
nf_tables_updtable(struct nft_ctx * ctx)1231 static int nf_tables_updtable(struct nft_ctx *ctx)
1232 {
1233 	struct nft_trans *trans;
1234 	u32 flags;
1235 	int ret;
1236 
1237 	if (!ctx->nla[NFTA_TABLE_FLAGS])
1238 		return 0;
1239 
1240 	flags = ntohl(nla_get_be32(ctx->nla[NFTA_TABLE_FLAGS]));
1241 	if (flags & ~NFT_TABLE_F_MASK)
1242 		return -EOPNOTSUPP;
1243 
1244 	if (flags == (ctx->table->flags & NFT_TABLE_F_MASK))
1245 		return 0;
1246 
1247 	if ((nft_table_has_owner(ctx->table) &&
1248 	     !(flags & NFT_TABLE_F_OWNER)) ||
1249 	    (!nft_table_has_owner(ctx->table) &&
1250 	     flags & NFT_TABLE_F_OWNER))
1251 		return -EOPNOTSUPP;
1252 
1253 	/* No dormant off/on/off/on games in single transaction */
1254 	if (nft_table_pending_update(ctx))
1255 		return -EINVAL;
1256 
1257 	trans = nft_trans_alloc(ctx, NFT_MSG_NEWTABLE,
1258 				sizeof(struct nft_trans_table));
1259 	if (trans == NULL)
1260 		return -ENOMEM;
1261 
1262 	if ((flags & NFT_TABLE_F_DORMANT) &&
1263 	    !(ctx->table->flags & NFT_TABLE_F_DORMANT)) {
1264 		ctx->table->flags |= NFT_TABLE_F_DORMANT;
1265 		if (!(ctx->table->flags & __NFT_TABLE_F_UPDATE))
1266 			ctx->table->flags |= __NFT_TABLE_F_WAS_AWAKEN;
1267 	} else if (!(flags & NFT_TABLE_F_DORMANT) &&
1268 		   ctx->table->flags & NFT_TABLE_F_DORMANT) {
1269 		ctx->table->flags &= ~NFT_TABLE_F_DORMANT;
1270 		if (!(ctx->table->flags & __NFT_TABLE_F_UPDATE)) {
1271 			ret = nf_tables_table_enable(ctx->net, ctx->table);
1272 			if (ret < 0)
1273 				goto err_register_hooks;
1274 
1275 			ctx->table->flags |= __NFT_TABLE_F_WAS_DORMANT;
1276 		}
1277 	}
1278 
1279 	nft_trans_table_update(trans) = true;
1280 	nft_trans_commit_list_add_tail(ctx->net, trans);
1281 
1282 	return 0;
1283 
1284 err_register_hooks:
1285 	ctx->table->flags |= NFT_TABLE_F_DORMANT;
1286 	nft_trans_destroy(trans);
1287 	return ret;
1288 }
1289 
nft_chain_hash(const void * data,u32 len,u32 seed)1290 static u32 nft_chain_hash(const void *data, u32 len, u32 seed)
1291 {
1292 	const char *name = data;
1293 
1294 	return jhash(name, strlen(name), seed);
1295 }
1296 
nft_chain_hash_obj(const void * data,u32 len,u32 seed)1297 static u32 nft_chain_hash_obj(const void *data, u32 len, u32 seed)
1298 {
1299 	const struct nft_chain *chain = data;
1300 
1301 	return nft_chain_hash(chain->name, 0, seed);
1302 }
1303 
nft_chain_hash_cmp(struct rhashtable_compare_arg * arg,const void * ptr)1304 static int nft_chain_hash_cmp(struct rhashtable_compare_arg *arg,
1305 			      const void *ptr)
1306 {
1307 	const struct nft_chain *chain = ptr;
1308 	const char *name = arg->key;
1309 
1310 	return strcmp(chain->name, name);
1311 }
1312 
nft_objname_hash(const void * data,u32 len,u32 seed)1313 static u32 nft_objname_hash(const void *data, u32 len, u32 seed)
1314 {
1315 	const struct nft_object_hash_key *k = data;
1316 
1317 	seed ^= hash_ptr(k->table, 32);
1318 
1319 	return jhash(k->name, strlen(k->name), seed);
1320 }
1321 
nft_objname_hash_obj(const void * data,u32 len,u32 seed)1322 static u32 nft_objname_hash_obj(const void *data, u32 len, u32 seed)
1323 {
1324 	const struct nft_object *obj = data;
1325 
1326 	return nft_objname_hash(&obj->key, 0, seed);
1327 }
1328 
nft_objname_hash_cmp(struct rhashtable_compare_arg * arg,const void * ptr)1329 static int nft_objname_hash_cmp(struct rhashtable_compare_arg *arg,
1330 				const void *ptr)
1331 {
1332 	const struct nft_object_hash_key *k = arg->key;
1333 	const struct nft_object *obj = ptr;
1334 
1335 	if (obj->key.table != k->table)
1336 		return -1;
1337 
1338 	return strcmp(obj->key.name, k->name);
1339 }
1340 
nft_supported_family(u8 family)1341 static bool nft_supported_family(u8 family)
1342 {
1343 	return false
1344 #ifdef CONFIG_NF_TABLES_INET
1345 		|| family == NFPROTO_INET
1346 #endif
1347 #ifdef CONFIG_NF_TABLES_IPV4
1348 		|| family == NFPROTO_IPV4
1349 #endif
1350 #ifdef CONFIG_NF_TABLES_ARP
1351 		|| family == NFPROTO_ARP
1352 #endif
1353 #ifdef CONFIG_NF_TABLES_NETDEV
1354 		|| family == NFPROTO_NETDEV
1355 #endif
1356 #if IS_ENABLED(CONFIG_NF_TABLES_BRIDGE)
1357 		|| family == NFPROTO_BRIDGE
1358 #endif
1359 #ifdef CONFIG_NF_TABLES_IPV6
1360 		|| family == NFPROTO_IPV6
1361 #endif
1362 		;
1363 }
1364 
nf_tables_newtable(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])1365 static int nf_tables_newtable(struct sk_buff *skb, const struct nfnl_info *info,
1366 			      const struct nlattr * const nla[])
1367 {
1368 	struct nftables_pernet *nft_net = nft_pernet(info->net);
1369 	struct netlink_ext_ack *extack = info->extack;
1370 	u8 genmask = nft_genmask_next(info->net);
1371 	u8 family = info->nfmsg->nfgen_family;
1372 	struct net *net = info->net;
1373 	const struct nlattr *attr;
1374 	struct nft_table *table;
1375 	struct nft_ctx ctx;
1376 	u32 flags = 0;
1377 	int err;
1378 
1379 	if (!nft_supported_family(family))
1380 		return -EOPNOTSUPP;
1381 
1382 	lockdep_assert_held(&nft_net->commit_mutex);
1383 	attr = nla[NFTA_TABLE_NAME];
1384 	table = nft_table_lookup(net, attr, family, genmask,
1385 				 NETLINK_CB(skb).portid);
1386 	if (IS_ERR(table)) {
1387 		if (PTR_ERR(table) != -ENOENT)
1388 			return PTR_ERR(table);
1389 	} else {
1390 		if (info->nlh->nlmsg_flags & NLM_F_EXCL) {
1391 			NL_SET_BAD_ATTR(extack, attr);
1392 			return -EEXIST;
1393 		}
1394 		if (info->nlh->nlmsg_flags & NLM_F_REPLACE)
1395 			return -EOPNOTSUPP;
1396 
1397 		nft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);
1398 
1399 		return nf_tables_updtable(&ctx);
1400 	}
1401 
1402 	if (nla[NFTA_TABLE_FLAGS]) {
1403 		flags = ntohl(nla_get_be32(nla[NFTA_TABLE_FLAGS]));
1404 		if (flags & ~NFT_TABLE_F_MASK)
1405 			return -EOPNOTSUPP;
1406 	}
1407 
1408 	err = -ENOMEM;
1409 	table = kzalloc(sizeof(*table), GFP_KERNEL_ACCOUNT);
1410 	if (table == NULL)
1411 		goto err_kzalloc;
1412 
1413 	table->validate_state = nft_net->validate_state;
1414 	table->name = nla_strdup(attr, GFP_KERNEL_ACCOUNT);
1415 	if (table->name == NULL)
1416 		goto err_strdup;
1417 
1418 	if (nla[NFTA_TABLE_USERDATA]) {
1419 		table->udata = nla_memdup(nla[NFTA_TABLE_USERDATA], GFP_KERNEL_ACCOUNT);
1420 		if (table->udata == NULL)
1421 			goto err_table_udata;
1422 
1423 		table->udlen = nla_len(nla[NFTA_TABLE_USERDATA]);
1424 	}
1425 
1426 	err = rhltable_init(&table->chains_ht, &nft_chain_ht_params);
1427 	if (err)
1428 		goto err_chain_ht;
1429 
1430 	INIT_LIST_HEAD(&table->chains);
1431 	INIT_LIST_HEAD(&table->sets);
1432 	INIT_LIST_HEAD(&table->objects);
1433 	INIT_LIST_HEAD(&table->flowtables);
1434 	table->family = family;
1435 	table->flags = flags;
1436 	table->handle = ++nft_net->table_handle;
1437 	if (table->flags & NFT_TABLE_F_OWNER)
1438 		table->nlpid = NETLINK_CB(skb).portid;
1439 
1440 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);
1441 	err = nft_trans_table_add(&ctx, NFT_MSG_NEWTABLE);
1442 	if (err < 0)
1443 		goto err_trans;
1444 
1445 	list_add_tail_rcu(&table->list, &nft_net->tables);
1446 	return 0;
1447 err_trans:
1448 	rhltable_destroy(&table->chains_ht);
1449 err_chain_ht:
1450 	kfree(table->udata);
1451 err_table_udata:
1452 	kfree(table->name);
1453 err_strdup:
1454 	kfree(table);
1455 err_kzalloc:
1456 	return err;
1457 }
1458 
nft_flush_table(struct nft_ctx * ctx)1459 static int nft_flush_table(struct nft_ctx *ctx)
1460 {
1461 	struct nft_flowtable *flowtable, *nft;
1462 	struct nft_chain *chain, *nc;
1463 	struct nft_object *obj, *ne;
1464 	struct nft_set *set, *ns;
1465 	int err;
1466 
1467 	list_for_each_entry(chain, &ctx->table->chains, list) {
1468 		if (!nft_is_active_next(ctx->net, chain))
1469 			continue;
1470 
1471 		if (nft_chain_binding(chain))
1472 			continue;
1473 
1474 		ctx->chain = chain;
1475 
1476 		err = nft_delrule_by_chain(ctx);
1477 		if (err < 0)
1478 			goto out;
1479 	}
1480 
1481 	list_for_each_entry_safe(set, ns, &ctx->table->sets, list) {
1482 		if (!nft_is_active_next(ctx->net, set))
1483 			continue;
1484 
1485 		if (nft_set_is_anonymous(set))
1486 			continue;
1487 
1488 		err = nft_delset(ctx, set);
1489 		if (err < 0)
1490 			goto out;
1491 	}
1492 
1493 	list_for_each_entry_safe(flowtable, nft, &ctx->table->flowtables, list) {
1494 		if (!nft_is_active_next(ctx->net, flowtable))
1495 			continue;
1496 
1497 		err = nft_delflowtable(ctx, flowtable);
1498 		if (err < 0)
1499 			goto out;
1500 	}
1501 
1502 	list_for_each_entry_safe(obj, ne, &ctx->table->objects, list) {
1503 		if (!nft_is_active_next(ctx->net, obj))
1504 			continue;
1505 
1506 		err = nft_delobj(ctx, obj);
1507 		if (err < 0)
1508 			goto out;
1509 	}
1510 
1511 	list_for_each_entry_safe(chain, nc, &ctx->table->chains, list) {
1512 		if (!nft_is_active_next(ctx->net, chain))
1513 			continue;
1514 
1515 		if (nft_chain_binding(chain))
1516 			continue;
1517 
1518 		ctx->chain = chain;
1519 
1520 		err = nft_delchain(ctx);
1521 		if (err < 0)
1522 			goto out;
1523 	}
1524 
1525 	err = nft_deltable(ctx);
1526 out:
1527 	return err;
1528 }
1529 
nft_flush(struct nft_ctx * ctx,int family)1530 static int nft_flush(struct nft_ctx *ctx, int family)
1531 {
1532 	struct nftables_pernet *nft_net = nft_pernet(ctx->net);
1533 	const struct nlattr * const *nla = ctx->nla;
1534 	struct nft_table *table, *nt;
1535 	int err = 0;
1536 
1537 	list_for_each_entry_safe(table, nt, &nft_net->tables, list) {
1538 		if (family != AF_UNSPEC && table->family != family)
1539 			continue;
1540 
1541 		ctx->family = table->family;
1542 
1543 		if (!nft_is_active_next(ctx->net, table))
1544 			continue;
1545 
1546 		if (nft_table_has_owner(table) && table->nlpid != ctx->portid)
1547 			continue;
1548 
1549 		if (nla[NFTA_TABLE_NAME] &&
1550 		    nla_strcmp(nla[NFTA_TABLE_NAME], table->name) != 0)
1551 			continue;
1552 
1553 		ctx->table = table;
1554 
1555 		err = nft_flush_table(ctx);
1556 		if (err < 0)
1557 			goto out;
1558 	}
1559 out:
1560 	return err;
1561 }
1562 
nf_tables_deltable(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])1563 static int nf_tables_deltable(struct sk_buff *skb, const struct nfnl_info *info,
1564 			      const struct nlattr * const nla[])
1565 {
1566 	struct netlink_ext_ack *extack = info->extack;
1567 	u8 genmask = nft_genmask_next(info->net);
1568 	u8 family = info->nfmsg->nfgen_family;
1569 	struct net *net = info->net;
1570 	const struct nlattr *attr;
1571 	struct nft_table *table;
1572 	struct nft_ctx ctx;
1573 
1574 	nft_ctx_init(&ctx, net, skb, info->nlh, 0, NULL, NULL, nla);
1575 	if (family == AF_UNSPEC ||
1576 	    (!nla[NFTA_TABLE_NAME] && !nla[NFTA_TABLE_HANDLE]))
1577 		return nft_flush(&ctx, family);
1578 
1579 	if (nla[NFTA_TABLE_HANDLE]) {
1580 		attr = nla[NFTA_TABLE_HANDLE];
1581 		table = nft_table_lookup_byhandle(net, attr, family, genmask,
1582 						  NETLINK_CB(skb).portid);
1583 	} else {
1584 		attr = nla[NFTA_TABLE_NAME];
1585 		table = nft_table_lookup(net, attr, family, genmask,
1586 					 NETLINK_CB(skb).portid);
1587 	}
1588 
1589 	if (IS_ERR(table)) {
1590 		if (PTR_ERR(table) == -ENOENT &&
1591 		    NFNL_MSG_TYPE(info->nlh->nlmsg_type) == NFT_MSG_DESTROYTABLE)
1592 			return 0;
1593 
1594 		NL_SET_BAD_ATTR(extack, attr);
1595 		return PTR_ERR(table);
1596 	}
1597 
1598 	if (info->nlh->nlmsg_flags & NLM_F_NONREC &&
1599 	    table->use > 0)
1600 		return -EBUSY;
1601 
1602 	ctx.family = family;
1603 	ctx.table = table;
1604 
1605 	return nft_flush_table(&ctx);
1606 }
1607 
nf_tables_table_destroy(struct nft_ctx * ctx)1608 static void nf_tables_table_destroy(struct nft_ctx *ctx)
1609 {
1610 	if (WARN_ON(ctx->table->use > 0))
1611 		return;
1612 
1613 	rhltable_destroy(&ctx->table->chains_ht);
1614 	kfree(ctx->table->name);
1615 	kfree(ctx->table->udata);
1616 	kfree(ctx->table);
1617 }
1618 
nft_register_chain_type(const struct nft_chain_type * ctype)1619 void nft_register_chain_type(const struct nft_chain_type *ctype)
1620 {
1621 	nfnl_lock(NFNL_SUBSYS_NFTABLES);
1622 	if (WARN_ON(__nft_chain_type_get(ctype->family, ctype->type))) {
1623 		nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1624 		return;
1625 	}
1626 	chain_type[ctype->family][ctype->type] = ctype;
1627 	nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1628 }
1629 EXPORT_SYMBOL_GPL(nft_register_chain_type);
1630 
nft_unregister_chain_type(const struct nft_chain_type * ctype)1631 void nft_unregister_chain_type(const struct nft_chain_type *ctype)
1632 {
1633 	nfnl_lock(NFNL_SUBSYS_NFTABLES);
1634 	chain_type[ctype->family][ctype->type] = NULL;
1635 	nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1636 }
1637 EXPORT_SYMBOL_GPL(nft_unregister_chain_type);
1638 
1639 /*
1640  * Chains
1641  */
1642 
1643 static struct nft_chain *
nft_chain_lookup_byhandle(const struct nft_table * table,u64 handle,u8 genmask)1644 nft_chain_lookup_byhandle(const struct nft_table *table, u64 handle, u8 genmask)
1645 {
1646 	struct nft_chain *chain;
1647 
1648 	list_for_each_entry(chain, &table->chains, list) {
1649 		if (chain->handle == handle &&
1650 		    nft_active_genmask(chain, genmask))
1651 			return chain;
1652 	}
1653 
1654 	return ERR_PTR(-ENOENT);
1655 }
1656 
lockdep_commit_lock_is_held(const struct net * net)1657 static bool lockdep_commit_lock_is_held(const struct net *net)
1658 {
1659 #ifdef CONFIG_PROVE_LOCKING
1660 	struct nftables_pernet *nft_net = nft_pernet(net);
1661 
1662 	return lockdep_is_held(&nft_net->commit_mutex);
1663 #else
1664 	return true;
1665 #endif
1666 }
1667 
nft_chain_lookup(struct net * net,struct nft_table * table,const struct nlattr * nla,u8 genmask)1668 static struct nft_chain *nft_chain_lookup(struct net *net,
1669 					  struct nft_table *table,
1670 					  const struct nlattr *nla, u8 genmask)
1671 {
1672 	char search[NFT_CHAIN_MAXNAMELEN + 1];
1673 	struct rhlist_head *tmp, *list;
1674 	struct nft_chain *chain;
1675 
1676 	if (nla == NULL)
1677 		return ERR_PTR(-EINVAL);
1678 
1679 	nla_strscpy(search, nla, sizeof(search));
1680 
1681 	WARN_ON(!rcu_read_lock_held() &&
1682 		!lockdep_commit_lock_is_held(net));
1683 
1684 	chain = ERR_PTR(-ENOENT);
1685 	rcu_read_lock();
1686 	list = rhltable_lookup(&table->chains_ht, search, nft_chain_ht_params);
1687 	if (!list)
1688 		goto out_unlock;
1689 
1690 	rhl_for_each_entry_rcu(chain, tmp, list, rhlhead) {
1691 		if (nft_active_genmask(chain, genmask))
1692 			goto out_unlock;
1693 	}
1694 	chain = ERR_PTR(-ENOENT);
1695 out_unlock:
1696 	rcu_read_unlock();
1697 	return chain;
1698 }
1699 
1700 static const struct nla_policy nft_chain_policy[NFTA_CHAIN_MAX + 1] = {
1701 	[NFTA_CHAIN_TABLE]	= { .type = NLA_STRING,
1702 				    .len = NFT_TABLE_MAXNAMELEN - 1 },
1703 	[NFTA_CHAIN_HANDLE]	= { .type = NLA_U64 },
1704 	[NFTA_CHAIN_NAME]	= { .type = NLA_STRING,
1705 				    .len = NFT_CHAIN_MAXNAMELEN - 1 },
1706 	[NFTA_CHAIN_HOOK]	= { .type = NLA_NESTED },
1707 	[NFTA_CHAIN_POLICY]	= { .type = NLA_U32 },
1708 	[NFTA_CHAIN_TYPE]	= { .type = NLA_STRING,
1709 				    .len = NFT_MODULE_AUTOLOAD_LIMIT },
1710 	[NFTA_CHAIN_COUNTERS]	= { .type = NLA_NESTED },
1711 	[NFTA_CHAIN_FLAGS]	= { .type = NLA_U32 },
1712 	[NFTA_CHAIN_ID]		= { .type = NLA_U32 },
1713 	[NFTA_CHAIN_USERDATA]	= { .type = NLA_BINARY,
1714 				    .len = NFT_USERDATA_MAXLEN },
1715 };
1716 
1717 static const struct nla_policy nft_hook_policy[NFTA_HOOK_MAX + 1] = {
1718 	[NFTA_HOOK_HOOKNUM]	= { .type = NLA_U32 },
1719 	[NFTA_HOOK_PRIORITY]	= { .type = NLA_U32 },
1720 	[NFTA_HOOK_DEV]		= { .type = NLA_STRING,
1721 				    .len = IFNAMSIZ - 1 },
1722 };
1723 
nft_dump_stats(struct sk_buff * skb,struct nft_stats __percpu * stats)1724 static int nft_dump_stats(struct sk_buff *skb, struct nft_stats __percpu *stats)
1725 {
1726 	struct nft_stats *cpu_stats, total;
1727 	struct nlattr *nest;
1728 	unsigned int seq;
1729 	u64 pkts, bytes;
1730 	int cpu;
1731 
1732 	if (!stats)
1733 		return 0;
1734 
1735 	memset(&total, 0, sizeof(total));
1736 	for_each_possible_cpu(cpu) {
1737 		cpu_stats = per_cpu_ptr(stats, cpu);
1738 		do {
1739 			seq = u64_stats_fetch_begin(&cpu_stats->syncp);
1740 			pkts = cpu_stats->pkts;
1741 			bytes = cpu_stats->bytes;
1742 		} while (u64_stats_fetch_retry(&cpu_stats->syncp, seq));
1743 		total.pkts += pkts;
1744 		total.bytes += bytes;
1745 	}
1746 	nest = nla_nest_start_noflag(skb, NFTA_CHAIN_COUNTERS);
1747 	if (nest == NULL)
1748 		goto nla_put_failure;
1749 
1750 	if (nla_put_be64(skb, NFTA_COUNTER_PACKETS, cpu_to_be64(total.pkts),
1751 			 NFTA_COUNTER_PAD) ||
1752 	    nla_put_be64(skb, NFTA_COUNTER_BYTES, cpu_to_be64(total.bytes),
1753 			 NFTA_COUNTER_PAD))
1754 		goto nla_put_failure;
1755 
1756 	nla_nest_end(skb, nest);
1757 	return 0;
1758 
1759 nla_put_failure:
1760 	return -ENOSPC;
1761 }
1762 
nft_dump_basechain_hook(struct sk_buff * skb,int family,const struct nft_base_chain * basechain,const struct list_head * hook_list)1763 static int nft_dump_basechain_hook(struct sk_buff *skb, int family,
1764 				   const struct nft_base_chain *basechain,
1765 				   const struct list_head *hook_list)
1766 {
1767 	const struct nf_hook_ops *ops = &basechain->ops;
1768 	struct nft_hook *hook, *first = NULL;
1769 	struct nlattr *nest, *nest_devs;
1770 	int n = 0;
1771 
1772 	nest = nla_nest_start_noflag(skb, NFTA_CHAIN_HOOK);
1773 	if (nest == NULL)
1774 		goto nla_put_failure;
1775 	if (nla_put_be32(skb, NFTA_HOOK_HOOKNUM, htonl(ops->hooknum)))
1776 		goto nla_put_failure;
1777 	if (nla_put_be32(skb, NFTA_HOOK_PRIORITY, htonl(ops->priority)))
1778 		goto nla_put_failure;
1779 
1780 	if (nft_base_chain_netdev(family, ops->hooknum)) {
1781 		nest_devs = nla_nest_start_noflag(skb, NFTA_HOOK_DEVS);
1782 		if (!nest_devs)
1783 			goto nla_put_failure;
1784 
1785 		if (!hook_list)
1786 			hook_list = &basechain->hook_list;
1787 
1788 		list_for_each_entry_rcu(hook, hook_list, list) {
1789 			if (!first)
1790 				first = hook;
1791 
1792 			if (nla_put_string(skb, NFTA_DEVICE_NAME,
1793 					   hook->ops.dev->name))
1794 				goto nla_put_failure;
1795 			n++;
1796 		}
1797 		nla_nest_end(skb, nest_devs);
1798 
1799 		if (n == 1 &&
1800 		    nla_put_string(skb, NFTA_HOOK_DEV, first->ops.dev->name))
1801 			goto nla_put_failure;
1802 	}
1803 	nla_nest_end(skb, nest);
1804 
1805 	return 0;
1806 nla_put_failure:
1807 	return -1;
1808 }
1809 
nf_tables_fill_chain_info(struct sk_buff * skb,struct net * net,u32 portid,u32 seq,int event,u32 flags,int family,const struct nft_table * table,const struct nft_chain * chain,const struct list_head * hook_list)1810 static int nf_tables_fill_chain_info(struct sk_buff *skb, struct net *net,
1811 				     u32 portid, u32 seq, int event, u32 flags,
1812 				     int family, const struct nft_table *table,
1813 				     const struct nft_chain *chain,
1814 				     const struct list_head *hook_list)
1815 {
1816 	struct nlmsghdr *nlh;
1817 
1818 	event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
1819 	nlh = nfnl_msg_put(skb, portid, seq, event, flags, family,
1820 			   NFNETLINK_V0, nft_base_seq(net));
1821 	if (!nlh)
1822 		goto nla_put_failure;
1823 
1824 	if (nla_put_string(skb, NFTA_CHAIN_TABLE, table->name) ||
1825 	    nla_put_string(skb, NFTA_CHAIN_NAME, chain->name) ||
1826 	    nla_put_be64(skb, NFTA_CHAIN_HANDLE, cpu_to_be64(chain->handle),
1827 			 NFTA_CHAIN_PAD))
1828 		goto nla_put_failure;
1829 
1830 	if (event == NFT_MSG_DELCHAIN && !hook_list) {
1831 		nlmsg_end(skb, nlh);
1832 		return 0;
1833 	}
1834 
1835 	if (nft_is_base_chain(chain)) {
1836 		const struct nft_base_chain *basechain = nft_base_chain(chain);
1837 		struct nft_stats __percpu *stats;
1838 
1839 		if (nft_dump_basechain_hook(skb, family, basechain, hook_list))
1840 			goto nla_put_failure;
1841 
1842 		if (nla_put_be32(skb, NFTA_CHAIN_POLICY,
1843 				 htonl(basechain->policy)))
1844 			goto nla_put_failure;
1845 
1846 		if (nla_put_string(skb, NFTA_CHAIN_TYPE, basechain->type->name))
1847 			goto nla_put_failure;
1848 
1849 		stats = rcu_dereference_check(basechain->stats,
1850 					      lockdep_commit_lock_is_held(net));
1851 		if (nft_dump_stats(skb, stats))
1852 			goto nla_put_failure;
1853 	}
1854 
1855 	if (chain->flags &&
1856 	    nla_put_be32(skb, NFTA_CHAIN_FLAGS, htonl(chain->flags)))
1857 		goto nla_put_failure;
1858 
1859 	if (nla_put_be32(skb, NFTA_CHAIN_USE, htonl(chain->use)))
1860 		goto nla_put_failure;
1861 
1862 	if (chain->udata &&
1863 	    nla_put(skb, NFTA_CHAIN_USERDATA, chain->udlen, chain->udata))
1864 		goto nla_put_failure;
1865 
1866 	nlmsg_end(skb, nlh);
1867 	return 0;
1868 
1869 nla_put_failure:
1870 	nlmsg_trim(skb, nlh);
1871 	return -1;
1872 }
1873 
nf_tables_chain_notify(const struct nft_ctx * ctx,int event,const struct list_head * hook_list)1874 static void nf_tables_chain_notify(const struct nft_ctx *ctx, int event,
1875 				   const struct list_head *hook_list)
1876 {
1877 	struct nftables_pernet *nft_net;
1878 	struct sk_buff *skb;
1879 	u16 flags = 0;
1880 	int err;
1881 
1882 	if (!ctx->report &&
1883 	    !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
1884 		return;
1885 
1886 	skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
1887 	if (skb == NULL)
1888 		goto err;
1889 
1890 	if (ctx->flags & (NLM_F_CREATE | NLM_F_EXCL))
1891 		flags |= ctx->flags & (NLM_F_CREATE | NLM_F_EXCL);
1892 
1893 	err = nf_tables_fill_chain_info(skb, ctx->net, ctx->portid, ctx->seq,
1894 					event, flags, ctx->family, ctx->table,
1895 					ctx->chain, hook_list);
1896 	if (err < 0) {
1897 		kfree_skb(skb);
1898 		goto err;
1899 	}
1900 
1901 	nft_net = nft_pernet(ctx->net);
1902 	nft_notify_enqueue(skb, ctx->report, &nft_net->notify_list);
1903 	return;
1904 err:
1905 	nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
1906 }
1907 
nf_tables_dump_chains(struct sk_buff * skb,struct netlink_callback * cb)1908 static int nf_tables_dump_chains(struct sk_buff *skb,
1909 				 struct netlink_callback *cb)
1910 {
1911 	const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
1912 	unsigned int idx = 0, s_idx = cb->args[0];
1913 	struct net *net = sock_net(skb->sk);
1914 	int family = nfmsg->nfgen_family;
1915 	struct nftables_pernet *nft_net;
1916 	const struct nft_table *table;
1917 	const struct nft_chain *chain;
1918 
1919 	rcu_read_lock();
1920 	nft_net = nft_pernet(net);
1921 	cb->seq = READ_ONCE(nft_net->base_seq);
1922 
1923 	list_for_each_entry_rcu(table, &nft_net->tables, list) {
1924 		if (family != NFPROTO_UNSPEC && family != table->family)
1925 			continue;
1926 
1927 		list_for_each_entry_rcu(chain, &table->chains, list) {
1928 			if (idx < s_idx)
1929 				goto cont;
1930 			if (idx > s_idx)
1931 				memset(&cb->args[1], 0,
1932 				       sizeof(cb->args) - sizeof(cb->args[0]));
1933 			if (!nft_is_active(net, chain))
1934 				continue;
1935 			if (nf_tables_fill_chain_info(skb, net,
1936 						      NETLINK_CB(cb->skb).portid,
1937 						      cb->nlh->nlmsg_seq,
1938 						      NFT_MSG_NEWCHAIN,
1939 						      NLM_F_MULTI,
1940 						      table->family, table,
1941 						      chain, NULL) < 0)
1942 				goto done;
1943 
1944 			nl_dump_check_consistent(cb, nlmsg_hdr(skb));
1945 cont:
1946 			idx++;
1947 		}
1948 	}
1949 done:
1950 	rcu_read_unlock();
1951 	cb->args[0] = idx;
1952 	return skb->len;
1953 }
1954 
1955 /* called with rcu_read_lock held */
nf_tables_getchain(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])1956 static int nf_tables_getchain(struct sk_buff *skb, const struct nfnl_info *info,
1957 			      const struct nlattr * const nla[])
1958 {
1959 	struct netlink_ext_ack *extack = info->extack;
1960 	u8 genmask = nft_genmask_cur(info->net);
1961 	u8 family = info->nfmsg->nfgen_family;
1962 	const struct nft_chain *chain;
1963 	struct net *net = info->net;
1964 	struct nft_table *table;
1965 	struct sk_buff *skb2;
1966 	int err;
1967 
1968 	if (info->nlh->nlmsg_flags & NLM_F_DUMP) {
1969 		struct netlink_dump_control c = {
1970 			.dump = nf_tables_dump_chains,
1971 			.module = THIS_MODULE,
1972 		};
1973 
1974 		return nft_netlink_dump_start_rcu(info->sk, skb, info->nlh, &c);
1975 	}
1976 
1977 	table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask, 0);
1978 	if (IS_ERR(table)) {
1979 		NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
1980 		return PTR_ERR(table);
1981 	}
1982 
1983 	chain = nft_chain_lookup(net, table, nla[NFTA_CHAIN_NAME], genmask);
1984 	if (IS_ERR(chain)) {
1985 		NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_NAME]);
1986 		return PTR_ERR(chain);
1987 	}
1988 
1989 	skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
1990 	if (!skb2)
1991 		return -ENOMEM;
1992 
1993 	err = nf_tables_fill_chain_info(skb2, net, NETLINK_CB(skb).portid,
1994 					info->nlh->nlmsg_seq, NFT_MSG_NEWCHAIN,
1995 					0, family, table, chain, NULL);
1996 	if (err < 0)
1997 		goto err_fill_chain_info;
1998 
1999 	return nfnetlink_unicast(skb2, net, NETLINK_CB(skb).portid);
2000 
2001 err_fill_chain_info:
2002 	kfree_skb(skb2);
2003 	return err;
2004 }
2005 
2006 static const struct nla_policy nft_counter_policy[NFTA_COUNTER_MAX + 1] = {
2007 	[NFTA_COUNTER_PACKETS]	= { .type = NLA_U64 },
2008 	[NFTA_COUNTER_BYTES]	= { .type = NLA_U64 },
2009 };
2010 
nft_stats_alloc(const struct nlattr * attr)2011 static struct nft_stats __percpu *nft_stats_alloc(const struct nlattr *attr)
2012 {
2013 	struct nlattr *tb[NFTA_COUNTER_MAX+1];
2014 	struct nft_stats __percpu *newstats;
2015 	struct nft_stats *stats;
2016 	int err;
2017 
2018 	err = nla_parse_nested_deprecated(tb, NFTA_COUNTER_MAX, attr,
2019 					  nft_counter_policy, NULL);
2020 	if (err < 0)
2021 		return ERR_PTR(err);
2022 
2023 	if (!tb[NFTA_COUNTER_BYTES] || !tb[NFTA_COUNTER_PACKETS])
2024 		return ERR_PTR(-EINVAL);
2025 
2026 	newstats = netdev_alloc_pcpu_stats(struct nft_stats);
2027 	if (newstats == NULL)
2028 		return ERR_PTR(-ENOMEM);
2029 
2030 	/* Restore old counters on this cpu, no problem. Per-cpu statistics
2031 	 * are not exposed to userspace.
2032 	 */
2033 	preempt_disable();
2034 	stats = this_cpu_ptr(newstats);
2035 	stats->bytes = be64_to_cpu(nla_get_be64(tb[NFTA_COUNTER_BYTES]));
2036 	stats->pkts = be64_to_cpu(nla_get_be64(tb[NFTA_COUNTER_PACKETS]));
2037 	preempt_enable();
2038 
2039 	return newstats;
2040 }
2041 
nft_chain_stats_replace(struct nft_trans * trans)2042 static void nft_chain_stats_replace(struct nft_trans *trans)
2043 {
2044 	struct nft_base_chain *chain = nft_base_chain(trans->ctx.chain);
2045 
2046 	if (!nft_trans_chain_stats(trans))
2047 		return;
2048 
2049 	nft_trans_chain_stats(trans) =
2050 		rcu_replace_pointer(chain->stats, nft_trans_chain_stats(trans),
2051 				    lockdep_commit_lock_is_held(trans->ctx.net));
2052 
2053 	if (!nft_trans_chain_stats(trans))
2054 		static_branch_inc(&nft_counters_enabled);
2055 }
2056 
nf_tables_chain_free_chain_rules(struct nft_chain * chain)2057 static void nf_tables_chain_free_chain_rules(struct nft_chain *chain)
2058 {
2059 	struct nft_rule_blob *g0 = rcu_dereference_raw(chain->blob_gen_0);
2060 	struct nft_rule_blob *g1 = rcu_dereference_raw(chain->blob_gen_1);
2061 
2062 	if (g0 != g1)
2063 		kvfree(g1);
2064 	kvfree(g0);
2065 
2066 	/* should be NULL either via abort or via successful commit */
2067 	WARN_ON_ONCE(chain->blob_next);
2068 	kvfree(chain->blob_next);
2069 }
2070 
nf_tables_chain_destroy(struct nft_ctx * ctx)2071 void nf_tables_chain_destroy(struct nft_ctx *ctx)
2072 {
2073 	struct nft_chain *chain = ctx->chain;
2074 	struct nft_hook *hook, *next;
2075 
2076 	if (WARN_ON(chain->use > 0))
2077 		return;
2078 
2079 	/* no concurrent access possible anymore */
2080 	nf_tables_chain_free_chain_rules(chain);
2081 
2082 	if (nft_is_base_chain(chain)) {
2083 		struct nft_base_chain *basechain = nft_base_chain(chain);
2084 
2085 		if (nft_base_chain_netdev(ctx->family, basechain->ops.hooknum)) {
2086 			list_for_each_entry_safe(hook, next,
2087 						 &basechain->hook_list, list) {
2088 				list_del_rcu(&hook->list);
2089 				kfree_rcu(hook, rcu);
2090 			}
2091 		}
2092 		module_put(basechain->type->owner);
2093 		if (rcu_access_pointer(basechain->stats)) {
2094 			static_branch_dec(&nft_counters_enabled);
2095 			free_percpu(rcu_dereference_raw(basechain->stats));
2096 		}
2097 		kfree(chain->name);
2098 		kfree(chain->udata);
2099 		kfree(basechain);
2100 	} else {
2101 		kfree(chain->name);
2102 		kfree(chain->udata);
2103 		kfree(chain);
2104 	}
2105 }
2106 
nft_netdev_hook_alloc(struct net * net,const struct nlattr * attr)2107 static struct nft_hook *nft_netdev_hook_alloc(struct net *net,
2108 					      const struct nlattr *attr)
2109 {
2110 	struct net_device *dev;
2111 	char ifname[IFNAMSIZ];
2112 	struct nft_hook *hook;
2113 	int err;
2114 
2115 	hook = kzalloc(sizeof(struct nft_hook), GFP_KERNEL_ACCOUNT);
2116 	if (!hook) {
2117 		err = -ENOMEM;
2118 		goto err_hook_alloc;
2119 	}
2120 
2121 	nla_strscpy(ifname, attr, IFNAMSIZ);
2122 	/* nf_tables_netdev_event() is called under rtnl_mutex, this is
2123 	 * indirectly serializing all the other holders of the commit_mutex with
2124 	 * the rtnl_mutex.
2125 	 */
2126 	dev = __dev_get_by_name(net, ifname);
2127 	if (!dev) {
2128 		err = -ENOENT;
2129 		goto err_hook_dev;
2130 	}
2131 	hook->ops.dev = dev;
2132 
2133 	return hook;
2134 
2135 err_hook_dev:
2136 	kfree(hook);
2137 err_hook_alloc:
2138 	return ERR_PTR(err);
2139 }
2140 
nft_hook_list_find(struct list_head * hook_list,const struct nft_hook * this)2141 static struct nft_hook *nft_hook_list_find(struct list_head *hook_list,
2142 					   const struct nft_hook *this)
2143 {
2144 	struct nft_hook *hook;
2145 
2146 	list_for_each_entry(hook, hook_list, list) {
2147 		if (this->ops.dev == hook->ops.dev)
2148 			return hook;
2149 	}
2150 
2151 	return NULL;
2152 }
2153 
nf_tables_parse_netdev_hooks(struct net * net,const struct nlattr * attr,struct list_head * hook_list,struct netlink_ext_ack * extack)2154 static int nf_tables_parse_netdev_hooks(struct net *net,
2155 					const struct nlattr *attr,
2156 					struct list_head *hook_list,
2157 					struct netlink_ext_ack *extack)
2158 {
2159 	struct nft_hook *hook, *next;
2160 	const struct nlattr *tmp;
2161 	int rem, n = 0, err;
2162 
2163 	nla_for_each_nested(tmp, attr, rem) {
2164 		if (nla_type(tmp) != NFTA_DEVICE_NAME) {
2165 			err = -EINVAL;
2166 			goto err_hook;
2167 		}
2168 
2169 		hook = nft_netdev_hook_alloc(net, tmp);
2170 		if (IS_ERR(hook)) {
2171 			NL_SET_BAD_ATTR(extack, tmp);
2172 			err = PTR_ERR(hook);
2173 			goto err_hook;
2174 		}
2175 		if (nft_hook_list_find(hook_list, hook)) {
2176 			NL_SET_BAD_ATTR(extack, tmp);
2177 			kfree(hook);
2178 			err = -EEXIST;
2179 			goto err_hook;
2180 		}
2181 		list_add_tail(&hook->list, hook_list);
2182 		n++;
2183 
2184 		if (n == NFT_NETDEVICE_MAX) {
2185 			err = -EFBIG;
2186 			goto err_hook;
2187 		}
2188 	}
2189 
2190 	return 0;
2191 
2192 err_hook:
2193 	list_for_each_entry_safe(hook, next, hook_list, list) {
2194 		list_del(&hook->list);
2195 		kfree(hook);
2196 	}
2197 	return err;
2198 }
2199 
2200 struct nft_chain_hook {
2201 	u32				num;
2202 	s32				priority;
2203 	const struct nft_chain_type	*type;
2204 	struct list_head		list;
2205 };
2206 
nft_chain_parse_netdev(struct net * net,struct nlattr * tb[],struct list_head * hook_list,struct netlink_ext_ack * extack,u32 flags)2207 static int nft_chain_parse_netdev(struct net *net, struct nlattr *tb[],
2208 				  struct list_head *hook_list,
2209 				  struct netlink_ext_ack *extack, u32 flags)
2210 {
2211 	struct nft_hook *hook;
2212 	int err;
2213 
2214 	if (tb[NFTA_HOOK_DEV]) {
2215 		hook = nft_netdev_hook_alloc(net, tb[NFTA_HOOK_DEV]);
2216 		if (IS_ERR(hook)) {
2217 			NL_SET_BAD_ATTR(extack, tb[NFTA_HOOK_DEV]);
2218 			return PTR_ERR(hook);
2219 		}
2220 
2221 		list_add_tail(&hook->list, hook_list);
2222 	} else if (tb[NFTA_HOOK_DEVS]) {
2223 		err = nf_tables_parse_netdev_hooks(net, tb[NFTA_HOOK_DEVS],
2224 						   hook_list, extack);
2225 		if (err < 0)
2226 			return err;
2227 
2228 	}
2229 
2230 	if (flags & NFT_CHAIN_HW_OFFLOAD &&
2231 	    list_empty(hook_list))
2232 		return -EINVAL;
2233 
2234 	return 0;
2235 }
2236 
nft_chain_parse_hook(struct net * net,struct nft_base_chain * basechain,const struct nlattr * const nla[],struct nft_chain_hook * hook,u8 family,u32 flags,struct netlink_ext_ack * extack)2237 static int nft_chain_parse_hook(struct net *net,
2238 				struct nft_base_chain *basechain,
2239 				const struct nlattr * const nla[],
2240 				struct nft_chain_hook *hook, u8 family,
2241 				u32 flags, struct netlink_ext_ack *extack)
2242 {
2243 	struct nftables_pernet *nft_net = nft_pernet(net);
2244 	struct nlattr *ha[NFTA_HOOK_MAX + 1];
2245 	const struct nft_chain_type *type;
2246 	int err;
2247 
2248 	lockdep_assert_held(&nft_net->commit_mutex);
2249 	lockdep_nfnl_nft_mutex_not_held();
2250 
2251 	err = nla_parse_nested_deprecated(ha, NFTA_HOOK_MAX,
2252 					  nla[NFTA_CHAIN_HOOK],
2253 					  nft_hook_policy, NULL);
2254 	if (err < 0)
2255 		return err;
2256 
2257 	if (!basechain) {
2258 		if (!ha[NFTA_HOOK_HOOKNUM] ||
2259 		    !ha[NFTA_HOOK_PRIORITY]) {
2260 			NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_NAME]);
2261 			return -ENOENT;
2262 		}
2263 
2264 		hook->num = ntohl(nla_get_be32(ha[NFTA_HOOK_HOOKNUM]));
2265 		hook->priority = ntohl(nla_get_be32(ha[NFTA_HOOK_PRIORITY]));
2266 
2267 		type = __nft_chain_type_get(family, NFT_CHAIN_T_DEFAULT);
2268 		if (!type)
2269 			return -EOPNOTSUPP;
2270 
2271 		if (nla[NFTA_CHAIN_TYPE]) {
2272 			type = nf_tables_chain_type_lookup(net, nla[NFTA_CHAIN_TYPE],
2273 							   family, true);
2274 			if (IS_ERR(type)) {
2275 				NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TYPE]);
2276 				return PTR_ERR(type);
2277 			}
2278 		}
2279 		if (hook->num >= NFT_MAX_HOOKS || !(type->hook_mask & (1 << hook->num)))
2280 			return -EOPNOTSUPP;
2281 
2282 		if (type->type == NFT_CHAIN_T_NAT &&
2283 		    hook->priority <= NF_IP_PRI_CONNTRACK)
2284 			return -EOPNOTSUPP;
2285 	} else {
2286 		if (ha[NFTA_HOOK_HOOKNUM]) {
2287 			hook->num = ntohl(nla_get_be32(ha[NFTA_HOOK_HOOKNUM]));
2288 			if (hook->num != basechain->ops.hooknum)
2289 				return -EOPNOTSUPP;
2290 		}
2291 		if (ha[NFTA_HOOK_PRIORITY]) {
2292 			hook->priority = ntohl(nla_get_be32(ha[NFTA_HOOK_PRIORITY]));
2293 			if (hook->priority != basechain->ops.priority)
2294 				return -EOPNOTSUPP;
2295 		}
2296 
2297 		if (nla[NFTA_CHAIN_TYPE]) {
2298 			type = __nf_tables_chain_type_lookup(nla[NFTA_CHAIN_TYPE],
2299 							     family);
2300 			if (!type) {
2301 				NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TYPE]);
2302 				return -ENOENT;
2303 			}
2304 		} else {
2305 			type = basechain->type;
2306 		}
2307 	}
2308 
2309 	if (!try_module_get(type->owner)) {
2310 		if (nla[NFTA_CHAIN_TYPE])
2311 			NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TYPE]);
2312 		return -ENOENT;
2313 	}
2314 
2315 	hook->type = type;
2316 
2317 	INIT_LIST_HEAD(&hook->list);
2318 	if (nft_base_chain_netdev(family, hook->num)) {
2319 		err = nft_chain_parse_netdev(net, ha, &hook->list, extack, flags);
2320 		if (err < 0) {
2321 			module_put(type->owner);
2322 			return err;
2323 		}
2324 	} else if (ha[NFTA_HOOK_DEV] || ha[NFTA_HOOK_DEVS]) {
2325 		module_put(type->owner);
2326 		return -EOPNOTSUPP;
2327 	}
2328 
2329 	return 0;
2330 }
2331 
nft_chain_release_hook(struct nft_chain_hook * hook)2332 static void nft_chain_release_hook(struct nft_chain_hook *hook)
2333 {
2334 	struct nft_hook *h, *next;
2335 
2336 	list_for_each_entry_safe(h, next, &hook->list, list) {
2337 		list_del(&h->list);
2338 		kfree(h);
2339 	}
2340 	module_put(hook->type->owner);
2341 }
2342 
nft_last_rule(const struct nft_chain * chain,const void * ptr)2343 static void nft_last_rule(const struct nft_chain *chain, const void *ptr)
2344 {
2345 	struct nft_rule_dp_last *lrule;
2346 
2347 	BUILD_BUG_ON(offsetof(struct nft_rule_dp_last, end) != 0);
2348 
2349 	lrule = (struct nft_rule_dp_last *)ptr;
2350 	lrule->end.is_last = 1;
2351 	lrule->chain = chain;
2352 	/* blob size does not include the trailer rule */
2353 }
2354 
nf_tables_chain_alloc_rules(const struct nft_chain * chain,unsigned int size)2355 static struct nft_rule_blob *nf_tables_chain_alloc_rules(const struct nft_chain *chain,
2356 							 unsigned int size)
2357 {
2358 	struct nft_rule_blob *blob;
2359 
2360 	if (size > INT_MAX)
2361 		return NULL;
2362 
2363 	size += sizeof(struct nft_rule_blob) + sizeof(struct nft_rule_dp_last);
2364 
2365 	blob = kvmalloc(size, GFP_KERNEL_ACCOUNT);
2366 	if (!blob)
2367 		return NULL;
2368 
2369 	blob->size = 0;
2370 	nft_last_rule(chain, blob->data);
2371 
2372 	return blob;
2373 }
2374 
nft_basechain_hook_init(struct nf_hook_ops * ops,u8 family,const struct nft_chain_hook * hook,struct nft_chain * chain)2375 static void nft_basechain_hook_init(struct nf_hook_ops *ops, u8 family,
2376 				    const struct nft_chain_hook *hook,
2377 				    struct nft_chain *chain)
2378 {
2379 	ops->pf			= family;
2380 	ops->hooknum		= hook->num;
2381 	ops->priority		= hook->priority;
2382 	ops->priv		= chain;
2383 	ops->hook		= hook->type->hooks[ops->hooknum];
2384 	ops->hook_ops_type	= NF_HOOK_OP_NF_TABLES;
2385 }
2386 
nft_basechain_init(struct nft_base_chain * basechain,u8 family,struct nft_chain_hook * hook,u32 flags)2387 static int nft_basechain_init(struct nft_base_chain *basechain, u8 family,
2388 			      struct nft_chain_hook *hook, u32 flags)
2389 {
2390 	struct nft_chain *chain;
2391 	struct nft_hook *h;
2392 
2393 	basechain->type = hook->type;
2394 	INIT_LIST_HEAD(&basechain->hook_list);
2395 	chain = &basechain->chain;
2396 
2397 	if (nft_base_chain_netdev(family, hook->num)) {
2398 		list_splice_init(&hook->list, &basechain->hook_list);
2399 		list_for_each_entry(h, &basechain->hook_list, list)
2400 			nft_basechain_hook_init(&h->ops, family, hook, chain);
2401 	}
2402 	nft_basechain_hook_init(&basechain->ops, family, hook, chain);
2403 
2404 	chain->flags |= NFT_CHAIN_BASE | flags;
2405 	basechain->policy = NF_ACCEPT;
2406 	if (chain->flags & NFT_CHAIN_HW_OFFLOAD &&
2407 	    !nft_chain_offload_support(basechain)) {
2408 		list_splice_init(&basechain->hook_list, &hook->list);
2409 		return -EOPNOTSUPP;
2410 	}
2411 
2412 	flow_block_init(&basechain->flow_block);
2413 
2414 	return 0;
2415 }
2416 
nft_chain_add(struct nft_table * table,struct nft_chain * chain)2417 int nft_chain_add(struct nft_table *table, struct nft_chain *chain)
2418 {
2419 	int err;
2420 
2421 	err = rhltable_insert_key(&table->chains_ht, chain->name,
2422 				  &chain->rhlhead, nft_chain_ht_params);
2423 	if (err)
2424 		return err;
2425 
2426 	list_add_tail_rcu(&chain->list, &table->chains);
2427 
2428 	return 0;
2429 }
2430 
2431 static u64 chain_id;
2432 
nf_tables_addchain(struct nft_ctx * ctx,u8 family,u8 genmask,u8 policy,u32 flags,struct netlink_ext_ack * extack)2433 static int nf_tables_addchain(struct nft_ctx *ctx, u8 family, u8 genmask,
2434 			      u8 policy, u32 flags,
2435 			      struct netlink_ext_ack *extack)
2436 {
2437 	const struct nlattr * const *nla = ctx->nla;
2438 	struct nft_table *table = ctx->table;
2439 	struct nft_base_chain *basechain;
2440 	struct net *net = ctx->net;
2441 	char name[NFT_NAME_MAXLEN];
2442 	struct nft_rule_blob *blob;
2443 	struct nft_trans *trans;
2444 	struct nft_chain *chain;
2445 	int err;
2446 
2447 	if (nla[NFTA_CHAIN_HOOK]) {
2448 		struct nft_stats __percpu *stats = NULL;
2449 		struct nft_chain_hook hook = {};
2450 
2451 		if (table->flags & __NFT_TABLE_F_UPDATE)
2452 			return -EINVAL;
2453 
2454 		if (flags & NFT_CHAIN_BINDING)
2455 			return -EOPNOTSUPP;
2456 
2457 		err = nft_chain_parse_hook(net, NULL, nla, &hook, family, flags,
2458 					   extack);
2459 		if (err < 0)
2460 			return err;
2461 
2462 		basechain = kzalloc(sizeof(*basechain), GFP_KERNEL_ACCOUNT);
2463 		if (basechain == NULL) {
2464 			nft_chain_release_hook(&hook);
2465 			return -ENOMEM;
2466 		}
2467 		chain = &basechain->chain;
2468 
2469 		if (nla[NFTA_CHAIN_COUNTERS]) {
2470 			stats = nft_stats_alloc(nla[NFTA_CHAIN_COUNTERS]);
2471 			if (IS_ERR(stats)) {
2472 				nft_chain_release_hook(&hook);
2473 				kfree(basechain);
2474 				return PTR_ERR(stats);
2475 			}
2476 			rcu_assign_pointer(basechain->stats, stats);
2477 		}
2478 
2479 		err = nft_basechain_init(basechain, family, &hook, flags);
2480 		if (err < 0) {
2481 			nft_chain_release_hook(&hook);
2482 			kfree(basechain);
2483 			free_percpu(stats);
2484 			return err;
2485 		}
2486 		if (stats)
2487 			static_branch_inc(&nft_counters_enabled);
2488 	} else {
2489 		if (flags & NFT_CHAIN_BASE)
2490 			return -EINVAL;
2491 		if (flags & NFT_CHAIN_HW_OFFLOAD)
2492 			return -EOPNOTSUPP;
2493 
2494 		chain = kzalloc(sizeof(*chain), GFP_KERNEL_ACCOUNT);
2495 		if (chain == NULL)
2496 			return -ENOMEM;
2497 
2498 		chain->flags = flags;
2499 	}
2500 	ctx->chain = chain;
2501 
2502 	INIT_LIST_HEAD(&chain->rules);
2503 	chain->handle = nf_tables_alloc_handle(table);
2504 	chain->table = table;
2505 
2506 	if (nla[NFTA_CHAIN_NAME]) {
2507 		chain->name = nla_strdup(nla[NFTA_CHAIN_NAME], GFP_KERNEL_ACCOUNT);
2508 	} else {
2509 		if (!(flags & NFT_CHAIN_BINDING)) {
2510 			err = -EINVAL;
2511 			goto err_destroy_chain;
2512 		}
2513 
2514 		snprintf(name, sizeof(name), "__chain%llu", ++chain_id);
2515 		chain->name = kstrdup(name, GFP_KERNEL_ACCOUNT);
2516 	}
2517 
2518 	if (!chain->name) {
2519 		err = -ENOMEM;
2520 		goto err_destroy_chain;
2521 	}
2522 
2523 	if (nla[NFTA_CHAIN_USERDATA]) {
2524 		chain->udata = nla_memdup(nla[NFTA_CHAIN_USERDATA], GFP_KERNEL_ACCOUNT);
2525 		if (chain->udata == NULL) {
2526 			err = -ENOMEM;
2527 			goto err_destroy_chain;
2528 		}
2529 		chain->udlen = nla_len(nla[NFTA_CHAIN_USERDATA]);
2530 	}
2531 
2532 	blob = nf_tables_chain_alloc_rules(chain, 0);
2533 	if (!blob) {
2534 		err = -ENOMEM;
2535 		goto err_destroy_chain;
2536 	}
2537 
2538 	RCU_INIT_POINTER(chain->blob_gen_0, blob);
2539 	RCU_INIT_POINTER(chain->blob_gen_1, blob);
2540 
2541 	if (!nft_use_inc(&table->use)) {
2542 		err = -EMFILE;
2543 		goto err_destroy_chain;
2544 	}
2545 
2546 	trans = nft_trans_chain_add(ctx, NFT_MSG_NEWCHAIN);
2547 	if (IS_ERR(trans)) {
2548 		err = PTR_ERR(trans);
2549 		goto err_trans;
2550 	}
2551 
2552 	nft_trans_chain_policy(trans) = NFT_CHAIN_POLICY_UNSET;
2553 	if (nft_is_base_chain(chain))
2554 		nft_trans_chain_policy(trans) = policy;
2555 
2556 	err = nft_chain_add(table, chain);
2557 	if (err < 0)
2558 		goto err_chain_add;
2559 
2560 	/* This must be LAST to ensure no packets are walking over this chain. */
2561 	err = nf_tables_register_hook(net, table, chain);
2562 	if (err < 0)
2563 		goto err_register_hook;
2564 
2565 	return 0;
2566 
2567 err_register_hook:
2568 	nft_chain_del(chain);
2569 err_chain_add:
2570 	nft_trans_destroy(trans);
2571 err_trans:
2572 	nft_use_dec_restore(&table->use);
2573 err_destroy_chain:
2574 	nf_tables_chain_destroy(ctx);
2575 
2576 	return err;
2577 }
2578 
nf_tables_updchain(struct nft_ctx * ctx,u8 genmask,u8 policy,u32 flags,const struct nlattr * attr,struct netlink_ext_ack * extack)2579 static int nf_tables_updchain(struct nft_ctx *ctx, u8 genmask, u8 policy,
2580 			      u32 flags, const struct nlattr *attr,
2581 			      struct netlink_ext_ack *extack)
2582 {
2583 	const struct nlattr * const *nla = ctx->nla;
2584 	struct nft_base_chain *basechain = NULL;
2585 	struct nft_table *table = ctx->table;
2586 	struct nft_chain *chain = ctx->chain;
2587 	struct nft_chain_hook hook = {};
2588 	struct nft_stats *stats = NULL;
2589 	struct nft_hook *h, *next;
2590 	struct nf_hook_ops *ops;
2591 	struct nft_trans *trans;
2592 	bool unregister = false;
2593 	int err;
2594 
2595 	if (chain->flags ^ flags)
2596 		return -EOPNOTSUPP;
2597 
2598 	INIT_LIST_HEAD(&hook.list);
2599 
2600 	if (nla[NFTA_CHAIN_HOOK]) {
2601 		if (!nft_is_base_chain(chain)) {
2602 			NL_SET_BAD_ATTR(extack, attr);
2603 			return -EEXIST;
2604 		}
2605 
2606 		basechain = nft_base_chain(chain);
2607 		err = nft_chain_parse_hook(ctx->net, basechain, nla, &hook,
2608 					   ctx->family, flags, extack);
2609 		if (err < 0)
2610 			return err;
2611 
2612 		if (basechain->type != hook.type) {
2613 			nft_chain_release_hook(&hook);
2614 			NL_SET_BAD_ATTR(extack, attr);
2615 			return -EEXIST;
2616 		}
2617 
2618 		if (nft_base_chain_netdev(ctx->family, basechain->ops.hooknum)) {
2619 			list_for_each_entry_safe(h, next, &hook.list, list) {
2620 				h->ops.pf	= basechain->ops.pf;
2621 				h->ops.hooknum	= basechain->ops.hooknum;
2622 				h->ops.priority	= basechain->ops.priority;
2623 				h->ops.priv	= basechain->ops.priv;
2624 				h->ops.hook	= basechain->ops.hook;
2625 
2626 				if (nft_hook_list_find(&basechain->hook_list, h)) {
2627 					list_del(&h->list);
2628 					kfree(h);
2629 				}
2630 			}
2631 		} else {
2632 			ops = &basechain->ops;
2633 			if (ops->hooknum != hook.num ||
2634 			    ops->priority != hook.priority) {
2635 				nft_chain_release_hook(&hook);
2636 				NL_SET_BAD_ATTR(extack, attr);
2637 				return -EEXIST;
2638 			}
2639 		}
2640 	}
2641 
2642 	if (nla[NFTA_CHAIN_HANDLE] &&
2643 	    nla[NFTA_CHAIN_NAME]) {
2644 		struct nft_chain *chain2;
2645 
2646 		chain2 = nft_chain_lookup(ctx->net, table,
2647 					  nla[NFTA_CHAIN_NAME], genmask);
2648 		if (!IS_ERR(chain2)) {
2649 			NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_NAME]);
2650 			err = -EEXIST;
2651 			goto err_hooks;
2652 		}
2653 	}
2654 
2655 	if (table->flags & __NFT_TABLE_F_UPDATE &&
2656 	    !list_empty(&hook.list)) {
2657 		NL_SET_BAD_ATTR(extack, attr);
2658 		err = -EOPNOTSUPP;
2659 		goto err_hooks;
2660 	}
2661 
2662 	if (!(table->flags & NFT_TABLE_F_DORMANT) &&
2663 	    nft_is_base_chain(chain) &&
2664 	    !list_empty(&hook.list)) {
2665 		basechain = nft_base_chain(chain);
2666 		ops = &basechain->ops;
2667 
2668 		if (nft_base_chain_netdev(table->family, basechain->ops.hooknum)) {
2669 			err = nft_netdev_register_hooks(ctx->net, &hook.list);
2670 			if (err < 0)
2671 				goto err_hooks;
2672 		}
2673 	}
2674 
2675 	unregister = true;
2676 
2677 	if (nla[NFTA_CHAIN_COUNTERS]) {
2678 		if (!nft_is_base_chain(chain)) {
2679 			err = -EOPNOTSUPP;
2680 			goto err_hooks;
2681 		}
2682 
2683 		stats = nft_stats_alloc(nla[NFTA_CHAIN_COUNTERS]);
2684 		if (IS_ERR(stats)) {
2685 			err = PTR_ERR(stats);
2686 			goto err_hooks;
2687 		}
2688 	}
2689 
2690 	err = -ENOMEM;
2691 	trans = nft_trans_alloc(ctx, NFT_MSG_NEWCHAIN,
2692 				sizeof(struct nft_trans_chain));
2693 	if (trans == NULL)
2694 		goto err_trans;
2695 
2696 	nft_trans_chain_stats(trans) = stats;
2697 	nft_trans_chain_update(trans) = true;
2698 
2699 	if (nla[NFTA_CHAIN_POLICY])
2700 		nft_trans_chain_policy(trans) = policy;
2701 	else
2702 		nft_trans_chain_policy(trans) = -1;
2703 
2704 	if (nla[NFTA_CHAIN_HANDLE] &&
2705 	    nla[NFTA_CHAIN_NAME]) {
2706 		struct nftables_pernet *nft_net = nft_pernet(ctx->net);
2707 		struct nft_trans *tmp;
2708 		char *name;
2709 
2710 		err = -ENOMEM;
2711 		name = nla_strdup(nla[NFTA_CHAIN_NAME], GFP_KERNEL_ACCOUNT);
2712 		if (!name)
2713 			goto err_trans;
2714 
2715 		err = -EEXIST;
2716 		list_for_each_entry(tmp, &nft_net->commit_list, list) {
2717 			if (tmp->msg_type == NFT_MSG_NEWCHAIN &&
2718 			    tmp->ctx.table == table &&
2719 			    nft_trans_chain_update(tmp) &&
2720 			    nft_trans_chain_name(tmp) &&
2721 			    strcmp(name, nft_trans_chain_name(tmp)) == 0) {
2722 				NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_NAME]);
2723 				kfree(name);
2724 				goto err_trans;
2725 			}
2726 		}
2727 
2728 		nft_trans_chain_name(trans) = name;
2729 	}
2730 
2731 	nft_trans_basechain(trans) = basechain;
2732 	INIT_LIST_HEAD(&nft_trans_chain_hooks(trans));
2733 	list_splice(&hook.list, &nft_trans_chain_hooks(trans));
2734 	if (nla[NFTA_CHAIN_HOOK])
2735 		module_put(hook.type->owner);
2736 
2737 	nft_trans_commit_list_add_tail(ctx->net, trans);
2738 
2739 	return 0;
2740 
2741 err_trans:
2742 	free_percpu(stats);
2743 	kfree(trans);
2744 err_hooks:
2745 	if (nla[NFTA_CHAIN_HOOK]) {
2746 		list_for_each_entry_safe(h, next, &hook.list, list) {
2747 			if (unregister)
2748 				nf_unregister_net_hook(ctx->net, &h->ops);
2749 			list_del(&h->list);
2750 			kfree_rcu(h, rcu);
2751 		}
2752 		module_put(hook.type->owner);
2753 	}
2754 
2755 	return err;
2756 }
2757 
nft_chain_lookup_byid(const struct net * net,const struct nft_table * table,const struct nlattr * nla,u8 genmask)2758 static struct nft_chain *nft_chain_lookup_byid(const struct net *net,
2759 					       const struct nft_table *table,
2760 					       const struct nlattr *nla, u8 genmask)
2761 {
2762 	struct nftables_pernet *nft_net = nft_pernet(net);
2763 	u32 id = ntohl(nla_get_be32(nla));
2764 	struct nft_trans *trans;
2765 
2766 	list_for_each_entry(trans, &nft_net->commit_list, list) {
2767 		struct nft_chain *chain = trans->ctx.chain;
2768 
2769 		if (trans->msg_type == NFT_MSG_NEWCHAIN &&
2770 		    chain->table == table &&
2771 		    id == nft_trans_chain_id(trans) &&
2772 		    nft_active_genmask(chain, genmask))
2773 			return chain;
2774 	}
2775 	return ERR_PTR(-ENOENT);
2776 }
2777 
nf_tables_newchain(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])2778 static int nf_tables_newchain(struct sk_buff *skb, const struct nfnl_info *info,
2779 			      const struct nlattr * const nla[])
2780 {
2781 	struct nftables_pernet *nft_net = nft_pernet(info->net);
2782 	struct netlink_ext_ack *extack = info->extack;
2783 	u8 genmask = nft_genmask_next(info->net);
2784 	u8 family = info->nfmsg->nfgen_family;
2785 	struct nft_chain *chain = NULL;
2786 	struct net *net = info->net;
2787 	const struct nlattr *attr;
2788 	struct nft_table *table;
2789 	u8 policy = NF_ACCEPT;
2790 	struct nft_ctx ctx;
2791 	u64 handle = 0;
2792 	u32 flags = 0;
2793 
2794 	lockdep_assert_held(&nft_net->commit_mutex);
2795 
2796 	table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask,
2797 				 NETLINK_CB(skb).portid);
2798 	if (IS_ERR(table)) {
2799 		NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
2800 		return PTR_ERR(table);
2801 	}
2802 
2803 	chain = NULL;
2804 	attr = nla[NFTA_CHAIN_NAME];
2805 
2806 	if (nla[NFTA_CHAIN_HANDLE]) {
2807 		handle = be64_to_cpu(nla_get_be64(nla[NFTA_CHAIN_HANDLE]));
2808 		chain = nft_chain_lookup_byhandle(table, handle, genmask);
2809 		if (IS_ERR(chain)) {
2810 			NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_HANDLE]);
2811 			return PTR_ERR(chain);
2812 		}
2813 		attr = nla[NFTA_CHAIN_HANDLE];
2814 	} else if (nla[NFTA_CHAIN_NAME]) {
2815 		chain = nft_chain_lookup(net, table, attr, genmask);
2816 		if (IS_ERR(chain)) {
2817 			if (PTR_ERR(chain) != -ENOENT) {
2818 				NL_SET_BAD_ATTR(extack, attr);
2819 				return PTR_ERR(chain);
2820 			}
2821 			chain = NULL;
2822 		}
2823 	} else if (!nla[NFTA_CHAIN_ID]) {
2824 		return -EINVAL;
2825 	}
2826 
2827 	if (nla[NFTA_CHAIN_POLICY]) {
2828 		if (chain != NULL &&
2829 		    !nft_is_base_chain(chain)) {
2830 			NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_POLICY]);
2831 			return -EOPNOTSUPP;
2832 		}
2833 
2834 		if (chain == NULL &&
2835 		    nla[NFTA_CHAIN_HOOK] == NULL) {
2836 			NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_POLICY]);
2837 			return -EOPNOTSUPP;
2838 		}
2839 
2840 		policy = ntohl(nla_get_be32(nla[NFTA_CHAIN_POLICY]));
2841 		switch (policy) {
2842 		case NF_DROP:
2843 		case NF_ACCEPT:
2844 			break;
2845 		default:
2846 			return -EINVAL;
2847 		}
2848 	}
2849 
2850 	if (nla[NFTA_CHAIN_FLAGS])
2851 		flags = ntohl(nla_get_be32(nla[NFTA_CHAIN_FLAGS]));
2852 	else if (chain)
2853 		flags = chain->flags;
2854 
2855 	if (flags & ~NFT_CHAIN_FLAGS)
2856 		return -EOPNOTSUPP;
2857 
2858 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, chain, nla);
2859 
2860 	if (chain != NULL) {
2861 		if (chain->flags & NFT_CHAIN_BINDING)
2862 			return -EINVAL;
2863 
2864 		if (info->nlh->nlmsg_flags & NLM_F_EXCL) {
2865 			NL_SET_BAD_ATTR(extack, attr);
2866 			return -EEXIST;
2867 		}
2868 		if (info->nlh->nlmsg_flags & NLM_F_REPLACE)
2869 			return -EOPNOTSUPP;
2870 
2871 		flags |= chain->flags & NFT_CHAIN_BASE;
2872 		return nf_tables_updchain(&ctx, genmask, policy, flags, attr,
2873 					  extack);
2874 	}
2875 
2876 	return nf_tables_addchain(&ctx, family, genmask, policy, flags, extack);
2877 }
2878 
nft_delchain_hook(struct nft_ctx * ctx,struct nft_base_chain * basechain,struct netlink_ext_ack * extack)2879 static int nft_delchain_hook(struct nft_ctx *ctx,
2880 			     struct nft_base_chain *basechain,
2881 			     struct netlink_ext_ack *extack)
2882 {
2883 	const struct nft_chain *chain = &basechain->chain;
2884 	const struct nlattr * const *nla = ctx->nla;
2885 	struct nft_chain_hook chain_hook = {};
2886 	struct nft_hook *this, *hook;
2887 	LIST_HEAD(chain_del_list);
2888 	struct nft_trans *trans;
2889 	int err;
2890 
2891 	if (ctx->table->flags & __NFT_TABLE_F_UPDATE)
2892 		return -EOPNOTSUPP;
2893 
2894 	err = nft_chain_parse_hook(ctx->net, basechain, nla, &chain_hook,
2895 				   ctx->family, chain->flags, extack);
2896 	if (err < 0)
2897 		return err;
2898 
2899 	list_for_each_entry(this, &chain_hook.list, list) {
2900 		hook = nft_hook_list_find(&basechain->hook_list, this);
2901 		if (!hook) {
2902 			err = -ENOENT;
2903 			goto err_chain_del_hook;
2904 		}
2905 		list_move(&hook->list, &chain_del_list);
2906 	}
2907 
2908 	trans = nft_trans_alloc(ctx, NFT_MSG_DELCHAIN,
2909 				sizeof(struct nft_trans_chain));
2910 	if (!trans) {
2911 		err = -ENOMEM;
2912 		goto err_chain_del_hook;
2913 	}
2914 
2915 	nft_trans_basechain(trans) = basechain;
2916 	nft_trans_chain_update(trans) = true;
2917 	INIT_LIST_HEAD(&nft_trans_chain_hooks(trans));
2918 	list_splice(&chain_del_list, &nft_trans_chain_hooks(trans));
2919 	nft_chain_release_hook(&chain_hook);
2920 
2921 	nft_trans_commit_list_add_tail(ctx->net, trans);
2922 
2923 	return 0;
2924 
2925 err_chain_del_hook:
2926 	list_splice(&chain_del_list, &basechain->hook_list);
2927 	nft_chain_release_hook(&chain_hook);
2928 
2929 	return err;
2930 }
2931 
nf_tables_delchain(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])2932 static int nf_tables_delchain(struct sk_buff *skb, const struct nfnl_info *info,
2933 			      const struct nlattr * const nla[])
2934 {
2935 	struct netlink_ext_ack *extack = info->extack;
2936 	u8 genmask = nft_genmask_next(info->net);
2937 	u8 family = info->nfmsg->nfgen_family;
2938 	struct net *net = info->net;
2939 	const struct nlattr *attr;
2940 	struct nft_table *table;
2941 	struct nft_chain *chain;
2942 	struct nft_rule *rule;
2943 	struct nft_ctx ctx;
2944 	u64 handle;
2945 	u32 use;
2946 	int err;
2947 
2948 	table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask,
2949 				 NETLINK_CB(skb).portid);
2950 	if (IS_ERR(table)) {
2951 		NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
2952 		return PTR_ERR(table);
2953 	}
2954 
2955 	if (nla[NFTA_CHAIN_HANDLE]) {
2956 		attr = nla[NFTA_CHAIN_HANDLE];
2957 		handle = be64_to_cpu(nla_get_be64(attr));
2958 		chain = nft_chain_lookup_byhandle(table, handle, genmask);
2959 	} else {
2960 		attr = nla[NFTA_CHAIN_NAME];
2961 		chain = nft_chain_lookup(net, table, attr, genmask);
2962 	}
2963 	if (IS_ERR(chain)) {
2964 		if (PTR_ERR(chain) == -ENOENT &&
2965 		    NFNL_MSG_TYPE(info->nlh->nlmsg_type) == NFT_MSG_DESTROYCHAIN)
2966 			return 0;
2967 
2968 		NL_SET_BAD_ATTR(extack, attr);
2969 		return PTR_ERR(chain);
2970 	}
2971 
2972 	if (nft_chain_binding(chain))
2973 		return -EOPNOTSUPP;
2974 
2975 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, chain, nla);
2976 
2977 	if (nla[NFTA_CHAIN_HOOK]) {
2978 		if (NFNL_MSG_TYPE(info->nlh->nlmsg_type) == NFT_MSG_DESTROYCHAIN ||
2979 		    chain->flags & NFT_CHAIN_HW_OFFLOAD)
2980 			return -EOPNOTSUPP;
2981 
2982 		if (nft_is_base_chain(chain)) {
2983 			struct nft_base_chain *basechain = nft_base_chain(chain);
2984 
2985 			if (nft_base_chain_netdev(table->family, basechain->ops.hooknum))
2986 				return nft_delchain_hook(&ctx, basechain, extack);
2987 		}
2988 	}
2989 
2990 	if (info->nlh->nlmsg_flags & NLM_F_NONREC &&
2991 	    chain->use > 0)
2992 		return -EBUSY;
2993 
2994 	use = chain->use;
2995 	list_for_each_entry(rule, &chain->rules, list) {
2996 		if (!nft_is_active_next(net, rule))
2997 			continue;
2998 		use--;
2999 
3000 		err = nft_delrule(&ctx, rule);
3001 		if (err < 0)
3002 			return err;
3003 	}
3004 
3005 	/* There are rules and elements that are still holding references to us,
3006 	 * we cannot do a recursive removal in this case.
3007 	 */
3008 	if (use > 0) {
3009 		NL_SET_BAD_ATTR(extack, attr);
3010 		return -EBUSY;
3011 	}
3012 
3013 	return nft_delchain(&ctx);
3014 }
3015 
3016 /*
3017  * Expressions
3018  */
3019 
3020 /**
3021  *	nft_register_expr - register nf_tables expr type
3022  *	@type: expr type
3023  *
3024  *	Registers the expr type for use with nf_tables. Returns zero on
3025  *	success or a negative errno code otherwise.
3026  */
nft_register_expr(struct nft_expr_type * type)3027 int nft_register_expr(struct nft_expr_type *type)
3028 {
3029 	nfnl_lock(NFNL_SUBSYS_NFTABLES);
3030 	if (type->family == NFPROTO_UNSPEC)
3031 		list_add_tail_rcu(&type->list, &nf_tables_expressions);
3032 	else
3033 		list_add_rcu(&type->list, &nf_tables_expressions);
3034 	nfnl_unlock(NFNL_SUBSYS_NFTABLES);
3035 	return 0;
3036 }
3037 EXPORT_SYMBOL_GPL(nft_register_expr);
3038 
3039 /**
3040  *	nft_unregister_expr - unregister nf_tables expr type
3041  *	@type: expr type
3042  *
3043  * 	Unregisters the expr typefor use with nf_tables.
3044  */
nft_unregister_expr(struct nft_expr_type * type)3045 void nft_unregister_expr(struct nft_expr_type *type)
3046 {
3047 	nfnl_lock(NFNL_SUBSYS_NFTABLES);
3048 	list_del_rcu(&type->list);
3049 	nfnl_unlock(NFNL_SUBSYS_NFTABLES);
3050 }
3051 EXPORT_SYMBOL_GPL(nft_unregister_expr);
3052 
__nft_expr_type_get(u8 family,struct nlattr * nla)3053 static const struct nft_expr_type *__nft_expr_type_get(u8 family,
3054 						       struct nlattr *nla)
3055 {
3056 	const struct nft_expr_type *type, *candidate = NULL;
3057 
3058 	list_for_each_entry_rcu(type, &nf_tables_expressions, list) {
3059 		if (!nla_strcmp(nla, type->name)) {
3060 			if (!type->family && !candidate)
3061 				candidate = type;
3062 			else if (type->family == family)
3063 				candidate = type;
3064 		}
3065 	}
3066 	return candidate;
3067 }
3068 
3069 #ifdef CONFIG_MODULES
nft_expr_type_request_module(struct net * net,u8 family,struct nlattr * nla)3070 static int nft_expr_type_request_module(struct net *net, u8 family,
3071 					struct nlattr *nla)
3072 {
3073 	if (nft_request_module(net, "nft-expr-%u-%.*s", family,
3074 			       nla_len(nla), (char *)nla_data(nla)) == -EAGAIN)
3075 		return -EAGAIN;
3076 
3077 	return 0;
3078 }
3079 #endif
3080 
nft_expr_type_get(struct net * net,u8 family,struct nlattr * nla)3081 static const struct nft_expr_type *nft_expr_type_get(struct net *net,
3082 						     u8 family,
3083 						     struct nlattr *nla)
3084 {
3085 	const struct nft_expr_type *type;
3086 
3087 	if (nla == NULL)
3088 		return ERR_PTR(-EINVAL);
3089 
3090 	rcu_read_lock();
3091 	type = __nft_expr_type_get(family, nla);
3092 	if (type != NULL && try_module_get(type->owner)) {
3093 		rcu_read_unlock();
3094 		return type;
3095 	}
3096 	rcu_read_unlock();
3097 
3098 	lockdep_nfnl_nft_mutex_not_held();
3099 #ifdef CONFIG_MODULES
3100 	if (type == NULL) {
3101 		if (nft_expr_type_request_module(net, family, nla) == -EAGAIN)
3102 			return ERR_PTR(-EAGAIN);
3103 
3104 		if (nft_request_module(net, "nft-expr-%.*s",
3105 				       nla_len(nla),
3106 				       (char *)nla_data(nla)) == -EAGAIN)
3107 			return ERR_PTR(-EAGAIN);
3108 	}
3109 #endif
3110 	return ERR_PTR(-ENOENT);
3111 }
3112 
3113 static const struct nla_policy nft_expr_policy[NFTA_EXPR_MAX + 1] = {
3114 	[NFTA_EXPR_NAME]	= { .type = NLA_STRING,
3115 				    .len = NFT_MODULE_AUTOLOAD_LIMIT },
3116 	[NFTA_EXPR_DATA]	= { .type = NLA_NESTED },
3117 };
3118 
nf_tables_fill_expr_info(struct sk_buff * skb,const struct nft_expr * expr,bool reset)3119 static int nf_tables_fill_expr_info(struct sk_buff *skb,
3120 				    const struct nft_expr *expr, bool reset)
3121 {
3122 	if (nla_put_string(skb, NFTA_EXPR_NAME, expr->ops->type->name))
3123 		goto nla_put_failure;
3124 
3125 	if (expr->ops->dump) {
3126 		struct nlattr *data = nla_nest_start_noflag(skb,
3127 							    NFTA_EXPR_DATA);
3128 		if (data == NULL)
3129 			goto nla_put_failure;
3130 		if (expr->ops->dump(skb, expr, reset) < 0)
3131 			goto nla_put_failure;
3132 		nla_nest_end(skb, data);
3133 	}
3134 
3135 	return skb->len;
3136 
3137 nla_put_failure:
3138 	return -1;
3139 };
3140 
nft_expr_dump(struct sk_buff * skb,unsigned int attr,const struct nft_expr * expr,bool reset)3141 int nft_expr_dump(struct sk_buff *skb, unsigned int attr,
3142 		  const struct nft_expr *expr, bool reset)
3143 {
3144 	struct nlattr *nest;
3145 
3146 	nest = nla_nest_start_noflag(skb, attr);
3147 	if (!nest)
3148 		goto nla_put_failure;
3149 	if (nf_tables_fill_expr_info(skb, expr, reset) < 0)
3150 		goto nla_put_failure;
3151 	nla_nest_end(skb, nest);
3152 	return 0;
3153 
3154 nla_put_failure:
3155 	return -1;
3156 }
3157 
3158 struct nft_expr_info {
3159 	const struct nft_expr_ops	*ops;
3160 	const struct nlattr		*attr;
3161 	struct nlattr			*tb[NFT_EXPR_MAXATTR + 1];
3162 };
3163 
nf_tables_expr_parse(const struct nft_ctx * ctx,const struct nlattr * nla,struct nft_expr_info * info)3164 static int nf_tables_expr_parse(const struct nft_ctx *ctx,
3165 				const struct nlattr *nla,
3166 				struct nft_expr_info *info)
3167 {
3168 	const struct nft_expr_type *type;
3169 	const struct nft_expr_ops *ops;
3170 	struct nlattr *tb[NFTA_EXPR_MAX + 1];
3171 	int err;
3172 
3173 	err = nla_parse_nested_deprecated(tb, NFTA_EXPR_MAX, nla,
3174 					  nft_expr_policy, NULL);
3175 	if (err < 0)
3176 		return err;
3177 
3178 	type = nft_expr_type_get(ctx->net, ctx->family, tb[NFTA_EXPR_NAME]);
3179 	if (IS_ERR(type))
3180 		return PTR_ERR(type);
3181 
3182 	if (tb[NFTA_EXPR_DATA]) {
3183 		err = nla_parse_nested_deprecated(info->tb, type->maxattr,
3184 						  tb[NFTA_EXPR_DATA],
3185 						  type->policy, NULL);
3186 		if (err < 0)
3187 			goto err1;
3188 	} else
3189 		memset(info->tb, 0, sizeof(info->tb[0]) * (type->maxattr + 1));
3190 
3191 	if (type->select_ops != NULL) {
3192 		ops = type->select_ops(ctx,
3193 				       (const struct nlattr * const *)info->tb);
3194 		if (IS_ERR(ops)) {
3195 			err = PTR_ERR(ops);
3196 #ifdef CONFIG_MODULES
3197 			if (err == -EAGAIN)
3198 				if (nft_expr_type_request_module(ctx->net,
3199 								 ctx->family,
3200 								 tb[NFTA_EXPR_NAME]) != -EAGAIN)
3201 					err = -ENOENT;
3202 #endif
3203 			goto err1;
3204 		}
3205 	} else
3206 		ops = type->ops;
3207 
3208 	info->attr = nla;
3209 	info->ops = ops;
3210 
3211 	return 0;
3212 
3213 err1:
3214 	module_put(type->owner);
3215 	return err;
3216 }
3217 
nft_expr_inner_parse(const struct nft_ctx * ctx,const struct nlattr * nla,struct nft_expr_info * info)3218 int nft_expr_inner_parse(const struct nft_ctx *ctx, const struct nlattr *nla,
3219 			 struct nft_expr_info *info)
3220 {
3221 	struct nlattr *tb[NFTA_EXPR_MAX + 1];
3222 	const struct nft_expr_type *type;
3223 	int err;
3224 
3225 	err = nla_parse_nested_deprecated(tb, NFTA_EXPR_MAX, nla,
3226 					  nft_expr_policy, NULL);
3227 	if (err < 0)
3228 		return err;
3229 
3230 	if (!tb[NFTA_EXPR_DATA] || !tb[NFTA_EXPR_NAME])
3231 		return -EINVAL;
3232 
3233 	type = __nft_expr_type_get(ctx->family, tb[NFTA_EXPR_NAME]);
3234 	if (!type)
3235 		return -ENOENT;
3236 
3237 	if (!type->inner_ops)
3238 		return -EOPNOTSUPP;
3239 
3240 	err = nla_parse_nested_deprecated(info->tb, type->maxattr,
3241 					  tb[NFTA_EXPR_DATA],
3242 					  type->policy, NULL);
3243 	if (err < 0)
3244 		goto err_nla_parse;
3245 
3246 	info->attr = nla;
3247 	info->ops = type->inner_ops;
3248 
3249 	return 0;
3250 
3251 err_nla_parse:
3252 	return err;
3253 }
3254 
nf_tables_newexpr(const struct nft_ctx * ctx,const struct nft_expr_info * expr_info,struct nft_expr * expr)3255 static int nf_tables_newexpr(const struct nft_ctx *ctx,
3256 			     const struct nft_expr_info *expr_info,
3257 			     struct nft_expr *expr)
3258 {
3259 	const struct nft_expr_ops *ops = expr_info->ops;
3260 	int err;
3261 
3262 	expr->ops = ops;
3263 	if (ops->init) {
3264 		err = ops->init(ctx, expr, (const struct nlattr **)expr_info->tb);
3265 		if (err < 0)
3266 			goto err1;
3267 	}
3268 
3269 	return 0;
3270 err1:
3271 	expr->ops = NULL;
3272 	return err;
3273 }
3274 
nf_tables_expr_destroy(const struct nft_ctx * ctx,struct nft_expr * expr)3275 static void nf_tables_expr_destroy(const struct nft_ctx *ctx,
3276 				   struct nft_expr *expr)
3277 {
3278 	const struct nft_expr_type *type = expr->ops->type;
3279 
3280 	if (expr->ops->destroy)
3281 		expr->ops->destroy(ctx, expr);
3282 	module_put(type->owner);
3283 }
3284 
nft_expr_init(const struct nft_ctx * ctx,const struct nlattr * nla)3285 static struct nft_expr *nft_expr_init(const struct nft_ctx *ctx,
3286 				      const struct nlattr *nla)
3287 {
3288 	struct nft_expr_info expr_info;
3289 	struct nft_expr *expr;
3290 	struct module *owner;
3291 	int err;
3292 
3293 	err = nf_tables_expr_parse(ctx, nla, &expr_info);
3294 	if (err < 0)
3295 		goto err_expr_parse;
3296 
3297 	err = -EOPNOTSUPP;
3298 	if (!(expr_info.ops->type->flags & NFT_EXPR_STATEFUL))
3299 		goto err_expr_stateful;
3300 
3301 	err = -ENOMEM;
3302 	expr = kzalloc(expr_info.ops->size, GFP_KERNEL_ACCOUNT);
3303 	if (expr == NULL)
3304 		goto err_expr_stateful;
3305 
3306 	err = nf_tables_newexpr(ctx, &expr_info, expr);
3307 	if (err < 0)
3308 		goto err_expr_new;
3309 
3310 	return expr;
3311 err_expr_new:
3312 	kfree(expr);
3313 err_expr_stateful:
3314 	owner = expr_info.ops->type->owner;
3315 	if (expr_info.ops->type->release_ops)
3316 		expr_info.ops->type->release_ops(expr_info.ops);
3317 
3318 	module_put(owner);
3319 err_expr_parse:
3320 	return ERR_PTR(err);
3321 }
3322 
nft_expr_clone(struct nft_expr * dst,struct nft_expr * src)3323 int nft_expr_clone(struct nft_expr *dst, struct nft_expr *src)
3324 {
3325 	int err;
3326 
3327 	if (src->ops->clone) {
3328 		dst->ops = src->ops;
3329 		err = src->ops->clone(dst, src);
3330 		if (err < 0)
3331 			return err;
3332 	} else {
3333 		memcpy(dst, src, src->ops->size);
3334 	}
3335 
3336 	__module_get(src->ops->type->owner);
3337 
3338 	return 0;
3339 }
3340 
nft_expr_destroy(const struct nft_ctx * ctx,struct nft_expr * expr)3341 void nft_expr_destroy(const struct nft_ctx *ctx, struct nft_expr *expr)
3342 {
3343 	nf_tables_expr_destroy(ctx, expr);
3344 	kfree(expr);
3345 }
3346 
3347 /*
3348  * Rules
3349  */
3350 
__nft_rule_lookup(const struct nft_chain * chain,u64 handle)3351 static struct nft_rule *__nft_rule_lookup(const struct nft_chain *chain,
3352 					  u64 handle)
3353 {
3354 	struct nft_rule *rule;
3355 
3356 	// FIXME: this sucks
3357 	list_for_each_entry_rcu(rule, &chain->rules, list) {
3358 		if (handle == rule->handle)
3359 			return rule;
3360 	}
3361 
3362 	return ERR_PTR(-ENOENT);
3363 }
3364 
nft_rule_lookup(const struct nft_chain * chain,const struct nlattr * nla)3365 static struct nft_rule *nft_rule_lookup(const struct nft_chain *chain,
3366 					const struct nlattr *nla)
3367 {
3368 	if (nla == NULL)
3369 		return ERR_PTR(-EINVAL);
3370 
3371 	return __nft_rule_lookup(chain, be64_to_cpu(nla_get_be64(nla)));
3372 }
3373 
3374 static const struct nla_policy nft_rule_policy[NFTA_RULE_MAX + 1] = {
3375 	[NFTA_RULE_TABLE]	= { .type = NLA_STRING,
3376 				    .len = NFT_TABLE_MAXNAMELEN - 1 },
3377 	[NFTA_RULE_CHAIN]	= { .type = NLA_STRING,
3378 				    .len = NFT_CHAIN_MAXNAMELEN - 1 },
3379 	[NFTA_RULE_HANDLE]	= { .type = NLA_U64 },
3380 	[NFTA_RULE_EXPRESSIONS]	= { .type = NLA_NESTED },
3381 	[NFTA_RULE_COMPAT]	= { .type = NLA_NESTED },
3382 	[NFTA_RULE_POSITION]	= { .type = NLA_U64 },
3383 	[NFTA_RULE_USERDATA]	= { .type = NLA_BINARY,
3384 				    .len = NFT_USERDATA_MAXLEN },
3385 	[NFTA_RULE_ID]		= { .type = NLA_U32 },
3386 	[NFTA_RULE_POSITION_ID]	= { .type = NLA_U32 },
3387 	[NFTA_RULE_CHAIN_ID]	= { .type = NLA_U32 },
3388 };
3389 
nf_tables_fill_rule_info(struct sk_buff * skb,struct net * net,u32 portid,u32 seq,int event,u32 flags,int family,const struct nft_table * table,const struct nft_chain * chain,const struct nft_rule * rule,u64 handle,bool reset)3390 static int nf_tables_fill_rule_info(struct sk_buff *skb, struct net *net,
3391 				    u32 portid, u32 seq, int event,
3392 				    u32 flags, int family,
3393 				    const struct nft_table *table,
3394 				    const struct nft_chain *chain,
3395 				    const struct nft_rule *rule, u64 handle,
3396 				    bool reset)
3397 {
3398 	struct nlmsghdr *nlh;
3399 	const struct nft_expr *expr, *next;
3400 	struct nlattr *list;
3401 	u16 type = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
3402 
3403 	nlh = nfnl_msg_put(skb, portid, seq, type, flags, family, NFNETLINK_V0,
3404 			   nft_base_seq(net));
3405 	if (!nlh)
3406 		goto nla_put_failure;
3407 
3408 	if (nla_put_string(skb, NFTA_RULE_TABLE, table->name))
3409 		goto nla_put_failure;
3410 	if (nla_put_string(skb, NFTA_RULE_CHAIN, chain->name))
3411 		goto nla_put_failure;
3412 	if (nla_put_be64(skb, NFTA_RULE_HANDLE, cpu_to_be64(rule->handle),
3413 			 NFTA_RULE_PAD))
3414 		goto nla_put_failure;
3415 
3416 	if (event != NFT_MSG_DELRULE && handle) {
3417 		if (nla_put_be64(skb, NFTA_RULE_POSITION, cpu_to_be64(handle),
3418 				 NFTA_RULE_PAD))
3419 			goto nla_put_failure;
3420 	}
3421 
3422 	if (chain->flags & NFT_CHAIN_HW_OFFLOAD)
3423 		nft_flow_rule_stats(chain, rule);
3424 
3425 	list = nla_nest_start_noflag(skb, NFTA_RULE_EXPRESSIONS);
3426 	if (list == NULL)
3427 		goto nla_put_failure;
3428 	nft_rule_for_each_expr(expr, next, rule) {
3429 		if (nft_expr_dump(skb, NFTA_LIST_ELEM, expr, reset) < 0)
3430 			goto nla_put_failure;
3431 	}
3432 	nla_nest_end(skb, list);
3433 
3434 	if (rule->udata) {
3435 		struct nft_userdata *udata = nft_userdata(rule);
3436 		if (nla_put(skb, NFTA_RULE_USERDATA, udata->len + 1,
3437 			    udata->data) < 0)
3438 			goto nla_put_failure;
3439 	}
3440 
3441 	nlmsg_end(skb, nlh);
3442 	return 0;
3443 
3444 nla_put_failure:
3445 	nlmsg_trim(skb, nlh);
3446 	return -1;
3447 }
3448 
nf_tables_rule_notify(const struct nft_ctx * ctx,const struct nft_rule * rule,int event)3449 static void nf_tables_rule_notify(const struct nft_ctx *ctx,
3450 				  const struct nft_rule *rule, int event)
3451 {
3452 	struct nftables_pernet *nft_net = nft_pernet(ctx->net);
3453 	const struct nft_rule *prule;
3454 	struct sk_buff *skb;
3455 	u64 handle = 0;
3456 	u16 flags = 0;
3457 	int err;
3458 
3459 	if (!ctx->report &&
3460 	    !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
3461 		return;
3462 
3463 	skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
3464 	if (skb == NULL)
3465 		goto err;
3466 
3467 	if (event == NFT_MSG_NEWRULE &&
3468 	    !list_is_first(&rule->list, &ctx->chain->rules) &&
3469 	    !list_is_last(&rule->list, &ctx->chain->rules)) {
3470 		prule = list_prev_entry(rule, list);
3471 		handle = prule->handle;
3472 	}
3473 	if (ctx->flags & (NLM_F_APPEND | NLM_F_REPLACE))
3474 		flags |= NLM_F_APPEND;
3475 	if (ctx->flags & (NLM_F_CREATE | NLM_F_EXCL))
3476 		flags |= ctx->flags & (NLM_F_CREATE | NLM_F_EXCL);
3477 
3478 	err = nf_tables_fill_rule_info(skb, ctx->net, ctx->portid, ctx->seq,
3479 				       event, flags, ctx->family, ctx->table,
3480 				       ctx->chain, rule, handle, false);
3481 	if (err < 0) {
3482 		kfree_skb(skb);
3483 		goto err;
3484 	}
3485 
3486 	nft_notify_enqueue(skb, ctx->report, &nft_net->notify_list);
3487 	return;
3488 err:
3489 	nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
3490 }
3491 
audit_log_rule_reset(const struct nft_table * table,unsigned int base_seq,unsigned int nentries)3492 static void audit_log_rule_reset(const struct nft_table *table,
3493 				 unsigned int base_seq,
3494 				 unsigned int nentries)
3495 {
3496 	char *buf = kasprintf(GFP_ATOMIC, "%s:%u",
3497 			      table->name, base_seq);
3498 
3499 	audit_log_nfcfg(buf, table->family, nentries,
3500 			AUDIT_NFT_OP_RULE_RESET, GFP_ATOMIC);
3501 	kfree(buf);
3502 }
3503 
3504 struct nft_rule_dump_ctx {
3505 	char *table;
3506 	char *chain;
3507 };
3508 
__nf_tables_dump_rules(struct sk_buff * skb,unsigned int * idx,struct netlink_callback * cb,const struct nft_table * table,const struct nft_chain * chain,bool reset)3509 static int __nf_tables_dump_rules(struct sk_buff *skb,
3510 				  unsigned int *idx,
3511 				  struct netlink_callback *cb,
3512 				  const struct nft_table *table,
3513 				  const struct nft_chain *chain,
3514 				  bool reset)
3515 {
3516 	struct net *net = sock_net(skb->sk);
3517 	const struct nft_rule *rule, *prule;
3518 	unsigned int s_idx = cb->args[0];
3519 	unsigned int entries = 0;
3520 	int ret = 0;
3521 	u64 handle;
3522 
3523 	prule = NULL;
3524 	list_for_each_entry_rcu(rule, &chain->rules, list) {
3525 		if (!nft_is_active(net, rule))
3526 			goto cont_skip;
3527 		if (*idx < s_idx)
3528 			goto cont;
3529 		if (prule)
3530 			handle = prule->handle;
3531 		else
3532 			handle = 0;
3533 
3534 		if (nf_tables_fill_rule_info(skb, net, NETLINK_CB(cb->skb).portid,
3535 					cb->nlh->nlmsg_seq,
3536 					NFT_MSG_NEWRULE,
3537 					NLM_F_MULTI | NLM_F_APPEND,
3538 					table->family,
3539 					table, chain, rule, handle, reset) < 0) {
3540 			ret = 1;
3541 			break;
3542 		}
3543 		entries++;
3544 		nl_dump_check_consistent(cb, nlmsg_hdr(skb));
3545 cont:
3546 		prule = rule;
3547 cont_skip:
3548 		(*idx)++;
3549 	}
3550 
3551 	if (reset && entries)
3552 		audit_log_rule_reset(table, cb->seq, entries);
3553 
3554 	return ret;
3555 }
3556 
nf_tables_dump_rules(struct sk_buff * skb,struct netlink_callback * cb)3557 static int nf_tables_dump_rules(struct sk_buff *skb,
3558 				struct netlink_callback *cb)
3559 {
3560 	const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
3561 	const struct nft_rule_dump_ctx *ctx = cb->data;
3562 	struct nft_table *table;
3563 	const struct nft_chain *chain;
3564 	unsigned int idx = 0;
3565 	struct net *net = sock_net(skb->sk);
3566 	int family = nfmsg->nfgen_family;
3567 	struct nftables_pernet *nft_net;
3568 	bool reset = false;
3569 
3570 	if (NFNL_MSG_TYPE(cb->nlh->nlmsg_type) == NFT_MSG_GETRULE_RESET)
3571 		reset = true;
3572 
3573 	rcu_read_lock();
3574 	nft_net = nft_pernet(net);
3575 	cb->seq = READ_ONCE(nft_net->base_seq);
3576 
3577 	list_for_each_entry_rcu(table, &nft_net->tables, list) {
3578 		if (family != NFPROTO_UNSPEC && family != table->family)
3579 			continue;
3580 
3581 		if (ctx && ctx->table && strcmp(ctx->table, table->name) != 0)
3582 			continue;
3583 
3584 		if (ctx && ctx->table && ctx->chain) {
3585 			struct rhlist_head *list, *tmp;
3586 
3587 			list = rhltable_lookup(&table->chains_ht, ctx->chain,
3588 					       nft_chain_ht_params);
3589 			if (!list)
3590 				goto done;
3591 
3592 			rhl_for_each_entry_rcu(chain, tmp, list, rhlhead) {
3593 				if (!nft_is_active(net, chain))
3594 					continue;
3595 				__nf_tables_dump_rules(skb, &idx,
3596 						       cb, table, chain, reset);
3597 				break;
3598 			}
3599 			goto done;
3600 		}
3601 
3602 		list_for_each_entry_rcu(chain, &table->chains, list) {
3603 			if (__nf_tables_dump_rules(skb, &idx,
3604 						   cb, table, chain, reset))
3605 				goto done;
3606 		}
3607 
3608 		if (ctx && ctx->table)
3609 			break;
3610 	}
3611 done:
3612 	rcu_read_unlock();
3613 
3614 	cb->args[0] = idx;
3615 	return skb->len;
3616 }
3617 
nf_tables_dump_rules_start(struct netlink_callback * cb)3618 static int nf_tables_dump_rules_start(struct netlink_callback *cb)
3619 {
3620 	const struct nlattr * const *nla = cb->data;
3621 	struct nft_rule_dump_ctx *ctx = NULL;
3622 
3623 	if (nla[NFTA_RULE_TABLE] || nla[NFTA_RULE_CHAIN]) {
3624 		ctx = kzalloc(sizeof(*ctx), GFP_ATOMIC);
3625 		if (!ctx)
3626 			return -ENOMEM;
3627 
3628 		if (nla[NFTA_RULE_TABLE]) {
3629 			ctx->table = nla_strdup(nla[NFTA_RULE_TABLE],
3630 							GFP_ATOMIC);
3631 			if (!ctx->table) {
3632 				kfree(ctx);
3633 				return -ENOMEM;
3634 			}
3635 		}
3636 		if (nla[NFTA_RULE_CHAIN]) {
3637 			ctx->chain = nla_strdup(nla[NFTA_RULE_CHAIN],
3638 						GFP_ATOMIC);
3639 			if (!ctx->chain) {
3640 				kfree(ctx->table);
3641 				kfree(ctx);
3642 				return -ENOMEM;
3643 			}
3644 		}
3645 	}
3646 
3647 	cb->data = ctx;
3648 	return 0;
3649 }
3650 
nf_tables_dump_rules_done(struct netlink_callback * cb)3651 static int nf_tables_dump_rules_done(struct netlink_callback *cb)
3652 {
3653 	struct nft_rule_dump_ctx *ctx = cb->data;
3654 
3655 	if (ctx) {
3656 		kfree(ctx->table);
3657 		kfree(ctx->chain);
3658 		kfree(ctx);
3659 	}
3660 	return 0;
3661 }
3662 
3663 /* called with rcu_read_lock held */
nf_tables_getrule(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])3664 static int nf_tables_getrule(struct sk_buff *skb, const struct nfnl_info *info,
3665 			     const struct nlattr * const nla[])
3666 {
3667 	struct netlink_ext_ack *extack = info->extack;
3668 	u8 genmask = nft_genmask_cur(info->net);
3669 	u8 family = info->nfmsg->nfgen_family;
3670 	const struct nft_chain *chain;
3671 	const struct nft_rule *rule;
3672 	struct net *net = info->net;
3673 	struct nft_table *table;
3674 	struct sk_buff *skb2;
3675 	bool reset = false;
3676 	int err;
3677 
3678 	if (info->nlh->nlmsg_flags & NLM_F_DUMP) {
3679 		struct netlink_dump_control c = {
3680 			.start= nf_tables_dump_rules_start,
3681 			.dump = nf_tables_dump_rules,
3682 			.done = nf_tables_dump_rules_done,
3683 			.module = THIS_MODULE,
3684 			.data = (void *)nla,
3685 		};
3686 
3687 		return nft_netlink_dump_start_rcu(info->sk, skb, info->nlh, &c);
3688 	}
3689 
3690 	table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask, 0);
3691 	if (IS_ERR(table)) {
3692 		NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
3693 		return PTR_ERR(table);
3694 	}
3695 
3696 	chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN], genmask);
3697 	if (IS_ERR(chain)) {
3698 		NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
3699 		return PTR_ERR(chain);
3700 	}
3701 
3702 	rule = nft_rule_lookup(chain, nla[NFTA_RULE_HANDLE]);
3703 	if (IS_ERR(rule)) {
3704 		NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
3705 		return PTR_ERR(rule);
3706 	}
3707 
3708 	skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
3709 	if (!skb2)
3710 		return -ENOMEM;
3711 
3712 	if (NFNL_MSG_TYPE(info->nlh->nlmsg_type) == NFT_MSG_GETRULE_RESET)
3713 		reset = true;
3714 
3715 	err = nf_tables_fill_rule_info(skb2, net, NETLINK_CB(skb).portid,
3716 				       info->nlh->nlmsg_seq, NFT_MSG_NEWRULE, 0,
3717 				       family, table, chain, rule, 0, reset);
3718 	if (err < 0)
3719 		goto err_fill_rule_info;
3720 
3721 	if (reset)
3722 		audit_log_rule_reset(table, nft_pernet(net)->base_seq, 1);
3723 
3724 	return nfnetlink_unicast(skb2, net, NETLINK_CB(skb).portid);
3725 
3726 err_fill_rule_info:
3727 	kfree_skb(skb2);
3728 	return err;
3729 }
3730 
nf_tables_rule_destroy(const struct nft_ctx * ctx,struct nft_rule * rule)3731 void nf_tables_rule_destroy(const struct nft_ctx *ctx, struct nft_rule *rule)
3732 {
3733 	struct nft_expr *expr, *next;
3734 
3735 	/*
3736 	 * Careful: some expressions might not be initialized in case this
3737 	 * is called on error from nf_tables_newrule().
3738 	 */
3739 	expr = nft_expr_first(rule);
3740 	while (nft_expr_more(rule, expr)) {
3741 		next = nft_expr_next(expr);
3742 		nf_tables_expr_destroy(ctx, expr);
3743 		expr = next;
3744 	}
3745 	kfree(rule);
3746 }
3747 
nf_tables_rule_release(const struct nft_ctx * ctx,struct nft_rule * rule)3748 static void nf_tables_rule_release(const struct nft_ctx *ctx, struct nft_rule *rule)
3749 {
3750 	nft_rule_expr_deactivate(ctx, rule, NFT_TRANS_RELEASE);
3751 	nf_tables_rule_destroy(ctx, rule);
3752 }
3753 
3754 /** nft_chain_validate - loop detection and hook validation
3755  *
3756  * @ctx: context containing call depth and base chain
3757  * @chain: chain to validate
3758  *
3759  * Walk through the rules of the given chain and chase all jumps/gotos
3760  * and set lookups until either the jump limit is hit or all reachable
3761  * chains have been validated.
3762  */
nft_chain_validate(const struct nft_ctx * ctx,const struct nft_chain * chain)3763 int nft_chain_validate(const struct nft_ctx *ctx, const struct nft_chain *chain)
3764 {
3765 	struct nft_expr *expr, *last;
3766 	const struct nft_data *data;
3767 	struct nft_rule *rule;
3768 	int err;
3769 
3770 	if (ctx->level == NFT_JUMP_STACK_SIZE)
3771 		return -EMLINK;
3772 
3773 	list_for_each_entry(rule, &chain->rules, list) {
3774 		if (fatal_signal_pending(current))
3775 			return -EINTR;
3776 
3777 		if (!nft_is_active_next(ctx->net, rule))
3778 			continue;
3779 
3780 		nft_rule_for_each_expr(expr, last, rule) {
3781 			if (!expr->ops->validate)
3782 				continue;
3783 
3784 			/* This may call nft_chain_validate() recursively,
3785 			 * callers that do so must increment ctx->level.
3786 			 */
3787 			err = expr->ops->validate(ctx, expr, &data);
3788 			if (err < 0)
3789 				return err;
3790 		}
3791 	}
3792 
3793 	return 0;
3794 }
3795 EXPORT_SYMBOL_GPL(nft_chain_validate);
3796 
nft_table_validate(struct net * net,const struct nft_table * table)3797 static int nft_table_validate(struct net *net, const struct nft_table *table)
3798 {
3799 	struct nft_chain *chain;
3800 	struct nft_ctx ctx = {
3801 		.net	= net,
3802 		.family	= table->family,
3803 	};
3804 	int err;
3805 
3806 	list_for_each_entry(chain, &table->chains, list) {
3807 		if (!nft_is_base_chain(chain))
3808 			continue;
3809 
3810 		ctx.chain = chain;
3811 		err = nft_chain_validate(&ctx, chain);
3812 		if (err < 0)
3813 			return err;
3814 
3815 		cond_resched();
3816 	}
3817 
3818 	return 0;
3819 }
3820 
nft_setelem_validate(const struct nft_ctx * ctx,struct nft_set * set,const struct nft_set_iter * iter,struct nft_set_elem * elem)3821 int nft_setelem_validate(const struct nft_ctx *ctx, struct nft_set *set,
3822 			 const struct nft_set_iter *iter,
3823 			 struct nft_set_elem *elem)
3824 {
3825 	const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
3826 	struct nft_ctx *pctx = (struct nft_ctx *)ctx;
3827 	const struct nft_data *data;
3828 	int err;
3829 
3830 	if (!nft_set_elem_active(ext, iter->genmask))
3831 		return 0;
3832 
3833 	if (nft_set_ext_exists(ext, NFT_SET_EXT_FLAGS) &&
3834 	    *nft_set_ext_flags(ext) & NFT_SET_ELEM_INTERVAL_END)
3835 		return 0;
3836 
3837 	data = nft_set_ext_data(ext);
3838 	switch (data->verdict.code) {
3839 	case NFT_JUMP:
3840 	case NFT_GOTO:
3841 		pctx->level++;
3842 		err = nft_chain_validate(ctx, data->verdict.chain);
3843 		if (err < 0)
3844 			return err;
3845 		pctx->level--;
3846 		break;
3847 	default:
3848 		break;
3849 	}
3850 
3851 	return 0;
3852 }
3853 
nft_set_catchall_validate(const struct nft_ctx * ctx,struct nft_set * set)3854 int nft_set_catchall_validate(const struct nft_ctx *ctx, struct nft_set *set)
3855 {
3856 	struct nft_set_iter dummy_iter = {
3857 		.genmask	= nft_genmask_next(ctx->net),
3858 	};
3859 	struct nft_set_elem_catchall *catchall;
3860 	struct nft_set_elem elem;
3861 
3862 	struct nft_set_ext *ext;
3863 	int ret = 0;
3864 
3865 	list_for_each_entry_rcu(catchall, &set->catchall_list, list) {
3866 		ext = nft_set_elem_ext(set, catchall->elem);
3867 		if (!nft_set_elem_active(ext, dummy_iter.genmask))
3868 			continue;
3869 
3870 		elem.priv = catchall->elem;
3871 		ret = nft_setelem_validate(ctx, set, &dummy_iter, &elem);
3872 		if (ret < 0)
3873 			return ret;
3874 	}
3875 
3876 	return ret;
3877 }
3878 
3879 static struct nft_rule *nft_rule_lookup_byid(const struct net *net,
3880 					     const struct nft_chain *chain,
3881 					     const struct nlattr *nla);
3882 
3883 #define NFT_RULE_MAXEXPRS	128
3884 
nf_tables_newrule(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])3885 static int nf_tables_newrule(struct sk_buff *skb, const struct nfnl_info *info,
3886 			     const struct nlattr * const nla[])
3887 {
3888 	struct nftables_pernet *nft_net = nft_pernet(info->net);
3889 	struct netlink_ext_ack *extack = info->extack;
3890 	unsigned int size, i, n, ulen = 0, usize = 0;
3891 	u8 genmask = nft_genmask_next(info->net);
3892 	struct nft_rule *rule, *old_rule = NULL;
3893 	struct nft_expr_info *expr_info = NULL;
3894 	u8 family = info->nfmsg->nfgen_family;
3895 	struct nft_flow_rule *flow = NULL;
3896 	struct net *net = info->net;
3897 	struct nft_userdata *udata;
3898 	struct nft_table *table;
3899 	struct nft_chain *chain;
3900 	struct nft_trans *trans;
3901 	u64 handle, pos_handle;
3902 	struct nft_expr *expr;
3903 	struct nft_ctx ctx;
3904 	struct nlattr *tmp;
3905 	int err, rem;
3906 
3907 	lockdep_assert_held(&nft_net->commit_mutex);
3908 
3909 	table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask,
3910 				 NETLINK_CB(skb).portid);
3911 	if (IS_ERR(table)) {
3912 		NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
3913 		return PTR_ERR(table);
3914 	}
3915 
3916 	if (nla[NFTA_RULE_CHAIN]) {
3917 		chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN],
3918 					 genmask);
3919 		if (IS_ERR(chain)) {
3920 			NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
3921 			return PTR_ERR(chain);
3922 		}
3923 
3924 	} else if (nla[NFTA_RULE_CHAIN_ID]) {
3925 		chain = nft_chain_lookup_byid(net, table, nla[NFTA_RULE_CHAIN_ID],
3926 					      genmask);
3927 		if (IS_ERR(chain)) {
3928 			NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN_ID]);
3929 			return PTR_ERR(chain);
3930 		}
3931 	} else {
3932 		return -EINVAL;
3933 	}
3934 
3935 	if (nft_chain_is_bound(chain))
3936 		return -EOPNOTSUPP;
3937 
3938 	if (nla[NFTA_RULE_HANDLE]) {
3939 		handle = be64_to_cpu(nla_get_be64(nla[NFTA_RULE_HANDLE]));
3940 		rule = __nft_rule_lookup(chain, handle);
3941 		if (IS_ERR(rule)) {
3942 			NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
3943 			return PTR_ERR(rule);
3944 		}
3945 
3946 		if (info->nlh->nlmsg_flags & NLM_F_EXCL) {
3947 			NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
3948 			return -EEXIST;
3949 		}
3950 		if (info->nlh->nlmsg_flags & NLM_F_REPLACE)
3951 			old_rule = rule;
3952 		else
3953 			return -EOPNOTSUPP;
3954 	} else {
3955 		if (!(info->nlh->nlmsg_flags & NLM_F_CREATE) ||
3956 		    info->nlh->nlmsg_flags & NLM_F_REPLACE)
3957 			return -EINVAL;
3958 		handle = nf_tables_alloc_handle(table);
3959 
3960 		if (nla[NFTA_RULE_POSITION]) {
3961 			pos_handle = be64_to_cpu(nla_get_be64(nla[NFTA_RULE_POSITION]));
3962 			old_rule = __nft_rule_lookup(chain, pos_handle);
3963 			if (IS_ERR(old_rule)) {
3964 				NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_POSITION]);
3965 				return PTR_ERR(old_rule);
3966 			}
3967 		} else if (nla[NFTA_RULE_POSITION_ID]) {
3968 			old_rule = nft_rule_lookup_byid(net, chain, nla[NFTA_RULE_POSITION_ID]);
3969 			if (IS_ERR(old_rule)) {
3970 				NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_POSITION_ID]);
3971 				return PTR_ERR(old_rule);
3972 			}
3973 		}
3974 	}
3975 
3976 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, chain, nla);
3977 
3978 	n = 0;
3979 	size = 0;
3980 	if (nla[NFTA_RULE_EXPRESSIONS]) {
3981 		expr_info = kvmalloc_array(NFT_RULE_MAXEXPRS,
3982 					   sizeof(struct nft_expr_info),
3983 					   GFP_KERNEL);
3984 		if (!expr_info)
3985 			return -ENOMEM;
3986 
3987 		nla_for_each_nested(tmp, nla[NFTA_RULE_EXPRESSIONS], rem) {
3988 			err = -EINVAL;
3989 			if (nla_type(tmp) != NFTA_LIST_ELEM)
3990 				goto err_release_expr;
3991 			if (n == NFT_RULE_MAXEXPRS)
3992 				goto err_release_expr;
3993 			err = nf_tables_expr_parse(&ctx, tmp, &expr_info[n]);
3994 			if (err < 0) {
3995 				NL_SET_BAD_ATTR(extack, tmp);
3996 				goto err_release_expr;
3997 			}
3998 			size += expr_info[n].ops->size;
3999 			n++;
4000 		}
4001 	}
4002 	/* Check for overflow of dlen field */
4003 	err = -EFBIG;
4004 	if (size >= 1 << 12)
4005 		goto err_release_expr;
4006 
4007 	if (nla[NFTA_RULE_USERDATA]) {
4008 		ulen = nla_len(nla[NFTA_RULE_USERDATA]);
4009 		if (ulen > 0)
4010 			usize = sizeof(struct nft_userdata) + ulen;
4011 	}
4012 
4013 	err = -ENOMEM;
4014 	rule = kzalloc(sizeof(*rule) + size + usize, GFP_KERNEL_ACCOUNT);
4015 	if (rule == NULL)
4016 		goto err_release_expr;
4017 
4018 	nft_activate_next(net, rule);
4019 
4020 	rule->handle = handle;
4021 	rule->dlen   = size;
4022 	rule->udata  = ulen ? 1 : 0;
4023 
4024 	if (ulen) {
4025 		udata = nft_userdata(rule);
4026 		udata->len = ulen - 1;
4027 		nla_memcpy(udata->data, nla[NFTA_RULE_USERDATA], ulen);
4028 	}
4029 
4030 	expr = nft_expr_first(rule);
4031 	for (i = 0; i < n; i++) {
4032 		err = nf_tables_newexpr(&ctx, &expr_info[i], expr);
4033 		if (err < 0) {
4034 			NL_SET_BAD_ATTR(extack, expr_info[i].attr);
4035 			goto err_release_rule;
4036 		}
4037 
4038 		if (expr_info[i].ops->validate)
4039 			nft_validate_state_update(table, NFT_VALIDATE_NEED);
4040 
4041 		expr_info[i].ops = NULL;
4042 		expr = nft_expr_next(expr);
4043 	}
4044 
4045 	if (chain->flags & NFT_CHAIN_HW_OFFLOAD) {
4046 		flow = nft_flow_rule_create(net, rule);
4047 		if (IS_ERR(flow)) {
4048 			err = PTR_ERR(flow);
4049 			goto err_release_rule;
4050 		}
4051 	}
4052 
4053 	if (!nft_use_inc(&chain->use)) {
4054 		err = -EMFILE;
4055 		goto err_release_rule;
4056 	}
4057 
4058 	if (info->nlh->nlmsg_flags & NLM_F_REPLACE) {
4059 		if (nft_chain_binding(chain)) {
4060 			err = -EOPNOTSUPP;
4061 			goto err_destroy_flow_rule;
4062 		}
4063 
4064 		err = nft_delrule(&ctx, old_rule);
4065 		if (err < 0)
4066 			goto err_destroy_flow_rule;
4067 
4068 		trans = nft_trans_rule_add(&ctx, NFT_MSG_NEWRULE, rule);
4069 		if (trans == NULL) {
4070 			err = -ENOMEM;
4071 			goto err_destroy_flow_rule;
4072 		}
4073 		list_add_tail_rcu(&rule->list, &old_rule->list);
4074 	} else {
4075 		trans = nft_trans_rule_add(&ctx, NFT_MSG_NEWRULE, rule);
4076 		if (!trans) {
4077 			err = -ENOMEM;
4078 			goto err_destroy_flow_rule;
4079 		}
4080 
4081 		if (info->nlh->nlmsg_flags & NLM_F_APPEND) {
4082 			if (old_rule)
4083 				list_add_rcu(&rule->list, &old_rule->list);
4084 			else
4085 				list_add_tail_rcu(&rule->list, &chain->rules);
4086 		 } else {
4087 			if (old_rule)
4088 				list_add_tail_rcu(&rule->list, &old_rule->list);
4089 			else
4090 				list_add_rcu(&rule->list, &chain->rules);
4091 		}
4092 	}
4093 	kvfree(expr_info);
4094 
4095 	if (flow)
4096 		nft_trans_flow_rule(trans) = flow;
4097 
4098 	if (table->validate_state == NFT_VALIDATE_DO)
4099 		return nft_table_validate(net, table);
4100 
4101 	return 0;
4102 
4103 err_destroy_flow_rule:
4104 	nft_use_dec_restore(&chain->use);
4105 	if (flow)
4106 		nft_flow_rule_destroy(flow);
4107 err_release_rule:
4108 	nft_rule_expr_deactivate(&ctx, rule, NFT_TRANS_PREPARE_ERROR);
4109 	nf_tables_rule_destroy(&ctx, rule);
4110 err_release_expr:
4111 	for (i = 0; i < n; i++) {
4112 		if (expr_info[i].ops) {
4113 			module_put(expr_info[i].ops->type->owner);
4114 			if (expr_info[i].ops->type->release_ops)
4115 				expr_info[i].ops->type->release_ops(expr_info[i].ops);
4116 		}
4117 	}
4118 	kvfree(expr_info);
4119 
4120 	return err;
4121 }
4122 
nft_rule_lookup_byid(const struct net * net,const struct nft_chain * chain,const struct nlattr * nla)4123 static struct nft_rule *nft_rule_lookup_byid(const struct net *net,
4124 					     const struct nft_chain *chain,
4125 					     const struct nlattr *nla)
4126 {
4127 	struct nftables_pernet *nft_net = nft_pernet(net);
4128 	u32 id = ntohl(nla_get_be32(nla));
4129 	struct nft_trans *trans;
4130 
4131 	list_for_each_entry(trans, &nft_net->commit_list, list) {
4132 		if (trans->msg_type == NFT_MSG_NEWRULE &&
4133 		    trans->ctx.chain == chain &&
4134 		    id == nft_trans_rule_id(trans))
4135 			return nft_trans_rule(trans);
4136 	}
4137 	return ERR_PTR(-ENOENT);
4138 }
4139 
nf_tables_delrule(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])4140 static int nf_tables_delrule(struct sk_buff *skb, const struct nfnl_info *info,
4141 			     const struct nlattr * const nla[])
4142 {
4143 	struct netlink_ext_ack *extack = info->extack;
4144 	u8 genmask = nft_genmask_next(info->net);
4145 	u8 family = info->nfmsg->nfgen_family;
4146 	struct nft_chain *chain = NULL;
4147 	struct net *net = info->net;
4148 	struct nft_table *table;
4149 	struct nft_rule *rule;
4150 	struct nft_ctx ctx;
4151 	int err = 0;
4152 
4153 	table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask,
4154 				 NETLINK_CB(skb).portid);
4155 	if (IS_ERR(table)) {
4156 		NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
4157 		return PTR_ERR(table);
4158 	}
4159 
4160 	if (nla[NFTA_RULE_CHAIN]) {
4161 		chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN],
4162 					 genmask);
4163 		if (IS_ERR(chain)) {
4164 			if (PTR_ERR(chain) == -ENOENT &&
4165 			    NFNL_MSG_TYPE(info->nlh->nlmsg_type) == NFT_MSG_DESTROYRULE)
4166 				return 0;
4167 
4168 			NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
4169 			return PTR_ERR(chain);
4170 		}
4171 		if (nft_chain_binding(chain))
4172 			return -EOPNOTSUPP;
4173 	}
4174 
4175 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, chain, nla);
4176 
4177 	if (chain) {
4178 		if (nla[NFTA_RULE_HANDLE]) {
4179 			rule = nft_rule_lookup(chain, nla[NFTA_RULE_HANDLE]);
4180 			if (IS_ERR(rule)) {
4181 				if (PTR_ERR(rule) == -ENOENT &&
4182 				    NFNL_MSG_TYPE(info->nlh->nlmsg_type) == NFT_MSG_DESTROYRULE)
4183 					return 0;
4184 
4185 				NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
4186 				return PTR_ERR(rule);
4187 			}
4188 
4189 			err = nft_delrule(&ctx, rule);
4190 		} else if (nla[NFTA_RULE_ID]) {
4191 			rule = nft_rule_lookup_byid(net, chain, nla[NFTA_RULE_ID]);
4192 			if (IS_ERR(rule)) {
4193 				NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_ID]);
4194 				return PTR_ERR(rule);
4195 			}
4196 
4197 			err = nft_delrule(&ctx, rule);
4198 		} else {
4199 			err = nft_delrule_by_chain(&ctx);
4200 		}
4201 	} else {
4202 		list_for_each_entry(chain, &table->chains, list) {
4203 			if (!nft_is_active_next(net, chain))
4204 				continue;
4205 			if (nft_chain_binding(chain))
4206 				continue;
4207 
4208 			ctx.chain = chain;
4209 			err = nft_delrule_by_chain(&ctx);
4210 			if (err < 0)
4211 				break;
4212 		}
4213 	}
4214 
4215 	return err;
4216 }
4217 
4218 /*
4219  * Sets
4220  */
4221 static const struct nft_set_type *nft_set_types[] = {
4222 	&nft_set_hash_fast_type,
4223 	&nft_set_hash_type,
4224 	&nft_set_rhash_type,
4225 	&nft_set_bitmap_type,
4226 	&nft_set_rbtree_type,
4227 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
4228 	&nft_set_pipapo_avx2_type,
4229 #endif
4230 	&nft_set_pipapo_type,
4231 };
4232 
4233 #define NFT_SET_FEATURES	(NFT_SET_INTERVAL | NFT_SET_MAP | \
4234 				 NFT_SET_TIMEOUT | NFT_SET_OBJECT | \
4235 				 NFT_SET_EVAL)
4236 
nft_set_ops_candidate(const struct nft_set_type * type,u32 flags)4237 static bool nft_set_ops_candidate(const struct nft_set_type *type, u32 flags)
4238 {
4239 	return (flags & type->features) == (flags & NFT_SET_FEATURES);
4240 }
4241 
4242 /*
4243  * Select a set implementation based on the data characteristics and the
4244  * given policy. The total memory use might not be known if no size is
4245  * given, in that case the amount of memory per element is used.
4246  */
4247 static const struct nft_set_ops *
nft_select_set_ops(const struct nft_ctx * ctx,const struct nlattr * const nla[],const struct nft_set_desc * desc)4248 nft_select_set_ops(const struct nft_ctx *ctx,
4249 		   const struct nlattr * const nla[],
4250 		   const struct nft_set_desc *desc)
4251 {
4252 	struct nftables_pernet *nft_net = nft_pernet(ctx->net);
4253 	const struct nft_set_ops *ops, *bops;
4254 	struct nft_set_estimate est, best;
4255 	const struct nft_set_type *type;
4256 	u32 flags = 0;
4257 	int i;
4258 
4259 	lockdep_assert_held(&nft_net->commit_mutex);
4260 	lockdep_nfnl_nft_mutex_not_held();
4261 
4262 	if (nla[NFTA_SET_FLAGS] != NULL)
4263 		flags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));
4264 
4265 	bops	    = NULL;
4266 	best.size   = ~0;
4267 	best.lookup = ~0;
4268 	best.space  = ~0;
4269 
4270 	for (i = 0; i < ARRAY_SIZE(nft_set_types); i++) {
4271 		type = nft_set_types[i];
4272 		ops = &type->ops;
4273 
4274 		if (!nft_set_ops_candidate(type, flags))
4275 			continue;
4276 		if (!ops->estimate(desc, flags, &est))
4277 			continue;
4278 
4279 		switch (desc->policy) {
4280 		case NFT_SET_POL_PERFORMANCE:
4281 			if (est.lookup < best.lookup)
4282 				break;
4283 			if (est.lookup == best.lookup &&
4284 			    est.space < best.space)
4285 				break;
4286 			continue;
4287 		case NFT_SET_POL_MEMORY:
4288 			if (!desc->size) {
4289 				if (est.space < best.space)
4290 					break;
4291 				if (est.space == best.space &&
4292 				    est.lookup < best.lookup)
4293 					break;
4294 			} else if (est.size < best.size || !bops) {
4295 				break;
4296 			}
4297 			continue;
4298 		default:
4299 			break;
4300 		}
4301 
4302 		bops = ops;
4303 		best = est;
4304 	}
4305 
4306 	if (bops != NULL)
4307 		return bops;
4308 
4309 	return ERR_PTR(-EOPNOTSUPP);
4310 }
4311 
4312 static const struct nla_policy nft_set_policy[NFTA_SET_MAX + 1] = {
4313 	[NFTA_SET_TABLE]		= { .type = NLA_STRING,
4314 					    .len = NFT_TABLE_MAXNAMELEN - 1 },
4315 	[NFTA_SET_NAME]			= { .type = NLA_STRING,
4316 					    .len = NFT_SET_MAXNAMELEN - 1 },
4317 	[NFTA_SET_FLAGS]		= { .type = NLA_U32 },
4318 	[NFTA_SET_KEY_TYPE]		= { .type = NLA_U32 },
4319 	[NFTA_SET_KEY_LEN]		= { .type = NLA_U32 },
4320 	[NFTA_SET_DATA_TYPE]		= { .type = NLA_U32 },
4321 	[NFTA_SET_DATA_LEN]		= { .type = NLA_U32 },
4322 	[NFTA_SET_POLICY]		= { .type = NLA_U32 },
4323 	[NFTA_SET_DESC]			= { .type = NLA_NESTED },
4324 	[NFTA_SET_ID]			= { .type = NLA_U32 },
4325 	[NFTA_SET_TIMEOUT]		= { .type = NLA_U64 },
4326 	[NFTA_SET_GC_INTERVAL]		= { .type = NLA_U32 },
4327 	[NFTA_SET_USERDATA]		= { .type = NLA_BINARY,
4328 					    .len  = NFT_USERDATA_MAXLEN },
4329 	[NFTA_SET_OBJ_TYPE]		= { .type = NLA_U32 },
4330 	[NFTA_SET_HANDLE]		= { .type = NLA_U64 },
4331 	[NFTA_SET_EXPR]			= { .type = NLA_NESTED },
4332 	[NFTA_SET_EXPRESSIONS]		= { .type = NLA_NESTED },
4333 };
4334 
4335 static const struct nla_policy nft_set_desc_policy[NFTA_SET_DESC_MAX + 1] = {
4336 	[NFTA_SET_DESC_SIZE]		= { .type = NLA_U32 },
4337 	[NFTA_SET_DESC_CONCAT]		= { .type = NLA_NESTED },
4338 };
4339 
nft_set_lookup(const struct nft_table * table,const struct nlattr * nla,u8 genmask)4340 static struct nft_set *nft_set_lookup(const struct nft_table *table,
4341 				      const struct nlattr *nla, u8 genmask)
4342 {
4343 	struct nft_set *set;
4344 
4345 	if (nla == NULL)
4346 		return ERR_PTR(-EINVAL);
4347 
4348 	list_for_each_entry_rcu(set, &table->sets, list) {
4349 		if (!nla_strcmp(nla, set->name) &&
4350 		    nft_active_genmask(set, genmask))
4351 			return set;
4352 	}
4353 	return ERR_PTR(-ENOENT);
4354 }
4355 
nft_set_lookup_byhandle(const struct nft_table * table,const struct nlattr * nla,u8 genmask)4356 static struct nft_set *nft_set_lookup_byhandle(const struct nft_table *table,
4357 					       const struct nlattr *nla,
4358 					       u8 genmask)
4359 {
4360 	struct nft_set *set;
4361 
4362 	list_for_each_entry(set, &table->sets, list) {
4363 		if (be64_to_cpu(nla_get_be64(nla)) == set->handle &&
4364 		    nft_active_genmask(set, genmask))
4365 			return set;
4366 	}
4367 	return ERR_PTR(-ENOENT);
4368 }
4369 
nft_set_lookup_byid(const struct net * net,const struct nft_table * table,const struct nlattr * nla,u8 genmask)4370 static struct nft_set *nft_set_lookup_byid(const struct net *net,
4371 					   const struct nft_table *table,
4372 					   const struct nlattr *nla, u8 genmask)
4373 {
4374 	struct nftables_pernet *nft_net = nft_pernet(net);
4375 	u32 id = ntohl(nla_get_be32(nla));
4376 	struct nft_trans *trans;
4377 
4378 	list_for_each_entry(trans, &nft_net->commit_list, list) {
4379 		if (trans->msg_type == NFT_MSG_NEWSET) {
4380 			struct nft_set *set = nft_trans_set(trans);
4381 
4382 			if (id == nft_trans_set_id(trans) &&
4383 			    set->table == table &&
4384 			    nft_active_genmask(set, genmask))
4385 				return set;
4386 		}
4387 	}
4388 	return ERR_PTR(-ENOENT);
4389 }
4390 
nft_set_lookup_global(const struct net * net,const struct nft_table * table,const struct nlattr * nla_set_name,const struct nlattr * nla_set_id,u8 genmask)4391 struct nft_set *nft_set_lookup_global(const struct net *net,
4392 				      const struct nft_table *table,
4393 				      const struct nlattr *nla_set_name,
4394 				      const struct nlattr *nla_set_id,
4395 				      u8 genmask)
4396 {
4397 	struct nft_set *set;
4398 
4399 	set = nft_set_lookup(table, nla_set_name, genmask);
4400 	if (IS_ERR(set)) {
4401 		if (!nla_set_id)
4402 			return set;
4403 
4404 		set = nft_set_lookup_byid(net, table, nla_set_id, genmask);
4405 	}
4406 	return set;
4407 }
4408 EXPORT_SYMBOL_GPL(nft_set_lookup_global);
4409 
nf_tables_set_alloc_name(struct nft_ctx * ctx,struct nft_set * set,const char * name)4410 static int nf_tables_set_alloc_name(struct nft_ctx *ctx, struct nft_set *set,
4411 				    const char *name)
4412 {
4413 	const struct nft_set *i;
4414 	const char *p;
4415 	unsigned long *inuse;
4416 	unsigned int n = 0, min = 0;
4417 
4418 	p = strchr(name, '%');
4419 	if (p != NULL) {
4420 		if (p[1] != 'd' || strchr(p + 2, '%'))
4421 			return -EINVAL;
4422 
4423 		if (strnlen(name, NFT_SET_MAX_ANONLEN) >= NFT_SET_MAX_ANONLEN)
4424 			return -EINVAL;
4425 
4426 		inuse = (unsigned long *)get_zeroed_page(GFP_KERNEL);
4427 		if (inuse == NULL)
4428 			return -ENOMEM;
4429 cont:
4430 		list_for_each_entry(i, &ctx->table->sets, list) {
4431 			int tmp;
4432 
4433 			if (!nft_is_active_next(ctx->net, i))
4434 				continue;
4435 			if (!sscanf(i->name, name, &tmp))
4436 				continue;
4437 			if (tmp < min || tmp >= min + BITS_PER_BYTE * PAGE_SIZE)
4438 				continue;
4439 
4440 			set_bit(tmp - min, inuse);
4441 		}
4442 
4443 		n = find_first_zero_bit(inuse, BITS_PER_BYTE * PAGE_SIZE);
4444 		if (n >= BITS_PER_BYTE * PAGE_SIZE) {
4445 			min += BITS_PER_BYTE * PAGE_SIZE;
4446 			memset(inuse, 0, PAGE_SIZE);
4447 			goto cont;
4448 		}
4449 		free_page((unsigned long)inuse);
4450 	}
4451 
4452 	set->name = kasprintf(GFP_KERNEL_ACCOUNT, name, min + n);
4453 	if (!set->name)
4454 		return -ENOMEM;
4455 
4456 	list_for_each_entry(i, &ctx->table->sets, list) {
4457 		if (!nft_is_active_next(ctx->net, i))
4458 			continue;
4459 		if (!strcmp(set->name, i->name)) {
4460 			kfree(set->name);
4461 			set->name = NULL;
4462 			return -ENFILE;
4463 		}
4464 	}
4465 	return 0;
4466 }
4467 
nf_msecs_to_jiffies64(const struct nlattr * nla,u64 * result)4468 int nf_msecs_to_jiffies64(const struct nlattr *nla, u64 *result)
4469 {
4470 	u64 ms = be64_to_cpu(nla_get_be64(nla));
4471 	u64 max = (u64)(~((u64)0));
4472 
4473 	max = div_u64(max, NSEC_PER_MSEC);
4474 	if (ms >= max)
4475 		return -ERANGE;
4476 
4477 	ms *= NSEC_PER_MSEC;
4478 	*result = nsecs_to_jiffies64(ms) ? : !!ms;
4479 	return 0;
4480 }
4481 
nf_jiffies64_to_msecs(u64 input)4482 __be64 nf_jiffies64_to_msecs(u64 input)
4483 {
4484 	return cpu_to_be64(jiffies64_to_msecs(input));
4485 }
4486 
nf_tables_fill_set_concat(struct sk_buff * skb,const struct nft_set * set)4487 static int nf_tables_fill_set_concat(struct sk_buff *skb,
4488 				     const struct nft_set *set)
4489 {
4490 	struct nlattr *concat, *field;
4491 	int i;
4492 
4493 	concat = nla_nest_start_noflag(skb, NFTA_SET_DESC_CONCAT);
4494 	if (!concat)
4495 		return -ENOMEM;
4496 
4497 	for (i = 0; i < set->field_count; i++) {
4498 		field = nla_nest_start_noflag(skb, NFTA_LIST_ELEM);
4499 		if (!field)
4500 			return -ENOMEM;
4501 
4502 		if (nla_put_be32(skb, NFTA_SET_FIELD_LEN,
4503 				 htonl(set->field_len[i])))
4504 			return -ENOMEM;
4505 
4506 		nla_nest_end(skb, field);
4507 	}
4508 
4509 	nla_nest_end(skb, concat);
4510 
4511 	return 0;
4512 }
4513 
nf_tables_fill_set(struct sk_buff * skb,const struct nft_ctx * ctx,const struct nft_set * set,u16 event,u16 flags)4514 static int nf_tables_fill_set(struct sk_buff *skb, const struct nft_ctx *ctx,
4515 			      const struct nft_set *set, u16 event, u16 flags)
4516 {
4517 	u64 timeout = READ_ONCE(set->timeout);
4518 	u32 gc_int = READ_ONCE(set->gc_int);
4519 	u32 portid = ctx->portid;
4520 	struct nlmsghdr *nlh;
4521 	struct nlattr *nest;
4522 	u32 seq = ctx->seq;
4523 	int i;
4524 
4525 	event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
4526 	nlh = nfnl_msg_put(skb, portid, seq, event, flags, ctx->family,
4527 			   NFNETLINK_V0, nft_base_seq(ctx->net));
4528 	if (!nlh)
4529 		goto nla_put_failure;
4530 
4531 	if (nla_put_string(skb, NFTA_SET_TABLE, ctx->table->name))
4532 		goto nla_put_failure;
4533 	if (nla_put_string(skb, NFTA_SET_NAME, set->name))
4534 		goto nla_put_failure;
4535 	if (nla_put_be64(skb, NFTA_SET_HANDLE, cpu_to_be64(set->handle),
4536 			 NFTA_SET_PAD))
4537 		goto nla_put_failure;
4538 
4539 	if (event == NFT_MSG_DELSET) {
4540 		nlmsg_end(skb, nlh);
4541 		return 0;
4542 	}
4543 
4544 	if (set->flags != 0)
4545 		if (nla_put_be32(skb, NFTA_SET_FLAGS, htonl(set->flags)))
4546 			goto nla_put_failure;
4547 
4548 	if (nla_put_be32(skb, NFTA_SET_KEY_TYPE, htonl(set->ktype)))
4549 		goto nla_put_failure;
4550 	if (nla_put_be32(skb, NFTA_SET_KEY_LEN, htonl(set->klen)))
4551 		goto nla_put_failure;
4552 	if (set->flags & NFT_SET_MAP) {
4553 		if (nla_put_be32(skb, NFTA_SET_DATA_TYPE, htonl(set->dtype)))
4554 			goto nla_put_failure;
4555 		if (nla_put_be32(skb, NFTA_SET_DATA_LEN, htonl(set->dlen)))
4556 			goto nla_put_failure;
4557 	}
4558 	if (set->flags & NFT_SET_OBJECT &&
4559 	    nla_put_be32(skb, NFTA_SET_OBJ_TYPE, htonl(set->objtype)))
4560 		goto nla_put_failure;
4561 
4562 	if (timeout &&
4563 	    nla_put_be64(skb, NFTA_SET_TIMEOUT,
4564 			 nf_jiffies64_to_msecs(timeout),
4565 			 NFTA_SET_PAD))
4566 		goto nla_put_failure;
4567 	if (gc_int &&
4568 	    nla_put_be32(skb, NFTA_SET_GC_INTERVAL, htonl(gc_int)))
4569 		goto nla_put_failure;
4570 
4571 	if (set->policy != NFT_SET_POL_PERFORMANCE) {
4572 		if (nla_put_be32(skb, NFTA_SET_POLICY, htonl(set->policy)))
4573 			goto nla_put_failure;
4574 	}
4575 
4576 	if (set->udata &&
4577 	    nla_put(skb, NFTA_SET_USERDATA, set->udlen, set->udata))
4578 		goto nla_put_failure;
4579 
4580 	nest = nla_nest_start_noflag(skb, NFTA_SET_DESC);
4581 	if (!nest)
4582 		goto nla_put_failure;
4583 	if (set->size &&
4584 	    nla_put_be32(skb, NFTA_SET_DESC_SIZE, htonl(set->size)))
4585 		goto nla_put_failure;
4586 
4587 	if (set->field_count > 1 &&
4588 	    nf_tables_fill_set_concat(skb, set))
4589 		goto nla_put_failure;
4590 
4591 	nla_nest_end(skb, nest);
4592 
4593 	if (set->num_exprs == 1) {
4594 		nest = nla_nest_start_noflag(skb, NFTA_SET_EXPR);
4595 		if (nf_tables_fill_expr_info(skb, set->exprs[0], false) < 0)
4596 			goto nla_put_failure;
4597 
4598 		nla_nest_end(skb, nest);
4599 	} else if (set->num_exprs > 1) {
4600 		nest = nla_nest_start_noflag(skb, NFTA_SET_EXPRESSIONS);
4601 		if (nest == NULL)
4602 			goto nla_put_failure;
4603 
4604 		for (i = 0; i < set->num_exprs; i++) {
4605 			if (nft_expr_dump(skb, NFTA_LIST_ELEM,
4606 					  set->exprs[i], false) < 0)
4607 				goto nla_put_failure;
4608 		}
4609 		nla_nest_end(skb, nest);
4610 	}
4611 
4612 	nlmsg_end(skb, nlh);
4613 	return 0;
4614 
4615 nla_put_failure:
4616 	nlmsg_trim(skb, nlh);
4617 	return -1;
4618 }
4619 
nf_tables_set_notify(const struct nft_ctx * ctx,const struct nft_set * set,int event,gfp_t gfp_flags)4620 static void nf_tables_set_notify(const struct nft_ctx *ctx,
4621 				 const struct nft_set *set, int event,
4622 			         gfp_t gfp_flags)
4623 {
4624 	struct nftables_pernet *nft_net = nft_pernet(ctx->net);
4625 	u32 portid = ctx->portid;
4626 	struct sk_buff *skb;
4627 	u16 flags = 0;
4628 	int err;
4629 
4630 	if (!ctx->report &&
4631 	    !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
4632 		return;
4633 
4634 	skb = nlmsg_new(NLMSG_GOODSIZE, gfp_flags);
4635 	if (skb == NULL)
4636 		goto err;
4637 
4638 	if (ctx->flags & (NLM_F_CREATE | NLM_F_EXCL))
4639 		flags |= ctx->flags & (NLM_F_CREATE | NLM_F_EXCL);
4640 
4641 	err = nf_tables_fill_set(skb, ctx, set, event, flags);
4642 	if (err < 0) {
4643 		kfree_skb(skb);
4644 		goto err;
4645 	}
4646 
4647 	nft_notify_enqueue(skb, ctx->report, &nft_net->notify_list);
4648 	return;
4649 err:
4650 	nfnetlink_set_err(ctx->net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
4651 }
4652 
nf_tables_dump_sets(struct sk_buff * skb,struct netlink_callback * cb)4653 static int nf_tables_dump_sets(struct sk_buff *skb, struct netlink_callback *cb)
4654 {
4655 	const struct nft_set *set;
4656 	unsigned int idx, s_idx = cb->args[0];
4657 	struct nft_table *table, *cur_table = (struct nft_table *)cb->args[2];
4658 	struct net *net = sock_net(skb->sk);
4659 	struct nft_ctx *ctx = cb->data, ctx_set;
4660 	struct nftables_pernet *nft_net;
4661 
4662 	if (cb->args[1])
4663 		return skb->len;
4664 
4665 	rcu_read_lock();
4666 	nft_net = nft_pernet(net);
4667 	cb->seq = READ_ONCE(nft_net->base_seq);
4668 
4669 	list_for_each_entry_rcu(table, &nft_net->tables, list) {
4670 		if (ctx->family != NFPROTO_UNSPEC &&
4671 		    ctx->family != table->family)
4672 			continue;
4673 
4674 		if (ctx->table && ctx->table != table)
4675 			continue;
4676 
4677 		if (cur_table) {
4678 			if (cur_table != table)
4679 				continue;
4680 
4681 			cur_table = NULL;
4682 		}
4683 		idx = 0;
4684 		list_for_each_entry_rcu(set, &table->sets, list) {
4685 			if (idx < s_idx)
4686 				goto cont;
4687 			if (!nft_is_active(net, set))
4688 				goto cont;
4689 
4690 			ctx_set = *ctx;
4691 			ctx_set.table = table;
4692 			ctx_set.family = table->family;
4693 
4694 			if (nf_tables_fill_set(skb, &ctx_set, set,
4695 					       NFT_MSG_NEWSET,
4696 					       NLM_F_MULTI) < 0) {
4697 				cb->args[0] = idx;
4698 				cb->args[2] = (unsigned long) table;
4699 				goto done;
4700 			}
4701 			nl_dump_check_consistent(cb, nlmsg_hdr(skb));
4702 cont:
4703 			idx++;
4704 		}
4705 		if (s_idx)
4706 			s_idx = 0;
4707 	}
4708 	cb->args[1] = 1;
4709 done:
4710 	rcu_read_unlock();
4711 	return skb->len;
4712 }
4713 
nf_tables_dump_sets_start(struct netlink_callback * cb)4714 static int nf_tables_dump_sets_start(struct netlink_callback *cb)
4715 {
4716 	struct nft_ctx *ctx_dump = NULL;
4717 
4718 	ctx_dump = kmemdup(cb->data, sizeof(*ctx_dump), GFP_ATOMIC);
4719 	if (ctx_dump == NULL)
4720 		return -ENOMEM;
4721 
4722 	cb->data = ctx_dump;
4723 	return 0;
4724 }
4725 
nf_tables_dump_sets_done(struct netlink_callback * cb)4726 static int nf_tables_dump_sets_done(struct netlink_callback *cb)
4727 {
4728 	kfree(cb->data);
4729 	return 0;
4730 }
4731 
4732 /* called with rcu_read_lock held */
nf_tables_getset(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])4733 static int nf_tables_getset(struct sk_buff *skb, const struct nfnl_info *info,
4734 			    const struct nlattr * const nla[])
4735 {
4736 	struct netlink_ext_ack *extack = info->extack;
4737 	u8 genmask = nft_genmask_cur(info->net);
4738 	u8 family = info->nfmsg->nfgen_family;
4739 	struct nft_table *table = NULL;
4740 	struct net *net = info->net;
4741 	const struct nft_set *set;
4742 	struct sk_buff *skb2;
4743 	struct nft_ctx ctx;
4744 	int err;
4745 
4746 	if (nla[NFTA_SET_TABLE]) {
4747 		table = nft_table_lookup(net, nla[NFTA_SET_TABLE], family,
4748 					 genmask, 0);
4749 		if (IS_ERR(table)) {
4750 			NL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);
4751 			return PTR_ERR(table);
4752 		}
4753 	}
4754 
4755 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);
4756 
4757 	if (info->nlh->nlmsg_flags & NLM_F_DUMP) {
4758 		struct netlink_dump_control c = {
4759 			.start = nf_tables_dump_sets_start,
4760 			.dump = nf_tables_dump_sets,
4761 			.done = nf_tables_dump_sets_done,
4762 			.data = &ctx,
4763 			.module = THIS_MODULE,
4764 		};
4765 
4766 		return nft_netlink_dump_start_rcu(info->sk, skb, info->nlh, &c);
4767 	}
4768 
4769 	/* Only accept unspec with dump */
4770 	if (info->nfmsg->nfgen_family == NFPROTO_UNSPEC)
4771 		return -EAFNOSUPPORT;
4772 	if (!nla[NFTA_SET_TABLE])
4773 		return -EINVAL;
4774 
4775 	set = nft_set_lookup(table, nla[NFTA_SET_NAME], genmask);
4776 	if (IS_ERR(set))
4777 		return PTR_ERR(set);
4778 
4779 	skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
4780 	if (skb2 == NULL)
4781 		return -ENOMEM;
4782 
4783 	err = nf_tables_fill_set(skb2, &ctx, set, NFT_MSG_NEWSET, 0);
4784 	if (err < 0)
4785 		goto err_fill_set_info;
4786 
4787 	return nfnetlink_unicast(skb2, net, NETLINK_CB(skb).portid);
4788 
4789 err_fill_set_info:
4790 	kfree_skb(skb2);
4791 	return err;
4792 }
4793 
4794 static const struct nla_policy nft_concat_policy[NFTA_SET_FIELD_MAX + 1] = {
4795 	[NFTA_SET_FIELD_LEN]	= { .type = NLA_U32 },
4796 };
4797 
nft_set_desc_concat_parse(const struct nlattr * attr,struct nft_set_desc * desc)4798 static int nft_set_desc_concat_parse(const struct nlattr *attr,
4799 				     struct nft_set_desc *desc)
4800 {
4801 	struct nlattr *tb[NFTA_SET_FIELD_MAX + 1];
4802 	u32 len;
4803 	int err;
4804 
4805 	if (desc->field_count >= ARRAY_SIZE(desc->field_len))
4806 		return -E2BIG;
4807 
4808 	err = nla_parse_nested_deprecated(tb, NFTA_SET_FIELD_MAX, attr,
4809 					  nft_concat_policy, NULL);
4810 	if (err < 0)
4811 		return err;
4812 
4813 	if (!tb[NFTA_SET_FIELD_LEN])
4814 		return -EINVAL;
4815 
4816 	len = ntohl(nla_get_be32(tb[NFTA_SET_FIELD_LEN]));
4817 	if (!len || len > U8_MAX)
4818 		return -EINVAL;
4819 
4820 	desc->field_len[desc->field_count++] = len;
4821 
4822 	return 0;
4823 }
4824 
nft_set_desc_concat(struct nft_set_desc * desc,const struct nlattr * nla)4825 static int nft_set_desc_concat(struct nft_set_desc *desc,
4826 			       const struct nlattr *nla)
4827 {
4828 	u32 num_regs = 0, key_num_regs = 0;
4829 	struct nlattr *attr;
4830 	int rem, err, i;
4831 
4832 	nla_for_each_nested(attr, nla, rem) {
4833 		if (nla_type(attr) != NFTA_LIST_ELEM)
4834 			return -EINVAL;
4835 
4836 		err = nft_set_desc_concat_parse(attr, desc);
4837 		if (err < 0)
4838 			return err;
4839 	}
4840 
4841 	for (i = 0; i < desc->field_count; i++)
4842 		num_regs += DIV_ROUND_UP(desc->field_len[i], sizeof(u32));
4843 
4844 	key_num_regs = DIV_ROUND_UP(desc->klen, sizeof(u32));
4845 	if (key_num_regs != num_regs)
4846 		return -EINVAL;
4847 
4848 	if (num_regs > NFT_REG32_COUNT)
4849 		return -E2BIG;
4850 
4851 	return 0;
4852 }
4853 
nf_tables_set_desc_parse(struct nft_set_desc * desc,const struct nlattr * nla)4854 static int nf_tables_set_desc_parse(struct nft_set_desc *desc,
4855 				    const struct nlattr *nla)
4856 {
4857 	struct nlattr *da[NFTA_SET_DESC_MAX + 1];
4858 	int err;
4859 
4860 	err = nla_parse_nested_deprecated(da, NFTA_SET_DESC_MAX, nla,
4861 					  nft_set_desc_policy, NULL);
4862 	if (err < 0)
4863 		return err;
4864 
4865 	if (da[NFTA_SET_DESC_SIZE] != NULL)
4866 		desc->size = ntohl(nla_get_be32(da[NFTA_SET_DESC_SIZE]));
4867 	if (da[NFTA_SET_DESC_CONCAT])
4868 		err = nft_set_desc_concat(desc, da[NFTA_SET_DESC_CONCAT]);
4869 
4870 	return err;
4871 }
4872 
nft_set_expr_alloc(struct nft_ctx * ctx,struct nft_set * set,const struct nlattr * const * nla,struct nft_expr ** exprs,int * num_exprs,u32 flags)4873 static int nft_set_expr_alloc(struct nft_ctx *ctx, struct nft_set *set,
4874 			      const struct nlattr * const *nla,
4875 			      struct nft_expr **exprs, int *num_exprs,
4876 			      u32 flags)
4877 {
4878 	struct nft_expr *expr;
4879 	int err, i;
4880 
4881 	if (nla[NFTA_SET_EXPR]) {
4882 		expr = nft_set_elem_expr_alloc(ctx, set, nla[NFTA_SET_EXPR]);
4883 		if (IS_ERR(expr)) {
4884 			err = PTR_ERR(expr);
4885 			goto err_set_expr_alloc;
4886 		}
4887 		exprs[0] = expr;
4888 		(*num_exprs)++;
4889 	} else if (nla[NFTA_SET_EXPRESSIONS]) {
4890 		struct nlattr *tmp;
4891 		int left;
4892 
4893 		if (!(flags & NFT_SET_EXPR)) {
4894 			err = -EINVAL;
4895 			goto err_set_expr_alloc;
4896 		}
4897 		i = 0;
4898 		nla_for_each_nested(tmp, nla[NFTA_SET_EXPRESSIONS], left) {
4899 			if (i == NFT_SET_EXPR_MAX) {
4900 				err = -E2BIG;
4901 				goto err_set_expr_alloc;
4902 			}
4903 			if (nla_type(tmp) != NFTA_LIST_ELEM) {
4904 				err = -EINVAL;
4905 				goto err_set_expr_alloc;
4906 			}
4907 			expr = nft_set_elem_expr_alloc(ctx, set, tmp);
4908 			if (IS_ERR(expr)) {
4909 				err = PTR_ERR(expr);
4910 				goto err_set_expr_alloc;
4911 			}
4912 			exprs[i++] = expr;
4913 			(*num_exprs)++;
4914 		}
4915 	}
4916 
4917 	return 0;
4918 
4919 err_set_expr_alloc:
4920 	for (i = 0; i < *num_exprs; i++)
4921 		nft_expr_destroy(ctx, exprs[i]);
4922 
4923 	return err;
4924 }
4925 
nft_set_is_same(const struct nft_set * set,const struct nft_set_desc * desc,struct nft_expr * exprs[],u32 num_exprs,u32 flags)4926 static bool nft_set_is_same(const struct nft_set *set,
4927 			    const struct nft_set_desc *desc,
4928 			    struct nft_expr *exprs[], u32 num_exprs, u32 flags)
4929 {
4930 	int i;
4931 
4932 	if (set->ktype != desc->ktype ||
4933 	    set->dtype != desc->dtype ||
4934 	    set->flags != flags ||
4935 	    set->klen != desc->klen ||
4936 	    set->dlen != desc->dlen ||
4937 	    set->field_count != desc->field_count ||
4938 	    set->num_exprs != num_exprs)
4939 		return false;
4940 
4941 	for (i = 0; i < desc->field_count; i++) {
4942 		if (set->field_len[i] != desc->field_len[i])
4943 			return false;
4944 	}
4945 
4946 	for (i = 0; i < num_exprs; i++) {
4947 		if (set->exprs[i]->ops != exprs[i]->ops)
4948 			return false;
4949 	}
4950 
4951 	return true;
4952 }
4953 
nf_tables_newset(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])4954 static int nf_tables_newset(struct sk_buff *skb, const struct nfnl_info *info,
4955 			    const struct nlattr * const nla[])
4956 {
4957 	struct netlink_ext_ack *extack = info->extack;
4958 	u8 genmask = nft_genmask_next(info->net);
4959 	u8 family = info->nfmsg->nfgen_family;
4960 	const struct nft_set_ops *ops;
4961 	struct net *net = info->net;
4962 	struct nft_set_desc desc;
4963 	struct nft_table *table;
4964 	unsigned char *udata;
4965 	struct nft_set *set;
4966 	struct nft_ctx ctx;
4967 	size_t alloc_size;
4968 	int num_exprs = 0;
4969 	char *name;
4970 	int err, i;
4971 	u16 udlen;
4972 	u32 flags;
4973 	u64 size;
4974 
4975 	if (nla[NFTA_SET_TABLE] == NULL ||
4976 	    nla[NFTA_SET_NAME] == NULL ||
4977 	    nla[NFTA_SET_KEY_LEN] == NULL ||
4978 	    nla[NFTA_SET_ID] == NULL)
4979 		return -EINVAL;
4980 
4981 	memset(&desc, 0, sizeof(desc));
4982 
4983 	desc.ktype = NFT_DATA_VALUE;
4984 	if (nla[NFTA_SET_KEY_TYPE] != NULL) {
4985 		desc.ktype = ntohl(nla_get_be32(nla[NFTA_SET_KEY_TYPE]));
4986 		if ((desc.ktype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK)
4987 			return -EINVAL;
4988 	}
4989 
4990 	desc.klen = ntohl(nla_get_be32(nla[NFTA_SET_KEY_LEN]));
4991 	if (desc.klen == 0 || desc.klen > NFT_DATA_VALUE_MAXLEN)
4992 		return -EINVAL;
4993 
4994 	flags = 0;
4995 	if (nla[NFTA_SET_FLAGS] != NULL) {
4996 		flags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));
4997 		if (flags & ~(NFT_SET_ANONYMOUS | NFT_SET_CONSTANT |
4998 			      NFT_SET_INTERVAL | NFT_SET_TIMEOUT |
4999 			      NFT_SET_MAP | NFT_SET_EVAL |
5000 			      NFT_SET_OBJECT | NFT_SET_CONCAT | NFT_SET_EXPR))
5001 			return -EOPNOTSUPP;
5002 		/* Only one of these operations is supported */
5003 		if ((flags & (NFT_SET_MAP | NFT_SET_OBJECT)) ==
5004 			     (NFT_SET_MAP | NFT_SET_OBJECT))
5005 			return -EOPNOTSUPP;
5006 		if ((flags & (NFT_SET_EVAL | NFT_SET_OBJECT)) ==
5007 			     (NFT_SET_EVAL | NFT_SET_OBJECT))
5008 			return -EOPNOTSUPP;
5009 		if ((flags & (NFT_SET_ANONYMOUS | NFT_SET_TIMEOUT | NFT_SET_EVAL)) ==
5010 			     (NFT_SET_ANONYMOUS | NFT_SET_TIMEOUT))
5011 			return -EOPNOTSUPP;
5012 		if ((flags & (NFT_SET_CONSTANT | NFT_SET_TIMEOUT)) ==
5013 			     (NFT_SET_CONSTANT | NFT_SET_TIMEOUT))
5014 			return -EOPNOTSUPP;
5015 	}
5016 
5017 	desc.dtype = 0;
5018 	if (nla[NFTA_SET_DATA_TYPE] != NULL) {
5019 		if (!(flags & NFT_SET_MAP))
5020 			return -EINVAL;
5021 
5022 		desc.dtype = ntohl(nla_get_be32(nla[NFTA_SET_DATA_TYPE]));
5023 		if ((desc.dtype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK &&
5024 		    desc.dtype != NFT_DATA_VERDICT)
5025 			return -EINVAL;
5026 
5027 		if (desc.dtype != NFT_DATA_VERDICT) {
5028 			if (nla[NFTA_SET_DATA_LEN] == NULL)
5029 				return -EINVAL;
5030 			desc.dlen = ntohl(nla_get_be32(nla[NFTA_SET_DATA_LEN]));
5031 			if (desc.dlen == 0 || desc.dlen > NFT_DATA_VALUE_MAXLEN)
5032 				return -EINVAL;
5033 		} else
5034 			desc.dlen = sizeof(struct nft_verdict);
5035 	} else if (flags & NFT_SET_MAP)
5036 		return -EINVAL;
5037 
5038 	if (nla[NFTA_SET_OBJ_TYPE] != NULL) {
5039 		if (!(flags & NFT_SET_OBJECT))
5040 			return -EINVAL;
5041 
5042 		desc.objtype = ntohl(nla_get_be32(nla[NFTA_SET_OBJ_TYPE]));
5043 		if (desc.objtype == NFT_OBJECT_UNSPEC ||
5044 		    desc.objtype > NFT_OBJECT_MAX)
5045 			return -EOPNOTSUPP;
5046 	} else if (flags & NFT_SET_OBJECT)
5047 		return -EINVAL;
5048 	else
5049 		desc.objtype = NFT_OBJECT_UNSPEC;
5050 
5051 	desc.timeout = 0;
5052 	if (nla[NFTA_SET_TIMEOUT] != NULL) {
5053 		if (!(flags & NFT_SET_TIMEOUT))
5054 			return -EINVAL;
5055 
5056 		if (flags & NFT_SET_ANONYMOUS)
5057 			return -EOPNOTSUPP;
5058 
5059 		err = nf_msecs_to_jiffies64(nla[NFTA_SET_TIMEOUT], &desc.timeout);
5060 		if (err)
5061 			return err;
5062 	}
5063 	desc.gc_int = 0;
5064 	if (nla[NFTA_SET_GC_INTERVAL] != NULL) {
5065 		if (!(flags & NFT_SET_TIMEOUT))
5066 			return -EINVAL;
5067 
5068 		if (flags & NFT_SET_ANONYMOUS)
5069 			return -EOPNOTSUPP;
5070 
5071 		desc.gc_int = ntohl(nla_get_be32(nla[NFTA_SET_GC_INTERVAL]));
5072 	}
5073 
5074 	desc.policy = NFT_SET_POL_PERFORMANCE;
5075 	if (nla[NFTA_SET_POLICY] != NULL) {
5076 		desc.policy = ntohl(nla_get_be32(nla[NFTA_SET_POLICY]));
5077 		switch (desc.policy) {
5078 		case NFT_SET_POL_PERFORMANCE:
5079 		case NFT_SET_POL_MEMORY:
5080 			break;
5081 		default:
5082 			return -EOPNOTSUPP;
5083 		}
5084 	}
5085 
5086 	if (nla[NFTA_SET_DESC] != NULL) {
5087 		err = nf_tables_set_desc_parse(&desc, nla[NFTA_SET_DESC]);
5088 		if (err < 0)
5089 			return err;
5090 
5091 		if (desc.field_count > 1) {
5092 			if (!(flags & NFT_SET_CONCAT))
5093 				return -EINVAL;
5094 		} else if (flags & NFT_SET_CONCAT) {
5095 			return -EINVAL;
5096 		}
5097 	} else if (flags & NFT_SET_CONCAT) {
5098 		return -EINVAL;
5099 	}
5100 
5101 	if (nla[NFTA_SET_EXPR] || nla[NFTA_SET_EXPRESSIONS])
5102 		desc.expr = true;
5103 
5104 	table = nft_table_lookup(net, nla[NFTA_SET_TABLE], family, genmask,
5105 				 NETLINK_CB(skb).portid);
5106 	if (IS_ERR(table)) {
5107 		NL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);
5108 		return PTR_ERR(table);
5109 	}
5110 
5111 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);
5112 
5113 	set = nft_set_lookup(table, nla[NFTA_SET_NAME], genmask);
5114 	if (IS_ERR(set)) {
5115 		if (PTR_ERR(set) != -ENOENT) {
5116 			NL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);
5117 			return PTR_ERR(set);
5118 		}
5119 	} else {
5120 		struct nft_expr *exprs[NFT_SET_EXPR_MAX] = {};
5121 
5122 		if (info->nlh->nlmsg_flags & NLM_F_EXCL) {
5123 			NL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);
5124 			return -EEXIST;
5125 		}
5126 		if (info->nlh->nlmsg_flags & NLM_F_REPLACE)
5127 			return -EOPNOTSUPP;
5128 
5129 		if (nft_set_is_anonymous(set))
5130 			return -EOPNOTSUPP;
5131 
5132 		err = nft_set_expr_alloc(&ctx, set, nla, exprs, &num_exprs, flags);
5133 		if (err < 0)
5134 			return err;
5135 
5136 		err = 0;
5137 		if (!nft_set_is_same(set, &desc, exprs, num_exprs, flags)) {
5138 			NL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);
5139 			err = -EEXIST;
5140 		}
5141 
5142 		for (i = 0; i < num_exprs; i++)
5143 			nft_expr_destroy(&ctx, exprs[i]);
5144 
5145 		if (err < 0)
5146 			return err;
5147 
5148 		return __nft_trans_set_add(&ctx, NFT_MSG_NEWSET, set, &desc);
5149 	}
5150 
5151 	if (!(info->nlh->nlmsg_flags & NLM_F_CREATE))
5152 		return -ENOENT;
5153 
5154 	ops = nft_select_set_ops(&ctx, nla, &desc);
5155 	if (IS_ERR(ops))
5156 		return PTR_ERR(ops);
5157 
5158 	udlen = 0;
5159 	if (nla[NFTA_SET_USERDATA])
5160 		udlen = nla_len(nla[NFTA_SET_USERDATA]);
5161 
5162 	size = 0;
5163 	if (ops->privsize != NULL)
5164 		size = ops->privsize(nla, &desc);
5165 	alloc_size = sizeof(*set) + size + udlen;
5166 	if (alloc_size < size || alloc_size > INT_MAX)
5167 		return -ENOMEM;
5168 
5169 	if (!nft_use_inc(&table->use))
5170 		return -EMFILE;
5171 
5172 	set = kvzalloc(alloc_size, GFP_KERNEL_ACCOUNT);
5173 	if (!set) {
5174 		err = -ENOMEM;
5175 		goto err_alloc;
5176 	}
5177 
5178 	name = nla_strdup(nla[NFTA_SET_NAME], GFP_KERNEL_ACCOUNT);
5179 	if (!name) {
5180 		err = -ENOMEM;
5181 		goto err_set_name;
5182 	}
5183 
5184 	err = nf_tables_set_alloc_name(&ctx, set, name);
5185 	kfree(name);
5186 	if (err < 0)
5187 		goto err_set_name;
5188 
5189 	udata = NULL;
5190 	if (udlen) {
5191 		udata = set->data + size;
5192 		nla_memcpy(udata, nla[NFTA_SET_USERDATA], udlen);
5193 	}
5194 
5195 	INIT_LIST_HEAD(&set->bindings);
5196 	INIT_LIST_HEAD(&set->catchall_list);
5197 	refcount_set(&set->refs, 1);
5198 	set->table = table;
5199 	write_pnet(&set->net, net);
5200 	set->ops = ops;
5201 	set->ktype = desc.ktype;
5202 	set->klen = desc.klen;
5203 	set->dtype = desc.dtype;
5204 	set->objtype = desc.objtype;
5205 	set->dlen = desc.dlen;
5206 	set->flags = flags;
5207 	set->size = desc.size;
5208 	set->policy = desc.policy;
5209 	set->udlen = udlen;
5210 	set->udata = udata;
5211 	set->timeout = desc.timeout;
5212 	set->gc_int = desc.gc_int;
5213 
5214 	set->field_count = desc.field_count;
5215 	for (i = 0; i < desc.field_count; i++)
5216 		set->field_len[i] = desc.field_len[i];
5217 
5218 	err = ops->init(set, &desc, nla);
5219 	if (err < 0)
5220 		goto err_set_init;
5221 
5222 	err = nft_set_expr_alloc(&ctx, set, nla, set->exprs, &num_exprs, flags);
5223 	if (err < 0)
5224 		goto err_set_destroy;
5225 
5226 	set->num_exprs = num_exprs;
5227 	set->handle = nf_tables_alloc_handle(table);
5228 	INIT_LIST_HEAD(&set->pending_update);
5229 
5230 	err = nft_trans_set_add(&ctx, NFT_MSG_NEWSET, set);
5231 	if (err < 0)
5232 		goto err_set_expr_alloc;
5233 
5234 	list_add_tail_rcu(&set->list, &table->sets);
5235 
5236 	return 0;
5237 
5238 err_set_expr_alloc:
5239 	for (i = 0; i < set->num_exprs; i++)
5240 		nft_expr_destroy(&ctx, set->exprs[i]);
5241 err_set_destroy:
5242 	ops->destroy(&ctx, set);
5243 err_set_init:
5244 	kfree(set->name);
5245 err_set_name:
5246 	kvfree(set);
5247 err_alloc:
5248 	nft_use_dec_restore(&table->use);
5249 
5250 	return err;
5251 }
5252 
nft_set_catchall_destroy(const struct nft_ctx * ctx,struct nft_set * set)5253 static void nft_set_catchall_destroy(const struct nft_ctx *ctx,
5254 				     struct nft_set *set)
5255 {
5256 	struct nft_set_elem_catchall *next, *catchall;
5257 
5258 	list_for_each_entry_safe(catchall, next, &set->catchall_list, list) {
5259 		list_del_rcu(&catchall->list);
5260 		nf_tables_set_elem_destroy(ctx, set, catchall->elem);
5261 		kfree_rcu(catchall, rcu);
5262 	}
5263 }
5264 
nft_set_put(struct nft_set * set)5265 static void nft_set_put(struct nft_set *set)
5266 {
5267 	if (refcount_dec_and_test(&set->refs)) {
5268 		kfree(set->name);
5269 		kvfree(set);
5270 	}
5271 }
5272 
nft_set_destroy(const struct nft_ctx * ctx,struct nft_set * set)5273 static void nft_set_destroy(const struct nft_ctx *ctx, struct nft_set *set)
5274 {
5275 	int i;
5276 
5277 	if (WARN_ON(set->use > 0))
5278 		return;
5279 
5280 	for (i = 0; i < set->num_exprs; i++)
5281 		nft_expr_destroy(ctx, set->exprs[i]);
5282 
5283 	set->ops->destroy(ctx, set);
5284 	nft_set_catchall_destroy(ctx, set);
5285 	nft_set_put(set);
5286 }
5287 
nf_tables_delset(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])5288 static int nf_tables_delset(struct sk_buff *skb, const struct nfnl_info *info,
5289 			    const struct nlattr * const nla[])
5290 {
5291 	struct netlink_ext_ack *extack = info->extack;
5292 	u8 genmask = nft_genmask_next(info->net);
5293 	u8 family = info->nfmsg->nfgen_family;
5294 	struct net *net = info->net;
5295 	const struct nlattr *attr;
5296 	struct nft_table *table;
5297 	struct nft_set *set;
5298 	struct nft_ctx ctx;
5299 
5300 	if (info->nfmsg->nfgen_family == NFPROTO_UNSPEC)
5301 		return -EAFNOSUPPORT;
5302 
5303 	table = nft_table_lookup(net, nla[NFTA_SET_TABLE], family,
5304 				 genmask, NETLINK_CB(skb).portid);
5305 	if (IS_ERR(table)) {
5306 		NL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);
5307 		return PTR_ERR(table);
5308 	}
5309 
5310 	if (nla[NFTA_SET_HANDLE]) {
5311 		attr = nla[NFTA_SET_HANDLE];
5312 		set = nft_set_lookup_byhandle(table, attr, genmask);
5313 	} else {
5314 		attr = nla[NFTA_SET_NAME];
5315 		set = nft_set_lookup(table, attr, genmask);
5316 	}
5317 
5318 	if (IS_ERR(set)) {
5319 		if (PTR_ERR(set) == -ENOENT &&
5320 		    NFNL_MSG_TYPE(info->nlh->nlmsg_type) == NFT_MSG_DESTROYSET)
5321 			return 0;
5322 
5323 		NL_SET_BAD_ATTR(extack, attr);
5324 		return PTR_ERR(set);
5325 	}
5326 	if (set->use ||
5327 	    (info->nlh->nlmsg_flags & NLM_F_NONREC &&
5328 	     atomic_read(&set->nelems) > 0)) {
5329 		NL_SET_BAD_ATTR(extack, attr);
5330 		return -EBUSY;
5331 	}
5332 
5333 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);
5334 
5335 	return nft_delset(&ctx, set);
5336 }
5337 
5338 static int nft_validate_register_store(const struct nft_ctx *ctx,
5339 				       enum nft_registers reg,
5340 				       const struct nft_data *data,
5341 				       enum nft_data_types type,
5342 				       unsigned int len);
5343 
nft_setelem_data_validate(const struct nft_ctx * ctx,struct nft_set * set,struct nft_set_elem * elem)5344 static int nft_setelem_data_validate(const struct nft_ctx *ctx,
5345 				     struct nft_set *set,
5346 				     struct nft_set_elem *elem)
5347 {
5348 	const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
5349 	enum nft_registers dreg;
5350 
5351 	dreg = nft_type_to_reg(set->dtype);
5352 	return nft_validate_register_store(ctx, dreg, nft_set_ext_data(ext),
5353 					   set->dtype == NFT_DATA_VERDICT ?
5354 					   NFT_DATA_VERDICT : NFT_DATA_VALUE,
5355 					   set->dlen);
5356 }
5357 
nf_tables_bind_check_setelem(const struct nft_ctx * ctx,struct nft_set * set,const struct nft_set_iter * iter,struct nft_set_elem * elem)5358 static int nf_tables_bind_check_setelem(const struct nft_ctx *ctx,
5359 					struct nft_set *set,
5360 					const struct nft_set_iter *iter,
5361 					struct nft_set_elem *elem)
5362 {
5363 	const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
5364 
5365 	if (!nft_set_elem_active(ext, iter->genmask))
5366 		return 0;
5367 
5368 	return nft_setelem_data_validate(ctx, set, elem);
5369 }
5370 
nft_set_catchall_bind_check(const struct nft_ctx * ctx,struct nft_set * set)5371 static int nft_set_catchall_bind_check(const struct nft_ctx *ctx,
5372 				       struct nft_set *set)
5373 {
5374 	u8 genmask = nft_genmask_next(ctx->net);
5375 	struct nft_set_elem_catchall *catchall;
5376 	struct nft_set_elem elem;
5377 	struct nft_set_ext *ext;
5378 	int ret = 0;
5379 
5380 	list_for_each_entry_rcu(catchall, &set->catchall_list, list) {
5381 		ext = nft_set_elem_ext(set, catchall->elem);
5382 		if (!nft_set_elem_active(ext, genmask))
5383 			continue;
5384 
5385 		elem.priv = catchall->elem;
5386 		ret = nft_setelem_data_validate(ctx, set, &elem);
5387 		if (ret < 0)
5388 			break;
5389 	}
5390 
5391 	return ret;
5392 }
5393 
nf_tables_bind_set(const struct nft_ctx * ctx,struct nft_set * set,struct nft_set_binding * binding)5394 int nf_tables_bind_set(const struct nft_ctx *ctx, struct nft_set *set,
5395 		       struct nft_set_binding *binding)
5396 {
5397 	struct nft_set_binding *i;
5398 	struct nft_set_iter iter;
5399 
5400 	if (!list_empty(&set->bindings) && nft_set_is_anonymous(set))
5401 		return -EBUSY;
5402 
5403 	if (binding->flags & NFT_SET_MAP) {
5404 		/* If the set is already bound to the same chain all
5405 		 * jumps are already validated for that chain.
5406 		 */
5407 		list_for_each_entry(i, &set->bindings, list) {
5408 			if (i->flags & NFT_SET_MAP &&
5409 			    i->chain == binding->chain)
5410 				goto bind;
5411 		}
5412 
5413 		iter.genmask	= nft_genmask_next(ctx->net);
5414 		iter.type	= NFT_ITER_UPDATE;
5415 		iter.skip 	= 0;
5416 		iter.count	= 0;
5417 		iter.err	= 0;
5418 		iter.fn		= nf_tables_bind_check_setelem;
5419 
5420 		set->ops->walk(ctx, set, &iter);
5421 		if (!iter.err)
5422 			iter.err = nft_set_catchall_bind_check(ctx, set);
5423 
5424 		if (iter.err < 0)
5425 			return iter.err;
5426 	}
5427 bind:
5428 	if (!nft_use_inc(&set->use))
5429 		return -EMFILE;
5430 
5431 	binding->chain = ctx->chain;
5432 	list_add_tail_rcu(&binding->list, &set->bindings);
5433 	nft_set_trans_bind(ctx, set);
5434 
5435 	return 0;
5436 }
5437 EXPORT_SYMBOL_GPL(nf_tables_bind_set);
5438 
nf_tables_unbind_set(const struct nft_ctx * ctx,struct nft_set * set,struct nft_set_binding * binding,bool event)5439 static void nf_tables_unbind_set(const struct nft_ctx *ctx, struct nft_set *set,
5440 				 struct nft_set_binding *binding, bool event)
5441 {
5442 	list_del_rcu(&binding->list);
5443 
5444 	if (list_empty(&set->bindings) && nft_set_is_anonymous(set)) {
5445 		list_del_rcu(&set->list);
5446 		set->dead = 1;
5447 		if (event)
5448 			nf_tables_set_notify(ctx, set, NFT_MSG_DELSET,
5449 					     GFP_KERNEL);
5450 	}
5451 }
5452 
5453 static void nft_setelem_data_activate(const struct net *net,
5454 				      const struct nft_set *set,
5455 				      struct nft_set_elem *elem);
5456 
nft_mapelem_activate(const struct nft_ctx * ctx,struct nft_set * set,const struct nft_set_iter * iter,struct nft_set_elem * elem)5457 static int nft_mapelem_activate(const struct nft_ctx *ctx,
5458 				struct nft_set *set,
5459 				const struct nft_set_iter *iter,
5460 				struct nft_set_elem *elem)
5461 {
5462 	struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
5463 
5464 	/* called from abort path, reverse check to undo changes. */
5465 	if (nft_set_elem_active(ext, iter->genmask))
5466 		return 0;
5467 
5468 	nft_clear(ctx->net, ext);
5469 	nft_setelem_data_activate(ctx->net, set, elem);
5470 
5471 	return 0;
5472 }
5473 
nft_map_catchall_activate(const struct nft_ctx * ctx,struct nft_set * set)5474 static void nft_map_catchall_activate(const struct nft_ctx *ctx,
5475 				      struct nft_set *set)
5476 {
5477 	u8 genmask = nft_genmask_next(ctx->net);
5478 	struct nft_set_elem_catchall *catchall;
5479 	struct nft_set_elem elem;
5480 	struct nft_set_ext *ext;
5481 
5482 	list_for_each_entry(catchall, &set->catchall_list, list) {
5483 		ext = nft_set_elem_ext(set, catchall->elem);
5484 		if (!nft_set_elem_active(ext, genmask))
5485 			continue;
5486 
5487 		nft_clear(ctx->net, ext);
5488 		elem.priv = catchall->elem;
5489 		nft_setelem_data_activate(ctx->net, set, &elem);
5490 		break;
5491 	}
5492 }
5493 
nft_map_activate(const struct nft_ctx * ctx,struct nft_set * set)5494 static void nft_map_activate(const struct nft_ctx *ctx, struct nft_set *set)
5495 {
5496 	struct nft_set_iter iter = {
5497 		.genmask	= nft_genmask_next(ctx->net),
5498 		.type		= NFT_ITER_UPDATE,
5499 		.fn		= nft_mapelem_activate,
5500 	};
5501 
5502 	set->ops->walk(ctx, set, &iter);
5503 	WARN_ON_ONCE(iter.err);
5504 
5505 	nft_map_catchall_activate(ctx, set);
5506 }
5507 
nf_tables_activate_set(const struct nft_ctx * ctx,struct nft_set * set)5508 void nf_tables_activate_set(const struct nft_ctx *ctx, struct nft_set *set)
5509 {
5510 	if (nft_set_is_anonymous(set)) {
5511 		if (set->flags & (NFT_SET_MAP | NFT_SET_OBJECT))
5512 			nft_map_activate(ctx, set);
5513 
5514 		nft_clear(ctx->net, set);
5515 	}
5516 
5517 	nft_use_inc_restore(&set->use);
5518 }
5519 EXPORT_SYMBOL_GPL(nf_tables_activate_set);
5520 
nf_tables_deactivate_set(const struct nft_ctx * ctx,struct nft_set * set,struct nft_set_binding * binding,enum nft_trans_phase phase)5521 void nf_tables_deactivate_set(const struct nft_ctx *ctx, struct nft_set *set,
5522 			      struct nft_set_binding *binding,
5523 			      enum nft_trans_phase phase)
5524 {
5525 	switch (phase) {
5526 	case NFT_TRANS_PREPARE_ERROR:
5527 		nft_set_trans_unbind(ctx, set);
5528 		if (nft_set_is_anonymous(set))
5529 			nft_deactivate_next(ctx->net, set);
5530 		else
5531 			list_del_rcu(&binding->list);
5532 
5533 		nft_use_dec(&set->use);
5534 		break;
5535 	case NFT_TRANS_PREPARE:
5536 		if (nft_set_is_anonymous(set)) {
5537 			if (set->flags & (NFT_SET_MAP | NFT_SET_OBJECT))
5538 				nft_map_deactivate(ctx, set);
5539 
5540 			nft_deactivate_next(ctx->net, set);
5541 		}
5542 		nft_use_dec(&set->use);
5543 		return;
5544 	case NFT_TRANS_ABORT:
5545 	case NFT_TRANS_RELEASE:
5546 		if (nft_set_is_anonymous(set) &&
5547 		    set->flags & (NFT_SET_MAP | NFT_SET_OBJECT))
5548 			nft_map_deactivate(ctx, set);
5549 
5550 		nft_use_dec(&set->use);
5551 		fallthrough;
5552 	default:
5553 		nf_tables_unbind_set(ctx, set, binding,
5554 				     phase == NFT_TRANS_COMMIT);
5555 	}
5556 }
5557 EXPORT_SYMBOL_GPL(nf_tables_deactivate_set);
5558 
nf_tables_destroy_set(const struct nft_ctx * ctx,struct nft_set * set)5559 void nf_tables_destroy_set(const struct nft_ctx *ctx, struct nft_set *set)
5560 {
5561 	if (list_empty(&set->bindings) && nft_set_is_anonymous(set))
5562 		nft_set_destroy(ctx, set);
5563 }
5564 EXPORT_SYMBOL_GPL(nf_tables_destroy_set);
5565 
5566 const struct nft_set_ext_type nft_set_ext_types[] = {
5567 	[NFT_SET_EXT_KEY]		= {
5568 		.align	= __alignof__(u32),
5569 	},
5570 	[NFT_SET_EXT_DATA]		= {
5571 		.align	= __alignof__(u32),
5572 	},
5573 	[NFT_SET_EXT_EXPRESSIONS]	= {
5574 		.align	= __alignof__(struct nft_set_elem_expr),
5575 	},
5576 	[NFT_SET_EXT_OBJREF]		= {
5577 		.len	= sizeof(struct nft_object *),
5578 		.align	= __alignof__(struct nft_object *),
5579 	},
5580 	[NFT_SET_EXT_FLAGS]		= {
5581 		.len	= sizeof(u8),
5582 		.align	= __alignof__(u8),
5583 	},
5584 	[NFT_SET_EXT_TIMEOUT]		= {
5585 		.len	= sizeof(u64),
5586 		.align	= __alignof__(u64),
5587 	},
5588 	[NFT_SET_EXT_EXPIRATION]	= {
5589 		.len	= sizeof(u64),
5590 		.align	= __alignof__(u64),
5591 	},
5592 	[NFT_SET_EXT_USERDATA]		= {
5593 		.len	= sizeof(struct nft_userdata),
5594 		.align	= __alignof__(struct nft_userdata),
5595 	},
5596 	[NFT_SET_EXT_KEY_END]		= {
5597 		.align	= __alignof__(u32),
5598 	},
5599 };
5600 
5601 /*
5602  * Set elements
5603  */
5604 
5605 static const struct nla_policy nft_set_elem_policy[NFTA_SET_ELEM_MAX + 1] = {
5606 	[NFTA_SET_ELEM_KEY]		= { .type = NLA_NESTED },
5607 	[NFTA_SET_ELEM_DATA]		= { .type = NLA_NESTED },
5608 	[NFTA_SET_ELEM_FLAGS]		= { .type = NLA_U32 },
5609 	[NFTA_SET_ELEM_TIMEOUT]		= { .type = NLA_U64 },
5610 	[NFTA_SET_ELEM_EXPIRATION]	= { .type = NLA_U64 },
5611 	[NFTA_SET_ELEM_USERDATA]	= { .type = NLA_BINARY,
5612 					    .len = NFT_USERDATA_MAXLEN },
5613 	[NFTA_SET_ELEM_EXPR]		= { .type = NLA_NESTED },
5614 	[NFTA_SET_ELEM_OBJREF]		= { .type = NLA_STRING,
5615 					    .len = NFT_OBJ_MAXNAMELEN - 1 },
5616 	[NFTA_SET_ELEM_KEY_END]		= { .type = NLA_NESTED },
5617 	[NFTA_SET_ELEM_EXPRESSIONS]	= { .type = NLA_NESTED },
5618 };
5619 
5620 static const struct nla_policy nft_set_elem_list_policy[NFTA_SET_ELEM_LIST_MAX + 1] = {
5621 	[NFTA_SET_ELEM_LIST_TABLE]	= { .type = NLA_STRING,
5622 					    .len = NFT_TABLE_MAXNAMELEN - 1 },
5623 	[NFTA_SET_ELEM_LIST_SET]	= { .type = NLA_STRING,
5624 					    .len = NFT_SET_MAXNAMELEN - 1 },
5625 	[NFTA_SET_ELEM_LIST_ELEMENTS]	= { .type = NLA_NESTED },
5626 	[NFTA_SET_ELEM_LIST_SET_ID]	= { .type = NLA_U32 },
5627 };
5628 
nft_set_elem_expr_dump(struct sk_buff * skb,const struct nft_set * set,const struct nft_set_ext * ext,bool reset)5629 static int nft_set_elem_expr_dump(struct sk_buff *skb,
5630 				  const struct nft_set *set,
5631 				  const struct nft_set_ext *ext,
5632 				  bool reset)
5633 {
5634 	struct nft_set_elem_expr *elem_expr;
5635 	u32 size, num_exprs = 0;
5636 	struct nft_expr *expr;
5637 	struct nlattr *nest;
5638 
5639 	elem_expr = nft_set_ext_expr(ext);
5640 	nft_setelem_expr_foreach(expr, elem_expr, size)
5641 		num_exprs++;
5642 
5643 	if (num_exprs == 1) {
5644 		expr = nft_setelem_expr_at(elem_expr, 0);
5645 		if (nft_expr_dump(skb, NFTA_SET_ELEM_EXPR, expr, reset) < 0)
5646 			return -1;
5647 
5648 		return 0;
5649 	} else if (num_exprs > 1) {
5650 		nest = nla_nest_start_noflag(skb, NFTA_SET_ELEM_EXPRESSIONS);
5651 		if (nest == NULL)
5652 			goto nla_put_failure;
5653 
5654 		nft_setelem_expr_foreach(expr, elem_expr, size) {
5655 			expr = nft_setelem_expr_at(elem_expr, size);
5656 			if (nft_expr_dump(skb, NFTA_LIST_ELEM, expr, reset) < 0)
5657 				goto nla_put_failure;
5658 		}
5659 		nla_nest_end(skb, nest);
5660 	}
5661 	return 0;
5662 
5663 nla_put_failure:
5664 	return -1;
5665 }
5666 
nf_tables_fill_setelem(struct sk_buff * skb,const struct nft_set * set,const struct nft_set_elem * elem,bool reset)5667 static int nf_tables_fill_setelem(struct sk_buff *skb,
5668 				  const struct nft_set *set,
5669 				  const struct nft_set_elem *elem,
5670 				  bool reset)
5671 {
5672 	const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
5673 	unsigned char *b = skb_tail_pointer(skb);
5674 	struct nlattr *nest;
5675 
5676 	nest = nla_nest_start_noflag(skb, NFTA_LIST_ELEM);
5677 	if (nest == NULL)
5678 		goto nla_put_failure;
5679 
5680 	if (nft_set_ext_exists(ext, NFT_SET_EXT_KEY) &&
5681 	    nft_data_dump(skb, NFTA_SET_ELEM_KEY, nft_set_ext_key(ext),
5682 			  NFT_DATA_VALUE, set->klen) < 0)
5683 		goto nla_put_failure;
5684 
5685 	if (nft_set_ext_exists(ext, NFT_SET_EXT_KEY_END) &&
5686 	    nft_data_dump(skb, NFTA_SET_ELEM_KEY_END, nft_set_ext_key_end(ext),
5687 			  NFT_DATA_VALUE, set->klen) < 0)
5688 		goto nla_put_failure;
5689 
5690 	if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA) &&
5691 	    nft_data_dump(skb, NFTA_SET_ELEM_DATA, nft_set_ext_data(ext),
5692 			  nft_set_datatype(set), set->dlen) < 0)
5693 		goto nla_put_failure;
5694 
5695 	if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPRESSIONS) &&
5696 	    nft_set_elem_expr_dump(skb, set, ext, reset))
5697 		goto nla_put_failure;
5698 
5699 	if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) &&
5700 	    nla_put_string(skb, NFTA_SET_ELEM_OBJREF,
5701 			   (*nft_set_ext_obj(ext))->key.name) < 0)
5702 		goto nla_put_failure;
5703 
5704 	if (nft_set_ext_exists(ext, NFT_SET_EXT_FLAGS) &&
5705 	    nla_put_be32(skb, NFTA_SET_ELEM_FLAGS,
5706 		         htonl(*nft_set_ext_flags(ext))))
5707 		goto nla_put_failure;
5708 
5709 	if (nft_set_ext_exists(ext, NFT_SET_EXT_TIMEOUT) &&
5710 	    nla_put_be64(skb, NFTA_SET_ELEM_TIMEOUT,
5711 			 nf_jiffies64_to_msecs(*nft_set_ext_timeout(ext)),
5712 			 NFTA_SET_ELEM_PAD))
5713 		goto nla_put_failure;
5714 
5715 	if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPIRATION)) {
5716 		u64 expires, now = get_jiffies_64();
5717 
5718 		expires = *nft_set_ext_expiration(ext);
5719 		if (time_before64(now, expires))
5720 			expires -= now;
5721 		else
5722 			expires = 0;
5723 
5724 		if (nla_put_be64(skb, NFTA_SET_ELEM_EXPIRATION,
5725 				 nf_jiffies64_to_msecs(expires),
5726 				 NFTA_SET_ELEM_PAD))
5727 			goto nla_put_failure;
5728 	}
5729 
5730 	if (nft_set_ext_exists(ext, NFT_SET_EXT_USERDATA)) {
5731 		struct nft_userdata *udata;
5732 
5733 		udata = nft_set_ext_userdata(ext);
5734 		if (nla_put(skb, NFTA_SET_ELEM_USERDATA,
5735 			    udata->len + 1, udata->data))
5736 			goto nla_put_failure;
5737 	}
5738 
5739 	nla_nest_end(skb, nest);
5740 	return 0;
5741 
5742 nla_put_failure:
5743 	nlmsg_trim(skb, b);
5744 	return -EMSGSIZE;
5745 }
5746 
5747 struct nft_set_dump_args {
5748 	const struct netlink_callback	*cb;
5749 	struct nft_set_iter		iter;
5750 	struct sk_buff			*skb;
5751 	bool				reset;
5752 };
5753 
nf_tables_dump_setelem(const struct nft_ctx * ctx,struct nft_set * set,const struct nft_set_iter * iter,struct nft_set_elem * elem)5754 static int nf_tables_dump_setelem(const struct nft_ctx *ctx,
5755 				  struct nft_set *set,
5756 				  const struct nft_set_iter *iter,
5757 				  struct nft_set_elem *elem)
5758 {
5759 	const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
5760 	struct nft_set_dump_args *args;
5761 
5762 	if (!nft_set_elem_active(ext, iter->genmask))
5763 		return 0;
5764 
5765 	if (nft_set_elem_expired(ext) || nft_set_elem_is_dead(ext))
5766 		return 0;
5767 
5768 	args = container_of(iter, struct nft_set_dump_args, iter);
5769 	return nf_tables_fill_setelem(args->skb, set, elem, args->reset);
5770 }
5771 
audit_log_nft_set_reset(const struct nft_table * table,unsigned int base_seq,unsigned int nentries)5772 static void audit_log_nft_set_reset(const struct nft_table *table,
5773 				    unsigned int base_seq,
5774 				    unsigned int nentries)
5775 {
5776 	char *buf = kasprintf(GFP_ATOMIC, "%s:%u", table->name, base_seq);
5777 
5778 	audit_log_nfcfg(buf, table->family, nentries,
5779 			AUDIT_NFT_OP_SETELEM_RESET, GFP_ATOMIC);
5780 	kfree(buf);
5781 }
5782 
5783 struct nft_set_dump_ctx {
5784 	const struct nft_set	*set;
5785 	struct nft_ctx		ctx;
5786 };
5787 
nft_set_catchall_dump(struct net * net,struct sk_buff * skb,const struct nft_set * set,bool reset,unsigned int base_seq)5788 static int nft_set_catchall_dump(struct net *net, struct sk_buff *skb,
5789 				 const struct nft_set *set, bool reset,
5790 				 unsigned int base_seq)
5791 {
5792 	struct nft_set_elem_catchall *catchall;
5793 	u8 genmask = nft_genmask_cur(net);
5794 	struct nft_set_elem elem;
5795 	struct nft_set_ext *ext;
5796 	int ret = 0;
5797 
5798 	list_for_each_entry_rcu(catchall, &set->catchall_list, list) {
5799 		ext = nft_set_elem_ext(set, catchall->elem);
5800 		if (!nft_set_elem_active(ext, genmask) ||
5801 		    nft_set_elem_expired(ext))
5802 			continue;
5803 
5804 		elem.priv = catchall->elem;
5805 		ret = nf_tables_fill_setelem(skb, set, &elem, reset);
5806 		if (reset && !ret)
5807 			audit_log_nft_set_reset(set->table, base_seq, 1);
5808 		break;
5809 	}
5810 
5811 	return ret;
5812 }
5813 
nf_tables_dump_set(struct sk_buff * skb,struct netlink_callback * cb)5814 static int nf_tables_dump_set(struct sk_buff *skb, struct netlink_callback *cb)
5815 {
5816 	struct nft_set_dump_ctx *dump_ctx = cb->data;
5817 	struct net *net = sock_net(skb->sk);
5818 	struct nftables_pernet *nft_net;
5819 	struct nft_table *table;
5820 	struct nft_set *set;
5821 	struct nft_set_dump_args args;
5822 	bool set_found = false;
5823 	struct nlmsghdr *nlh;
5824 	struct nlattr *nest;
5825 	bool reset = false;
5826 	u32 portid, seq;
5827 	int event;
5828 
5829 	rcu_read_lock();
5830 	nft_net = nft_pernet(net);
5831 	cb->seq = READ_ONCE(nft_net->base_seq);
5832 
5833 	list_for_each_entry_rcu(table, &nft_net->tables, list) {
5834 		if (dump_ctx->ctx.family != NFPROTO_UNSPEC &&
5835 		    dump_ctx->ctx.family != table->family)
5836 			continue;
5837 
5838 		if (table != dump_ctx->ctx.table)
5839 			continue;
5840 
5841 		list_for_each_entry_rcu(set, &table->sets, list) {
5842 			if (set == dump_ctx->set) {
5843 				set_found = true;
5844 				break;
5845 			}
5846 		}
5847 		break;
5848 	}
5849 
5850 	if (!set_found) {
5851 		rcu_read_unlock();
5852 		return -ENOENT;
5853 	}
5854 
5855 	event  = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, NFT_MSG_NEWSETELEM);
5856 	portid = NETLINK_CB(cb->skb).portid;
5857 	seq    = cb->nlh->nlmsg_seq;
5858 
5859 	nlh = nfnl_msg_put(skb, portid, seq, event, NLM_F_MULTI,
5860 			   table->family, NFNETLINK_V0, nft_base_seq(net));
5861 	if (!nlh)
5862 		goto nla_put_failure;
5863 
5864 	if (nla_put_string(skb, NFTA_SET_ELEM_LIST_TABLE, table->name))
5865 		goto nla_put_failure;
5866 	if (nla_put_string(skb, NFTA_SET_ELEM_LIST_SET, set->name))
5867 		goto nla_put_failure;
5868 
5869 	nest = nla_nest_start_noflag(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
5870 	if (nest == NULL)
5871 		goto nla_put_failure;
5872 
5873 	if (NFNL_MSG_TYPE(cb->nlh->nlmsg_type) == NFT_MSG_GETSETELEM_RESET)
5874 		reset = true;
5875 
5876 	args.cb			= cb;
5877 	args.skb		= skb;
5878 	args.reset		= reset;
5879 	args.iter.genmask	= nft_genmask_cur(net);
5880 	args.iter.type		= NFT_ITER_READ;
5881 	args.iter.skip		= cb->args[0];
5882 	args.iter.count		= 0;
5883 	args.iter.err		= 0;
5884 	args.iter.fn		= nf_tables_dump_setelem;
5885 	set->ops->walk(&dump_ctx->ctx, set, &args.iter);
5886 
5887 	if (!args.iter.err && args.iter.count == cb->args[0])
5888 		args.iter.err = nft_set_catchall_dump(net, skb, set,
5889 						      reset, cb->seq);
5890 	nla_nest_end(skb, nest);
5891 	nlmsg_end(skb, nlh);
5892 
5893 	if (reset && args.iter.count > args.iter.skip)
5894 		audit_log_nft_set_reset(table, cb->seq,
5895 					args.iter.count - args.iter.skip);
5896 
5897 	rcu_read_unlock();
5898 
5899 	if (args.iter.err && args.iter.err != -EMSGSIZE)
5900 		return args.iter.err;
5901 	if (args.iter.count == cb->args[0])
5902 		return 0;
5903 
5904 	cb->args[0] = args.iter.count;
5905 	return skb->len;
5906 
5907 nla_put_failure:
5908 	rcu_read_unlock();
5909 	return -ENOSPC;
5910 }
5911 
nf_tables_dump_set_start(struct netlink_callback * cb)5912 static int nf_tables_dump_set_start(struct netlink_callback *cb)
5913 {
5914 	struct nft_set_dump_ctx *dump_ctx = cb->data;
5915 
5916 	cb->data = kmemdup(dump_ctx, sizeof(*dump_ctx), GFP_ATOMIC);
5917 
5918 	return cb->data ? 0 : -ENOMEM;
5919 }
5920 
nf_tables_dump_set_done(struct netlink_callback * cb)5921 static int nf_tables_dump_set_done(struct netlink_callback *cb)
5922 {
5923 	kfree(cb->data);
5924 	return 0;
5925 }
5926 
nf_tables_fill_setelem_info(struct sk_buff * skb,const struct nft_ctx * ctx,u32 seq,u32 portid,int event,u16 flags,const struct nft_set * set,const struct nft_set_elem * elem,bool reset)5927 static int nf_tables_fill_setelem_info(struct sk_buff *skb,
5928 				       const struct nft_ctx *ctx, u32 seq,
5929 				       u32 portid, int event, u16 flags,
5930 				       const struct nft_set *set,
5931 				       const struct nft_set_elem *elem,
5932 				       bool reset)
5933 {
5934 	struct nlmsghdr *nlh;
5935 	struct nlattr *nest;
5936 	int err;
5937 
5938 	event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
5939 	nlh = nfnl_msg_put(skb, portid, seq, event, flags, ctx->family,
5940 			   NFNETLINK_V0, nft_base_seq(ctx->net));
5941 	if (!nlh)
5942 		goto nla_put_failure;
5943 
5944 	if (nla_put_string(skb, NFTA_SET_TABLE, ctx->table->name))
5945 		goto nla_put_failure;
5946 	if (nla_put_string(skb, NFTA_SET_NAME, set->name))
5947 		goto nla_put_failure;
5948 
5949 	nest = nla_nest_start_noflag(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
5950 	if (nest == NULL)
5951 		goto nla_put_failure;
5952 
5953 	err = nf_tables_fill_setelem(skb, set, elem, reset);
5954 	if (err < 0)
5955 		goto nla_put_failure;
5956 
5957 	nla_nest_end(skb, nest);
5958 
5959 	nlmsg_end(skb, nlh);
5960 	return 0;
5961 
5962 nla_put_failure:
5963 	nlmsg_trim(skb, nlh);
5964 	return -1;
5965 }
5966 
nft_setelem_parse_flags(const struct nft_set * set,const struct nlattr * attr,u32 * flags)5967 static int nft_setelem_parse_flags(const struct nft_set *set,
5968 				   const struct nlattr *attr, u32 *flags)
5969 {
5970 	if (attr == NULL)
5971 		return 0;
5972 
5973 	*flags = ntohl(nla_get_be32(attr));
5974 	if (*flags & ~(NFT_SET_ELEM_INTERVAL_END | NFT_SET_ELEM_CATCHALL))
5975 		return -EOPNOTSUPP;
5976 	if (!(set->flags & NFT_SET_INTERVAL) &&
5977 	    *flags & NFT_SET_ELEM_INTERVAL_END)
5978 		return -EINVAL;
5979 	if ((*flags & (NFT_SET_ELEM_INTERVAL_END | NFT_SET_ELEM_CATCHALL)) ==
5980 	    (NFT_SET_ELEM_INTERVAL_END | NFT_SET_ELEM_CATCHALL))
5981 		return -EINVAL;
5982 
5983 	return 0;
5984 }
5985 
nft_setelem_parse_key(struct nft_ctx * ctx,struct nft_set * set,struct nft_data * key,struct nlattr * attr)5986 static int nft_setelem_parse_key(struct nft_ctx *ctx, struct nft_set *set,
5987 				 struct nft_data *key, struct nlattr *attr)
5988 {
5989 	struct nft_data_desc desc = {
5990 		.type	= NFT_DATA_VALUE,
5991 		.size	= NFT_DATA_VALUE_MAXLEN,
5992 		.len	= set->klen,
5993 	};
5994 
5995 	return nft_data_init(ctx, key, &desc, attr);
5996 }
5997 
nft_setelem_parse_data(struct nft_ctx * ctx,struct nft_set * set,struct nft_data_desc * desc,struct nft_data * data,struct nlattr * attr)5998 static int nft_setelem_parse_data(struct nft_ctx *ctx, struct nft_set *set,
5999 				  struct nft_data_desc *desc,
6000 				  struct nft_data *data,
6001 				  struct nlattr *attr)
6002 {
6003 	u32 dtype;
6004 
6005 	if (set->dtype == NFT_DATA_VERDICT)
6006 		dtype = NFT_DATA_VERDICT;
6007 	else
6008 		dtype = NFT_DATA_VALUE;
6009 
6010 	desc->type = dtype;
6011 	desc->size = NFT_DATA_VALUE_MAXLEN;
6012 	desc->len = set->dlen;
6013 	desc->flags = NFT_DATA_DESC_SETELEM;
6014 
6015 	return nft_data_init(ctx, data, desc, attr);
6016 }
6017 
nft_setelem_catchall_get(const struct net * net,const struct nft_set * set)6018 static void *nft_setelem_catchall_get(const struct net *net,
6019 				      const struct nft_set *set)
6020 {
6021 	struct nft_set_elem_catchall *catchall;
6022 	u8 genmask = nft_genmask_cur(net);
6023 	struct nft_set_ext *ext;
6024 	void *priv = NULL;
6025 
6026 	list_for_each_entry_rcu(catchall, &set->catchall_list, list) {
6027 		ext = nft_set_elem_ext(set, catchall->elem);
6028 		if (!nft_set_elem_active(ext, genmask) ||
6029 		    nft_set_elem_expired(ext))
6030 			continue;
6031 
6032 		priv = catchall->elem;
6033 		break;
6034 	}
6035 
6036 	return priv;
6037 }
6038 
nft_setelem_get(struct nft_ctx * ctx,struct nft_set * set,struct nft_set_elem * elem,u32 flags)6039 static int nft_setelem_get(struct nft_ctx *ctx, struct nft_set *set,
6040 			   struct nft_set_elem *elem, u32 flags)
6041 {
6042 	void *priv;
6043 
6044 	if (!(flags & NFT_SET_ELEM_CATCHALL)) {
6045 		priv = set->ops->get(ctx->net, set, elem, flags);
6046 		if (IS_ERR(priv))
6047 			return PTR_ERR(priv);
6048 	} else {
6049 		priv = nft_setelem_catchall_get(ctx->net, set);
6050 		if (!priv)
6051 			return -ENOENT;
6052 	}
6053 	elem->priv = priv;
6054 
6055 	return 0;
6056 }
6057 
nft_get_set_elem(struct nft_ctx * ctx,struct nft_set * set,const struct nlattr * attr,bool reset)6058 static int nft_get_set_elem(struct nft_ctx *ctx, struct nft_set *set,
6059 			    const struct nlattr *attr, bool reset)
6060 {
6061 	struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
6062 	struct nft_set_elem elem;
6063 	struct sk_buff *skb;
6064 	uint32_t flags = 0;
6065 	int err;
6066 
6067 	err = nla_parse_nested_deprecated(nla, NFTA_SET_ELEM_MAX, attr,
6068 					  nft_set_elem_policy, NULL);
6069 	if (err < 0)
6070 		return err;
6071 
6072 	err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
6073 	if (err < 0)
6074 		return err;
6075 
6076 	if (!nla[NFTA_SET_ELEM_KEY] && !(flags & NFT_SET_ELEM_CATCHALL))
6077 		return -EINVAL;
6078 
6079 	if (nla[NFTA_SET_ELEM_KEY]) {
6080 		err = nft_setelem_parse_key(ctx, set, &elem.key.val,
6081 					    nla[NFTA_SET_ELEM_KEY]);
6082 		if (err < 0)
6083 			return err;
6084 	}
6085 
6086 	if (nla[NFTA_SET_ELEM_KEY_END]) {
6087 		err = nft_setelem_parse_key(ctx, set, &elem.key_end.val,
6088 					    nla[NFTA_SET_ELEM_KEY_END]);
6089 		if (err < 0)
6090 			return err;
6091 	}
6092 
6093 	err = nft_setelem_get(ctx, set, &elem, flags);
6094 	if (err < 0)
6095 		return err;
6096 
6097 	err = -ENOMEM;
6098 	skb = nlmsg_new(NLMSG_GOODSIZE, GFP_ATOMIC);
6099 	if (skb == NULL)
6100 		return err;
6101 
6102 	err = nf_tables_fill_setelem_info(skb, ctx, ctx->seq, ctx->portid,
6103 					  NFT_MSG_NEWSETELEM, 0, set, &elem,
6104 					  reset);
6105 	if (err < 0)
6106 		goto err_fill_setelem;
6107 
6108 	return nfnetlink_unicast(skb, ctx->net, ctx->portid);
6109 
6110 err_fill_setelem:
6111 	kfree_skb(skb);
6112 	return err;
6113 }
6114 
6115 /* called with rcu_read_lock held */
nf_tables_getsetelem(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])6116 static int nf_tables_getsetelem(struct sk_buff *skb,
6117 				const struct nfnl_info *info,
6118 				const struct nlattr * const nla[])
6119 {
6120 	struct netlink_ext_ack *extack = info->extack;
6121 	u8 genmask = nft_genmask_cur(info->net);
6122 	u8 family = info->nfmsg->nfgen_family;
6123 	int rem, err = 0, nelems = 0;
6124 	struct net *net = info->net;
6125 	struct nft_table *table;
6126 	struct nft_set *set;
6127 	struct nlattr *attr;
6128 	struct nft_ctx ctx;
6129 	bool reset = false;
6130 
6131 	table = nft_table_lookup(net, nla[NFTA_SET_ELEM_LIST_TABLE], family,
6132 				 genmask, 0);
6133 	if (IS_ERR(table)) {
6134 		NL_SET_BAD_ATTR(extack, nla[NFTA_SET_ELEM_LIST_TABLE]);
6135 		return PTR_ERR(table);
6136 	}
6137 
6138 	set = nft_set_lookup(table, nla[NFTA_SET_ELEM_LIST_SET], genmask);
6139 	if (IS_ERR(set))
6140 		return PTR_ERR(set);
6141 
6142 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);
6143 
6144 	if (info->nlh->nlmsg_flags & NLM_F_DUMP) {
6145 		struct netlink_dump_control c = {
6146 			.start = nf_tables_dump_set_start,
6147 			.dump = nf_tables_dump_set,
6148 			.done = nf_tables_dump_set_done,
6149 			.module = THIS_MODULE,
6150 		};
6151 		struct nft_set_dump_ctx dump_ctx = {
6152 			.set = set,
6153 			.ctx = ctx,
6154 		};
6155 
6156 		c.data = &dump_ctx;
6157 		return nft_netlink_dump_start_rcu(info->sk, skb, info->nlh, &c);
6158 	}
6159 
6160 	if (!nla[NFTA_SET_ELEM_LIST_ELEMENTS])
6161 		return -EINVAL;
6162 
6163 	if (NFNL_MSG_TYPE(info->nlh->nlmsg_type) == NFT_MSG_GETSETELEM_RESET)
6164 		reset = true;
6165 
6166 	nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
6167 		err = nft_get_set_elem(&ctx, set, attr, reset);
6168 		if (err < 0) {
6169 			NL_SET_BAD_ATTR(extack, attr);
6170 			break;
6171 		}
6172 		nelems++;
6173 	}
6174 
6175 	if (reset)
6176 		audit_log_nft_set_reset(table, nft_pernet(net)->base_seq,
6177 					nelems);
6178 
6179 	return err;
6180 }
6181 
nf_tables_setelem_notify(const struct nft_ctx * ctx,const struct nft_set * set,const struct nft_set_elem * elem,int event)6182 static void nf_tables_setelem_notify(const struct nft_ctx *ctx,
6183 				     const struct nft_set *set,
6184 				     const struct nft_set_elem *elem,
6185 				     int event)
6186 {
6187 	struct nftables_pernet *nft_net;
6188 	struct net *net = ctx->net;
6189 	u32 portid = ctx->portid;
6190 	struct sk_buff *skb;
6191 	u16 flags = 0;
6192 	int err;
6193 
6194 	if (!ctx->report && !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
6195 		return;
6196 
6197 	skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
6198 	if (skb == NULL)
6199 		goto err;
6200 
6201 	if (ctx->flags & (NLM_F_CREATE | NLM_F_EXCL))
6202 		flags |= ctx->flags & (NLM_F_CREATE | NLM_F_EXCL);
6203 
6204 	err = nf_tables_fill_setelem_info(skb, ctx, 0, portid, event, flags,
6205 					  set, elem, false);
6206 	if (err < 0) {
6207 		kfree_skb(skb);
6208 		goto err;
6209 	}
6210 
6211 	nft_net = nft_pernet(net);
6212 	nft_notify_enqueue(skb, ctx->report, &nft_net->notify_list);
6213 	return;
6214 err:
6215 	nfnetlink_set_err(net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
6216 }
6217 
nft_trans_elem_alloc(struct nft_ctx * ctx,int msg_type,struct nft_set * set)6218 static struct nft_trans *nft_trans_elem_alloc(struct nft_ctx *ctx,
6219 					      int msg_type,
6220 					      struct nft_set *set)
6221 {
6222 	struct nft_trans *trans;
6223 
6224 	trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_elem));
6225 	if (trans == NULL)
6226 		return NULL;
6227 
6228 	nft_trans_elem_set(trans) = set;
6229 	return trans;
6230 }
6231 
nft_set_elem_expr_alloc(const struct nft_ctx * ctx,const struct nft_set * set,const struct nlattr * attr)6232 struct nft_expr *nft_set_elem_expr_alloc(const struct nft_ctx *ctx,
6233 					 const struct nft_set *set,
6234 					 const struct nlattr *attr)
6235 {
6236 	struct nft_expr *expr;
6237 	int err;
6238 
6239 	expr = nft_expr_init(ctx, attr);
6240 	if (IS_ERR(expr))
6241 		return expr;
6242 
6243 	err = -EOPNOTSUPP;
6244 	if (expr->ops->type->flags & NFT_EXPR_GC) {
6245 		if (set->flags & NFT_SET_TIMEOUT)
6246 			goto err_set_elem_expr;
6247 		if (!set->ops->gc_init)
6248 			goto err_set_elem_expr;
6249 		set->ops->gc_init(set);
6250 	}
6251 
6252 	return expr;
6253 
6254 err_set_elem_expr:
6255 	nft_expr_destroy(ctx, expr);
6256 	return ERR_PTR(err);
6257 }
6258 
nft_set_ext_check(const struct nft_set_ext_tmpl * tmpl,u8 id,u32 len)6259 static int nft_set_ext_check(const struct nft_set_ext_tmpl *tmpl, u8 id, u32 len)
6260 {
6261 	len += nft_set_ext_types[id].len;
6262 	if (len > tmpl->ext_len[id] ||
6263 	    len > U8_MAX)
6264 		return -1;
6265 
6266 	return 0;
6267 }
6268 
nft_set_ext_memcpy(const struct nft_set_ext_tmpl * tmpl,u8 id,void * to,const void * from,u32 len)6269 static int nft_set_ext_memcpy(const struct nft_set_ext_tmpl *tmpl, u8 id,
6270 			      void *to, const void *from, u32 len)
6271 {
6272 	if (nft_set_ext_check(tmpl, id, len) < 0)
6273 		return -1;
6274 
6275 	memcpy(to, from, len);
6276 
6277 	return 0;
6278 }
6279 
nft_set_elem_init(const struct nft_set * set,const struct nft_set_ext_tmpl * tmpl,const u32 * key,const u32 * key_end,const u32 * data,u64 timeout,u64 expiration,gfp_t gfp)6280 void *nft_set_elem_init(const struct nft_set *set,
6281 			const struct nft_set_ext_tmpl *tmpl,
6282 			const u32 *key, const u32 *key_end,
6283 			const u32 *data, u64 timeout, u64 expiration, gfp_t gfp)
6284 {
6285 	struct nft_set_ext *ext;
6286 	void *elem;
6287 
6288 	elem = kzalloc(set->ops->elemsize + tmpl->len, gfp);
6289 	if (elem == NULL)
6290 		return ERR_PTR(-ENOMEM);
6291 
6292 	ext = nft_set_elem_ext(set, elem);
6293 	nft_set_ext_init(ext, tmpl);
6294 
6295 	if (nft_set_ext_exists(ext, NFT_SET_EXT_KEY) &&
6296 	    nft_set_ext_memcpy(tmpl, NFT_SET_EXT_KEY,
6297 			       nft_set_ext_key(ext), key, set->klen) < 0)
6298 		goto err_ext_check;
6299 
6300 	if (nft_set_ext_exists(ext, NFT_SET_EXT_KEY_END) &&
6301 	    nft_set_ext_memcpy(tmpl, NFT_SET_EXT_KEY_END,
6302 			       nft_set_ext_key_end(ext), key_end, set->klen) < 0)
6303 		goto err_ext_check;
6304 
6305 	if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA) &&
6306 	    nft_set_ext_memcpy(tmpl, NFT_SET_EXT_DATA,
6307 			       nft_set_ext_data(ext), data, set->dlen) < 0)
6308 		goto err_ext_check;
6309 
6310 	if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPIRATION)) {
6311 		*nft_set_ext_expiration(ext) = get_jiffies_64() + expiration;
6312 		if (expiration == 0)
6313 			*nft_set_ext_expiration(ext) += timeout;
6314 	}
6315 	if (nft_set_ext_exists(ext, NFT_SET_EXT_TIMEOUT))
6316 		*nft_set_ext_timeout(ext) = timeout;
6317 
6318 	return elem;
6319 
6320 err_ext_check:
6321 	kfree(elem);
6322 
6323 	return ERR_PTR(-EINVAL);
6324 }
6325 
__nft_set_elem_expr_destroy(const struct nft_ctx * ctx,struct nft_expr * expr)6326 static void __nft_set_elem_expr_destroy(const struct nft_ctx *ctx,
6327 					struct nft_expr *expr)
6328 {
6329 	if (expr->ops->destroy_clone) {
6330 		expr->ops->destroy_clone(ctx, expr);
6331 		module_put(expr->ops->type->owner);
6332 	} else {
6333 		nf_tables_expr_destroy(ctx, expr);
6334 	}
6335 }
6336 
nft_set_elem_expr_destroy(const struct nft_ctx * ctx,struct nft_set_elem_expr * elem_expr)6337 static void nft_set_elem_expr_destroy(const struct nft_ctx *ctx,
6338 				      struct nft_set_elem_expr *elem_expr)
6339 {
6340 	struct nft_expr *expr;
6341 	u32 size;
6342 
6343 	nft_setelem_expr_foreach(expr, elem_expr, size)
6344 		__nft_set_elem_expr_destroy(ctx, expr);
6345 }
6346 
6347 /* Drop references and destroy. Called from gc, dynset and abort path. */
nft_set_elem_destroy(const struct nft_set * set,void * elem,bool destroy_expr)6348 void nft_set_elem_destroy(const struct nft_set *set, void *elem,
6349 			  bool destroy_expr)
6350 {
6351 	struct nft_set_ext *ext = nft_set_elem_ext(set, elem);
6352 	struct nft_ctx ctx = {
6353 		.net	= read_pnet(&set->net),
6354 		.family	= set->table->family,
6355 	};
6356 
6357 	nft_data_release(nft_set_ext_key(ext), NFT_DATA_VALUE);
6358 	if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
6359 		nft_data_release(nft_set_ext_data(ext), set->dtype);
6360 	if (destroy_expr && nft_set_ext_exists(ext, NFT_SET_EXT_EXPRESSIONS))
6361 		nft_set_elem_expr_destroy(&ctx, nft_set_ext_expr(ext));
6362 
6363 	if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
6364 		nft_use_dec(&(*nft_set_ext_obj(ext))->use);
6365 	kfree(elem);
6366 }
6367 EXPORT_SYMBOL_GPL(nft_set_elem_destroy);
6368 
6369 /* Destroy element. References have been already dropped in the preparation
6370  * path via nft_setelem_data_deactivate().
6371  */
nf_tables_set_elem_destroy(const struct nft_ctx * ctx,const struct nft_set * set,void * elem)6372 void nf_tables_set_elem_destroy(const struct nft_ctx *ctx,
6373 				const struct nft_set *set, void *elem)
6374 {
6375 	struct nft_set_ext *ext = nft_set_elem_ext(set, elem);
6376 
6377 	if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPRESSIONS))
6378 		nft_set_elem_expr_destroy(ctx, nft_set_ext_expr(ext));
6379 
6380 	kfree(elem);
6381 }
6382 
nft_set_elem_expr_clone(const struct nft_ctx * ctx,struct nft_set * set,struct nft_expr * expr_array[])6383 int nft_set_elem_expr_clone(const struct nft_ctx *ctx, struct nft_set *set,
6384 			    struct nft_expr *expr_array[])
6385 {
6386 	struct nft_expr *expr;
6387 	int err, i, k;
6388 
6389 	for (i = 0; i < set->num_exprs; i++) {
6390 		expr = kzalloc(set->exprs[i]->ops->size, GFP_KERNEL_ACCOUNT);
6391 		if (!expr)
6392 			goto err_expr;
6393 
6394 		err = nft_expr_clone(expr, set->exprs[i]);
6395 		if (err < 0) {
6396 			kfree(expr);
6397 			goto err_expr;
6398 		}
6399 		expr_array[i] = expr;
6400 	}
6401 
6402 	return 0;
6403 
6404 err_expr:
6405 	for (k = i - 1; k >= 0; k--)
6406 		nft_expr_destroy(ctx, expr_array[k]);
6407 
6408 	return -ENOMEM;
6409 }
6410 
nft_set_elem_expr_setup(struct nft_ctx * ctx,const struct nft_set_ext_tmpl * tmpl,const struct nft_set_ext * ext,struct nft_expr * expr_array[],u32 num_exprs)6411 static int nft_set_elem_expr_setup(struct nft_ctx *ctx,
6412 				   const struct nft_set_ext_tmpl *tmpl,
6413 				   const struct nft_set_ext *ext,
6414 				   struct nft_expr *expr_array[],
6415 				   u32 num_exprs)
6416 {
6417 	struct nft_set_elem_expr *elem_expr = nft_set_ext_expr(ext);
6418 	u32 len = sizeof(struct nft_set_elem_expr);
6419 	struct nft_expr *expr;
6420 	int i, err;
6421 
6422 	if (num_exprs == 0)
6423 		return 0;
6424 
6425 	for (i = 0; i < num_exprs; i++)
6426 		len += expr_array[i]->ops->size;
6427 
6428 	if (nft_set_ext_check(tmpl, NFT_SET_EXT_EXPRESSIONS, len) < 0)
6429 		return -EINVAL;
6430 
6431 	for (i = 0; i < num_exprs; i++) {
6432 		expr = nft_setelem_expr_at(elem_expr, elem_expr->size);
6433 		err = nft_expr_clone(expr, expr_array[i]);
6434 		if (err < 0)
6435 			goto err_elem_expr_setup;
6436 
6437 		elem_expr->size += expr_array[i]->ops->size;
6438 		nft_expr_destroy(ctx, expr_array[i]);
6439 		expr_array[i] = NULL;
6440 	}
6441 
6442 	return 0;
6443 
6444 err_elem_expr_setup:
6445 	for (; i < num_exprs; i++) {
6446 		nft_expr_destroy(ctx, expr_array[i]);
6447 		expr_array[i] = NULL;
6448 	}
6449 
6450 	return -ENOMEM;
6451 }
6452 
nft_set_catchall_lookup(const struct net * net,const struct nft_set * set)6453 struct nft_set_ext *nft_set_catchall_lookup(const struct net *net,
6454 					    const struct nft_set *set)
6455 {
6456 	struct nft_set_elem_catchall *catchall;
6457 	u8 genmask = nft_genmask_cur(net);
6458 	struct nft_set_ext *ext;
6459 
6460 	list_for_each_entry_rcu(catchall, &set->catchall_list, list) {
6461 		ext = nft_set_elem_ext(set, catchall->elem);
6462 		if (nft_set_elem_active(ext, genmask) &&
6463 		    !nft_set_elem_expired(ext) &&
6464 		    !nft_set_elem_is_dead(ext))
6465 			return ext;
6466 	}
6467 
6468 	return NULL;
6469 }
6470 EXPORT_SYMBOL_GPL(nft_set_catchall_lookup);
6471 
nft_setelem_catchall_insert(const struct net * net,struct nft_set * set,const struct nft_set_elem * elem,struct nft_set_ext ** pext)6472 static int nft_setelem_catchall_insert(const struct net *net,
6473 				       struct nft_set *set,
6474 				       const struct nft_set_elem *elem,
6475 				       struct nft_set_ext **pext)
6476 {
6477 	struct nft_set_elem_catchall *catchall;
6478 	u8 genmask = nft_genmask_next(net);
6479 	struct nft_set_ext *ext;
6480 
6481 	list_for_each_entry(catchall, &set->catchall_list, list) {
6482 		ext = nft_set_elem_ext(set, catchall->elem);
6483 		if (nft_set_elem_active(ext, genmask)) {
6484 			*pext = ext;
6485 			return -EEXIST;
6486 		}
6487 	}
6488 
6489 	catchall = kmalloc(sizeof(*catchall), GFP_KERNEL);
6490 	if (!catchall)
6491 		return -ENOMEM;
6492 
6493 	catchall->elem = elem->priv;
6494 	list_add_tail_rcu(&catchall->list, &set->catchall_list);
6495 
6496 	return 0;
6497 }
6498 
nft_setelem_insert(const struct net * net,struct nft_set * set,const struct nft_set_elem * elem,struct nft_set_ext ** ext,unsigned int flags)6499 static int nft_setelem_insert(const struct net *net,
6500 			      struct nft_set *set,
6501 			      const struct nft_set_elem *elem,
6502 			      struct nft_set_ext **ext, unsigned int flags)
6503 {
6504 	int ret;
6505 
6506 	if (flags & NFT_SET_ELEM_CATCHALL)
6507 		ret = nft_setelem_catchall_insert(net, set, elem, ext);
6508 	else
6509 		ret = set->ops->insert(net, set, elem, ext);
6510 
6511 	return ret;
6512 }
6513 
nft_setelem_is_catchall(const struct nft_set * set,const struct nft_set_elem * elem)6514 static bool nft_setelem_is_catchall(const struct nft_set *set,
6515 				    const struct nft_set_elem *elem)
6516 {
6517 	struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
6518 
6519 	if (nft_set_ext_exists(ext, NFT_SET_EXT_FLAGS) &&
6520 	    *nft_set_ext_flags(ext) & NFT_SET_ELEM_CATCHALL)
6521 		return true;
6522 
6523 	return false;
6524 }
6525 
nft_setelem_activate(struct net * net,struct nft_set * set,struct nft_set_elem * elem)6526 static void nft_setelem_activate(struct net *net, struct nft_set *set,
6527 				 struct nft_set_elem *elem)
6528 {
6529 	struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
6530 
6531 	if (nft_setelem_is_catchall(set, elem)) {
6532 		nft_clear(net, ext);
6533 	} else {
6534 		set->ops->activate(net, set, elem);
6535 	}
6536 }
6537 
nft_setelem_catchall_deactivate(const struct net * net,struct nft_set * set,struct nft_set_elem * elem)6538 static int nft_setelem_catchall_deactivate(const struct net *net,
6539 					   struct nft_set *set,
6540 					   struct nft_set_elem *elem)
6541 {
6542 	struct nft_set_elem_catchall *catchall;
6543 	struct nft_set_ext *ext;
6544 
6545 	list_for_each_entry(catchall, &set->catchall_list, list) {
6546 		ext = nft_set_elem_ext(set, catchall->elem);
6547 		if (!nft_is_active_next(net, ext))
6548 			continue;
6549 
6550 		kfree(elem->priv);
6551 		elem->priv = catchall->elem;
6552 		nft_set_elem_change_active(net, set, ext);
6553 		return 0;
6554 	}
6555 
6556 	return -ENOENT;
6557 }
6558 
__nft_setelem_deactivate(const struct net * net,struct nft_set * set,struct nft_set_elem * elem)6559 static int __nft_setelem_deactivate(const struct net *net,
6560 				    struct nft_set *set,
6561 				    struct nft_set_elem *elem)
6562 {
6563 	void *priv;
6564 
6565 	priv = set->ops->deactivate(net, set, elem);
6566 	if (!priv)
6567 		return -ENOENT;
6568 
6569 	kfree(elem->priv);
6570 	elem->priv = priv;
6571 	set->ndeact++;
6572 
6573 	return 0;
6574 }
6575 
nft_setelem_deactivate(const struct net * net,struct nft_set * set,struct nft_set_elem * elem,u32 flags)6576 static int nft_setelem_deactivate(const struct net *net,
6577 				  struct nft_set *set,
6578 				  struct nft_set_elem *elem, u32 flags)
6579 {
6580 	int ret;
6581 
6582 	if (flags & NFT_SET_ELEM_CATCHALL)
6583 		ret = nft_setelem_catchall_deactivate(net, set, elem);
6584 	else
6585 		ret = __nft_setelem_deactivate(net, set, elem);
6586 
6587 	return ret;
6588 }
6589 
nft_setelem_catchall_destroy(struct nft_set_elem_catchall * catchall)6590 static void nft_setelem_catchall_destroy(struct nft_set_elem_catchall *catchall)
6591 {
6592 	list_del_rcu(&catchall->list);
6593 	kfree_rcu(catchall, rcu);
6594 }
6595 
nft_setelem_catchall_remove(const struct net * net,const struct nft_set * set,const struct nft_set_elem * elem)6596 static void nft_setelem_catchall_remove(const struct net *net,
6597 					const struct nft_set *set,
6598 					const struct nft_set_elem *elem)
6599 {
6600 	struct nft_set_elem_catchall *catchall, *next;
6601 
6602 	list_for_each_entry_safe(catchall, next, &set->catchall_list, list) {
6603 		if (catchall->elem == elem->priv) {
6604 			nft_setelem_catchall_destroy(catchall);
6605 			break;
6606 		}
6607 	}
6608 }
6609 
nft_setelem_remove(const struct net * net,const struct nft_set * set,const struct nft_set_elem * elem)6610 static void nft_setelem_remove(const struct net *net,
6611 			       const struct nft_set *set,
6612 			       const struct nft_set_elem *elem)
6613 {
6614 	if (nft_setelem_is_catchall(set, elem))
6615 		nft_setelem_catchall_remove(net, set, elem);
6616 	else
6617 		set->ops->remove(net, set, elem);
6618 }
6619 
nft_setelem_valid_key_end(const struct nft_set * set,struct nlattr ** nla,u32 flags)6620 static bool nft_setelem_valid_key_end(const struct nft_set *set,
6621 				      struct nlattr **nla, u32 flags)
6622 {
6623 	if ((set->flags & (NFT_SET_CONCAT | NFT_SET_INTERVAL)) ==
6624 			  (NFT_SET_CONCAT | NFT_SET_INTERVAL)) {
6625 		if (flags & NFT_SET_ELEM_INTERVAL_END)
6626 			return false;
6627 
6628 		if (nla[NFTA_SET_ELEM_KEY_END] &&
6629 		    flags & NFT_SET_ELEM_CATCHALL)
6630 			return false;
6631 	} else {
6632 		if (nla[NFTA_SET_ELEM_KEY_END])
6633 			return false;
6634 	}
6635 
6636 	return true;
6637 }
6638 
nft_add_set_elem(struct nft_ctx * ctx,struct nft_set * set,const struct nlattr * attr,u32 nlmsg_flags)6639 static int nft_add_set_elem(struct nft_ctx *ctx, struct nft_set *set,
6640 			    const struct nlattr *attr, u32 nlmsg_flags)
6641 {
6642 	struct nft_expr *expr_array[NFT_SET_EXPR_MAX] = {};
6643 	struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
6644 	u8 genmask = nft_genmask_next(ctx->net);
6645 	u32 flags = 0, size = 0, num_exprs = 0;
6646 	struct nft_set_ext_tmpl tmpl;
6647 	struct nft_set_ext *ext, *ext2;
6648 	struct nft_set_elem elem;
6649 	struct nft_set_binding *binding;
6650 	struct nft_object *obj = NULL;
6651 	struct nft_userdata *udata;
6652 	struct nft_data_desc desc;
6653 	enum nft_registers dreg;
6654 	struct nft_trans *trans;
6655 	u64 timeout;
6656 	u64 expiration;
6657 	int err, i;
6658 	u8 ulen;
6659 
6660 	err = nla_parse_nested_deprecated(nla, NFTA_SET_ELEM_MAX, attr,
6661 					  nft_set_elem_policy, NULL);
6662 	if (err < 0)
6663 		return err;
6664 
6665 	nft_set_ext_prepare(&tmpl);
6666 
6667 	err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
6668 	if (err < 0)
6669 		return err;
6670 
6671 	if (((flags & NFT_SET_ELEM_CATCHALL) && nla[NFTA_SET_ELEM_KEY]) ||
6672 	    (!(flags & NFT_SET_ELEM_CATCHALL) && !nla[NFTA_SET_ELEM_KEY]))
6673 		return -EINVAL;
6674 
6675 	if (flags != 0) {
6676 		err = nft_set_ext_add(&tmpl, NFT_SET_EXT_FLAGS);
6677 		if (err < 0)
6678 			return err;
6679 	}
6680 
6681 	if (set->flags & NFT_SET_MAP) {
6682 		if (nla[NFTA_SET_ELEM_DATA] == NULL &&
6683 		    !(flags & NFT_SET_ELEM_INTERVAL_END))
6684 			return -EINVAL;
6685 	} else {
6686 		if (nla[NFTA_SET_ELEM_DATA] != NULL)
6687 			return -EINVAL;
6688 	}
6689 
6690 	if (set->flags & NFT_SET_OBJECT) {
6691 		if (!nla[NFTA_SET_ELEM_OBJREF] &&
6692 		    !(flags & NFT_SET_ELEM_INTERVAL_END))
6693 			return -EINVAL;
6694 	} else {
6695 		if (nla[NFTA_SET_ELEM_OBJREF])
6696 			return -EINVAL;
6697 	}
6698 
6699 	if (!nft_setelem_valid_key_end(set, nla, flags))
6700 		return -EINVAL;
6701 
6702 	if ((flags & NFT_SET_ELEM_INTERVAL_END) &&
6703 	     (nla[NFTA_SET_ELEM_DATA] ||
6704 	      nla[NFTA_SET_ELEM_OBJREF] ||
6705 	      nla[NFTA_SET_ELEM_TIMEOUT] ||
6706 	      nla[NFTA_SET_ELEM_EXPIRATION] ||
6707 	      nla[NFTA_SET_ELEM_USERDATA] ||
6708 	      nla[NFTA_SET_ELEM_EXPR] ||
6709 	      nla[NFTA_SET_ELEM_KEY_END] ||
6710 	      nla[NFTA_SET_ELEM_EXPRESSIONS]))
6711 		return -EINVAL;
6712 
6713 	timeout = 0;
6714 	if (nla[NFTA_SET_ELEM_TIMEOUT] != NULL) {
6715 		if (!(set->flags & NFT_SET_TIMEOUT))
6716 			return -EINVAL;
6717 		err = nf_msecs_to_jiffies64(nla[NFTA_SET_ELEM_TIMEOUT],
6718 					    &timeout);
6719 		if (err)
6720 			return err;
6721 	} else if (set->flags & NFT_SET_TIMEOUT &&
6722 		   !(flags & NFT_SET_ELEM_INTERVAL_END)) {
6723 		timeout = set->timeout;
6724 	}
6725 
6726 	expiration = 0;
6727 	if (nla[NFTA_SET_ELEM_EXPIRATION] != NULL) {
6728 		if (!(set->flags & NFT_SET_TIMEOUT))
6729 			return -EINVAL;
6730 		if (timeout == 0)
6731 			return -EOPNOTSUPP;
6732 
6733 		err = nf_msecs_to_jiffies64(nla[NFTA_SET_ELEM_EXPIRATION],
6734 					    &expiration);
6735 		if (err)
6736 			return err;
6737 
6738 		if (expiration > timeout)
6739 			return -ERANGE;
6740 	}
6741 
6742 	if (nla[NFTA_SET_ELEM_EXPR]) {
6743 		struct nft_expr *expr;
6744 
6745 		if (set->num_exprs && set->num_exprs != 1)
6746 			return -EOPNOTSUPP;
6747 
6748 		expr = nft_set_elem_expr_alloc(ctx, set,
6749 					       nla[NFTA_SET_ELEM_EXPR]);
6750 		if (IS_ERR(expr))
6751 			return PTR_ERR(expr);
6752 
6753 		expr_array[0] = expr;
6754 		num_exprs = 1;
6755 
6756 		if (set->num_exprs && set->exprs[0]->ops != expr->ops) {
6757 			err = -EOPNOTSUPP;
6758 			goto err_set_elem_expr;
6759 		}
6760 	} else if (nla[NFTA_SET_ELEM_EXPRESSIONS]) {
6761 		struct nft_expr *expr;
6762 		struct nlattr *tmp;
6763 		int left;
6764 
6765 		i = 0;
6766 		nla_for_each_nested(tmp, nla[NFTA_SET_ELEM_EXPRESSIONS], left) {
6767 			if (i == NFT_SET_EXPR_MAX ||
6768 			    (set->num_exprs && set->num_exprs == i)) {
6769 				err = -E2BIG;
6770 				goto err_set_elem_expr;
6771 			}
6772 			if (nla_type(tmp) != NFTA_LIST_ELEM) {
6773 				err = -EINVAL;
6774 				goto err_set_elem_expr;
6775 			}
6776 			expr = nft_set_elem_expr_alloc(ctx, set, tmp);
6777 			if (IS_ERR(expr)) {
6778 				err = PTR_ERR(expr);
6779 				goto err_set_elem_expr;
6780 			}
6781 			expr_array[i] = expr;
6782 			num_exprs++;
6783 
6784 			if (set->num_exprs && expr->ops != set->exprs[i]->ops) {
6785 				err = -EOPNOTSUPP;
6786 				goto err_set_elem_expr;
6787 			}
6788 			i++;
6789 		}
6790 		if (set->num_exprs && set->num_exprs != i) {
6791 			err = -EOPNOTSUPP;
6792 			goto err_set_elem_expr;
6793 		}
6794 	} else if (set->num_exprs > 0 &&
6795 		   !(flags & NFT_SET_ELEM_INTERVAL_END)) {
6796 		err = nft_set_elem_expr_clone(ctx, set, expr_array);
6797 		if (err < 0)
6798 			goto err_set_elem_expr_clone;
6799 
6800 		num_exprs = set->num_exprs;
6801 	}
6802 
6803 	if (nla[NFTA_SET_ELEM_KEY]) {
6804 		err = nft_setelem_parse_key(ctx, set, &elem.key.val,
6805 					    nla[NFTA_SET_ELEM_KEY]);
6806 		if (err < 0)
6807 			goto err_set_elem_expr;
6808 
6809 		err = nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY, set->klen);
6810 		if (err < 0)
6811 			goto err_parse_key;
6812 	}
6813 
6814 	if (nla[NFTA_SET_ELEM_KEY_END]) {
6815 		err = nft_setelem_parse_key(ctx, set, &elem.key_end.val,
6816 					    nla[NFTA_SET_ELEM_KEY_END]);
6817 		if (err < 0)
6818 			goto err_parse_key;
6819 
6820 		err = nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY_END, set->klen);
6821 		if (err < 0)
6822 			goto err_parse_key_end;
6823 	}
6824 
6825 	if (timeout > 0) {
6826 		err = nft_set_ext_add(&tmpl, NFT_SET_EXT_EXPIRATION);
6827 		if (err < 0)
6828 			goto err_parse_key_end;
6829 
6830 		if (timeout != set->timeout) {
6831 			err = nft_set_ext_add(&tmpl, NFT_SET_EXT_TIMEOUT);
6832 			if (err < 0)
6833 				goto err_parse_key_end;
6834 		}
6835 	}
6836 
6837 	if (num_exprs) {
6838 		for (i = 0; i < num_exprs; i++)
6839 			size += expr_array[i]->ops->size;
6840 
6841 		err = nft_set_ext_add_length(&tmpl, NFT_SET_EXT_EXPRESSIONS,
6842 					     sizeof(struct nft_set_elem_expr) + size);
6843 		if (err < 0)
6844 			goto err_parse_key_end;
6845 	}
6846 
6847 	if (nla[NFTA_SET_ELEM_OBJREF] != NULL) {
6848 		obj = nft_obj_lookup(ctx->net, ctx->table,
6849 				     nla[NFTA_SET_ELEM_OBJREF],
6850 				     set->objtype, genmask);
6851 		if (IS_ERR(obj)) {
6852 			err = PTR_ERR(obj);
6853 			obj = NULL;
6854 			goto err_parse_key_end;
6855 		}
6856 
6857 		if (!nft_use_inc(&obj->use)) {
6858 			err = -EMFILE;
6859 			obj = NULL;
6860 			goto err_parse_key_end;
6861 		}
6862 
6863 		err = nft_set_ext_add(&tmpl, NFT_SET_EXT_OBJREF);
6864 		if (err < 0)
6865 			goto err_parse_key_end;
6866 	}
6867 
6868 	if (nla[NFTA_SET_ELEM_DATA] != NULL) {
6869 		err = nft_setelem_parse_data(ctx, set, &desc, &elem.data.val,
6870 					     nla[NFTA_SET_ELEM_DATA]);
6871 		if (err < 0)
6872 			goto err_parse_key_end;
6873 
6874 		dreg = nft_type_to_reg(set->dtype);
6875 		list_for_each_entry(binding, &set->bindings, list) {
6876 			struct nft_ctx bind_ctx = {
6877 				.net	= ctx->net,
6878 				.family	= ctx->family,
6879 				.table	= ctx->table,
6880 				.chain	= (struct nft_chain *)binding->chain,
6881 			};
6882 
6883 			if (!(binding->flags & NFT_SET_MAP))
6884 				continue;
6885 
6886 			err = nft_validate_register_store(&bind_ctx, dreg,
6887 							  &elem.data.val,
6888 							  desc.type, desc.len);
6889 			if (err < 0)
6890 				goto err_parse_data;
6891 
6892 			if (desc.type == NFT_DATA_VERDICT &&
6893 			    (elem.data.val.verdict.code == NFT_GOTO ||
6894 			     elem.data.val.verdict.code == NFT_JUMP))
6895 				nft_validate_state_update(ctx->table,
6896 							  NFT_VALIDATE_NEED);
6897 		}
6898 
6899 		err = nft_set_ext_add_length(&tmpl, NFT_SET_EXT_DATA, desc.len);
6900 		if (err < 0)
6901 			goto err_parse_data;
6902 	}
6903 
6904 	/* The full maximum length of userdata can exceed the maximum
6905 	 * offset value (U8_MAX) for following extensions, therefor it
6906 	 * must be the last extension added.
6907 	 */
6908 	ulen = 0;
6909 	if (nla[NFTA_SET_ELEM_USERDATA] != NULL) {
6910 		ulen = nla_len(nla[NFTA_SET_ELEM_USERDATA]);
6911 		if (ulen > 0) {
6912 			err = nft_set_ext_add_length(&tmpl, NFT_SET_EXT_USERDATA,
6913 						     ulen);
6914 			if (err < 0)
6915 				goto err_parse_data;
6916 		}
6917 	}
6918 
6919 	elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data,
6920 				      elem.key_end.val.data, elem.data.val.data,
6921 				      timeout, expiration, GFP_KERNEL_ACCOUNT);
6922 	if (IS_ERR(elem.priv)) {
6923 		err = PTR_ERR(elem.priv);
6924 		goto err_parse_data;
6925 	}
6926 
6927 	ext = nft_set_elem_ext(set, elem.priv);
6928 	if (flags)
6929 		*nft_set_ext_flags(ext) = flags;
6930 
6931 	if (obj)
6932 		*nft_set_ext_obj(ext) = obj;
6933 
6934 	if (ulen > 0) {
6935 		if (nft_set_ext_check(&tmpl, NFT_SET_EXT_USERDATA, ulen) < 0) {
6936 			err = -EINVAL;
6937 			goto err_elem_free;
6938 		}
6939 		udata = nft_set_ext_userdata(ext);
6940 		udata->len = ulen - 1;
6941 		nla_memcpy(&udata->data, nla[NFTA_SET_ELEM_USERDATA], ulen);
6942 	}
6943 	err = nft_set_elem_expr_setup(ctx, &tmpl, ext, expr_array, num_exprs);
6944 	if (err < 0)
6945 		goto err_elem_free;
6946 
6947 	trans = nft_trans_elem_alloc(ctx, NFT_MSG_NEWSETELEM, set);
6948 	if (trans == NULL) {
6949 		err = -ENOMEM;
6950 		goto err_elem_free;
6951 	}
6952 
6953 	ext->genmask = nft_genmask_cur(ctx->net);
6954 
6955 	err = nft_setelem_insert(ctx->net, set, &elem, &ext2, flags);
6956 	if (err) {
6957 		if (err == -EEXIST) {
6958 			if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA) ^
6959 			    nft_set_ext_exists(ext2, NFT_SET_EXT_DATA) ||
6960 			    nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) ^
6961 			    nft_set_ext_exists(ext2, NFT_SET_EXT_OBJREF))
6962 				goto err_element_clash;
6963 			if ((nft_set_ext_exists(ext, NFT_SET_EXT_DATA) &&
6964 			     nft_set_ext_exists(ext2, NFT_SET_EXT_DATA) &&
6965 			     memcmp(nft_set_ext_data(ext),
6966 				    nft_set_ext_data(ext2), set->dlen) != 0) ||
6967 			    (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) &&
6968 			     nft_set_ext_exists(ext2, NFT_SET_EXT_OBJREF) &&
6969 			     *nft_set_ext_obj(ext) != *nft_set_ext_obj(ext2)))
6970 				goto err_element_clash;
6971 			else if (!(nlmsg_flags & NLM_F_EXCL))
6972 				err = 0;
6973 		} else if (err == -ENOTEMPTY) {
6974 			/* ENOTEMPTY reports overlapping between this element
6975 			 * and an existing one.
6976 			 */
6977 			err = -EEXIST;
6978 		}
6979 		goto err_element_clash;
6980 	}
6981 
6982 	if (!(flags & NFT_SET_ELEM_CATCHALL)) {
6983 		unsigned int max = set->size ? set->size + set->ndeact : UINT_MAX;
6984 
6985 		if (!atomic_add_unless(&set->nelems, 1, max)) {
6986 			err = -ENFILE;
6987 			goto err_set_full;
6988 		}
6989 	}
6990 
6991 	nft_trans_elem(trans) = elem;
6992 	nft_trans_commit_list_add_tail(ctx->net, trans);
6993 	return 0;
6994 
6995 err_set_full:
6996 	nft_setelem_remove(ctx->net, set, &elem);
6997 err_element_clash:
6998 	kfree(trans);
6999 err_elem_free:
7000 	nf_tables_set_elem_destroy(ctx, set, elem.priv);
7001 err_parse_data:
7002 	if (nla[NFTA_SET_ELEM_DATA] != NULL)
7003 		nft_data_release(&elem.data.val, desc.type);
7004 err_parse_key_end:
7005 	if (obj)
7006 		nft_use_dec_restore(&obj->use);
7007 
7008 	nft_data_release(&elem.key_end.val, NFT_DATA_VALUE);
7009 err_parse_key:
7010 	nft_data_release(&elem.key.val, NFT_DATA_VALUE);
7011 err_set_elem_expr:
7012 	for (i = 0; i < num_exprs && expr_array[i]; i++)
7013 		nft_expr_destroy(ctx, expr_array[i]);
7014 err_set_elem_expr_clone:
7015 	return err;
7016 }
7017 
nf_tables_newsetelem(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])7018 static int nf_tables_newsetelem(struct sk_buff *skb,
7019 				const struct nfnl_info *info,
7020 				const struct nlattr * const nla[])
7021 {
7022 	struct netlink_ext_ack *extack = info->extack;
7023 	u8 genmask = nft_genmask_next(info->net);
7024 	u8 family = info->nfmsg->nfgen_family;
7025 	struct net *net = info->net;
7026 	const struct nlattr *attr;
7027 	struct nft_table *table;
7028 	struct nft_set *set;
7029 	struct nft_ctx ctx;
7030 	int rem, err;
7031 
7032 	if (nla[NFTA_SET_ELEM_LIST_ELEMENTS] == NULL)
7033 		return -EINVAL;
7034 
7035 	table = nft_table_lookup(net, nla[NFTA_SET_ELEM_LIST_TABLE], family,
7036 				 genmask, NETLINK_CB(skb).portid);
7037 	if (IS_ERR(table)) {
7038 		NL_SET_BAD_ATTR(extack, nla[NFTA_SET_ELEM_LIST_TABLE]);
7039 		return PTR_ERR(table);
7040 	}
7041 
7042 	set = nft_set_lookup_global(net, table, nla[NFTA_SET_ELEM_LIST_SET],
7043 				    nla[NFTA_SET_ELEM_LIST_SET_ID], genmask);
7044 	if (IS_ERR(set))
7045 		return PTR_ERR(set);
7046 
7047 	if (!list_empty(&set->bindings) &&
7048 	    (set->flags & (NFT_SET_CONSTANT | NFT_SET_ANONYMOUS)))
7049 		return -EBUSY;
7050 
7051 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);
7052 
7053 	nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
7054 		err = nft_add_set_elem(&ctx, set, attr, info->nlh->nlmsg_flags);
7055 		if (err < 0) {
7056 			NL_SET_BAD_ATTR(extack, attr);
7057 			return err;
7058 		}
7059 	}
7060 
7061 	if (table->validate_state == NFT_VALIDATE_DO)
7062 		return nft_table_validate(net, table);
7063 
7064 	return 0;
7065 }
7066 
7067 /**
7068  *	nft_data_hold - hold a nft_data item
7069  *
7070  *	@data: struct nft_data to release
7071  *	@type: type of data
7072  *
7073  *	Hold a nft_data item. NFT_DATA_VALUE types can be silently discarded,
7074  *	NFT_DATA_VERDICT bumps the reference to chains in case of NFT_JUMP and
7075  *	NFT_GOTO verdicts. This function must be called on active data objects
7076  *	from the second phase of the commit protocol.
7077  */
nft_data_hold(const struct nft_data * data,enum nft_data_types type)7078 void nft_data_hold(const struct nft_data *data, enum nft_data_types type)
7079 {
7080 	struct nft_chain *chain;
7081 
7082 	if (type == NFT_DATA_VERDICT) {
7083 		switch (data->verdict.code) {
7084 		case NFT_JUMP:
7085 		case NFT_GOTO:
7086 			chain = data->verdict.chain;
7087 			nft_use_inc_restore(&chain->use);
7088 			break;
7089 		}
7090 	}
7091 }
7092 
nft_setelem_active_next(const struct net * net,const struct nft_set * set,struct nft_set_elem * elem)7093 static int nft_setelem_active_next(const struct net *net,
7094 				   const struct nft_set *set,
7095 				   struct nft_set_elem *elem)
7096 {
7097 	const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
7098 	u8 genmask = nft_genmask_next(net);
7099 
7100 	return nft_set_elem_active(ext, genmask);
7101 }
7102 
nft_setelem_data_activate(const struct net * net,const struct nft_set * set,struct nft_set_elem * elem)7103 static void nft_setelem_data_activate(const struct net *net,
7104 				      const struct nft_set *set,
7105 				      struct nft_set_elem *elem)
7106 {
7107 	const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
7108 
7109 	if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
7110 		nft_data_hold(nft_set_ext_data(ext), set->dtype);
7111 	if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
7112 		nft_use_inc_restore(&(*nft_set_ext_obj(ext))->use);
7113 }
7114 
nft_setelem_data_deactivate(const struct net * net,const struct nft_set * set,struct nft_set_elem * elem)7115 void nft_setelem_data_deactivate(const struct net *net,
7116 				 const struct nft_set *set,
7117 				 struct nft_set_elem *elem)
7118 {
7119 	const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
7120 
7121 	if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
7122 		nft_data_release(nft_set_ext_data(ext), set->dtype);
7123 	if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
7124 		nft_use_dec(&(*nft_set_ext_obj(ext))->use);
7125 }
7126 
nft_del_setelem(struct nft_ctx * ctx,struct nft_set * set,const struct nlattr * attr)7127 static int nft_del_setelem(struct nft_ctx *ctx, struct nft_set *set,
7128 			   const struct nlattr *attr)
7129 {
7130 	struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
7131 	struct nft_set_ext_tmpl tmpl;
7132 	struct nft_set_elem elem;
7133 	struct nft_set_ext *ext;
7134 	struct nft_trans *trans;
7135 	u32 flags = 0;
7136 	int err;
7137 
7138 	err = nla_parse_nested_deprecated(nla, NFTA_SET_ELEM_MAX, attr,
7139 					  nft_set_elem_policy, NULL);
7140 	if (err < 0)
7141 		return err;
7142 
7143 	err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
7144 	if (err < 0)
7145 		return err;
7146 
7147 	if (!nla[NFTA_SET_ELEM_KEY] && !(flags & NFT_SET_ELEM_CATCHALL))
7148 		return -EINVAL;
7149 
7150 	if (!nft_setelem_valid_key_end(set, nla, flags))
7151 		return -EINVAL;
7152 
7153 	nft_set_ext_prepare(&tmpl);
7154 
7155 	if (flags != 0) {
7156 		err = nft_set_ext_add(&tmpl, NFT_SET_EXT_FLAGS);
7157 		if (err < 0)
7158 			return err;
7159 	}
7160 
7161 	if (nla[NFTA_SET_ELEM_KEY]) {
7162 		err = nft_setelem_parse_key(ctx, set, &elem.key.val,
7163 					    nla[NFTA_SET_ELEM_KEY]);
7164 		if (err < 0)
7165 			return err;
7166 
7167 		err = nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY, set->klen);
7168 		if (err < 0)
7169 			goto fail_elem;
7170 	}
7171 
7172 	if (nla[NFTA_SET_ELEM_KEY_END]) {
7173 		err = nft_setelem_parse_key(ctx, set, &elem.key_end.val,
7174 					    nla[NFTA_SET_ELEM_KEY_END]);
7175 		if (err < 0)
7176 			goto fail_elem;
7177 
7178 		err = nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY_END, set->klen);
7179 		if (err < 0)
7180 			goto fail_elem_key_end;
7181 	}
7182 
7183 	err = -ENOMEM;
7184 	elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data,
7185 				      elem.key_end.val.data, NULL, 0, 0,
7186 				      GFP_KERNEL_ACCOUNT);
7187 	if (IS_ERR(elem.priv)) {
7188 		err = PTR_ERR(elem.priv);
7189 		goto fail_elem_key_end;
7190 	}
7191 
7192 	ext = nft_set_elem_ext(set, elem.priv);
7193 	if (flags)
7194 		*nft_set_ext_flags(ext) = flags;
7195 
7196 	trans = nft_trans_elem_alloc(ctx, NFT_MSG_DELSETELEM, set);
7197 	if (trans == NULL)
7198 		goto fail_trans;
7199 
7200 	err = nft_setelem_deactivate(ctx->net, set, &elem, flags);
7201 	if (err < 0)
7202 		goto fail_ops;
7203 
7204 	nft_setelem_data_deactivate(ctx->net, set, &elem);
7205 
7206 	nft_trans_elem(trans) = elem;
7207 	nft_trans_commit_list_add_tail(ctx->net, trans);
7208 	return 0;
7209 
7210 fail_ops:
7211 	kfree(trans);
7212 fail_trans:
7213 	kfree(elem.priv);
7214 fail_elem_key_end:
7215 	nft_data_release(&elem.key_end.val, NFT_DATA_VALUE);
7216 fail_elem:
7217 	nft_data_release(&elem.key.val, NFT_DATA_VALUE);
7218 	return err;
7219 }
7220 
nft_setelem_flush(const struct nft_ctx * ctx,struct nft_set * set,const struct nft_set_iter * iter,struct nft_set_elem * elem)7221 static int nft_setelem_flush(const struct nft_ctx *ctx,
7222 			     struct nft_set *set,
7223 			     const struct nft_set_iter *iter,
7224 			     struct nft_set_elem *elem)
7225 {
7226 	const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
7227 	struct nft_trans *trans;
7228 	int err;
7229 
7230 	if (!nft_set_elem_active(ext, iter->genmask))
7231 		return 0;
7232 
7233 	trans = nft_trans_alloc_gfp(ctx, NFT_MSG_DELSETELEM,
7234 				    sizeof(struct nft_trans_elem), GFP_ATOMIC);
7235 	if (!trans)
7236 		return -ENOMEM;
7237 
7238 	if (!set->ops->flush(ctx->net, set, elem->priv)) {
7239 		err = -ENOENT;
7240 		goto err1;
7241 	}
7242 	set->ndeact++;
7243 
7244 	nft_setelem_data_deactivate(ctx->net, set, elem);
7245 	nft_trans_elem_set(trans) = set;
7246 	nft_trans_elem(trans) = *elem;
7247 	nft_trans_commit_list_add_tail(ctx->net, trans);
7248 
7249 	return 0;
7250 err1:
7251 	kfree(trans);
7252 	return err;
7253 }
7254 
__nft_set_catchall_flush(const struct nft_ctx * ctx,struct nft_set * set,struct nft_set_elem * elem)7255 static int __nft_set_catchall_flush(const struct nft_ctx *ctx,
7256 				    struct nft_set *set,
7257 				    struct nft_set_elem *elem)
7258 {
7259 	struct nft_trans *trans;
7260 
7261 	trans = nft_trans_alloc_gfp(ctx, NFT_MSG_DELSETELEM,
7262 				    sizeof(struct nft_trans_elem), GFP_KERNEL);
7263 	if (!trans)
7264 		return -ENOMEM;
7265 
7266 	nft_setelem_data_deactivate(ctx->net, set, elem);
7267 	nft_trans_elem_set(trans) = set;
7268 	nft_trans_elem(trans) = *elem;
7269 	nft_trans_commit_list_add_tail(ctx->net, trans);
7270 
7271 	return 0;
7272 }
7273 
nft_set_catchall_flush(const struct nft_ctx * ctx,struct nft_set * set)7274 static int nft_set_catchall_flush(const struct nft_ctx *ctx,
7275 				  struct nft_set *set)
7276 {
7277 	u8 genmask = nft_genmask_next(ctx->net);
7278 	struct nft_set_elem_catchall *catchall;
7279 	struct nft_set_elem elem;
7280 	struct nft_set_ext *ext;
7281 	int ret = 0;
7282 
7283 	list_for_each_entry_rcu(catchall, &set->catchall_list, list) {
7284 		ext = nft_set_elem_ext(set, catchall->elem);
7285 		if (!nft_set_elem_active(ext, genmask))
7286 			continue;
7287 
7288 		elem.priv = catchall->elem;
7289 		ret = __nft_set_catchall_flush(ctx, set, &elem);
7290 		if (ret < 0)
7291 			break;
7292 		nft_set_elem_change_active(ctx->net, set, ext);
7293 	}
7294 
7295 	return ret;
7296 }
7297 
nft_set_flush(struct nft_ctx * ctx,struct nft_set * set,u8 genmask)7298 static int nft_set_flush(struct nft_ctx *ctx, struct nft_set *set, u8 genmask)
7299 {
7300 	struct nft_set_iter iter = {
7301 		.genmask	= genmask,
7302 		.type		= NFT_ITER_UPDATE,
7303 		.fn		= nft_setelem_flush,
7304 	};
7305 
7306 	set->ops->walk(ctx, set, &iter);
7307 	if (!iter.err)
7308 		iter.err = nft_set_catchall_flush(ctx, set);
7309 
7310 	return iter.err;
7311 }
7312 
nf_tables_delsetelem(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])7313 static int nf_tables_delsetelem(struct sk_buff *skb,
7314 				const struct nfnl_info *info,
7315 				const struct nlattr * const nla[])
7316 {
7317 	struct netlink_ext_ack *extack = info->extack;
7318 	u8 genmask = nft_genmask_next(info->net);
7319 	u8 family = info->nfmsg->nfgen_family;
7320 	struct net *net = info->net;
7321 	const struct nlattr *attr;
7322 	struct nft_table *table;
7323 	struct nft_set *set;
7324 	struct nft_ctx ctx;
7325 	int rem, err = 0;
7326 
7327 	table = nft_table_lookup(net, nla[NFTA_SET_ELEM_LIST_TABLE], family,
7328 				 genmask, NETLINK_CB(skb).portid);
7329 	if (IS_ERR(table)) {
7330 		NL_SET_BAD_ATTR(extack, nla[NFTA_SET_ELEM_LIST_TABLE]);
7331 		return PTR_ERR(table);
7332 	}
7333 
7334 	set = nft_set_lookup(table, nla[NFTA_SET_ELEM_LIST_SET], genmask);
7335 	if (IS_ERR(set))
7336 		return PTR_ERR(set);
7337 
7338 	if (nft_set_is_anonymous(set))
7339 		return -EOPNOTSUPP;
7340 
7341 	if (!list_empty(&set->bindings) && (set->flags & NFT_SET_CONSTANT))
7342 		return -EBUSY;
7343 
7344 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);
7345 
7346 	if (!nla[NFTA_SET_ELEM_LIST_ELEMENTS])
7347 		return nft_set_flush(&ctx, set, genmask);
7348 
7349 	nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
7350 		err = nft_del_setelem(&ctx, set, attr);
7351 		if (err == -ENOENT &&
7352 		    NFNL_MSG_TYPE(info->nlh->nlmsg_type) == NFT_MSG_DESTROYSETELEM)
7353 			continue;
7354 
7355 		if (err < 0) {
7356 			NL_SET_BAD_ATTR(extack, attr);
7357 			return err;
7358 		}
7359 	}
7360 
7361 	return 0;
7362 }
7363 
7364 /*
7365  * Stateful objects
7366  */
7367 
7368 /**
7369  *	nft_register_obj- register nf_tables stateful object type
7370  *	@obj_type: object type
7371  *
7372  *	Registers the object type for use with nf_tables. Returns zero on
7373  *	success or a negative errno code otherwise.
7374  */
nft_register_obj(struct nft_object_type * obj_type)7375 int nft_register_obj(struct nft_object_type *obj_type)
7376 {
7377 	if (obj_type->type == NFT_OBJECT_UNSPEC)
7378 		return -EINVAL;
7379 
7380 	nfnl_lock(NFNL_SUBSYS_NFTABLES);
7381 	list_add_rcu(&obj_type->list, &nf_tables_objects);
7382 	nfnl_unlock(NFNL_SUBSYS_NFTABLES);
7383 	return 0;
7384 }
7385 EXPORT_SYMBOL_GPL(nft_register_obj);
7386 
7387 /**
7388  *	nft_unregister_obj - unregister nf_tables object type
7389  *	@obj_type: object type
7390  *
7391  * 	Unregisters the object type for use with nf_tables.
7392  */
nft_unregister_obj(struct nft_object_type * obj_type)7393 void nft_unregister_obj(struct nft_object_type *obj_type)
7394 {
7395 	nfnl_lock(NFNL_SUBSYS_NFTABLES);
7396 	list_del_rcu(&obj_type->list);
7397 	nfnl_unlock(NFNL_SUBSYS_NFTABLES);
7398 }
7399 EXPORT_SYMBOL_GPL(nft_unregister_obj);
7400 
nft_obj_lookup(const struct net * net,const struct nft_table * table,const struct nlattr * nla,u32 objtype,u8 genmask)7401 struct nft_object *nft_obj_lookup(const struct net *net,
7402 				  const struct nft_table *table,
7403 				  const struct nlattr *nla, u32 objtype,
7404 				  u8 genmask)
7405 {
7406 	struct nft_object_hash_key k = { .table = table };
7407 	char search[NFT_OBJ_MAXNAMELEN];
7408 	struct rhlist_head *tmp, *list;
7409 	struct nft_object *obj;
7410 
7411 	nla_strscpy(search, nla, sizeof(search));
7412 	k.name = search;
7413 
7414 	WARN_ON_ONCE(!rcu_read_lock_held() &&
7415 		     !lockdep_commit_lock_is_held(net));
7416 
7417 	rcu_read_lock();
7418 	list = rhltable_lookup(&nft_objname_ht, &k, nft_objname_ht_params);
7419 	if (!list)
7420 		goto out;
7421 
7422 	rhl_for_each_entry_rcu(obj, tmp, list, rhlhead) {
7423 		if (objtype == obj->ops->type->type &&
7424 		    nft_active_genmask(obj, genmask)) {
7425 			rcu_read_unlock();
7426 			return obj;
7427 		}
7428 	}
7429 out:
7430 	rcu_read_unlock();
7431 	return ERR_PTR(-ENOENT);
7432 }
7433 EXPORT_SYMBOL_GPL(nft_obj_lookup);
7434 
nft_obj_lookup_byhandle(const struct nft_table * table,const struct nlattr * nla,u32 objtype,u8 genmask)7435 static struct nft_object *nft_obj_lookup_byhandle(const struct nft_table *table,
7436 						  const struct nlattr *nla,
7437 						  u32 objtype, u8 genmask)
7438 {
7439 	struct nft_object *obj;
7440 
7441 	list_for_each_entry(obj, &table->objects, list) {
7442 		if (be64_to_cpu(nla_get_be64(nla)) == obj->handle &&
7443 		    objtype == obj->ops->type->type &&
7444 		    nft_active_genmask(obj, genmask))
7445 			return obj;
7446 	}
7447 	return ERR_PTR(-ENOENT);
7448 }
7449 
7450 static const struct nla_policy nft_obj_policy[NFTA_OBJ_MAX + 1] = {
7451 	[NFTA_OBJ_TABLE]	= { .type = NLA_STRING,
7452 				    .len = NFT_TABLE_MAXNAMELEN - 1 },
7453 	[NFTA_OBJ_NAME]		= { .type = NLA_STRING,
7454 				    .len = NFT_OBJ_MAXNAMELEN - 1 },
7455 	[NFTA_OBJ_TYPE]		= { .type = NLA_U32 },
7456 	[NFTA_OBJ_DATA]		= { .type = NLA_NESTED },
7457 	[NFTA_OBJ_HANDLE]	= { .type = NLA_U64},
7458 	[NFTA_OBJ_USERDATA]	= { .type = NLA_BINARY,
7459 				    .len = NFT_USERDATA_MAXLEN },
7460 };
7461 
nft_obj_init(const struct nft_ctx * ctx,const struct nft_object_type * type,const struct nlattr * attr)7462 static struct nft_object *nft_obj_init(const struct nft_ctx *ctx,
7463 				       const struct nft_object_type *type,
7464 				       const struct nlattr *attr)
7465 {
7466 	struct nlattr **tb;
7467 	const struct nft_object_ops *ops;
7468 	struct nft_object *obj;
7469 	int err = -ENOMEM;
7470 
7471 	tb = kmalloc_array(type->maxattr + 1, sizeof(*tb), GFP_KERNEL);
7472 	if (!tb)
7473 		goto err1;
7474 
7475 	if (attr) {
7476 		err = nla_parse_nested_deprecated(tb, type->maxattr, attr,
7477 						  type->policy, NULL);
7478 		if (err < 0)
7479 			goto err2;
7480 	} else {
7481 		memset(tb, 0, sizeof(tb[0]) * (type->maxattr + 1));
7482 	}
7483 
7484 	if (type->select_ops) {
7485 		ops = type->select_ops(ctx, (const struct nlattr * const *)tb);
7486 		if (IS_ERR(ops)) {
7487 			err = PTR_ERR(ops);
7488 			goto err2;
7489 		}
7490 	} else {
7491 		ops = type->ops;
7492 	}
7493 
7494 	err = -ENOMEM;
7495 	obj = kzalloc(sizeof(*obj) + ops->size, GFP_KERNEL_ACCOUNT);
7496 	if (!obj)
7497 		goto err2;
7498 
7499 	err = ops->init(ctx, (const struct nlattr * const *)tb, obj);
7500 	if (err < 0)
7501 		goto err3;
7502 
7503 	obj->ops = ops;
7504 
7505 	kfree(tb);
7506 	return obj;
7507 err3:
7508 	kfree(obj);
7509 err2:
7510 	kfree(tb);
7511 err1:
7512 	return ERR_PTR(err);
7513 }
7514 
nft_object_dump(struct sk_buff * skb,unsigned int attr,struct nft_object * obj,bool reset)7515 static int nft_object_dump(struct sk_buff *skb, unsigned int attr,
7516 			   struct nft_object *obj, bool reset)
7517 {
7518 	struct nlattr *nest;
7519 
7520 	nest = nla_nest_start_noflag(skb, attr);
7521 	if (!nest)
7522 		goto nla_put_failure;
7523 	if (obj->ops->dump(skb, obj, reset) < 0)
7524 		goto nla_put_failure;
7525 	nla_nest_end(skb, nest);
7526 	return 0;
7527 
7528 nla_put_failure:
7529 	return -1;
7530 }
7531 
__nft_obj_type_get(u32 objtype,u8 family)7532 static const struct nft_object_type *__nft_obj_type_get(u32 objtype, u8 family)
7533 {
7534 	const struct nft_object_type *type;
7535 
7536 	list_for_each_entry_rcu(type, &nf_tables_objects, list) {
7537 		if (type->family != NFPROTO_UNSPEC &&
7538 		    type->family != family)
7539 			continue;
7540 
7541 		if (objtype == type->type)
7542 			return type;
7543 	}
7544 	return NULL;
7545 }
7546 
7547 static const struct nft_object_type *
nft_obj_type_get(struct net * net,u32 objtype,u8 family)7548 nft_obj_type_get(struct net *net, u32 objtype, u8 family)
7549 {
7550 	const struct nft_object_type *type;
7551 
7552 	rcu_read_lock();
7553 	type = __nft_obj_type_get(objtype, family);
7554 	if (type != NULL && try_module_get(type->owner)) {
7555 		rcu_read_unlock();
7556 		return type;
7557 	}
7558 	rcu_read_unlock();
7559 
7560 	lockdep_nfnl_nft_mutex_not_held();
7561 #ifdef CONFIG_MODULES
7562 	if (type == NULL) {
7563 		if (nft_request_module(net, "nft-obj-%u", objtype) == -EAGAIN)
7564 			return ERR_PTR(-EAGAIN);
7565 	}
7566 #endif
7567 	return ERR_PTR(-ENOENT);
7568 }
7569 
nf_tables_updobj(const struct nft_ctx * ctx,const struct nft_object_type * type,const struct nlattr * attr,struct nft_object * obj)7570 static int nf_tables_updobj(const struct nft_ctx *ctx,
7571 			    const struct nft_object_type *type,
7572 			    const struct nlattr *attr,
7573 			    struct nft_object *obj)
7574 {
7575 	struct nft_object *newobj;
7576 	struct nft_trans *trans;
7577 	int err = -ENOMEM;
7578 
7579 	if (!try_module_get(type->owner))
7580 		return -ENOENT;
7581 
7582 	trans = nft_trans_alloc(ctx, NFT_MSG_NEWOBJ,
7583 				sizeof(struct nft_trans_obj));
7584 	if (!trans)
7585 		goto err_trans;
7586 
7587 	newobj = nft_obj_init(ctx, type, attr);
7588 	if (IS_ERR(newobj)) {
7589 		err = PTR_ERR(newobj);
7590 		goto err_free_trans;
7591 	}
7592 
7593 	nft_trans_obj(trans) = obj;
7594 	nft_trans_obj_update(trans) = true;
7595 	nft_trans_obj_newobj(trans) = newobj;
7596 	nft_trans_commit_list_add_tail(ctx->net, trans);
7597 
7598 	return 0;
7599 
7600 err_free_trans:
7601 	kfree(trans);
7602 err_trans:
7603 	module_put(type->owner);
7604 	return err;
7605 }
7606 
nf_tables_newobj(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])7607 static int nf_tables_newobj(struct sk_buff *skb, const struct nfnl_info *info,
7608 			    const struct nlattr * const nla[])
7609 {
7610 	struct netlink_ext_ack *extack = info->extack;
7611 	u8 genmask = nft_genmask_next(info->net);
7612 	u8 family = info->nfmsg->nfgen_family;
7613 	const struct nft_object_type *type;
7614 	struct net *net = info->net;
7615 	struct nft_table *table;
7616 	struct nft_object *obj;
7617 	struct nft_ctx ctx;
7618 	u32 objtype;
7619 	int err;
7620 
7621 	if (!nla[NFTA_OBJ_TYPE] ||
7622 	    !nla[NFTA_OBJ_NAME] ||
7623 	    !nla[NFTA_OBJ_DATA])
7624 		return -EINVAL;
7625 
7626 	table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask,
7627 				 NETLINK_CB(skb).portid);
7628 	if (IS_ERR(table)) {
7629 		NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
7630 		return PTR_ERR(table);
7631 	}
7632 
7633 	objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
7634 	obj = nft_obj_lookup(net, table, nla[NFTA_OBJ_NAME], objtype, genmask);
7635 	if (IS_ERR(obj)) {
7636 		err = PTR_ERR(obj);
7637 		if (err != -ENOENT) {
7638 			NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
7639 			return err;
7640 		}
7641 	} else {
7642 		if (info->nlh->nlmsg_flags & NLM_F_EXCL) {
7643 			NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
7644 			return -EEXIST;
7645 		}
7646 		if (info->nlh->nlmsg_flags & NLM_F_REPLACE)
7647 			return -EOPNOTSUPP;
7648 
7649 		type = __nft_obj_type_get(objtype, family);
7650 		if (WARN_ON_ONCE(!type))
7651 			return -ENOENT;
7652 
7653 		nft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);
7654 
7655 		return nf_tables_updobj(&ctx, type, nla[NFTA_OBJ_DATA], obj);
7656 	}
7657 
7658 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);
7659 
7660 	if (!nft_use_inc(&table->use))
7661 		return -EMFILE;
7662 
7663 	type = nft_obj_type_get(net, objtype, family);
7664 	if (IS_ERR(type)) {
7665 		err = PTR_ERR(type);
7666 		goto err_type;
7667 	}
7668 
7669 	obj = nft_obj_init(&ctx, type, nla[NFTA_OBJ_DATA]);
7670 	if (IS_ERR(obj)) {
7671 		err = PTR_ERR(obj);
7672 		goto err_init;
7673 	}
7674 	obj->key.table = table;
7675 	obj->handle = nf_tables_alloc_handle(table);
7676 
7677 	obj->key.name = nla_strdup(nla[NFTA_OBJ_NAME], GFP_KERNEL_ACCOUNT);
7678 	if (!obj->key.name) {
7679 		err = -ENOMEM;
7680 		goto err_strdup;
7681 	}
7682 
7683 	if (nla[NFTA_OBJ_USERDATA]) {
7684 		obj->udata = nla_memdup(nla[NFTA_OBJ_USERDATA], GFP_KERNEL_ACCOUNT);
7685 		if (obj->udata == NULL)
7686 			goto err_userdata;
7687 
7688 		obj->udlen = nla_len(nla[NFTA_OBJ_USERDATA]);
7689 	}
7690 
7691 	err = nft_trans_obj_add(&ctx, NFT_MSG_NEWOBJ, obj);
7692 	if (err < 0)
7693 		goto err_trans;
7694 
7695 	err = rhltable_insert(&nft_objname_ht, &obj->rhlhead,
7696 			      nft_objname_ht_params);
7697 	if (err < 0)
7698 		goto err_obj_ht;
7699 
7700 	list_add_tail_rcu(&obj->list, &table->objects);
7701 
7702 	return 0;
7703 err_obj_ht:
7704 	/* queued in transaction log */
7705 	INIT_LIST_HEAD(&obj->list);
7706 	return err;
7707 err_trans:
7708 	kfree(obj->udata);
7709 err_userdata:
7710 	kfree(obj->key.name);
7711 err_strdup:
7712 	if (obj->ops->destroy)
7713 		obj->ops->destroy(&ctx, obj);
7714 	kfree(obj);
7715 err_init:
7716 	module_put(type->owner);
7717 err_type:
7718 	nft_use_dec_restore(&table->use);
7719 
7720 	return err;
7721 }
7722 
nf_tables_fill_obj_info(struct sk_buff * skb,struct net * net,u32 portid,u32 seq,int event,u32 flags,int family,const struct nft_table * table,struct nft_object * obj,bool reset)7723 static int nf_tables_fill_obj_info(struct sk_buff *skb, struct net *net,
7724 				   u32 portid, u32 seq, int event, u32 flags,
7725 				   int family, const struct nft_table *table,
7726 				   struct nft_object *obj, bool reset)
7727 {
7728 	struct nlmsghdr *nlh;
7729 
7730 	event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
7731 	nlh = nfnl_msg_put(skb, portid, seq, event, flags, family,
7732 			   NFNETLINK_V0, nft_base_seq(net));
7733 	if (!nlh)
7734 		goto nla_put_failure;
7735 
7736 	if (nla_put_string(skb, NFTA_OBJ_TABLE, table->name) ||
7737 	    nla_put_string(skb, NFTA_OBJ_NAME, obj->key.name) ||
7738 	    nla_put_be64(skb, NFTA_OBJ_HANDLE, cpu_to_be64(obj->handle),
7739 			 NFTA_OBJ_PAD))
7740 		goto nla_put_failure;
7741 
7742 	if (event == NFT_MSG_DELOBJ) {
7743 		nlmsg_end(skb, nlh);
7744 		return 0;
7745 	}
7746 
7747 	if (nla_put_be32(skb, NFTA_OBJ_TYPE, htonl(obj->ops->type->type)) ||
7748 	    nla_put_be32(skb, NFTA_OBJ_USE, htonl(obj->use)) ||
7749 	    nft_object_dump(skb, NFTA_OBJ_DATA, obj, reset))
7750 		goto nla_put_failure;
7751 
7752 	if (obj->udata &&
7753 	    nla_put(skb, NFTA_OBJ_USERDATA, obj->udlen, obj->udata))
7754 		goto nla_put_failure;
7755 
7756 	nlmsg_end(skb, nlh);
7757 	return 0;
7758 
7759 nla_put_failure:
7760 	nlmsg_trim(skb, nlh);
7761 	return -1;
7762 }
7763 
audit_log_obj_reset(const struct nft_table * table,unsigned int base_seq,unsigned int nentries)7764 static void audit_log_obj_reset(const struct nft_table *table,
7765 				unsigned int base_seq, unsigned int nentries)
7766 {
7767 	char *buf = kasprintf(GFP_ATOMIC, "%s:%u", table->name, base_seq);
7768 
7769 	audit_log_nfcfg(buf, table->family, nentries,
7770 			AUDIT_NFT_OP_OBJ_RESET, GFP_ATOMIC);
7771 	kfree(buf);
7772 }
7773 
7774 struct nft_obj_dump_ctx {
7775 	unsigned int	s_idx;
7776 	char		*table;
7777 	u32		type;
7778 	bool		reset;
7779 };
7780 
nf_tables_dump_obj(struct sk_buff * skb,struct netlink_callback * cb)7781 static int nf_tables_dump_obj(struct sk_buff *skb, struct netlink_callback *cb)
7782 {
7783 	const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
7784 	struct nft_obj_dump_ctx *ctx = (void *)cb->ctx;
7785 	struct net *net = sock_net(skb->sk);
7786 	int family = nfmsg->nfgen_family;
7787 	struct nftables_pernet *nft_net;
7788 	const struct nft_table *table;
7789 	unsigned int entries = 0;
7790 	struct nft_object *obj;
7791 	unsigned int idx = 0;
7792 	int rc = 0;
7793 
7794 	rcu_read_lock();
7795 	nft_net = nft_pernet(net);
7796 	cb->seq = READ_ONCE(nft_net->base_seq);
7797 
7798 	list_for_each_entry_rcu(table, &nft_net->tables, list) {
7799 		if (family != NFPROTO_UNSPEC && family != table->family)
7800 			continue;
7801 
7802 		entries = 0;
7803 		list_for_each_entry_rcu(obj, &table->objects, list) {
7804 			if (!nft_is_active(net, obj))
7805 				goto cont;
7806 			if (idx < ctx->s_idx)
7807 				goto cont;
7808 			if (ctx->table && strcmp(ctx->table, table->name))
7809 				goto cont;
7810 			if (ctx->type != NFT_OBJECT_UNSPEC &&
7811 			    obj->ops->type->type != ctx->type)
7812 				goto cont;
7813 
7814 			rc = nf_tables_fill_obj_info(skb, net,
7815 						     NETLINK_CB(cb->skb).portid,
7816 						     cb->nlh->nlmsg_seq,
7817 						     NFT_MSG_NEWOBJ,
7818 						     NLM_F_MULTI | NLM_F_APPEND,
7819 						     table->family, table,
7820 						     obj, ctx->reset);
7821 			if (rc < 0)
7822 				break;
7823 
7824 			entries++;
7825 			nl_dump_check_consistent(cb, nlmsg_hdr(skb));
7826 cont:
7827 			idx++;
7828 		}
7829 		if (ctx->reset && entries)
7830 			audit_log_obj_reset(table, nft_net->base_seq, entries);
7831 		if (rc < 0)
7832 			break;
7833 	}
7834 	rcu_read_unlock();
7835 
7836 	ctx->s_idx = idx;
7837 	return skb->len;
7838 }
7839 
nf_tables_dumpreset_obj(struct sk_buff * skb,struct netlink_callback * cb)7840 static int nf_tables_dumpreset_obj(struct sk_buff *skb,
7841 				   struct netlink_callback *cb)
7842 {
7843 	struct nftables_pernet *nft_net = nft_pernet(sock_net(skb->sk));
7844 	int ret;
7845 
7846 	mutex_lock(&nft_net->commit_mutex);
7847 	ret = nf_tables_dump_obj(skb, cb);
7848 	mutex_unlock(&nft_net->commit_mutex);
7849 
7850 	return ret;
7851 }
7852 
nf_tables_dump_obj_start(struct netlink_callback * cb)7853 static int nf_tables_dump_obj_start(struct netlink_callback *cb)
7854 {
7855 	struct nft_obj_dump_ctx *ctx = (void *)cb->ctx;
7856 	const struct nlattr * const *nla = cb->data;
7857 
7858 	BUILD_BUG_ON(sizeof(*ctx) > sizeof(cb->ctx));
7859 
7860 	if (nla[NFTA_OBJ_TABLE]) {
7861 		ctx->table = nla_strdup(nla[NFTA_OBJ_TABLE], GFP_ATOMIC);
7862 		if (!ctx->table)
7863 			return -ENOMEM;
7864 	}
7865 
7866 	if (nla[NFTA_OBJ_TYPE])
7867 		ctx->type = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
7868 
7869 	return 0;
7870 }
7871 
nf_tables_dumpreset_obj_start(struct netlink_callback * cb)7872 static int nf_tables_dumpreset_obj_start(struct netlink_callback *cb)
7873 {
7874 	struct nft_obj_dump_ctx *ctx = (void *)cb->ctx;
7875 
7876 	ctx->reset = true;
7877 
7878 	return nf_tables_dump_obj_start(cb);
7879 }
7880 
nf_tables_dump_obj_done(struct netlink_callback * cb)7881 static int nf_tables_dump_obj_done(struct netlink_callback *cb)
7882 {
7883 	struct nft_obj_dump_ctx *ctx = (void *)cb->ctx;
7884 
7885 	kfree(ctx->table);
7886 
7887 	return 0;
7888 }
7889 
7890 /* called with rcu_read_lock held */
7891 static struct sk_buff *
nf_tables_getobj_single(u32 portid,const struct nfnl_info * info,const struct nlattr * const nla[],bool reset)7892 nf_tables_getobj_single(u32 portid, const struct nfnl_info *info,
7893 			const struct nlattr * const nla[], bool reset)
7894 {
7895 	struct netlink_ext_ack *extack = info->extack;
7896 	u8 genmask = nft_genmask_cur(info->net);
7897 	u8 family = info->nfmsg->nfgen_family;
7898 	const struct nft_table *table;
7899 	struct net *net = info->net;
7900 	struct nft_object *obj;
7901 	struct sk_buff *skb2;
7902 	u32 objtype;
7903 	int err;
7904 
7905 	if (!nla[NFTA_OBJ_NAME] ||
7906 	    !nla[NFTA_OBJ_TYPE])
7907 		return ERR_PTR(-EINVAL);
7908 
7909 	table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask, 0);
7910 	if (IS_ERR(table)) {
7911 		NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
7912 		return ERR_CAST(table);
7913 	}
7914 
7915 	objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
7916 	obj = nft_obj_lookup(net, table, nla[NFTA_OBJ_NAME], objtype, genmask);
7917 	if (IS_ERR(obj)) {
7918 		NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
7919 		return ERR_CAST(obj);
7920 	}
7921 
7922 	skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
7923 	if (!skb2)
7924 		return ERR_PTR(-ENOMEM);
7925 
7926 	err = nf_tables_fill_obj_info(skb2, net, portid,
7927 				      info->nlh->nlmsg_seq, NFT_MSG_NEWOBJ, 0,
7928 				      family, table, obj, reset);
7929 	if (err < 0) {
7930 		kfree_skb(skb2);
7931 		return ERR_PTR(err);
7932 	}
7933 
7934 	return skb2;
7935 }
7936 
nf_tables_getobj(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])7937 static int nf_tables_getobj(struct sk_buff *skb, const struct nfnl_info *info,
7938 			    const struct nlattr * const nla[])
7939 {
7940 	u32 portid = NETLINK_CB(skb).portid;
7941 	struct sk_buff *skb2;
7942 
7943 	if (info->nlh->nlmsg_flags & NLM_F_DUMP) {
7944 		struct netlink_dump_control c = {
7945 			.start = nf_tables_dump_obj_start,
7946 			.dump = nf_tables_dump_obj,
7947 			.done = nf_tables_dump_obj_done,
7948 			.module = THIS_MODULE,
7949 			.data = (void *)nla,
7950 		};
7951 
7952 		return nft_netlink_dump_start_rcu(info->sk, skb, info->nlh, &c);
7953 	}
7954 
7955 	skb2 = nf_tables_getobj_single(portid, info, nla, false);
7956 	if (IS_ERR(skb2))
7957 		return PTR_ERR(skb2);
7958 
7959 	return nfnetlink_unicast(skb2, info->net, portid);
7960 }
7961 
nf_tables_getobj_reset(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])7962 static int nf_tables_getobj_reset(struct sk_buff *skb,
7963 				  const struct nfnl_info *info,
7964 				  const struct nlattr * const nla[])
7965 {
7966 	struct nftables_pernet *nft_net = nft_pernet(info->net);
7967 	u32 portid = NETLINK_CB(skb).portid;
7968 	struct net *net = info->net;
7969 	struct sk_buff *skb2;
7970 	char *buf;
7971 
7972 	if (info->nlh->nlmsg_flags & NLM_F_DUMP) {
7973 		struct netlink_dump_control c = {
7974 			.start = nf_tables_dumpreset_obj_start,
7975 			.dump = nf_tables_dumpreset_obj,
7976 			.done = nf_tables_dump_obj_done,
7977 			.module = THIS_MODULE,
7978 			.data = (void *)nla,
7979 		};
7980 
7981 		return nft_netlink_dump_start_rcu(info->sk, skb, info->nlh, &c);
7982 	}
7983 
7984 	if (!try_module_get(THIS_MODULE))
7985 		return -EINVAL;
7986 	rcu_read_unlock();
7987 	mutex_lock(&nft_net->commit_mutex);
7988 	skb2 = nf_tables_getobj_single(portid, info, nla, true);
7989 	mutex_unlock(&nft_net->commit_mutex);
7990 	rcu_read_lock();
7991 	module_put(THIS_MODULE);
7992 
7993 	if (IS_ERR(skb2))
7994 		return PTR_ERR(skb2);
7995 
7996 	buf = kasprintf(GFP_ATOMIC, "%.*s:%u",
7997 			nla_len(nla[NFTA_OBJ_TABLE]),
7998 			(char *)nla_data(nla[NFTA_OBJ_TABLE]),
7999 			nft_net->base_seq);
8000 	audit_log_nfcfg(buf, info->nfmsg->nfgen_family, 1,
8001 			AUDIT_NFT_OP_OBJ_RESET, GFP_ATOMIC);
8002 	kfree(buf);
8003 
8004 	return nfnetlink_unicast(skb2, net, portid);
8005 }
8006 
nft_obj_destroy(const struct nft_ctx * ctx,struct nft_object * obj)8007 static void nft_obj_destroy(const struct nft_ctx *ctx, struct nft_object *obj)
8008 {
8009 	if (obj->ops->destroy)
8010 		obj->ops->destroy(ctx, obj);
8011 
8012 	module_put(obj->ops->type->owner);
8013 	kfree(obj->key.name);
8014 	kfree(obj->udata);
8015 	kfree(obj);
8016 }
8017 
nf_tables_delobj(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])8018 static int nf_tables_delobj(struct sk_buff *skb, const struct nfnl_info *info,
8019 			    const struct nlattr * const nla[])
8020 {
8021 	struct netlink_ext_ack *extack = info->extack;
8022 	u8 genmask = nft_genmask_next(info->net);
8023 	u8 family = info->nfmsg->nfgen_family;
8024 	struct net *net = info->net;
8025 	const struct nlattr *attr;
8026 	struct nft_table *table;
8027 	struct nft_object *obj;
8028 	struct nft_ctx ctx;
8029 	u32 objtype;
8030 
8031 	if (!nla[NFTA_OBJ_TYPE] ||
8032 	    (!nla[NFTA_OBJ_NAME] && !nla[NFTA_OBJ_HANDLE]))
8033 		return -EINVAL;
8034 
8035 	table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask,
8036 				 NETLINK_CB(skb).portid);
8037 	if (IS_ERR(table)) {
8038 		NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
8039 		return PTR_ERR(table);
8040 	}
8041 
8042 	objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
8043 	if (nla[NFTA_OBJ_HANDLE]) {
8044 		attr = nla[NFTA_OBJ_HANDLE];
8045 		obj = nft_obj_lookup_byhandle(table, attr, objtype, genmask);
8046 	} else {
8047 		attr = nla[NFTA_OBJ_NAME];
8048 		obj = nft_obj_lookup(net, table, attr, objtype, genmask);
8049 	}
8050 
8051 	if (IS_ERR(obj)) {
8052 		if (PTR_ERR(obj) == -ENOENT &&
8053 		    NFNL_MSG_TYPE(info->nlh->nlmsg_type) == NFT_MSG_DESTROYOBJ)
8054 			return 0;
8055 
8056 		NL_SET_BAD_ATTR(extack, attr);
8057 		return PTR_ERR(obj);
8058 	}
8059 	if (obj->use > 0) {
8060 		NL_SET_BAD_ATTR(extack, attr);
8061 		return -EBUSY;
8062 	}
8063 
8064 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);
8065 
8066 	return nft_delobj(&ctx, obj);
8067 }
8068 
8069 static void
__nft_obj_notify(struct net * net,const struct nft_table * table,struct nft_object * obj,u32 portid,u32 seq,int event,u16 flags,int family,int report,gfp_t gfp)8070 __nft_obj_notify(struct net *net, const struct nft_table *table,
8071 		 struct nft_object *obj, u32 portid, u32 seq, int event,
8072 		 u16 flags, int family, int report, gfp_t gfp)
8073 {
8074 	struct nftables_pernet *nft_net = nft_pernet(net);
8075 	struct sk_buff *skb;
8076 	int err;
8077 
8078 	if (!report &&
8079 	    !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
8080 		return;
8081 
8082 	skb = nlmsg_new(NLMSG_GOODSIZE, gfp);
8083 	if (skb == NULL)
8084 		goto err;
8085 
8086 	err = nf_tables_fill_obj_info(skb, net, portid, seq, event,
8087 				      flags & (NLM_F_CREATE | NLM_F_EXCL),
8088 				      family, table, obj, false);
8089 	if (err < 0) {
8090 		kfree_skb(skb);
8091 		goto err;
8092 	}
8093 
8094 	nft_notify_enqueue(skb, report, &nft_net->notify_list);
8095 	return;
8096 err:
8097 	nfnetlink_set_err(net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
8098 }
8099 
nft_obj_notify(struct net * net,const struct nft_table * table,struct nft_object * obj,u32 portid,u32 seq,int event,u16 flags,int family,int report,gfp_t gfp)8100 void nft_obj_notify(struct net *net, const struct nft_table *table,
8101 		    struct nft_object *obj, u32 portid, u32 seq, int event,
8102 		    u16 flags, int family, int report, gfp_t gfp)
8103 {
8104 	struct nftables_pernet *nft_net = nft_pernet(net);
8105 	char *buf = kasprintf(gfp, "%s:%u",
8106 			      table->name, nft_net->base_seq);
8107 
8108 	audit_log_nfcfg(buf,
8109 			family,
8110 			obj->handle,
8111 			event == NFT_MSG_NEWOBJ ?
8112 				 AUDIT_NFT_OP_OBJ_REGISTER :
8113 				 AUDIT_NFT_OP_OBJ_UNREGISTER,
8114 			gfp);
8115 	kfree(buf);
8116 
8117 	__nft_obj_notify(net, table, obj, portid, seq, event,
8118 			 flags, family, report, gfp);
8119 }
8120 EXPORT_SYMBOL_GPL(nft_obj_notify);
8121 
nf_tables_obj_notify(const struct nft_ctx * ctx,struct nft_object * obj,int event)8122 static void nf_tables_obj_notify(const struct nft_ctx *ctx,
8123 				 struct nft_object *obj, int event)
8124 {
8125 	__nft_obj_notify(ctx->net, ctx->table, obj, ctx->portid,
8126 			 ctx->seq, event, ctx->flags, ctx->family,
8127 			 ctx->report, GFP_KERNEL);
8128 }
8129 
8130 /*
8131  * Flow tables
8132  */
nft_register_flowtable_type(struct nf_flowtable_type * type)8133 void nft_register_flowtable_type(struct nf_flowtable_type *type)
8134 {
8135 	nfnl_lock(NFNL_SUBSYS_NFTABLES);
8136 	list_add_tail_rcu(&type->list, &nf_tables_flowtables);
8137 	nfnl_unlock(NFNL_SUBSYS_NFTABLES);
8138 }
8139 EXPORT_SYMBOL_GPL(nft_register_flowtable_type);
8140 
nft_unregister_flowtable_type(struct nf_flowtable_type * type)8141 void nft_unregister_flowtable_type(struct nf_flowtable_type *type)
8142 {
8143 	nfnl_lock(NFNL_SUBSYS_NFTABLES);
8144 	list_del_rcu(&type->list);
8145 	nfnl_unlock(NFNL_SUBSYS_NFTABLES);
8146 }
8147 EXPORT_SYMBOL_GPL(nft_unregister_flowtable_type);
8148 
8149 static const struct nla_policy nft_flowtable_policy[NFTA_FLOWTABLE_MAX + 1] = {
8150 	[NFTA_FLOWTABLE_TABLE]		= { .type = NLA_STRING,
8151 					    .len = NFT_NAME_MAXLEN - 1 },
8152 	[NFTA_FLOWTABLE_NAME]		= { .type = NLA_STRING,
8153 					    .len = NFT_NAME_MAXLEN - 1 },
8154 	[NFTA_FLOWTABLE_HOOK]		= { .type = NLA_NESTED },
8155 	[NFTA_FLOWTABLE_HANDLE]		= { .type = NLA_U64 },
8156 	[NFTA_FLOWTABLE_FLAGS]		= { .type = NLA_U32 },
8157 };
8158 
nft_flowtable_lookup(const struct nft_table * table,const struct nlattr * nla,u8 genmask)8159 struct nft_flowtable *nft_flowtable_lookup(const struct nft_table *table,
8160 					   const struct nlattr *nla, u8 genmask)
8161 {
8162 	struct nft_flowtable *flowtable;
8163 
8164 	list_for_each_entry_rcu(flowtable, &table->flowtables, list) {
8165 		if (!nla_strcmp(nla, flowtable->name) &&
8166 		    nft_active_genmask(flowtable, genmask))
8167 			return flowtable;
8168 	}
8169 	return ERR_PTR(-ENOENT);
8170 }
8171 EXPORT_SYMBOL_GPL(nft_flowtable_lookup);
8172 
nf_tables_deactivate_flowtable(const struct nft_ctx * ctx,struct nft_flowtable * flowtable,enum nft_trans_phase phase)8173 void nf_tables_deactivate_flowtable(const struct nft_ctx *ctx,
8174 				    struct nft_flowtable *flowtable,
8175 				    enum nft_trans_phase phase)
8176 {
8177 	switch (phase) {
8178 	case NFT_TRANS_PREPARE_ERROR:
8179 	case NFT_TRANS_PREPARE:
8180 	case NFT_TRANS_ABORT:
8181 	case NFT_TRANS_RELEASE:
8182 		nft_use_dec(&flowtable->use);
8183 		fallthrough;
8184 	default:
8185 		return;
8186 	}
8187 }
8188 EXPORT_SYMBOL_GPL(nf_tables_deactivate_flowtable);
8189 
8190 static struct nft_flowtable *
nft_flowtable_lookup_byhandle(const struct nft_table * table,const struct nlattr * nla,u8 genmask)8191 nft_flowtable_lookup_byhandle(const struct nft_table *table,
8192 			      const struct nlattr *nla, u8 genmask)
8193 {
8194        struct nft_flowtable *flowtable;
8195 
8196        list_for_each_entry(flowtable, &table->flowtables, list) {
8197                if (be64_to_cpu(nla_get_be64(nla)) == flowtable->handle &&
8198                    nft_active_genmask(flowtable, genmask))
8199                        return flowtable;
8200        }
8201        return ERR_PTR(-ENOENT);
8202 }
8203 
8204 struct nft_flowtable_hook {
8205 	u32			num;
8206 	int			priority;
8207 	struct list_head	list;
8208 };
8209 
8210 static const struct nla_policy nft_flowtable_hook_policy[NFTA_FLOWTABLE_HOOK_MAX + 1] = {
8211 	[NFTA_FLOWTABLE_HOOK_NUM]	= { .type = NLA_U32 },
8212 	[NFTA_FLOWTABLE_HOOK_PRIORITY]	= { .type = NLA_U32 },
8213 	[NFTA_FLOWTABLE_HOOK_DEVS]	= { .type = NLA_NESTED },
8214 };
8215 
nft_flowtable_parse_hook(const struct nft_ctx * ctx,const struct nlattr * const nla[],struct nft_flowtable_hook * flowtable_hook,struct nft_flowtable * flowtable,struct netlink_ext_ack * extack,bool add)8216 static int nft_flowtable_parse_hook(const struct nft_ctx *ctx,
8217 				    const struct nlattr * const nla[],
8218 				    struct nft_flowtable_hook *flowtable_hook,
8219 				    struct nft_flowtable *flowtable,
8220 				    struct netlink_ext_ack *extack, bool add)
8221 {
8222 	struct nlattr *tb[NFTA_FLOWTABLE_HOOK_MAX + 1];
8223 	struct nft_hook *hook;
8224 	int hooknum, priority;
8225 	int err;
8226 
8227 	INIT_LIST_HEAD(&flowtable_hook->list);
8228 
8229 	err = nla_parse_nested_deprecated(tb, NFTA_FLOWTABLE_HOOK_MAX,
8230 					  nla[NFTA_FLOWTABLE_HOOK],
8231 					  nft_flowtable_hook_policy, NULL);
8232 	if (err < 0)
8233 		return err;
8234 
8235 	if (add) {
8236 		if (!tb[NFTA_FLOWTABLE_HOOK_NUM] ||
8237 		    !tb[NFTA_FLOWTABLE_HOOK_PRIORITY]) {
8238 			NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_NAME]);
8239 			return -ENOENT;
8240 		}
8241 
8242 		hooknum = ntohl(nla_get_be32(tb[NFTA_FLOWTABLE_HOOK_NUM]));
8243 		if (hooknum != NF_NETDEV_INGRESS)
8244 			return -EOPNOTSUPP;
8245 
8246 		priority = ntohl(nla_get_be32(tb[NFTA_FLOWTABLE_HOOK_PRIORITY]));
8247 
8248 		flowtable_hook->priority	= priority;
8249 		flowtable_hook->num		= hooknum;
8250 	} else {
8251 		if (tb[NFTA_FLOWTABLE_HOOK_NUM]) {
8252 			hooknum = ntohl(nla_get_be32(tb[NFTA_FLOWTABLE_HOOK_NUM]));
8253 			if (hooknum != flowtable->hooknum)
8254 				return -EOPNOTSUPP;
8255 		}
8256 
8257 		if (tb[NFTA_FLOWTABLE_HOOK_PRIORITY]) {
8258 			priority = ntohl(nla_get_be32(tb[NFTA_FLOWTABLE_HOOK_PRIORITY]));
8259 			if (priority != flowtable->data.priority)
8260 				return -EOPNOTSUPP;
8261 		}
8262 
8263 		flowtable_hook->priority	= flowtable->data.priority;
8264 		flowtable_hook->num		= flowtable->hooknum;
8265 	}
8266 
8267 	if (tb[NFTA_FLOWTABLE_HOOK_DEVS]) {
8268 		err = nf_tables_parse_netdev_hooks(ctx->net,
8269 						   tb[NFTA_FLOWTABLE_HOOK_DEVS],
8270 						   &flowtable_hook->list,
8271 						   extack);
8272 		if (err < 0)
8273 			return err;
8274 	}
8275 
8276 	list_for_each_entry(hook, &flowtable_hook->list, list) {
8277 		hook->ops.pf		= NFPROTO_NETDEV;
8278 		hook->ops.hooknum	= flowtable_hook->num;
8279 		hook->ops.priority	= flowtable_hook->priority;
8280 		hook->ops.priv		= &flowtable->data;
8281 		hook->ops.hook		= flowtable->data.type->hook;
8282 	}
8283 
8284 	return err;
8285 }
8286 
8287 /* call under rcu_read_lock */
__nft_flowtable_type_get(u8 family)8288 static const struct nf_flowtable_type *__nft_flowtable_type_get(u8 family)
8289 {
8290 	const struct nf_flowtable_type *type;
8291 
8292 	list_for_each_entry_rcu(type, &nf_tables_flowtables, list) {
8293 		if (family == type->family)
8294 			return type;
8295 	}
8296 	return NULL;
8297 }
8298 
8299 static const struct nf_flowtable_type *
nft_flowtable_type_get(struct net * net,u8 family)8300 nft_flowtable_type_get(struct net *net, u8 family)
8301 {
8302 	const struct nf_flowtable_type *type;
8303 
8304 	rcu_read_lock();
8305 	type = __nft_flowtable_type_get(family);
8306 	if (type != NULL && try_module_get(type->owner)) {
8307 		rcu_read_unlock();
8308 		return type;
8309 	}
8310 	rcu_read_unlock();
8311 
8312 	lockdep_nfnl_nft_mutex_not_held();
8313 #ifdef CONFIG_MODULES
8314 	if (type == NULL) {
8315 		if (nft_request_module(net, "nf-flowtable-%u", family) == -EAGAIN)
8316 			return ERR_PTR(-EAGAIN);
8317 	}
8318 #endif
8319 	return ERR_PTR(-ENOENT);
8320 }
8321 
8322 /* Only called from error and netdev event paths. */
nft_unregister_flowtable_hook(struct net * net,struct nft_flowtable * flowtable,struct nft_hook * hook)8323 static void nft_unregister_flowtable_hook(struct net *net,
8324 					  struct nft_flowtable *flowtable,
8325 					  struct nft_hook *hook)
8326 {
8327 	nf_unregister_net_hook(net, &hook->ops);
8328 	flowtable->data.type->setup(&flowtable->data, hook->ops.dev,
8329 				    FLOW_BLOCK_UNBIND);
8330 }
8331 
__nft_unregister_flowtable_net_hooks(struct net * net,struct list_head * hook_list,bool release_netdev)8332 static void __nft_unregister_flowtable_net_hooks(struct net *net,
8333 						 struct list_head *hook_list,
8334 					         bool release_netdev)
8335 {
8336 	struct nft_hook *hook, *next;
8337 
8338 	list_for_each_entry_safe(hook, next, hook_list, list) {
8339 		nf_unregister_net_hook(net, &hook->ops);
8340 		if (release_netdev) {
8341 			list_del(&hook->list);
8342 			kfree_rcu(hook, rcu);
8343 		}
8344 	}
8345 }
8346 
nft_unregister_flowtable_net_hooks(struct net * net,struct list_head * hook_list)8347 static void nft_unregister_flowtable_net_hooks(struct net *net,
8348 					       struct list_head *hook_list)
8349 {
8350 	__nft_unregister_flowtable_net_hooks(net, hook_list, false);
8351 }
8352 
nft_register_flowtable_net_hooks(struct net * net,struct nft_table * table,struct list_head * hook_list,struct nft_flowtable * flowtable)8353 static int nft_register_flowtable_net_hooks(struct net *net,
8354 					    struct nft_table *table,
8355 					    struct list_head *hook_list,
8356 					    struct nft_flowtable *flowtable)
8357 {
8358 	struct nft_hook *hook, *hook2, *next;
8359 	struct nft_flowtable *ft;
8360 	int err, i = 0;
8361 
8362 	list_for_each_entry(hook, hook_list, list) {
8363 		list_for_each_entry(ft, &table->flowtables, list) {
8364 			if (!nft_is_active_next(net, ft))
8365 				continue;
8366 
8367 			list_for_each_entry(hook2, &ft->hook_list, list) {
8368 				if (hook->ops.dev == hook2->ops.dev &&
8369 				    hook->ops.pf == hook2->ops.pf) {
8370 					err = -EEXIST;
8371 					goto err_unregister_net_hooks;
8372 				}
8373 			}
8374 		}
8375 
8376 		err = flowtable->data.type->setup(&flowtable->data,
8377 						  hook->ops.dev,
8378 						  FLOW_BLOCK_BIND);
8379 		if (err < 0)
8380 			goto err_unregister_net_hooks;
8381 
8382 		err = nf_register_net_hook(net, &hook->ops);
8383 		if (err < 0) {
8384 			flowtable->data.type->setup(&flowtable->data,
8385 						    hook->ops.dev,
8386 						    FLOW_BLOCK_UNBIND);
8387 			goto err_unregister_net_hooks;
8388 		}
8389 
8390 		i++;
8391 	}
8392 
8393 	return 0;
8394 
8395 err_unregister_net_hooks:
8396 	list_for_each_entry_safe(hook, next, hook_list, list) {
8397 		if (i-- <= 0)
8398 			break;
8399 
8400 		nft_unregister_flowtable_hook(net, flowtable, hook);
8401 		list_del_rcu(&hook->list);
8402 		kfree_rcu(hook, rcu);
8403 	}
8404 
8405 	return err;
8406 }
8407 
nft_hooks_destroy(struct list_head * hook_list)8408 static void nft_hooks_destroy(struct list_head *hook_list)
8409 {
8410 	struct nft_hook *hook, *next;
8411 
8412 	list_for_each_entry_safe(hook, next, hook_list, list) {
8413 		list_del_rcu(&hook->list);
8414 		kfree_rcu(hook, rcu);
8415 	}
8416 }
8417 
nft_flowtable_update(struct nft_ctx * ctx,const struct nlmsghdr * nlh,struct nft_flowtable * flowtable,struct netlink_ext_ack * extack)8418 static int nft_flowtable_update(struct nft_ctx *ctx, const struct nlmsghdr *nlh,
8419 				struct nft_flowtable *flowtable,
8420 				struct netlink_ext_ack *extack)
8421 {
8422 	const struct nlattr * const *nla = ctx->nla;
8423 	struct nft_flowtable_hook flowtable_hook;
8424 	struct nft_hook *hook, *next;
8425 	struct nft_trans *trans;
8426 	bool unregister = false;
8427 	u32 flags;
8428 	int err;
8429 
8430 	err = nft_flowtable_parse_hook(ctx, nla, &flowtable_hook, flowtable,
8431 				       extack, false);
8432 	if (err < 0)
8433 		return err;
8434 
8435 	list_for_each_entry_safe(hook, next, &flowtable_hook.list, list) {
8436 		if (nft_hook_list_find(&flowtable->hook_list, hook)) {
8437 			list_del(&hook->list);
8438 			kfree(hook);
8439 		}
8440 	}
8441 
8442 	if (nla[NFTA_FLOWTABLE_FLAGS]) {
8443 		flags = ntohl(nla_get_be32(nla[NFTA_FLOWTABLE_FLAGS]));
8444 		if (flags & ~NFT_FLOWTABLE_MASK) {
8445 			err = -EOPNOTSUPP;
8446 			goto err_flowtable_update_hook;
8447 		}
8448 		if ((flowtable->data.flags & NFT_FLOWTABLE_HW_OFFLOAD) ^
8449 		    (flags & NFT_FLOWTABLE_HW_OFFLOAD)) {
8450 			err = -EOPNOTSUPP;
8451 			goto err_flowtable_update_hook;
8452 		}
8453 	} else {
8454 		flags = flowtable->data.flags;
8455 	}
8456 
8457 	err = nft_register_flowtable_net_hooks(ctx->net, ctx->table,
8458 					       &flowtable_hook.list, flowtable);
8459 	if (err < 0)
8460 		goto err_flowtable_update_hook;
8461 
8462 	trans = nft_trans_alloc(ctx, NFT_MSG_NEWFLOWTABLE,
8463 				sizeof(struct nft_trans_flowtable));
8464 	if (!trans) {
8465 		unregister = true;
8466 		err = -ENOMEM;
8467 		goto err_flowtable_update_hook;
8468 	}
8469 
8470 	nft_trans_flowtable_flags(trans) = flags;
8471 	nft_trans_flowtable(trans) = flowtable;
8472 	nft_trans_flowtable_update(trans) = true;
8473 	INIT_LIST_HEAD(&nft_trans_flowtable_hooks(trans));
8474 	list_splice(&flowtable_hook.list, &nft_trans_flowtable_hooks(trans));
8475 
8476 	nft_trans_commit_list_add_tail(ctx->net, trans);
8477 
8478 	return 0;
8479 
8480 err_flowtable_update_hook:
8481 	list_for_each_entry_safe(hook, next, &flowtable_hook.list, list) {
8482 		if (unregister)
8483 			nft_unregister_flowtable_hook(ctx->net, flowtable, hook);
8484 		list_del_rcu(&hook->list);
8485 		kfree_rcu(hook, rcu);
8486 	}
8487 
8488 	return err;
8489 
8490 }
8491 
nf_tables_newflowtable(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])8492 static int nf_tables_newflowtable(struct sk_buff *skb,
8493 				  const struct nfnl_info *info,
8494 				  const struct nlattr * const nla[])
8495 {
8496 	struct netlink_ext_ack *extack = info->extack;
8497 	struct nft_flowtable_hook flowtable_hook;
8498 	u8 genmask = nft_genmask_next(info->net);
8499 	u8 family = info->nfmsg->nfgen_family;
8500 	const struct nf_flowtable_type *type;
8501 	struct nft_flowtable *flowtable;
8502 	struct net *net = info->net;
8503 	struct nft_table *table;
8504 	struct nft_trans *trans;
8505 	struct nft_ctx ctx;
8506 	int err;
8507 
8508 	if (!nla[NFTA_FLOWTABLE_TABLE] ||
8509 	    !nla[NFTA_FLOWTABLE_NAME] ||
8510 	    !nla[NFTA_FLOWTABLE_HOOK])
8511 		return -EINVAL;
8512 
8513 	table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
8514 				 genmask, NETLINK_CB(skb).portid);
8515 	if (IS_ERR(table)) {
8516 		NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_TABLE]);
8517 		return PTR_ERR(table);
8518 	}
8519 
8520 	flowtable = nft_flowtable_lookup(table, nla[NFTA_FLOWTABLE_NAME],
8521 					 genmask);
8522 	if (IS_ERR(flowtable)) {
8523 		err = PTR_ERR(flowtable);
8524 		if (err != -ENOENT) {
8525 			NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_NAME]);
8526 			return err;
8527 		}
8528 	} else {
8529 		if (info->nlh->nlmsg_flags & NLM_F_EXCL) {
8530 			NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_NAME]);
8531 			return -EEXIST;
8532 		}
8533 
8534 		nft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);
8535 
8536 		return nft_flowtable_update(&ctx, info->nlh, flowtable, extack);
8537 	}
8538 
8539 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);
8540 
8541 	if (!nft_use_inc(&table->use))
8542 		return -EMFILE;
8543 
8544 	flowtable = kzalloc(sizeof(*flowtable), GFP_KERNEL_ACCOUNT);
8545 	if (!flowtable) {
8546 		err = -ENOMEM;
8547 		goto flowtable_alloc;
8548 	}
8549 
8550 	flowtable->table = table;
8551 	flowtable->handle = nf_tables_alloc_handle(table);
8552 	INIT_LIST_HEAD(&flowtable->hook_list);
8553 
8554 	flowtable->name = nla_strdup(nla[NFTA_FLOWTABLE_NAME], GFP_KERNEL_ACCOUNT);
8555 	if (!flowtable->name) {
8556 		err = -ENOMEM;
8557 		goto err1;
8558 	}
8559 
8560 	type = nft_flowtable_type_get(net, family);
8561 	if (IS_ERR(type)) {
8562 		err = PTR_ERR(type);
8563 		goto err2;
8564 	}
8565 
8566 	if (nla[NFTA_FLOWTABLE_FLAGS]) {
8567 		flowtable->data.flags =
8568 			ntohl(nla_get_be32(nla[NFTA_FLOWTABLE_FLAGS]));
8569 		if (flowtable->data.flags & ~NFT_FLOWTABLE_MASK) {
8570 			err = -EOPNOTSUPP;
8571 			goto err3;
8572 		}
8573 	}
8574 
8575 	write_pnet(&flowtable->data.net, net);
8576 	flowtable->data.type = type;
8577 	err = type->init(&flowtable->data);
8578 	if (err < 0)
8579 		goto err3;
8580 
8581 	err = nft_flowtable_parse_hook(&ctx, nla, &flowtable_hook, flowtable,
8582 				       extack, true);
8583 	if (err < 0)
8584 		goto err_flowtable_parse_hooks;
8585 
8586 	list_splice(&flowtable_hook.list, &flowtable->hook_list);
8587 	flowtable->data.priority = flowtable_hook.priority;
8588 	flowtable->hooknum = flowtable_hook.num;
8589 
8590 	trans = nft_trans_flowtable_add(&ctx, NFT_MSG_NEWFLOWTABLE, flowtable);
8591 	if (IS_ERR(trans)) {
8592 		err = PTR_ERR(trans);
8593 		goto err_flowtable_trans;
8594 	}
8595 
8596 	/* This must be LAST to ensure no packets are walking over this flowtable. */
8597 	err = nft_register_flowtable_net_hooks(ctx.net, table,
8598 					       &flowtable->hook_list,
8599 					       flowtable);
8600 	if (err < 0)
8601 		goto err_flowtable_hooks;
8602 
8603 	list_add_tail_rcu(&flowtable->list, &table->flowtables);
8604 
8605 	return 0;
8606 
8607 err_flowtable_hooks:
8608 	nft_trans_destroy(trans);
8609 err_flowtable_trans:
8610 	nft_hooks_destroy(&flowtable->hook_list);
8611 err_flowtable_parse_hooks:
8612 	flowtable->data.type->free(&flowtable->data);
8613 err3:
8614 	module_put(type->owner);
8615 err2:
8616 	kfree(flowtable->name);
8617 err1:
8618 	kfree(flowtable);
8619 flowtable_alloc:
8620 	nft_use_dec_restore(&table->use);
8621 
8622 	return err;
8623 }
8624 
nft_flowtable_hook_release(struct nft_flowtable_hook * flowtable_hook)8625 static void nft_flowtable_hook_release(struct nft_flowtable_hook *flowtable_hook)
8626 {
8627 	struct nft_hook *this, *next;
8628 
8629 	list_for_each_entry_safe(this, next, &flowtable_hook->list, list) {
8630 		list_del(&this->list);
8631 		kfree(this);
8632 	}
8633 }
8634 
nft_delflowtable_hook(struct nft_ctx * ctx,struct nft_flowtable * flowtable,struct netlink_ext_ack * extack)8635 static int nft_delflowtable_hook(struct nft_ctx *ctx,
8636 				 struct nft_flowtable *flowtable,
8637 				 struct netlink_ext_ack *extack)
8638 {
8639 	const struct nlattr * const *nla = ctx->nla;
8640 	struct nft_flowtable_hook flowtable_hook;
8641 	LIST_HEAD(flowtable_del_list);
8642 	struct nft_hook *this, *hook;
8643 	struct nft_trans *trans;
8644 	int err;
8645 
8646 	err = nft_flowtable_parse_hook(ctx, nla, &flowtable_hook, flowtable,
8647 				       extack, false);
8648 	if (err < 0)
8649 		return err;
8650 
8651 	list_for_each_entry(this, &flowtable_hook.list, list) {
8652 		hook = nft_hook_list_find(&flowtable->hook_list, this);
8653 		if (!hook) {
8654 			err = -ENOENT;
8655 			goto err_flowtable_del_hook;
8656 		}
8657 		list_move(&hook->list, &flowtable_del_list);
8658 	}
8659 
8660 	trans = nft_trans_alloc(ctx, NFT_MSG_DELFLOWTABLE,
8661 				sizeof(struct nft_trans_flowtable));
8662 	if (!trans) {
8663 		err = -ENOMEM;
8664 		goto err_flowtable_del_hook;
8665 	}
8666 
8667 	nft_trans_flowtable(trans) = flowtable;
8668 	nft_trans_flowtable_update(trans) = true;
8669 	INIT_LIST_HEAD(&nft_trans_flowtable_hooks(trans));
8670 	list_splice(&flowtable_del_list, &nft_trans_flowtable_hooks(trans));
8671 	nft_flowtable_hook_release(&flowtable_hook);
8672 
8673 	nft_trans_commit_list_add_tail(ctx->net, trans);
8674 
8675 	return 0;
8676 
8677 err_flowtable_del_hook:
8678 	list_splice(&flowtable_del_list, &flowtable->hook_list);
8679 	nft_flowtable_hook_release(&flowtable_hook);
8680 
8681 	return err;
8682 }
8683 
nf_tables_delflowtable(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])8684 static int nf_tables_delflowtable(struct sk_buff *skb,
8685 				  const struct nfnl_info *info,
8686 				  const struct nlattr * const nla[])
8687 {
8688 	struct netlink_ext_ack *extack = info->extack;
8689 	u8 genmask = nft_genmask_next(info->net);
8690 	u8 family = info->nfmsg->nfgen_family;
8691 	struct nft_flowtable *flowtable;
8692 	struct net *net = info->net;
8693 	const struct nlattr *attr;
8694 	struct nft_table *table;
8695 	struct nft_ctx ctx;
8696 
8697 	if (!nla[NFTA_FLOWTABLE_TABLE] ||
8698 	    (!nla[NFTA_FLOWTABLE_NAME] &&
8699 	     !nla[NFTA_FLOWTABLE_HANDLE]))
8700 		return -EINVAL;
8701 
8702 	table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
8703 				 genmask, NETLINK_CB(skb).portid);
8704 	if (IS_ERR(table)) {
8705 		NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_TABLE]);
8706 		return PTR_ERR(table);
8707 	}
8708 
8709 	if (nla[NFTA_FLOWTABLE_HANDLE]) {
8710 		attr = nla[NFTA_FLOWTABLE_HANDLE];
8711 		flowtable = nft_flowtable_lookup_byhandle(table, attr, genmask);
8712 	} else {
8713 		attr = nla[NFTA_FLOWTABLE_NAME];
8714 		flowtable = nft_flowtable_lookup(table, attr, genmask);
8715 	}
8716 
8717 	if (IS_ERR(flowtable)) {
8718 		if (PTR_ERR(flowtable) == -ENOENT &&
8719 		    NFNL_MSG_TYPE(info->nlh->nlmsg_type) == NFT_MSG_DESTROYFLOWTABLE)
8720 			return 0;
8721 
8722 		NL_SET_BAD_ATTR(extack, attr);
8723 		return PTR_ERR(flowtable);
8724 	}
8725 
8726 	nft_ctx_init(&ctx, net, skb, info->nlh, family, table, NULL, nla);
8727 
8728 	if (nla[NFTA_FLOWTABLE_HOOK])
8729 		return nft_delflowtable_hook(&ctx, flowtable, extack);
8730 
8731 	if (flowtable->use > 0) {
8732 		NL_SET_BAD_ATTR(extack, attr);
8733 		return -EBUSY;
8734 	}
8735 
8736 	return nft_delflowtable(&ctx, flowtable);
8737 }
8738 
nf_tables_fill_flowtable_info(struct sk_buff * skb,struct net * net,u32 portid,u32 seq,int event,u32 flags,int family,struct nft_flowtable * flowtable,struct list_head * hook_list)8739 static int nf_tables_fill_flowtable_info(struct sk_buff *skb, struct net *net,
8740 					 u32 portid, u32 seq, int event,
8741 					 u32 flags, int family,
8742 					 struct nft_flowtable *flowtable,
8743 					 struct list_head *hook_list)
8744 {
8745 	struct nlattr *nest, *nest_devs;
8746 	struct nft_hook *hook;
8747 	struct nlmsghdr *nlh;
8748 
8749 	event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
8750 	nlh = nfnl_msg_put(skb, portid, seq, event, flags, family,
8751 			   NFNETLINK_V0, nft_base_seq(net));
8752 	if (!nlh)
8753 		goto nla_put_failure;
8754 
8755 	if (nla_put_string(skb, NFTA_FLOWTABLE_TABLE, flowtable->table->name) ||
8756 	    nla_put_string(skb, NFTA_FLOWTABLE_NAME, flowtable->name) ||
8757 	    nla_put_be64(skb, NFTA_FLOWTABLE_HANDLE, cpu_to_be64(flowtable->handle),
8758 			 NFTA_FLOWTABLE_PAD))
8759 		goto nla_put_failure;
8760 
8761 	if (event == NFT_MSG_DELFLOWTABLE && !hook_list) {
8762 		nlmsg_end(skb, nlh);
8763 		return 0;
8764 	}
8765 
8766 	if (nla_put_be32(skb, NFTA_FLOWTABLE_USE, htonl(flowtable->use)) ||
8767 	    nla_put_be32(skb, NFTA_FLOWTABLE_FLAGS, htonl(flowtable->data.flags)))
8768 		goto nla_put_failure;
8769 
8770 	nest = nla_nest_start_noflag(skb, NFTA_FLOWTABLE_HOOK);
8771 	if (!nest)
8772 		goto nla_put_failure;
8773 	if (nla_put_be32(skb, NFTA_FLOWTABLE_HOOK_NUM, htonl(flowtable->hooknum)) ||
8774 	    nla_put_be32(skb, NFTA_FLOWTABLE_HOOK_PRIORITY, htonl(flowtable->data.priority)))
8775 		goto nla_put_failure;
8776 
8777 	nest_devs = nla_nest_start_noflag(skb, NFTA_FLOWTABLE_HOOK_DEVS);
8778 	if (!nest_devs)
8779 		goto nla_put_failure;
8780 
8781 	if (!hook_list)
8782 		hook_list = &flowtable->hook_list;
8783 
8784 	list_for_each_entry_rcu(hook, hook_list, list) {
8785 		if (nla_put_string(skb, NFTA_DEVICE_NAME, hook->ops.dev->name))
8786 			goto nla_put_failure;
8787 	}
8788 	nla_nest_end(skb, nest_devs);
8789 	nla_nest_end(skb, nest);
8790 
8791 	nlmsg_end(skb, nlh);
8792 	return 0;
8793 
8794 nla_put_failure:
8795 	nlmsg_trim(skb, nlh);
8796 	return -1;
8797 }
8798 
8799 struct nft_flowtable_filter {
8800 	char		*table;
8801 };
8802 
nf_tables_dump_flowtable(struct sk_buff * skb,struct netlink_callback * cb)8803 static int nf_tables_dump_flowtable(struct sk_buff *skb,
8804 				    struct netlink_callback *cb)
8805 {
8806 	const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
8807 	struct nft_flowtable_filter *filter = cb->data;
8808 	unsigned int idx = 0, s_idx = cb->args[0];
8809 	struct net *net = sock_net(skb->sk);
8810 	int family = nfmsg->nfgen_family;
8811 	struct nft_flowtable *flowtable;
8812 	struct nftables_pernet *nft_net;
8813 	const struct nft_table *table;
8814 
8815 	rcu_read_lock();
8816 	nft_net = nft_pernet(net);
8817 	cb->seq = READ_ONCE(nft_net->base_seq);
8818 
8819 	list_for_each_entry_rcu(table, &nft_net->tables, list) {
8820 		if (family != NFPROTO_UNSPEC && family != table->family)
8821 			continue;
8822 
8823 		list_for_each_entry_rcu(flowtable, &table->flowtables, list) {
8824 			if (!nft_is_active(net, flowtable))
8825 				goto cont;
8826 			if (idx < s_idx)
8827 				goto cont;
8828 			if (idx > s_idx)
8829 				memset(&cb->args[1], 0,
8830 				       sizeof(cb->args) - sizeof(cb->args[0]));
8831 			if (filter && filter->table &&
8832 			    strcmp(filter->table, table->name))
8833 				goto cont;
8834 
8835 			if (nf_tables_fill_flowtable_info(skb, net, NETLINK_CB(cb->skb).portid,
8836 							  cb->nlh->nlmsg_seq,
8837 							  NFT_MSG_NEWFLOWTABLE,
8838 							  NLM_F_MULTI | NLM_F_APPEND,
8839 							  table->family,
8840 							  flowtable, NULL) < 0)
8841 				goto done;
8842 
8843 			nl_dump_check_consistent(cb, nlmsg_hdr(skb));
8844 cont:
8845 			idx++;
8846 		}
8847 	}
8848 done:
8849 	rcu_read_unlock();
8850 
8851 	cb->args[0] = idx;
8852 	return skb->len;
8853 }
8854 
nf_tables_dump_flowtable_start(struct netlink_callback * cb)8855 static int nf_tables_dump_flowtable_start(struct netlink_callback *cb)
8856 {
8857 	const struct nlattr * const *nla = cb->data;
8858 	struct nft_flowtable_filter *filter = NULL;
8859 
8860 	if (nla[NFTA_FLOWTABLE_TABLE]) {
8861 		filter = kzalloc(sizeof(*filter), GFP_ATOMIC);
8862 		if (!filter)
8863 			return -ENOMEM;
8864 
8865 		filter->table = nla_strdup(nla[NFTA_FLOWTABLE_TABLE],
8866 					   GFP_ATOMIC);
8867 		if (!filter->table) {
8868 			kfree(filter);
8869 			return -ENOMEM;
8870 		}
8871 	}
8872 
8873 	cb->data = filter;
8874 	return 0;
8875 }
8876 
nf_tables_dump_flowtable_done(struct netlink_callback * cb)8877 static int nf_tables_dump_flowtable_done(struct netlink_callback *cb)
8878 {
8879 	struct nft_flowtable_filter *filter = cb->data;
8880 
8881 	if (!filter)
8882 		return 0;
8883 
8884 	kfree(filter->table);
8885 	kfree(filter);
8886 
8887 	return 0;
8888 }
8889 
8890 /* called with rcu_read_lock held */
nf_tables_getflowtable(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])8891 static int nf_tables_getflowtable(struct sk_buff *skb,
8892 				  const struct nfnl_info *info,
8893 				  const struct nlattr * const nla[])
8894 {
8895 	u8 genmask = nft_genmask_cur(info->net);
8896 	u8 family = info->nfmsg->nfgen_family;
8897 	struct nft_flowtable *flowtable;
8898 	const struct nft_table *table;
8899 	struct net *net = info->net;
8900 	struct sk_buff *skb2;
8901 	int err;
8902 
8903 	if (info->nlh->nlmsg_flags & NLM_F_DUMP) {
8904 		struct netlink_dump_control c = {
8905 			.start = nf_tables_dump_flowtable_start,
8906 			.dump = nf_tables_dump_flowtable,
8907 			.done = nf_tables_dump_flowtable_done,
8908 			.module = THIS_MODULE,
8909 			.data = (void *)nla,
8910 		};
8911 
8912 		return nft_netlink_dump_start_rcu(info->sk, skb, info->nlh, &c);
8913 	}
8914 
8915 	if (!nla[NFTA_FLOWTABLE_NAME])
8916 		return -EINVAL;
8917 
8918 	table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
8919 				 genmask, 0);
8920 	if (IS_ERR(table))
8921 		return PTR_ERR(table);
8922 
8923 	flowtable = nft_flowtable_lookup(table, nla[NFTA_FLOWTABLE_NAME],
8924 					 genmask);
8925 	if (IS_ERR(flowtable))
8926 		return PTR_ERR(flowtable);
8927 
8928 	skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
8929 	if (!skb2)
8930 		return -ENOMEM;
8931 
8932 	err = nf_tables_fill_flowtable_info(skb2, net, NETLINK_CB(skb).portid,
8933 					    info->nlh->nlmsg_seq,
8934 					    NFT_MSG_NEWFLOWTABLE, 0, family,
8935 					    flowtable, NULL);
8936 	if (err < 0)
8937 		goto err_fill_flowtable_info;
8938 
8939 	return nfnetlink_unicast(skb2, net, NETLINK_CB(skb).portid);
8940 
8941 err_fill_flowtable_info:
8942 	kfree_skb(skb2);
8943 	return err;
8944 }
8945 
nf_tables_flowtable_notify(struct nft_ctx * ctx,struct nft_flowtable * flowtable,struct list_head * hook_list,int event)8946 static void nf_tables_flowtable_notify(struct nft_ctx *ctx,
8947 				       struct nft_flowtable *flowtable,
8948 				       struct list_head *hook_list, int event)
8949 {
8950 	struct nftables_pernet *nft_net = nft_pernet(ctx->net);
8951 	struct sk_buff *skb;
8952 	u16 flags = 0;
8953 	int err;
8954 
8955 	if (!ctx->report &&
8956 	    !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
8957 		return;
8958 
8959 	skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
8960 	if (skb == NULL)
8961 		goto err;
8962 
8963 	if (ctx->flags & (NLM_F_CREATE | NLM_F_EXCL))
8964 		flags |= ctx->flags & (NLM_F_CREATE | NLM_F_EXCL);
8965 
8966 	err = nf_tables_fill_flowtable_info(skb, ctx->net, ctx->portid,
8967 					    ctx->seq, event, flags,
8968 					    ctx->family, flowtable, hook_list);
8969 	if (err < 0) {
8970 		kfree_skb(skb);
8971 		goto err;
8972 	}
8973 
8974 	nft_notify_enqueue(skb, ctx->report, &nft_net->notify_list);
8975 	return;
8976 err:
8977 	nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
8978 }
8979 
nf_tables_flowtable_destroy(struct nft_flowtable * flowtable)8980 static void nf_tables_flowtable_destroy(struct nft_flowtable *flowtable)
8981 {
8982 	struct nft_hook *hook, *next;
8983 
8984 	flowtable->data.type->free(&flowtable->data);
8985 	list_for_each_entry_safe(hook, next, &flowtable->hook_list, list) {
8986 		flowtable->data.type->setup(&flowtable->data, hook->ops.dev,
8987 					    FLOW_BLOCK_UNBIND);
8988 		list_del_rcu(&hook->list);
8989 		kfree_rcu(hook, rcu);
8990 	}
8991 	kfree(flowtable->name);
8992 	module_put(flowtable->data.type->owner);
8993 	kfree(flowtable);
8994 }
8995 
nf_tables_fill_gen_info(struct sk_buff * skb,struct net * net,u32 portid,u32 seq)8996 static int nf_tables_fill_gen_info(struct sk_buff *skb, struct net *net,
8997 				   u32 portid, u32 seq)
8998 {
8999 	struct nftables_pernet *nft_net = nft_pernet(net);
9000 	struct nlmsghdr *nlh;
9001 	char buf[TASK_COMM_LEN];
9002 	int event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, NFT_MSG_NEWGEN);
9003 
9004 	nlh = nfnl_msg_put(skb, portid, seq, event, 0, AF_UNSPEC,
9005 			   NFNETLINK_V0, nft_base_seq(net));
9006 	if (!nlh)
9007 		goto nla_put_failure;
9008 
9009 	if (nla_put_be32(skb, NFTA_GEN_ID, htonl(nft_net->base_seq)) ||
9010 	    nla_put_be32(skb, NFTA_GEN_PROC_PID, htonl(task_pid_nr(current))) ||
9011 	    nla_put_string(skb, NFTA_GEN_PROC_NAME, get_task_comm(buf, current)))
9012 		goto nla_put_failure;
9013 
9014 	nlmsg_end(skb, nlh);
9015 	return 0;
9016 
9017 nla_put_failure:
9018 	nlmsg_trim(skb, nlh);
9019 	return -EMSGSIZE;
9020 }
9021 
nft_flowtable_event(unsigned long event,struct net_device * dev,struct nft_flowtable * flowtable)9022 static void nft_flowtable_event(unsigned long event, struct net_device *dev,
9023 				struct nft_flowtable *flowtable)
9024 {
9025 	struct nft_hook *hook;
9026 
9027 	list_for_each_entry(hook, &flowtable->hook_list, list) {
9028 		if (hook->ops.dev != dev)
9029 			continue;
9030 
9031 		/* flow_offload_netdev_event() cleans up entries for us. */
9032 		nft_unregister_flowtable_hook(dev_net(dev), flowtable, hook);
9033 		list_del_rcu(&hook->list);
9034 		kfree_rcu(hook, rcu);
9035 		break;
9036 	}
9037 }
9038 
nf_tables_flowtable_event(struct notifier_block * this,unsigned long event,void * ptr)9039 static int nf_tables_flowtable_event(struct notifier_block *this,
9040 				     unsigned long event, void *ptr)
9041 {
9042 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
9043 	struct nft_flowtable *flowtable;
9044 	struct nftables_pernet *nft_net;
9045 	struct nft_table *table;
9046 	struct net *net;
9047 
9048 	if (event != NETDEV_UNREGISTER)
9049 		return 0;
9050 
9051 	net = dev_net(dev);
9052 	nft_net = nft_pernet(net);
9053 	mutex_lock(&nft_net->commit_mutex);
9054 	list_for_each_entry(table, &nft_net->tables, list) {
9055 		list_for_each_entry(flowtable, &table->flowtables, list) {
9056 			nft_flowtable_event(event, dev, flowtable);
9057 		}
9058 	}
9059 	mutex_unlock(&nft_net->commit_mutex);
9060 
9061 	return NOTIFY_DONE;
9062 }
9063 
9064 static struct notifier_block nf_tables_flowtable_notifier = {
9065 	.notifier_call	= nf_tables_flowtable_event,
9066 };
9067 
nf_tables_gen_notify(struct net * net,struct sk_buff * skb,int event)9068 static void nf_tables_gen_notify(struct net *net, struct sk_buff *skb,
9069 				 int event)
9070 {
9071 	struct nlmsghdr *nlh = nlmsg_hdr(skb);
9072 	struct sk_buff *skb2;
9073 	int err;
9074 
9075 	if (!nlmsg_report(nlh) &&
9076 	    !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
9077 		return;
9078 
9079 	skb2 = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
9080 	if (skb2 == NULL)
9081 		goto err;
9082 
9083 	err = nf_tables_fill_gen_info(skb2, net, NETLINK_CB(skb).portid,
9084 				      nlh->nlmsg_seq);
9085 	if (err < 0) {
9086 		kfree_skb(skb2);
9087 		goto err;
9088 	}
9089 
9090 	nfnetlink_send(skb2, net, NETLINK_CB(skb).portid, NFNLGRP_NFTABLES,
9091 		       nlmsg_report(nlh), GFP_KERNEL);
9092 	return;
9093 err:
9094 	nfnetlink_set_err(net, NETLINK_CB(skb).portid, NFNLGRP_NFTABLES,
9095 			  -ENOBUFS);
9096 }
9097 
nf_tables_getgen(struct sk_buff * skb,const struct nfnl_info * info,const struct nlattr * const nla[])9098 static int nf_tables_getgen(struct sk_buff *skb, const struct nfnl_info *info,
9099 			    const struct nlattr * const nla[])
9100 {
9101 	struct sk_buff *skb2;
9102 	int err;
9103 
9104 	skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
9105 	if (skb2 == NULL)
9106 		return -ENOMEM;
9107 
9108 	err = nf_tables_fill_gen_info(skb2, info->net, NETLINK_CB(skb).portid,
9109 				      info->nlh->nlmsg_seq);
9110 	if (err < 0)
9111 		goto err_fill_gen_info;
9112 
9113 	return nfnetlink_unicast(skb2, info->net, NETLINK_CB(skb).portid);
9114 
9115 err_fill_gen_info:
9116 	kfree_skb(skb2);
9117 	return err;
9118 }
9119 
9120 static const struct nfnl_callback nf_tables_cb[NFT_MSG_MAX] = {
9121 	[NFT_MSG_NEWTABLE] = {
9122 		.call		= nf_tables_newtable,
9123 		.type		= NFNL_CB_BATCH,
9124 		.attr_count	= NFTA_TABLE_MAX,
9125 		.policy		= nft_table_policy,
9126 	},
9127 	[NFT_MSG_GETTABLE] = {
9128 		.call		= nf_tables_gettable,
9129 		.type		= NFNL_CB_RCU,
9130 		.attr_count	= NFTA_TABLE_MAX,
9131 		.policy		= nft_table_policy,
9132 	},
9133 	[NFT_MSG_DELTABLE] = {
9134 		.call		= nf_tables_deltable,
9135 		.type		= NFNL_CB_BATCH,
9136 		.attr_count	= NFTA_TABLE_MAX,
9137 		.policy		= nft_table_policy,
9138 	},
9139 	[NFT_MSG_DESTROYTABLE] = {
9140 		.call		= nf_tables_deltable,
9141 		.type		= NFNL_CB_BATCH,
9142 		.attr_count	= NFTA_TABLE_MAX,
9143 		.policy		= nft_table_policy,
9144 	},
9145 	[NFT_MSG_NEWCHAIN] = {
9146 		.call		= nf_tables_newchain,
9147 		.type		= NFNL_CB_BATCH,
9148 		.attr_count	= NFTA_CHAIN_MAX,
9149 		.policy		= nft_chain_policy,
9150 	},
9151 	[NFT_MSG_GETCHAIN] = {
9152 		.call		= nf_tables_getchain,
9153 		.type		= NFNL_CB_RCU,
9154 		.attr_count	= NFTA_CHAIN_MAX,
9155 		.policy		= nft_chain_policy,
9156 	},
9157 	[NFT_MSG_DELCHAIN] = {
9158 		.call		= nf_tables_delchain,
9159 		.type		= NFNL_CB_BATCH,
9160 		.attr_count	= NFTA_CHAIN_MAX,
9161 		.policy		= nft_chain_policy,
9162 	},
9163 	[NFT_MSG_DESTROYCHAIN] = {
9164 		.call		= nf_tables_delchain,
9165 		.type		= NFNL_CB_BATCH,
9166 		.attr_count	= NFTA_CHAIN_MAX,
9167 		.policy		= nft_chain_policy,
9168 	},
9169 	[NFT_MSG_NEWRULE] = {
9170 		.call		= nf_tables_newrule,
9171 		.type		= NFNL_CB_BATCH,
9172 		.attr_count	= NFTA_RULE_MAX,
9173 		.policy		= nft_rule_policy,
9174 	},
9175 	[NFT_MSG_GETRULE] = {
9176 		.call		= nf_tables_getrule,
9177 		.type		= NFNL_CB_RCU,
9178 		.attr_count	= NFTA_RULE_MAX,
9179 		.policy		= nft_rule_policy,
9180 	},
9181 	[NFT_MSG_GETRULE_RESET] = {
9182 		.call		= nf_tables_getrule,
9183 		.type		= NFNL_CB_RCU,
9184 		.attr_count	= NFTA_RULE_MAX,
9185 		.policy		= nft_rule_policy,
9186 	},
9187 	[NFT_MSG_DELRULE] = {
9188 		.call		= nf_tables_delrule,
9189 		.type		= NFNL_CB_BATCH,
9190 		.attr_count	= NFTA_RULE_MAX,
9191 		.policy		= nft_rule_policy,
9192 	},
9193 	[NFT_MSG_DESTROYRULE] = {
9194 		.call		= nf_tables_delrule,
9195 		.type		= NFNL_CB_BATCH,
9196 		.attr_count	= NFTA_RULE_MAX,
9197 		.policy		= nft_rule_policy,
9198 	},
9199 	[NFT_MSG_NEWSET] = {
9200 		.call		= nf_tables_newset,
9201 		.type		= NFNL_CB_BATCH,
9202 		.attr_count	= NFTA_SET_MAX,
9203 		.policy		= nft_set_policy,
9204 	},
9205 	[NFT_MSG_GETSET] = {
9206 		.call		= nf_tables_getset,
9207 		.type		= NFNL_CB_RCU,
9208 		.attr_count	= NFTA_SET_MAX,
9209 		.policy		= nft_set_policy,
9210 	},
9211 	[NFT_MSG_DELSET] = {
9212 		.call		= nf_tables_delset,
9213 		.type		= NFNL_CB_BATCH,
9214 		.attr_count	= NFTA_SET_MAX,
9215 		.policy		= nft_set_policy,
9216 	},
9217 	[NFT_MSG_DESTROYSET] = {
9218 		.call		= nf_tables_delset,
9219 		.type		= NFNL_CB_BATCH,
9220 		.attr_count	= NFTA_SET_MAX,
9221 		.policy		= nft_set_policy,
9222 	},
9223 	[NFT_MSG_NEWSETELEM] = {
9224 		.call		= nf_tables_newsetelem,
9225 		.type		= NFNL_CB_BATCH,
9226 		.attr_count	= NFTA_SET_ELEM_LIST_MAX,
9227 		.policy		= nft_set_elem_list_policy,
9228 	},
9229 	[NFT_MSG_GETSETELEM] = {
9230 		.call		= nf_tables_getsetelem,
9231 		.type		= NFNL_CB_RCU,
9232 		.attr_count	= NFTA_SET_ELEM_LIST_MAX,
9233 		.policy		= nft_set_elem_list_policy,
9234 	},
9235 	[NFT_MSG_GETSETELEM_RESET] = {
9236 		.call		= nf_tables_getsetelem,
9237 		.type		= NFNL_CB_RCU,
9238 		.attr_count	= NFTA_SET_ELEM_LIST_MAX,
9239 		.policy		= nft_set_elem_list_policy,
9240 	},
9241 	[NFT_MSG_DELSETELEM] = {
9242 		.call		= nf_tables_delsetelem,
9243 		.type		= NFNL_CB_BATCH,
9244 		.attr_count	= NFTA_SET_ELEM_LIST_MAX,
9245 		.policy		= nft_set_elem_list_policy,
9246 	},
9247 	[NFT_MSG_DESTROYSETELEM] = {
9248 		.call		= nf_tables_delsetelem,
9249 		.type		= NFNL_CB_BATCH,
9250 		.attr_count	= NFTA_SET_ELEM_LIST_MAX,
9251 		.policy		= nft_set_elem_list_policy,
9252 	},
9253 	[NFT_MSG_GETGEN] = {
9254 		.call		= nf_tables_getgen,
9255 		.type		= NFNL_CB_RCU,
9256 	},
9257 	[NFT_MSG_NEWOBJ] = {
9258 		.call		= nf_tables_newobj,
9259 		.type		= NFNL_CB_BATCH,
9260 		.attr_count	= NFTA_OBJ_MAX,
9261 		.policy		= nft_obj_policy,
9262 	},
9263 	[NFT_MSG_GETOBJ] = {
9264 		.call		= nf_tables_getobj,
9265 		.type		= NFNL_CB_RCU,
9266 		.attr_count	= NFTA_OBJ_MAX,
9267 		.policy		= nft_obj_policy,
9268 	},
9269 	[NFT_MSG_DELOBJ] = {
9270 		.call		= nf_tables_delobj,
9271 		.type		= NFNL_CB_BATCH,
9272 		.attr_count	= NFTA_OBJ_MAX,
9273 		.policy		= nft_obj_policy,
9274 	},
9275 	[NFT_MSG_DESTROYOBJ] = {
9276 		.call		= nf_tables_delobj,
9277 		.type		= NFNL_CB_BATCH,
9278 		.attr_count	= NFTA_OBJ_MAX,
9279 		.policy		= nft_obj_policy,
9280 	},
9281 	[NFT_MSG_GETOBJ_RESET] = {
9282 		.call		= nf_tables_getobj_reset,
9283 		.type		= NFNL_CB_RCU,
9284 		.attr_count	= NFTA_OBJ_MAX,
9285 		.policy		= nft_obj_policy,
9286 	},
9287 	[NFT_MSG_NEWFLOWTABLE] = {
9288 		.call		= nf_tables_newflowtable,
9289 		.type		= NFNL_CB_BATCH,
9290 		.attr_count	= NFTA_FLOWTABLE_MAX,
9291 		.policy		= nft_flowtable_policy,
9292 	},
9293 	[NFT_MSG_GETFLOWTABLE] = {
9294 		.call		= nf_tables_getflowtable,
9295 		.type		= NFNL_CB_RCU,
9296 		.attr_count	= NFTA_FLOWTABLE_MAX,
9297 		.policy		= nft_flowtable_policy,
9298 	},
9299 	[NFT_MSG_DELFLOWTABLE] = {
9300 		.call		= nf_tables_delflowtable,
9301 		.type		= NFNL_CB_BATCH,
9302 		.attr_count	= NFTA_FLOWTABLE_MAX,
9303 		.policy		= nft_flowtable_policy,
9304 	},
9305 	[NFT_MSG_DESTROYFLOWTABLE] = {
9306 		.call		= nf_tables_delflowtable,
9307 		.type		= NFNL_CB_BATCH,
9308 		.attr_count	= NFTA_FLOWTABLE_MAX,
9309 		.policy		= nft_flowtable_policy,
9310 	},
9311 };
9312 
nf_tables_validate(struct net * net)9313 static int nf_tables_validate(struct net *net)
9314 {
9315 	struct nftables_pernet *nft_net = nft_pernet(net);
9316 	struct nft_table *table;
9317 
9318 	list_for_each_entry(table, &nft_net->tables, list) {
9319 		switch (table->validate_state) {
9320 		case NFT_VALIDATE_SKIP:
9321 			continue;
9322 		case NFT_VALIDATE_NEED:
9323 			nft_validate_state_update(table, NFT_VALIDATE_DO);
9324 			fallthrough;
9325 		case NFT_VALIDATE_DO:
9326 			if (nft_table_validate(net, table) < 0)
9327 				return -EAGAIN;
9328 
9329 			nft_validate_state_update(table, NFT_VALIDATE_SKIP);
9330 			break;
9331 		}
9332 	}
9333 
9334 	return 0;
9335 }
9336 
9337 /* a drop policy has to be deferred until all rules have been activated,
9338  * otherwise a large ruleset that contains a drop-policy base chain will
9339  * cause all packets to get dropped until the full transaction has been
9340  * processed.
9341  *
9342  * We defer the drop policy until the transaction has been finalized.
9343  */
nft_chain_commit_drop_policy(struct nft_trans * trans)9344 static void nft_chain_commit_drop_policy(struct nft_trans *trans)
9345 {
9346 	struct nft_base_chain *basechain;
9347 
9348 	if (nft_trans_chain_policy(trans) != NF_DROP)
9349 		return;
9350 
9351 	if (!nft_is_base_chain(trans->ctx.chain))
9352 		return;
9353 
9354 	basechain = nft_base_chain(trans->ctx.chain);
9355 	basechain->policy = NF_DROP;
9356 }
9357 
nft_chain_commit_update(struct nft_trans * trans)9358 static void nft_chain_commit_update(struct nft_trans *trans)
9359 {
9360 	struct nft_base_chain *basechain;
9361 
9362 	if (nft_trans_chain_name(trans)) {
9363 		rhltable_remove(&trans->ctx.table->chains_ht,
9364 				&trans->ctx.chain->rhlhead,
9365 				nft_chain_ht_params);
9366 		swap(trans->ctx.chain->name, nft_trans_chain_name(trans));
9367 		rhltable_insert_key(&trans->ctx.table->chains_ht,
9368 				    trans->ctx.chain->name,
9369 				    &trans->ctx.chain->rhlhead,
9370 				    nft_chain_ht_params);
9371 	}
9372 
9373 	if (!nft_is_base_chain(trans->ctx.chain))
9374 		return;
9375 
9376 	nft_chain_stats_replace(trans);
9377 
9378 	basechain = nft_base_chain(trans->ctx.chain);
9379 
9380 	switch (nft_trans_chain_policy(trans)) {
9381 	case NF_DROP:
9382 	case NF_ACCEPT:
9383 		basechain->policy = nft_trans_chain_policy(trans);
9384 		break;
9385 	}
9386 }
9387 
nft_obj_commit_update(struct nft_trans * trans)9388 static void nft_obj_commit_update(struct nft_trans *trans)
9389 {
9390 	struct nft_object *newobj;
9391 	struct nft_object *obj;
9392 
9393 	obj = nft_trans_obj(trans);
9394 	newobj = nft_trans_obj_newobj(trans);
9395 
9396 	if (obj->ops->update)
9397 		obj->ops->update(obj, newobj);
9398 
9399 	nft_obj_destroy(&trans->ctx, newobj);
9400 }
9401 
nft_commit_release(struct nft_trans * trans)9402 static void nft_commit_release(struct nft_trans *trans)
9403 {
9404 	switch (trans->msg_type) {
9405 	case NFT_MSG_DELTABLE:
9406 	case NFT_MSG_DESTROYTABLE:
9407 		nf_tables_table_destroy(&trans->ctx);
9408 		break;
9409 	case NFT_MSG_NEWCHAIN:
9410 		free_percpu(nft_trans_chain_stats(trans));
9411 		kfree(nft_trans_chain_name(trans));
9412 		break;
9413 	case NFT_MSG_DELCHAIN:
9414 	case NFT_MSG_DESTROYCHAIN:
9415 		if (nft_trans_chain_update(trans))
9416 			nft_hooks_destroy(&nft_trans_chain_hooks(trans));
9417 		else
9418 			nf_tables_chain_destroy(&trans->ctx);
9419 		break;
9420 	case NFT_MSG_DELRULE:
9421 	case NFT_MSG_DESTROYRULE:
9422 		nf_tables_rule_destroy(&trans->ctx, nft_trans_rule(trans));
9423 		break;
9424 	case NFT_MSG_DELSET:
9425 	case NFT_MSG_DESTROYSET:
9426 		nft_set_destroy(&trans->ctx, nft_trans_set(trans));
9427 		break;
9428 	case NFT_MSG_DELSETELEM:
9429 	case NFT_MSG_DESTROYSETELEM:
9430 		nf_tables_set_elem_destroy(&trans->ctx,
9431 					   nft_trans_elem_set(trans),
9432 					   nft_trans_elem(trans).priv);
9433 		break;
9434 	case NFT_MSG_DELOBJ:
9435 	case NFT_MSG_DESTROYOBJ:
9436 		nft_obj_destroy(&trans->ctx, nft_trans_obj(trans));
9437 		break;
9438 	case NFT_MSG_DELFLOWTABLE:
9439 	case NFT_MSG_DESTROYFLOWTABLE:
9440 		if (nft_trans_flowtable_update(trans))
9441 			nft_hooks_destroy(&nft_trans_flowtable_hooks(trans));
9442 		else
9443 			nf_tables_flowtable_destroy(nft_trans_flowtable(trans));
9444 		break;
9445 	}
9446 
9447 	if (trans->put_net)
9448 		put_net(trans->ctx.net);
9449 
9450 	kfree(trans);
9451 }
9452 
nf_tables_trans_destroy_work(struct work_struct * w)9453 static void nf_tables_trans_destroy_work(struct work_struct *w)
9454 {
9455 	struct nft_trans *trans, *next;
9456 	LIST_HEAD(head);
9457 
9458 	spin_lock(&nf_tables_destroy_list_lock);
9459 	list_splice_init(&nf_tables_destroy_list, &head);
9460 	spin_unlock(&nf_tables_destroy_list_lock);
9461 
9462 	if (list_empty(&head))
9463 		return;
9464 
9465 	synchronize_rcu();
9466 
9467 	list_for_each_entry_safe(trans, next, &head, list) {
9468 		nft_trans_list_del(trans);
9469 		nft_commit_release(trans);
9470 	}
9471 }
9472 
nf_tables_trans_destroy_flush_work(void)9473 void nf_tables_trans_destroy_flush_work(void)
9474 {
9475 	flush_work(&trans_destroy_work);
9476 }
9477 EXPORT_SYMBOL_GPL(nf_tables_trans_destroy_flush_work);
9478 
nft_expr_reduce(struct nft_regs_track * track,const struct nft_expr * expr)9479 static bool nft_expr_reduce(struct nft_regs_track *track,
9480 			    const struct nft_expr *expr)
9481 {
9482 	return false;
9483 }
9484 
nf_tables_commit_chain_prepare(struct net * net,struct nft_chain * chain)9485 static int nf_tables_commit_chain_prepare(struct net *net, struct nft_chain *chain)
9486 {
9487 	const struct nft_expr *expr, *last;
9488 	struct nft_regs_track track = {};
9489 	unsigned int size, data_size;
9490 	void *data, *data_boundary;
9491 	struct nft_rule_dp *prule;
9492 	struct nft_rule *rule;
9493 
9494 	/* already handled or inactive chain? */
9495 	if (chain->blob_next || !nft_is_active_next(net, chain))
9496 		return 0;
9497 
9498 	data_size = 0;
9499 	list_for_each_entry(rule, &chain->rules, list) {
9500 		if (nft_is_active_next(net, rule)) {
9501 			data_size += sizeof(*prule) + rule->dlen;
9502 			if (data_size > INT_MAX)
9503 				return -ENOMEM;
9504 		}
9505 	}
9506 
9507 	chain->blob_next = nf_tables_chain_alloc_rules(chain, data_size);
9508 	if (!chain->blob_next)
9509 		return -ENOMEM;
9510 
9511 	data = (void *)chain->blob_next->data;
9512 	data_boundary = data + data_size;
9513 	size = 0;
9514 
9515 	list_for_each_entry(rule, &chain->rules, list) {
9516 		if (!nft_is_active_next(net, rule))
9517 			continue;
9518 
9519 		prule = (struct nft_rule_dp *)data;
9520 		data += offsetof(struct nft_rule_dp, data);
9521 		if (WARN_ON_ONCE(data > data_boundary))
9522 			return -ENOMEM;
9523 
9524 		size = 0;
9525 		track.last = nft_expr_last(rule);
9526 		nft_rule_for_each_expr(expr, last, rule) {
9527 			track.cur = expr;
9528 
9529 			if (nft_expr_reduce(&track, expr)) {
9530 				expr = track.cur;
9531 				continue;
9532 			}
9533 
9534 			if (WARN_ON_ONCE(data + size + expr->ops->size > data_boundary))
9535 				return -ENOMEM;
9536 
9537 			memcpy(data + size, expr, expr->ops->size);
9538 			size += expr->ops->size;
9539 		}
9540 		if (WARN_ON_ONCE(size >= 1 << 12))
9541 			return -ENOMEM;
9542 
9543 		prule->handle = rule->handle;
9544 		prule->dlen = size;
9545 		prule->is_last = 0;
9546 
9547 		data += size;
9548 		size = 0;
9549 		chain->blob_next->size += (unsigned long)(data - (void *)prule);
9550 	}
9551 
9552 	if (WARN_ON_ONCE(data > data_boundary))
9553 		return -ENOMEM;
9554 
9555 	prule = (struct nft_rule_dp *)data;
9556 	nft_last_rule(chain, prule);
9557 
9558 	return 0;
9559 }
9560 
nf_tables_commit_chain_prepare_cancel(struct net * net)9561 static void nf_tables_commit_chain_prepare_cancel(struct net *net)
9562 {
9563 	struct nftables_pernet *nft_net = nft_pernet(net);
9564 	struct nft_trans *trans, *next;
9565 
9566 	list_for_each_entry_safe(trans, next, &nft_net->commit_list, list) {
9567 		struct nft_chain *chain = trans->ctx.chain;
9568 
9569 		if (trans->msg_type == NFT_MSG_NEWRULE ||
9570 		    trans->msg_type == NFT_MSG_DELRULE) {
9571 			kvfree(chain->blob_next);
9572 			chain->blob_next = NULL;
9573 		}
9574 	}
9575 }
9576 
__nf_tables_commit_chain_free_rules(struct rcu_head * h)9577 static void __nf_tables_commit_chain_free_rules(struct rcu_head *h)
9578 {
9579 	struct nft_rule_dp_last *l = container_of(h, struct nft_rule_dp_last, h);
9580 
9581 	kvfree(l->blob);
9582 }
9583 
nf_tables_commit_chain_free_rules_old(struct nft_rule_blob * blob)9584 static void nf_tables_commit_chain_free_rules_old(struct nft_rule_blob *blob)
9585 {
9586 	struct nft_rule_dp_last *last;
9587 
9588 	/* last rule trailer is after end marker */
9589 	last = (void *)blob + sizeof(*blob) + blob->size;
9590 	last->blob = blob;
9591 
9592 	call_rcu(&last->h, __nf_tables_commit_chain_free_rules);
9593 }
9594 
nf_tables_commit_chain(struct net * net,struct nft_chain * chain)9595 static void nf_tables_commit_chain(struct net *net, struct nft_chain *chain)
9596 {
9597 	struct nft_rule_blob *g0, *g1;
9598 	bool next_genbit;
9599 
9600 	next_genbit = nft_gencursor_next(net);
9601 
9602 	g0 = rcu_dereference_protected(chain->blob_gen_0,
9603 				       lockdep_commit_lock_is_held(net));
9604 	g1 = rcu_dereference_protected(chain->blob_gen_1,
9605 				       lockdep_commit_lock_is_held(net));
9606 
9607 	/* No changes to this chain? */
9608 	if (chain->blob_next == NULL) {
9609 		/* chain had no change in last or next generation */
9610 		if (g0 == g1)
9611 			return;
9612 		/*
9613 		 * chain had no change in this generation; make sure next
9614 		 * one uses same rules as current generation.
9615 		 */
9616 		if (next_genbit) {
9617 			rcu_assign_pointer(chain->blob_gen_1, g0);
9618 			nf_tables_commit_chain_free_rules_old(g1);
9619 		} else {
9620 			rcu_assign_pointer(chain->blob_gen_0, g1);
9621 			nf_tables_commit_chain_free_rules_old(g0);
9622 		}
9623 
9624 		return;
9625 	}
9626 
9627 	if (next_genbit)
9628 		rcu_assign_pointer(chain->blob_gen_1, chain->blob_next);
9629 	else
9630 		rcu_assign_pointer(chain->blob_gen_0, chain->blob_next);
9631 
9632 	chain->blob_next = NULL;
9633 
9634 	if (g0 == g1)
9635 		return;
9636 
9637 	if (next_genbit)
9638 		nf_tables_commit_chain_free_rules_old(g1);
9639 	else
9640 		nf_tables_commit_chain_free_rules_old(g0);
9641 }
9642 
nft_obj_del(struct nft_object * obj)9643 static void nft_obj_del(struct nft_object *obj)
9644 {
9645 	rhltable_remove(&nft_objname_ht, &obj->rhlhead, nft_objname_ht_params);
9646 	list_del_rcu(&obj->list);
9647 }
9648 
nft_chain_del(struct nft_chain * chain)9649 void nft_chain_del(struct nft_chain *chain)
9650 {
9651 	struct nft_table *table = chain->table;
9652 
9653 	WARN_ON_ONCE(rhltable_remove(&table->chains_ht, &chain->rhlhead,
9654 				     nft_chain_ht_params));
9655 	list_del_rcu(&chain->list);
9656 }
9657 
nft_trans_gc_setelem_remove(struct nft_ctx * ctx,struct nft_trans_gc * trans)9658 static void nft_trans_gc_setelem_remove(struct nft_ctx *ctx,
9659 					struct nft_trans_gc *trans)
9660 {
9661 	void **priv = trans->priv;
9662 	unsigned int i;
9663 
9664 	for (i = 0; i < trans->count; i++) {
9665 		struct nft_set_elem elem = {
9666 			.priv = priv[i],
9667 		};
9668 
9669 		nft_setelem_data_deactivate(ctx->net, trans->set, &elem);
9670 		nft_setelem_remove(ctx->net, trans->set, &elem);
9671 	}
9672 }
9673 
nft_trans_gc_destroy(struct nft_trans_gc * trans)9674 void nft_trans_gc_destroy(struct nft_trans_gc *trans)
9675 {
9676 	nft_set_put(trans->set);
9677 	put_net(trans->net);
9678 	kfree(trans);
9679 }
9680 
nft_trans_gc_trans_free(struct rcu_head * rcu)9681 static void nft_trans_gc_trans_free(struct rcu_head *rcu)
9682 {
9683 	struct nft_set_elem elem = {};
9684 	struct nft_trans_gc *trans;
9685 	struct nft_ctx ctx = {};
9686 	unsigned int i;
9687 
9688 	trans = container_of(rcu, struct nft_trans_gc, rcu);
9689 	ctx.net	= read_pnet(&trans->set->net);
9690 
9691 	for (i = 0; i < trans->count; i++) {
9692 		elem.priv = trans->priv[i];
9693 		if (!nft_setelem_is_catchall(trans->set, &elem))
9694 			atomic_dec(&trans->set->nelems);
9695 
9696 		nf_tables_set_elem_destroy(&ctx, trans->set, elem.priv);
9697 	}
9698 
9699 	nft_trans_gc_destroy(trans);
9700 }
9701 
nft_trans_gc_work_done(struct nft_trans_gc * trans)9702 static bool nft_trans_gc_work_done(struct nft_trans_gc *trans)
9703 {
9704 	struct nftables_pernet *nft_net;
9705 	struct nft_ctx ctx = {};
9706 
9707 	nft_net = nft_pernet(trans->net);
9708 
9709 	mutex_lock(&nft_net->commit_mutex);
9710 
9711 	/* Check for race with transaction, otherwise this batch refers to
9712 	 * stale objects that might not be there anymore. Skip transaction if
9713 	 * set has been destroyed from control plane transaction in case gc
9714 	 * worker loses race.
9715 	 */
9716 	if (READ_ONCE(nft_net->gc_seq) != trans->seq || trans->set->dead) {
9717 		mutex_unlock(&nft_net->commit_mutex);
9718 		return false;
9719 	}
9720 
9721 	ctx.net = trans->net;
9722 	ctx.table = trans->set->table;
9723 
9724 	nft_trans_gc_setelem_remove(&ctx, trans);
9725 	mutex_unlock(&nft_net->commit_mutex);
9726 
9727 	return true;
9728 }
9729 
nft_trans_gc_work(struct work_struct * work)9730 static void nft_trans_gc_work(struct work_struct *work)
9731 {
9732 	struct nft_trans_gc *trans, *next;
9733 	LIST_HEAD(trans_gc_list);
9734 
9735 	spin_lock(&nf_tables_gc_list_lock);
9736 	list_splice_init(&nf_tables_gc_list, &trans_gc_list);
9737 	spin_unlock(&nf_tables_gc_list_lock);
9738 
9739 	list_for_each_entry_safe(trans, next, &trans_gc_list, list) {
9740 		list_del(&trans->list);
9741 		if (!nft_trans_gc_work_done(trans)) {
9742 			nft_trans_gc_destroy(trans);
9743 			continue;
9744 		}
9745 		call_rcu(&trans->rcu, nft_trans_gc_trans_free);
9746 	}
9747 }
9748 
nft_trans_gc_alloc(struct nft_set * set,unsigned int gc_seq,gfp_t gfp)9749 struct nft_trans_gc *nft_trans_gc_alloc(struct nft_set *set,
9750 					unsigned int gc_seq, gfp_t gfp)
9751 {
9752 	struct net *net = read_pnet(&set->net);
9753 	struct nft_trans_gc *trans;
9754 
9755 	trans = kzalloc(sizeof(*trans), gfp);
9756 	if (!trans)
9757 		return NULL;
9758 
9759 	trans->net = maybe_get_net(net);
9760 	if (!trans->net) {
9761 		kfree(trans);
9762 		return NULL;
9763 	}
9764 
9765 	refcount_inc(&set->refs);
9766 	trans->set = set;
9767 	trans->seq = gc_seq;
9768 
9769 	return trans;
9770 }
9771 
nft_trans_gc_elem_add(struct nft_trans_gc * trans,void * priv)9772 void nft_trans_gc_elem_add(struct nft_trans_gc *trans, void *priv)
9773 {
9774 	trans->priv[trans->count++] = priv;
9775 }
9776 
nft_trans_gc_queue_work(struct nft_trans_gc * trans)9777 static void nft_trans_gc_queue_work(struct nft_trans_gc *trans)
9778 {
9779 	spin_lock(&nf_tables_gc_list_lock);
9780 	list_add_tail(&trans->list, &nf_tables_gc_list);
9781 	spin_unlock(&nf_tables_gc_list_lock);
9782 
9783 	schedule_work(&trans_gc_work);
9784 }
9785 
nft_trans_gc_space(struct nft_trans_gc * trans)9786 static int nft_trans_gc_space(struct nft_trans_gc *trans)
9787 {
9788 	return NFT_TRANS_GC_BATCHCOUNT - trans->count;
9789 }
9790 
nft_trans_gc_queue_async(struct nft_trans_gc * gc,unsigned int gc_seq,gfp_t gfp)9791 struct nft_trans_gc *nft_trans_gc_queue_async(struct nft_trans_gc *gc,
9792 					      unsigned int gc_seq, gfp_t gfp)
9793 {
9794 	struct nft_set *set;
9795 
9796 	if (nft_trans_gc_space(gc))
9797 		return gc;
9798 
9799 	set = gc->set;
9800 	nft_trans_gc_queue_work(gc);
9801 
9802 	return nft_trans_gc_alloc(set, gc_seq, gfp);
9803 }
9804 
nft_trans_gc_queue_async_done(struct nft_trans_gc * trans)9805 void nft_trans_gc_queue_async_done(struct nft_trans_gc *trans)
9806 {
9807 	if (trans->count == 0) {
9808 		nft_trans_gc_destroy(trans);
9809 		return;
9810 	}
9811 
9812 	nft_trans_gc_queue_work(trans);
9813 }
9814 
nft_trans_gc_queue_sync(struct nft_trans_gc * gc,gfp_t gfp)9815 struct nft_trans_gc *nft_trans_gc_queue_sync(struct nft_trans_gc *gc, gfp_t gfp)
9816 {
9817 	struct nft_set *set;
9818 
9819 	if (WARN_ON_ONCE(!lockdep_commit_lock_is_held(gc->net)))
9820 		return NULL;
9821 
9822 	if (nft_trans_gc_space(gc))
9823 		return gc;
9824 
9825 	set = gc->set;
9826 	call_rcu(&gc->rcu, nft_trans_gc_trans_free);
9827 
9828 	return nft_trans_gc_alloc(set, 0, gfp);
9829 }
9830 
nft_trans_gc_queue_sync_done(struct nft_trans_gc * trans)9831 void nft_trans_gc_queue_sync_done(struct nft_trans_gc *trans)
9832 {
9833 	WARN_ON_ONCE(!lockdep_commit_lock_is_held(trans->net));
9834 
9835 	if (trans->count == 0) {
9836 		nft_trans_gc_destroy(trans);
9837 		return;
9838 	}
9839 
9840 	call_rcu(&trans->rcu, nft_trans_gc_trans_free);
9841 }
9842 
nft_trans_gc_catchall_async(struct nft_trans_gc * gc,unsigned int gc_seq)9843 struct nft_trans_gc *nft_trans_gc_catchall_async(struct nft_trans_gc *gc,
9844 						 unsigned int gc_seq)
9845 {
9846 	struct nft_set_elem_catchall *catchall;
9847 	const struct nft_set *set = gc->set;
9848 	struct nft_set_ext *ext;
9849 
9850 	list_for_each_entry_rcu(catchall, &set->catchall_list, list) {
9851 		ext = nft_set_elem_ext(set, catchall->elem);
9852 
9853 		if (!nft_set_elem_expired(ext))
9854 			continue;
9855 		if (nft_set_elem_is_dead(ext))
9856 			goto dead_elem;
9857 
9858 		nft_set_elem_dead(ext);
9859 dead_elem:
9860 		gc = nft_trans_gc_queue_async(gc, gc_seq, GFP_ATOMIC);
9861 		if (!gc)
9862 			return NULL;
9863 
9864 		nft_trans_gc_elem_add(gc, catchall->elem);
9865 	}
9866 
9867 	return gc;
9868 }
9869 
nft_trans_gc_catchall_sync(struct nft_trans_gc * gc)9870 struct nft_trans_gc *nft_trans_gc_catchall_sync(struct nft_trans_gc *gc)
9871 {
9872 	struct nft_set_elem_catchall *catchall, *next;
9873 	const struct nft_set *set = gc->set;
9874 	struct nft_set_elem elem;
9875 	struct nft_set_ext *ext;
9876 
9877 	WARN_ON_ONCE(!lockdep_commit_lock_is_held(gc->net));
9878 
9879 	list_for_each_entry_safe(catchall, next, &set->catchall_list, list) {
9880 		ext = nft_set_elem_ext(set, catchall->elem);
9881 
9882 		if (!nft_set_elem_expired(ext))
9883 			continue;
9884 
9885 		gc = nft_trans_gc_queue_sync(gc, GFP_KERNEL);
9886 		if (!gc)
9887 			return NULL;
9888 
9889 		memset(&elem, 0, sizeof(elem));
9890 		elem.priv = catchall->elem;
9891 
9892 		nft_setelem_data_deactivate(gc->net, gc->set, &elem);
9893 		nft_setelem_catchall_destroy(catchall);
9894 		nft_trans_gc_elem_add(gc, elem.priv);
9895 	}
9896 
9897 	return gc;
9898 }
9899 
nf_tables_module_autoload_cleanup(struct net * net)9900 static void nf_tables_module_autoload_cleanup(struct net *net)
9901 {
9902 	struct nftables_pernet *nft_net = nft_pernet(net);
9903 	struct nft_module_request *req, *next;
9904 
9905 	WARN_ON_ONCE(!list_empty(&nft_net->commit_list));
9906 	list_for_each_entry_safe(req, next, &nft_net->module_list, list) {
9907 		WARN_ON_ONCE(!req->done);
9908 		list_del(&req->list);
9909 		kfree(req);
9910 	}
9911 }
9912 
nf_tables_commit_release(struct net * net)9913 static void nf_tables_commit_release(struct net *net)
9914 {
9915 	struct nftables_pernet *nft_net = nft_pernet(net);
9916 	struct nft_trans *trans;
9917 
9918 	/* all side effects have to be made visible.
9919 	 * For example, if a chain named 'foo' has been deleted, a
9920 	 * new transaction must not find it anymore.
9921 	 *
9922 	 * Memory reclaim happens asynchronously from work queue
9923 	 * to prevent expensive synchronize_rcu() in commit phase.
9924 	 */
9925 	if (list_empty(&nft_net->commit_list)) {
9926 		nf_tables_module_autoload_cleanup(net);
9927 		mutex_unlock(&nft_net->commit_mutex);
9928 		return;
9929 	}
9930 
9931 	trans = list_last_entry(&nft_net->commit_list,
9932 				struct nft_trans, list);
9933 	get_net(trans->ctx.net);
9934 	WARN_ON_ONCE(trans->put_net);
9935 
9936 	trans->put_net = true;
9937 	spin_lock(&nf_tables_destroy_list_lock);
9938 	list_splice_tail_init(&nft_net->commit_list, &nf_tables_destroy_list);
9939 	spin_unlock(&nf_tables_destroy_list_lock);
9940 
9941 	nf_tables_module_autoload_cleanup(net);
9942 	schedule_work(&trans_destroy_work);
9943 
9944 	mutex_unlock(&nft_net->commit_mutex);
9945 }
9946 
nft_commit_notify(struct net * net,u32 portid)9947 static void nft_commit_notify(struct net *net, u32 portid)
9948 {
9949 	struct nftables_pernet *nft_net = nft_pernet(net);
9950 	struct sk_buff *batch_skb = NULL, *nskb, *skb;
9951 	unsigned char *data;
9952 	int len;
9953 
9954 	list_for_each_entry_safe(skb, nskb, &nft_net->notify_list, list) {
9955 		if (!batch_skb) {
9956 new_batch:
9957 			batch_skb = skb;
9958 			len = NLMSG_GOODSIZE - skb->len;
9959 			list_del(&skb->list);
9960 			continue;
9961 		}
9962 		len -= skb->len;
9963 		if (len > 0 && NFT_CB(skb).report == NFT_CB(batch_skb).report) {
9964 			data = skb_put(batch_skb, skb->len);
9965 			memcpy(data, skb->data, skb->len);
9966 			list_del(&skb->list);
9967 			kfree_skb(skb);
9968 			continue;
9969 		}
9970 		nfnetlink_send(batch_skb, net, portid, NFNLGRP_NFTABLES,
9971 			       NFT_CB(batch_skb).report, GFP_KERNEL);
9972 		goto new_batch;
9973 	}
9974 
9975 	if (batch_skb) {
9976 		nfnetlink_send(batch_skb, net, portid, NFNLGRP_NFTABLES,
9977 			       NFT_CB(batch_skb).report, GFP_KERNEL);
9978 	}
9979 
9980 	WARN_ON_ONCE(!list_empty(&nft_net->notify_list));
9981 }
9982 
nf_tables_commit_audit_alloc(struct list_head * adl,struct nft_table * table)9983 static int nf_tables_commit_audit_alloc(struct list_head *adl,
9984 					struct nft_table *table)
9985 {
9986 	struct nft_audit_data *adp;
9987 
9988 	list_for_each_entry(adp, adl, list) {
9989 		if (adp->table == table)
9990 			return 0;
9991 	}
9992 	adp = kzalloc(sizeof(*adp), GFP_KERNEL);
9993 	if (!adp)
9994 		return -ENOMEM;
9995 	adp->table = table;
9996 	list_add(&adp->list, adl);
9997 	return 0;
9998 }
9999 
nf_tables_commit_audit_free(struct list_head * adl)10000 static void nf_tables_commit_audit_free(struct list_head *adl)
10001 {
10002 	struct nft_audit_data *adp, *adn;
10003 
10004 	list_for_each_entry_safe(adp, adn, adl, list) {
10005 		list_del(&adp->list);
10006 		kfree(adp);
10007 	}
10008 }
10009 
nf_tables_commit_audit_collect(struct list_head * adl,struct nft_table * table,u32 op)10010 static void nf_tables_commit_audit_collect(struct list_head *adl,
10011 					   struct nft_table *table, u32 op)
10012 {
10013 	struct nft_audit_data *adp;
10014 
10015 	list_for_each_entry(adp, adl, list) {
10016 		if (adp->table == table)
10017 			goto found;
10018 	}
10019 	WARN_ONCE(1, "table=%s not expected in commit list", table->name);
10020 	return;
10021 found:
10022 	adp->entries++;
10023 	if (!adp->op || adp->op > op)
10024 		adp->op = op;
10025 }
10026 
10027 #define AUNFTABLENAMELEN (NFT_TABLE_MAXNAMELEN + 22)
10028 
nf_tables_commit_audit_log(struct list_head * adl,u32 generation)10029 static void nf_tables_commit_audit_log(struct list_head *adl, u32 generation)
10030 {
10031 	struct nft_audit_data *adp, *adn;
10032 	char aubuf[AUNFTABLENAMELEN];
10033 
10034 	list_for_each_entry_safe(adp, adn, adl, list) {
10035 		snprintf(aubuf, AUNFTABLENAMELEN, "%s:%u", adp->table->name,
10036 			 generation);
10037 		audit_log_nfcfg(aubuf, adp->table->family, adp->entries,
10038 				nft2audit_op[adp->op], GFP_KERNEL);
10039 		list_del(&adp->list);
10040 		kfree(adp);
10041 	}
10042 }
10043 
nft_set_commit_update(struct list_head * set_update_list)10044 static void nft_set_commit_update(struct list_head *set_update_list)
10045 {
10046 	struct nft_set *set, *next;
10047 
10048 	list_for_each_entry_safe(set, next, set_update_list, pending_update) {
10049 		list_del_init(&set->pending_update);
10050 
10051 		if (!set->ops->commit || set->dead)
10052 			continue;
10053 
10054 		set->ops->commit(set);
10055 	}
10056 }
10057 
nft_gc_seq_begin(struct nftables_pernet * nft_net)10058 static unsigned int nft_gc_seq_begin(struct nftables_pernet *nft_net)
10059 {
10060 	unsigned int gc_seq;
10061 
10062 	/* Bump gc counter, it becomes odd, this is the busy mark. */
10063 	gc_seq = READ_ONCE(nft_net->gc_seq);
10064 	WRITE_ONCE(nft_net->gc_seq, ++gc_seq);
10065 
10066 	return gc_seq;
10067 }
10068 
nft_gc_seq_end(struct nftables_pernet * nft_net,unsigned int gc_seq)10069 static void nft_gc_seq_end(struct nftables_pernet *nft_net, unsigned int gc_seq)
10070 {
10071 	WRITE_ONCE(nft_net->gc_seq, ++gc_seq);
10072 }
10073 
nf_tables_commit(struct net * net,struct sk_buff * skb)10074 static int nf_tables_commit(struct net *net, struct sk_buff *skb)
10075 {
10076 	struct nftables_pernet *nft_net = nft_pernet(net);
10077 	struct nft_trans *trans, *next;
10078 	unsigned int base_seq, gc_seq;
10079 	LIST_HEAD(set_update_list);
10080 	struct nft_trans_elem *te;
10081 	struct nft_chain *chain;
10082 	struct nft_table *table;
10083 	LIST_HEAD(adl);
10084 	int err;
10085 
10086 	if (list_empty(&nft_net->commit_list)) {
10087 		mutex_unlock(&nft_net->commit_mutex);
10088 		return 0;
10089 	}
10090 
10091 	list_for_each_entry(trans, &nft_net->binding_list, binding_list) {
10092 		switch (trans->msg_type) {
10093 		case NFT_MSG_NEWSET:
10094 			if (!nft_trans_set_update(trans) &&
10095 			    nft_set_is_anonymous(nft_trans_set(trans)) &&
10096 			    !nft_trans_set_bound(trans)) {
10097 				pr_warn_once("nftables ruleset with unbound set\n");
10098 				return -EINVAL;
10099 			}
10100 			break;
10101 		case NFT_MSG_NEWCHAIN:
10102 			if (!nft_trans_chain_update(trans) &&
10103 			    nft_chain_binding(nft_trans_chain(trans)) &&
10104 			    !nft_trans_chain_bound(trans)) {
10105 				pr_warn_once("nftables ruleset with unbound chain\n");
10106 				return -EINVAL;
10107 			}
10108 			break;
10109 		}
10110 	}
10111 
10112 	/* 0. Validate ruleset, otherwise roll back for error reporting. */
10113 	if (nf_tables_validate(net) < 0) {
10114 		nft_net->validate_state = NFT_VALIDATE_DO;
10115 		return -EAGAIN;
10116 	}
10117 
10118 	err = nft_flow_rule_offload_commit(net);
10119 	if (err < 0)
10120 		return err;
10121 
10122 	/* 1.  Allocate space for next generation rules_gen_X[] */
10123 	list_for_each_entry_safe(trans, next, &nft_net->commit_list, list) {
10124 		int ret;
10125 
10126 		ret = nf_tables_commit_audit_alloc(&adl, trans->ctx.table);
10127 		if (ret) {
10128 			nf_tables_commit_chain_prepare_cancel(net);
10129 			nf_tables_commit_audit_free(&adl);
10130 			return ret;
10131 		}
10132 		if (trans->msg_type == NFT_MSG_NEWRULE ||
10133 		    trans->msg_type == NFT_MSG_DELRULE) {
10134 			chain = trans->ctx.chain;
10135 
10136 			ret = nf_tables_commit_chain_prepare(net, chain);
10137 			if (ret < 0) {
10138 				nf_tables_commit_chain_prepare_cancel(net);
10139 				nf_tables_commit_audit_free(&adl);
10140 				return ret;
10141 			}
10142 		}
10143 	}
10144 
10145 	/* step 2.  Make rules_gen_X visible to packet path */
10146 	list_for_each_entry(table, &nft_net->tables, list) {
10147 		list_for_each_entry(chain, &table->chains, list)
10148 			nf_tables_commit_chain(net, chain);
10149 	}
10150 
10151 	/*
10152 	 * Bump generation counter, invalidate any dump in progress.
10153 	 * Cannot fail after this point.
10154 	 */
10155 	base_seq = READ_ONCE(nft_net->base_seq);
10156 	while (++base_seq == 0)
10157 		;
10158 
10159 	WRITE_ONCE(nft_net->base_seq, base_seq);
10160 
10161 	gc_seq = nft_gc_seq_begin(nft_net);
10162 
10163 	/* step 3. Start new generation, rules_gen_X now in use. */
10164 	net->nft.gencursor = nft_gencursor_next(net);
10165 
10166 	list_for_each_entry_safe(trans, next, &nft_net->commit_list, list) {
10167 		nf_tables_commit_audit_collect(&adl, trans->ctx.table,
10168 					       trans->msg_type);
10169 		switch (trans->msg_type) {
10170 		case NFT_MSG_NEWTABLE:
10171 			if (nft_trans_table_update(trans)) {
10172 				if (!(trans->ctx.table->flags & __NFT_TABLE_F_UPDATE)) {
10173 					nft_trans_destroy(trans);
10174 					break;
10175 				}
10176 				if (trans->ctx.table->flags & NFT_TABLE_F_DORMANT)
10177 					nf_tables_table_disable(net, trans->ctx.table);
10178 
10179 				trans->ctx.table->flags &= ~__NFT_TABLE_F_UPDATE;
10180 			} else {
10181 				nft_clear(net, trans->ctx.table);
10182 			}
10183 			nf_tables_table_notify(&trans->ctx, NFT_MSG_NEWTABLE);
10184 			nft_trans_destroy(trans);
10185 			break;
10186 		case NFT_MSG_DELTABLE:
10187 		case NFT_MSG_DESTROYTABLE:
10188 			list_del_rcu(&trans->ctx.table->list);
10189 			nf_tables_table_notify(&trans->ctx, trans->msg_type);
10190 			break;
10191 		case NFT_MSG_NEWCHAIN:
10192 			if (nft_trans_chain_update(trans)) {
10193 				nft_chain_commit_update(trans);
10194 				nf_tables_chain_notify(&trans->ctx, NFT_MSG_NEWCHAIN,
10195 						       &nft_trans_chain_hooks(trans));
10196 				list_splice(&nft_trans_chain_hooks(trans),
10197 					    &nft_trans_basechain(trans)->hook_list);
10198 				/* trans destroyed after rcu grace period */
10199 			} else {
10200 				nft_chain_commit_drop_policy(trans);
10201 				nft_clear(net, trans->ctx.chain);
10202 				nf_tables_chain_notify(&trans->ctx, NFT_MSG_NEWCHAIN, NULL);
10203 				nft_trans_destroy(trans);
10204 			}
10205 			break;
10206 		case NFT_MSG_DELCHAIN:
10207 		case NFT_MSG_DESTROYCHAIN:
10208 			if (nft_trans_chain_update(trans)) {
10209 				nf_tables_chain_notify(&trans->ctx, NFT_MSG_DELCHAIN,
10210 						       &nft_trans_chain_hooks(trans));
10211 				if (!(trans->ctx.table->flags & NFT_TABLE_F_DORMANT)) {
10212 					nft_netdev_unregister_hooks(net,
10213 								    &nft_trans_chain_hooks(trans),
10214 								    true);
10215 				}
10216 			} else {
10217 				nft_chain_del(trans->ctx.chain);
10218 				nf_tables_chain_notify(&trans->ctx, NFT_MSG_DELCHAIN,
10219 						       NULL);
10220 				nf_tables_unregister_hook(trans->ctx.net,
10221 							  trans->ctx.table,
10222 							  trans->ctx.chain);
10223 			}
10224 			break;
10225 		case NFT_MSG_NEWRULE:
10226 			nft_clear(trans->ctx.net, nft_trans_rule(trans));
10227 			nf_tables_rule_notify(&trans->ctx,
10228 					      nft_trans_rule(trans),
10229 					      NFT_MSG_NEWRULE);
10230 			if (trans->ctx.chain->flags & NFT_CHAIN_HW_OFFLOAD)
10231 				nft_flow_rule_destroy(nft_trans_flow_rule(trans));
10232 
10233 			nft_trans_destroy(trans);
10234 			break;
10235 		case NFT_MSG_DELRULE:
10236 		case NFT_MSG_DESTROYRULE:
10237 			list_del_rcu(&nft_trans_rule(trans)->list);
10238 			nf_tables_rule_notify(&trans->ctx,
10239 					      nft_trans_rule(trans),
10240 					      trans->msg_type);
10241 			nft_rule_expr_deactivate(&trans->ctx,
10242 						 nft_trans_rule(trans),
10243 						 NFT_TRANS_COMMIT);
10244 
10245 			if (trans->ctx.chain->flags & NFT_CHAIN_HW_OFFLOAD)
10246 				nft_flow_rule_destroy(nft_trans_flow_rule(trans));
10247 			break;
10248 		case NFT_MSG_NEWSET:
10249 			if (nft_trans_set_update(trans)) {
10250 				struct nft_set *set = nft_trans_set(trans);
10251 
10252 				WRITE_ONCE(set->timeout, nft_trans_set_timeout(trans));
10253 				WRITE_ONCE(set->gc_int, nft_trans_set_gc_int(trans));
10254 
10255 				if (nft_trans_set_size(trans))
10256 					WRITE_ONCE(set->size, nft_trans_set_size(trans));
10257 			} else {
10258 				nft_clear(net, nft_trans_set(trans));
10259 				/* This avoids hitting -EBUSY when deleting the table
10260 				 * from the transaction.
10261 				 */
10262 				if (nft_set_is_anonymous(nft_trans_set(trans)) &&
10263 				    !list_empty(&nft_trans_set(trans)->bindings))
10264 					nft_use_dec(&trans->ctx.table->use);
10265 			}
10266 			nf_tables_set_notify(&trans->ctx, nft_trans_set(trans),
10267 					     NFT_MSG_NEWSET, GFP_KERNEL);
10268 			nft_trans_destroy(trans);
10269 			break;
10270 		case NFT_MSG_DELSET:
10271 		case NFT_MSG_DESTROYSET:
10272 			nft_trans_set(trans)->dead = 1;
10273 			list_del_rcu(&nft_trans_set(trans)->list);
10274 			nf_tables_set_notify(&trans->ctx, nft_trans_set(trans),
10275 					     trans->msg_type, GFP_KERNEL);
10276 			break;
10277 		case NFT_MSG_NEWSETELEM:
10278 			te = (struct nft_trans_elem *)trans->data;
10279 
10280 			nft_setelem_activate(net, te->set, &te->elem);
10281 			nf_tables_setelem_notify(&trans->ctx, te->set,
10282 						 &te->elem,
10283 						 NFT_MSG_NEWSETELEM);
10284 			if (te->set->ops->commit &&
10285 			    list_empty(&te->set->pending_update)) {
10286 				list_add_tail(&te->set->pending_update,
10287 					      &set_update_list);
10288 			}
10289 			nft_trans_destroy(trans);
10290 			break;
10291 		case NFT_MSG_DELSETELEM:
10292 		case NFT_MSG_DESTROYSETELEM:
10293 			te = (struct nft_trans_elem *)trans->data;
10294 
10295 			nf_tables_setelem_notify(&trans->ctx, te->set,
10296 						 &te->elem,
10297 						 trans->msg_type);
10298 			nft_setelem_remove(net, te->set, &te->elem);
10299 			if (!nft_setelem_is_catchall(te->set, &te->elem)) {
10300 				atomic_dec(&te->set->nelems);
10301 				te->set->ndeact--;
10302 			}
10303 			if (te->set->ops->commit &&
10304 			    list_empty(&te->set->pending_update)) {
10305 				list_add_tail(&te->set->pending_update,
10306 					      &set_update_list);
10307 			}
10308 			break;
10309 		case NFT_MSG_NEWOBJ:
10310 			if (nft_trans_obj_update(trans)) {
10311 				nft_obj_commit_update(trans);
10312 				nf_tables_obj_notify(&trans->ctx,
10313 						     nft_trans_obj(trans),
10314 						     NFT_MSG_NEWOBJ);
10315 			} else {
10316 				nft_clear(net, nft_trans_obj(trans));
10317 				nf_tables_obj_notify(&trans->ctx,
10318 						     nft_trans_obj(trans),
10319 						     NFT_MSG_NEWOBJ);
10320 				nft_trans_destroy(trans);
10321 			}
10322 			break;
10323 		case NFT_MSG_DELOBJ:
10324 		case NFT_MSG_DESTROYOBJ:
10325 			nft_obj_del(nft_trans_obj(trans));
10326 			nf_tables_obj_notify(&trans->ctx, nft_trans_obj(trans),
10327 					     trans->msg_type);
10328 			break;
10329 		case NFT_MSG_NEWFLOWTABLE:
10330 			if (nft_trans_flowtable_update(trans)) {
10331 				nft_trans_flowtable(trans)->data.flags =
10332 					nft_trans_flowtable_flags(trans);
10333 				nf_tables_flowtable_notify(&trans->ctx,
10334 							   nft_trans_flowtable(trans),
10335 							   &nft_trans_flowtable_hooks(trans),
10336 							   NFT_MSG_NEWFLOWTABLE);
10337 				list_splice(&nft_trans_flowtable_hooks(trans),
10338 					    &nft_trans_flowtable(trans)->hook_list);
10339 			} else {
10340 				nft_clear(net, nft_trans_flowtable(trans));
10341 				nf_tables_flowtable_notify(&trans->ctx,
10342 							   nft_trans_flowtable(trans),
10343 							   NULL,
10344 							   NFT_MSG_NEWFLOWTABLE);
10345 			}
10346 			nft_trans_destroy(trans);
10347 			break;
10348 		case NFT_MSG_DELFLOWTABLE:
10349 		case NFT_MSG_DESTROYFLOWTABLE:
10350 			if (nft_trans_flowtable_update(trans)) {
10351 				nf_tables_flowtable_notify(&trans->ctx,
10352 							   nft_trans_flowtable(trans),
10353 							   &nft_trans_flowtable_hooks(trans),
10354 							   trans->msg_type);
10355 				nft_unregister_flowtable_net_hooks(net,
10356 								   &nft_trans_flowtable_hooks(trans));
10357 			} else {
10358 				list_del_rcu(&nft_trans_flowtable(trans)->list);
10359 				nf_tables_flowtable_notify(&trans->ctx,
10360 							   nft_trans_flowtable(trans),
10361 							   NULL,
10362 							   trans->msg_type);
10363 				nft_unregister_flowtable_net_hooks(net,
10364 						&nft_trans_flowtable(trans)->hook_list);
10365 			}
10366 			break;
10367 		}
10368 	}
10369 
10370 	nft_set_commit_update(&set_update_list);
10371 
10372 	nft_commit_notify(net, NETLINK_CB(skb).portid);
10373 	nf_tables_gen_notify(net, skb, NFT_MSG_NEWGEN);
10374 	nf_tables_commit_audit_log(&adl, nft_net->base_seq);
10375 
10376 	nft_gc_seq_end(nft_net, gc_seq);
10377 	nft_net->validate_state = NFT_VALIDATE_SKIP;
10378 	nf_tables_commit_release(net);
10379 
10380 	return 0;
10381 }
10382 
nf_tables_module_autoload(struct net * net)10383 static void nf_tables_module_autoload(struct net *net)
10384 {
10385 	struct nftables_pernet *nft_net = nft_pernet(net);
10386 	struct nft_module_request *req, *next;
10387 	LIST_HEAD(module_list);
10388 
10389 	list_splice_init(&nft_net->module_list, &module_list);
10390 	mutex_unlock(&nft_net->commit_mutex);
10391 	list_for_each_entry_safe(req, next, &module_list, list) {
10392 		request_module("%s", req->module);
10393 		req->done = true;
10394 	}
10395 	mutex_lock(&nft_net->commit_mutex);
10396 	list_splice(&module_list, &nft_net->module_list);
10397 }
10398 
nf_tables_abort_release(struct nft_trans * trans)10399 static void nf_tables_abort_release(struct nft_trans *trans)
10400 {
10401 	switch (trans->msg_type) {
10402 	case NFT_MSG_NEWTABLE:
10403 		nf_tables_table_destroy(&trans->ctx);
10404 		break;
10405 	case NFT_MSG_NEWCHAIN:
10406 		if (nft_trans_chain_update(trans))
10407 			nft_hooks_destroy(&nft_trans_chain_hooks(trans));
10408 		else
10409 			nf_tables_chain_destroy(&trans->ctx);
10410 		break;
10411 	case NFT_MSG_NEWRULE:
10412 		nf_tables_rule_destroy(&trans->ctx, nft_trans_rule(trans));
10413 		break;
10414 	case NFT_MSG_NEWSET:
10415 		nft_set_destroy(&trans->ctx, nft_trans_set(trans));
10416 		break;
10417 	case NFT_MSG_NEWSETELEM:
10418 		nft_set_elem_destroy(nft_trans_elem_set(trans),
10419 				     nft_trans_elem(trans).priv, true);
10420 		break;
10421 	case NFT_MSG_NEWOBJ:
10422 		nft_obj_destroy(&trans->ctx, nft_trans_obj(trans));
10423 		break;
10424 	case NFT_MSG_NEWFLOWTABLE:
10425 		if (nft_trans_flowtable_update(trans))
10426 			nft_hooks_destroy(&nft_trans_flowtable_hooks(trans));
10427 		else
10428 			nf_tables_flowtable_destroy(nft_trans_flowtable(trans));
10429 		break;
10430 	}
10431 	kfree(trans);
10432 }
10433 
nft_set_abort_update(struct list_head * set_update_list)10434 static void nft_set_abort_update(struct list_head *set_update_list)
10435 {
10436 	struct nft_set *set, *next;
10437 
10438 	list_for_each_entry_safe(set, next, set_update_list, pending_update) {
10439 		list_del_init(&set->pending_update);
10440 
10441 		if (!set->ops->abort)
10442 			continue;
10443 
10444 		set->ops->abort(set);
10445 	}
10446 }
10447 
__nf_tables_abort(struct net * net,enum nfnl_abort_action action)10448 static int __nf_tables_abort(struct net *net, enum nfnl_abort_action action)
10449 {
10450 	struct nftables_pernet *nft_net = nft_pernet(net);
10451 	struct nft_trans *trans, *next;
10452 	LIST_HEAD(set_update_list);
10453 	struct nft_trans_elem *te;
10454 	int err = 0;
10455 
10456 	if (action == NFNL_ABORT_VALIDATE &&
10457 	    nf_tables_validate(net) < 0)
10458 		err = -EAGAIN;
10459 
10460 	list_for_each_entry_safe_reverse(trans, next, &nft_net->commit_list,
10461 					 list) {
10462 		switch (trans->msg_type) {
10463 		case NFT_MSG_NEWTABLE:
10464 			if (nft_trans_table_update(trans)) {
10465 				if (!(trans->ctx.table->flags & __NFT_TABLE_F_UPDATE)) {
10466 					nft_trans_destroy(trans);
10467 					break;
10468 				}
10469 				if (trans->ctx.table->flags & __NFT_TABLE_F_WAS_DORMANT) {
10470 					nf_tables_table_disable(net, trans->ctx.table);
10471 					trans->ctx.table->flags |= NFT_TABLE_F_DORMANT;
10472 				} else if (trans->ctx.table->flags & __NFT_TABLE_F_WAS_AWAKEN) {
10473 					trans->ctx.table->flags &= ~NFT_TABLE_F_DORMANT;
10474 				}
10475 				trans->ctx.table->flags &= ~__NFT_TABLE_F_UPDATE;
10476 				nft_trans_destroy(trans);
10477 			} else {
10478 				list_del_rcu(&trans->ctx.table->list);
10479 			}
10480 			break;
10481 		case NFT_MSG_DELTABLE:
10482 		case NFT_MSG_DESTROYTABLE:
10483 			nft_clear(trans->ctx.net, trans->ctx.table);
10484 			nft_trans_destroy(trans);
10485 			break;
10486 		case NFT_MSG_NEWCHAIN:
10487 			if (nft_trans_chain_update(trans)) {
10488 				if (!(trans->ctx.table->flags & NFT_TABLE_F_DORMANT)) {
10489 					nft_netdev_unregister_hooks(net,
10490 								    &nft_trans_chain_hooks(trans),
10491 								    true);
10492 				}
10493 				free_percpu(nft_trans_chain_stats(trans));
10494 				kfree(nft_trans_chain_name(trans));
10495 				nft_trans_destroy(trans);
10496 			} else {
10497 				if (nft_trans_chain_bound(trans)) {
10498 					nft_trans_destroy(trans);
10499 					break;
10500 				}
10501 				nft_use_dec_restore(&trans->ctx.table->use);
10502 				nft_chain_del(trans->ctx.chain);
10503 				nf_tables_unregister_hook(trans->ctx.net,
10504 							  trans->ctx.table,
10505 							  trans->ctx.chain);
10506 			}
10507 			break;
10508 		case NFT_MSG_DELCHAIN:
10509 		case NFT_MSG_DESTROYCHAIN:
10510 			if (nft_trans_chain_update(trans)) {
10511 				list_splice(&nft_trans_chain_hooks(trans),
10512 					    &nft_trans_basechain(trans)->hook_list);
10513 			} else {
10514 				nft_use_inc_restore(&trans->ctx.table->use);
10515 				nft_clear(trans->ctx.net, trans->ctx.chain);
10516 			}
10517 			nft_trans_destroy(trans);
10518 			break;
10519 		case NFT_MSG_NEWRULE:
10520 			if (nft_trans_rule_bound(trans)) {
10521 				nft_trans_destroy(trans);
10522 				break;
10523 			}
10524 			nft_use_dec_restore(&trans->ctx.chain->use);
10525 			list_del_rcu(&nft_trans_rule(trans)->list);
10526 			nft_rule_expr_deactivate(&trans->ctx,
10527 						 nft_trans_rule(trans),
10528 						 NFT_TRANS_ABORT);
10529 			if (trans->ctx.chain->flags & NFT_CHAIN_HW_OFFLOAD)
10530 				nft_flow_rule_destroy(nft_trans_flow_rule(trans));
10531 			break;
10532 		case NFT_MSG_DELRULE:
10533 		case NFT_MSG_DESTROYRULE:
10534 			nft_use_inc_restore(&trans->ctx.chain->use);
10535 			nft_clear(trans->ctx.net, nft_trans_rule(trans));
10536 			nft_rule_expr_activate(&trans->ctx, nft_trans_rule(trans));
10537 			if (trans->ctx.chain->flags & NFT_CHAIN_HW_OFFLOAD)
10538 				nft_flow_rule_destroy(nft_trans_flow_rule(trans));
10539 
10540 			nft_trans_destroy(trans);
10541 			break;
10542 		case NFT_MSG_NEWSET:
10543 			if (nft_trans_set_update(trans)) {
10544 				nft_trans_destroy(trans);
10545 				break;
10546 			}
10547 			nft_use_dec_restore(&trans->ctx.table->use);
10548 			if (nft_trans_set_bound(trans)) {
10549 				nft_trans_destroy(trans);
10550 				break;
10551 			}
10552 			nft_trans_set(trans)->dead = 1;
10553 			list_del_rcu(&nft_trans_set(trans)->list);
10554 			break;
10555 		case NFT_MSG_DELSET:
10556 		case NFT_MSG_DESTROYSET:
10557 			nft_use_inc_restore(&trans->ctx.table->use);
10558 			nft_clear(trans->ctx.net, nft_trans_set(trans));
10559 			if (nft_trans_set(trans)->flags & (NFT_SET_MAP | NFT_SET_OBJECT))
10560 				nft_map_activate(&trans->ctx, nft_trans_set(trans));
10561 
10562 			nft_trans_destroy(trans);
10563 			break;
10564 		case NFT_MSG_NEWSETELEM:
10565 			if (nft_trans_elem_set_bound(trans)) {
10566 				nft_trans_destroy(trans);
10567 				break;
10568 			}
10569 			te = (struct nft_trans_elem *)trans->data;
10570 			nft_setelem_remove(net, te->set, &te->elem);
10571 			if (!nft_setelem_is_catchall(te->set, &te->elem))
10572 				atomic_dec(&te->set->nelems);
10573 
10574 			if (te->set->ops->abort &&
10575 			    list_empty(&te->set->pending_update)) {
10576 				list_add_tail(&te->set->pending_update,
10577 					      &set_update_list);
10578 			}
10579 			break;
10580 		case NFT_MSG_DELSETELEM:
10581 		case NFT_MSG_DESTROYSETELEM:
10582 			te = (struct nft_trans_elem *)trans->data;
10583 
10584 			if (!nft_setelem_active_next(net, te->set, &te->elem)) {
10585 				nft_setelem_data_activate(net, te->set, &te->elem);
10586 				nft_setelem_activate(net, te->set, &te->elem);
10587 			}
10588 			if (!nft_setelem_is_catchall(te->set, &te->elem))
10589 				te->set->ndeact--;
10590 
10591 			if (te->set->ops->abort &&
10592 			    list_empty(&te->set->pending_update)) {
10593 				list_add_tail(&te->set->pending_update,
10594 					      &set_update_list);
10595 			}
10596 			nft_trans_destroy(trans);
10597 			break;
10598 		case NFT_MSG_NEWOBJ:
10599 			if (nft_trans_obj_update(trans)) {
10600 				nft_obj_destroy(&trans->ctx, nft_trans_obj_newobj(trans));
10601 				nft_trans_destroy(trans);
10602 			} else {
10603 				nft_use_dec_restore(&trans->ctx.table->use);
10604 				nft_obj_del(nft_trans_obj(trans));
10605 			}
10606 			break;
10607 		case NFT_MSG_DELOBJ:
10608 		case NFT_MSG_DESTROYOBJ:
10609 			nft_use_inc_restore(&trans->ctx.table->use);
10610 			nft_clear(trans->ctx.net, nft_trans_obj(trans));
10611 			nft_trans_destroy(trans);
10612 			break;
10613 		case NFT_MSG_NEWFLOWTABLE:
10614 			if (nft_trans_flowtable_update(trans)) {
10615 				nft_unregister_flowtable_net_hooks(net,
10616 						&nft_trans_flowtable_hooks(trans));
10617 			} else {
10618 				nft_use_dec_restore(&trans->ctx.table->use);
10619 				list_del_rcu(&nft_trans_flowtable(trans)->list);
10620 				nft_unregister_flowtable_net_hooks(net,
10621 						&nft_trans_flowtable(trans)->hook_list);
10622 			}
10623 			break;
10624 		case NFT_MSG_DELFLOWTABLE:
10625 		case NFT_MSG_DESTROYFLOWTABLE:
10626 			if (nft_trans_flowtable_update(trans)) {
10627 				list_splice(&nft_trans_flowtable_hooks(trans),
10628 					    &nft_trans_flowtable(trans)->hook_list);
10629 			} else {
10630 				nft_use_inc_restore(&trans->ctx.table->use);
10631 				nft_clear(trans->ctx.net, nft_trans_flowtable(trans));
10632 			}
10633 			nft_trans_destroy(trans);
10634 			break;
10635 		}
10636 	}
10637 
10638 	nft_set_abort_update(&set_update_list);
10639 
10640 	synchronize_rcu();
10641 
10642 	list_for_each_entry_safe_reverse(trans, next,
10643 					 &nft_net->commit_list, list) {
10644 		nft_trans_list_del(trans);
10645 		nf_tables_abort_release(trans);
10646 	}
10647 
10648 	return err;
10649 }
10650 
nf_tables_abort(struct net * net,struct sk_buff * skb,enum nfnl_abort_action action)10651 static int nf_tables_abort(struct net *net, struct sk_buff *skb,
10652 			   enum nfnl_abort_action action)
10653 {
10654 	struct nftables_pernet *nft_net = nft_pernet(net);
10655 	unsigned int gc_seq;
10656 	int ret;
10657 
10658 	gc_seq = nft_gc_seq_begin(nft_net);
10659 	ret = __nf_tables_abort(net, action);
10660 	nft_gc_seq_end(nft_net, gc_seq);
10661 
10662 	WARN_ON_ONCE(!list_empty(&nft_net->commit_list));
10663 
10664 	/* module autoload needs to happen after GC sequence update because it
10665 	 * temporarily releases and grabs mutex again.
10666 	 */
10667 	if (action == NFNL_ABORT_AUTOLOAD)
10668 		nf_tables_module_autoload(net);
10669 	else
10670 		nf_tables_module_autoload_cleanup(net);
10671 
10672 	mutex_unlock(&nft_net->commit_mutex);
10673 
10674 	return ret;
10675 }
10676 
nf_tables_valid_genid(struct net * net,u32 genid)10677 static bool nf_tables_valid_genid(struct net *net, u32 genid)
10678 {
10679 	struct nftables_pernet *nft_net = nft_pernet(net);
10680 	bool genid_ok;
10681 
10682 	mutex_lock(&nft_net->commit_mutex);
10683 
10684 	genid_ok = genid == 0 || nft_net->base_seq == genid;
10685 	if (!genid_ok)
10686 		mutex_unlock(&nft_net->commit_mutex);
10687 
10688 	/* else, commit mutex has to be released by commit or abort function */
10689 	return genid_ok;
10690 }
10691 
10692 static const struct nfnetlink_subsystem nf_tables_subsys = {
10693 	.name		= "nf_tables",
10694 	.subsys_id	= NFNL_SUBSYS_NFTABLES,
10695 	.cb_count	= NFT_MSG_MAX,
10696 	.cb		= nf_tables_cb,
10697 	.commit		= nf_tables_commit,
10698 	.abort		= nf_tables_abort,
10699 	.valid_genid	= nf_tables_valid_genid,
10700 	.owner		= THIS_MODULE,
10701 };
10702 
nft_chain_validate_dependency(const struct nft_chain * chain,enum nft_chain_types type)10703 int nft_chain_validate_dependency(const struct nft_chain *chain,
10704 				  enum nft_chain_types type)
10705 {
10706 	const struct nft_base_chain *basechain;
10707 
10708 	if (nft_is_base_chain(chain)) {
10709 		basechain = nft_base_chain(chain);
10710 		if (basechain->type->type != type)
10711 			return -EOPNOTSUPP;
10712 	}
10713 	return 0;
10714 }
10715 EXPORT_SYMBOL_GPL(nft_chain_validate_dependency);
10716 
nft_chain_validate_hooks(const struct nft_chain * chain,unsigned int hook_flags)10717 int nft_chain_validate_hooks(const struct nft_chain *chain,
10718 			     unsigned int hook_flags)
10719 {
10720 	struct nft_base_chain *basechain;
10721 
10722 	if (nft_is_base_chain(chain)) {
10723 		basechain = nft_base_chain(chain);
10724 
10725 		if ((1 << basechain->ops.hooknum) & hook_flags)
10726 			return 0;
10727 
10728 		return -EOPNOTSUPP;
10729 	}
10730 
10731 	return 0;
10732 }
10733 EXPORT_SYMBOL_GPL(nft_chain_validate_hooks);
10734 
10735 /**
10736  *	nft_parse_u32_check - fetch u32 attribute and check for maximum value
10737  *
10738  *	@attr: netlink attribute to fetch value from
10739  *	@max: maximum value to be stored in dest
10740  *	@dest: pointer to the variable
10741  *
10742  *	Parse, check and store a given u32 netlink attribute into variable.
10743  *	This function returns -ERANGE if the value goes over maximum value.
10744  *	Otherwise a 0 is returned and the attribute value is stored in the
10745  *	destination variable.
10746  */
nft_parse_u32_check(const struct nlattr * attr,int max,u32 * dest)10747 int nft_parse_u32_check(const struct nlattr *attr, int max, u32 *dest)
10748 {
10749 	u32 val;
10750 
10751 	val = ntohl(nla_get_be32(attr));
10752 	if (val > max)
10753 		return -ERANGE;
10754 
10755 	*dest = val;
10756 	return 0;
10757 }
10758 EXPORT_SYMBOL_GPL(nft_parse_u32_check);
10759 
nft_parse_register(const struct nlattr * attr,u32 * preg)10760 static int nft_parse_register(const struct nlattr *attr, u32 *preg)
10761 {
10762 	unsigned int reg;
10763 
10764 	reg = ntohl(nla_get_be32(attr));
10765 	switch (reg) {
10766 	case NFT_REG_VERDICT...NFT_REG_4:
10767 		*preg = reg * NFT_REG_SIZE / NFT_REG32_SIZE;
10768 		break;
10769 	case NFT_REG32_00...NFT_REG32_15:
10770 		*preg = reg + NFT_REG_SIZE / NFT_REG32_SIZE - NFT_REG32_00;
10771 		break;
10772 	default:
10773 		return -ERANGE;
10774 	}
10775 
10776 	return 0;
10777 }
10778 
10779 /**
10780  *	nft_dump_register - dump a register value to a netlink attribute
10781  *
10782  *	@skb: socket buffer
10783  *	@attr: attribute number
10784  *	@reg: register number
10785  *
10786  *	Construct a netlink attribute containing the register number. For
10787  *	compatibility reasons, register numbers being a multiple of 4 are
10788  *	translated to the corresponding 128 bit register numbers.
10789  */
nft_dump_register(struct sk_buff * skb,unsigned int attr,unsigned int reg)10790 int nft_dump_register(struct sk_buff *skb, unsigned int attr, unsigned int reg)
10791 {
10792 	if (reg % (NFT_REG_SIZE / NFT_REG32_SIZE) == 0)
10793 		reg = reg / (NFT_REG_SIZE / NFT_REG32_SIZE);
10794 	else
10795 		reg = reg - NFT_REG_SIZE / NFT_REG32_SIZE + NFT_REG32_00;
10796 
10797 	return nla_put_be32(skb, attr, htonl(reg));
10798 }
10799 EXPORT_SYMBOL_GPL(nft_dump_register);
10800 
nft_validate_register_load(enum nft_registers reg,unsigned int len)10801 static int nft_validate_register_load(enum nft_registers reg, unsigned int len)
10802 {
10803 	if (reg < NFT_REG_1 * NFT_REG_SIZE / NFT_REG32_SIZE)
10804 		return -EINVAL;
10805 	if (len == 0)
10806 		return -EINVAL;
10807 	if (reg * NFT_REG32_SIZE + len > sizeof_field(struct nft_regs, data))
10808 		return -ERANGE;
10809 
10810 	return 0;
10811 }
10812 
nft_parse_register_load(const struct nlattr * attr,u8 * sreg,u32 len)10813 int nft_parse_register_load(const struct nlattr *attr, u8 *sreg, u32 len)
10814 {
10815 	u32 reg;
10816 	int err;
10817 
10818 	err = nft_parse_register(attr, &reg);
10819 	if (err < 0)
10820 		return err;
10821 
10822 	err = nft_validate_register_load(reg, len);
10823 	if (err < 0)
10824 		return err;
10825 
10826 	*sreg = reg;
10827 	return 0;
10828 }
10829 EXPORT_SYMBOL_GPL(nft_parse_register_load);
10830 
nft_validate_register_store(const struct nft_ctx * ctx,enum nft_registers reg,const struct nft_data * data,enum nft_data_types type,unsigned int len)10831 static int nft_validate_register_store(const struct nft_ctx *ctx,
10832 				       enum nft_registers reg,
10833 				       const struct nft_data *data,
10834 				       enum nft_data_types type,
10835 				       unsigned int len)
10836 {
10837 	int err;
10838 
10839 	switch (reg) {
10840 	case NFT_REG_VERDICT:
10841 		if (type != NFT_DATA_VERDICT)
10842 			return -EINVAL;
10843 
10844 		if (data != NULL &&
10845 		    (data->verdict.code == NFT_GOTO ||
10846 		     data->verdict.code == NFT_JUMP)) {
10847 			err = nft_chain_validate(ctx, data->verdict.chain);
10848 			if (err < 0)
10849 				return err;
10850 		}
10851 
10852 		return 0;
10853 	default:
10854 		if (type != NFT_DATA_VALUE)
10855 			return -EINVAL;
10856 
10857 		if (reg < NFT_REG_1 * NFT_REG_SIZE / NFT_REG32_SIZE)
10858 			return -EINVAL;
10859 		if (len == 0)
10860 			return -EINVAL;
10861 		if (reg * NFT_REG32_SIZE + len >
10862 		    sizeof_field(struct nft_regs, data))
10863 			return -ERANGE;
10864 
10865 		return 0;
10866 	}
10867 }
10868 
nft_parse_register_store(const struct nft_ctx * ctx,const struct nlattr * attr,u8 * dreg,const struct nft_data * data,enum nft_data_types type,unsigned int len)10869 int nft_parse_register_store(const struct nft_ctx *ctx,
10870 			     const struct nlattr *attr, u8 *dreg,
10871 			     const struct nft_data *data,
10872 			     enum nft_data_types type, unsigned int len)
10873 {
10874 	int err;
10875 	u32 reg;
10876 
10877 	err = nft_parse_register(attr, &reg);
10878 	if (err < 0)
10879 		return err;
10880 
10881 	err = nft_validate_register_store(ctx, reg, data, type, len);
10882 	if (err < 0)
10883 		return err;
10884 
10885 	*dreg = reg;
10886 	return 0;
10887 }
10888 EXPORT_SYMBOL_GPL(nft_parse_register_store);
10889 
10890 static const struct nla_policy nft_verdict_policy[NFTA_VERDICT_MAX + 1] = {
10891 	[NFTA_VERDICT_CODE]	= { .type = NLA_U32 },
10892 	[NFTA_VERDICT_CHAIN]	= { .type = NLA_STRING,
10893 				    .len = NFT_CHAIN_MAXNAMELEN - 1 },
10894 	[NFTA_VERDICT_CHAIN_ID]	= { .type = NLA_U32 },
10895 };
10896 
nft_verdict_init(const struct nft_ctx * ctx,struct nft_data * data,struct nft_data_desc * desc,const struct nlattr * nla)10897 static int nft_verdict_init(const struct nft_ctx *ctx, struct nft_data *data,
10898 			    struct nft_data_desc *desc, const struct nlattr *nla)
10899 {
10900 	u8 genmask = nft_genmask_next(ctx->net);
10901 	struct nlattr *tb[NFTA_VERDICT_MAX + 1];
10902 	struct nft_chain *chain;
10903 	int err;
10904 
10905 	err = nla_parse_nested_deprecated(tb, NFTA_VERDICT_MAX, nla,
10906 					  nft_verdict_policy, NULL);
10907 	if (err < 0)
10908 		return err;
10909 
10910 	if (!tb[NFTA_VERDICT_CODE])
10911 		return -EINVAL;
10912 
10913 	/* zero padding hole for memcmp */
10914 	memset(data, 0, sizeof(*data));
10915 	data->verdict.code = ntohl(nla_get_be32(tb[NFTA_VERDICT_CODE]));
10916 
10917 	switch (data->verdict.code) {
10918 	case NF_ACCEPT:
10919 	case NF_DROP:
10920 	case NF_QUEUE:
10921 		break;
10922 	case NFT_CONTINUE:
10923 	case NFT_BREAK:
10924 	case NFT_RETURN:
10925 		break;
10926 	case NFT_JUMP:
10927 	case NFT_GOTO:
10928 		if (tb[NFTA_VERDICT_CHAIN]) {
10929 			chain = nft_chain_lookup(ctx->net, ctx->table,
10930 						 tb[NFTA_VERDICT_CHAIN],
10931 						 genmask);
10932 		} else if (tb[NFTA_VERDICT_CHAIN_ID]) {
10933 			chain = nft_chain_lookup_byid(ctx->net, ctx->table,
10934 						      tb[NFTA_VERDICT_CHAIN_ID],
10935 						      genmask);
10936 			if (IS_ERR(chain))
10937 				return PTR_ERR(chain);
10938 		} else {
10939 			return -EINVAL;
10940 		}
10941 
10942 		if (IS_ERR(chain))
10943 			return PTR_ERR(chain);
10944 		if (nft_is_base_chain(chain))
10945 			return -EOPNOTSUPP;
10946 		if (nft_chain_is_bound(chain))
10947 			return -EINVAL;
10948 		if (desc->flags & NFT_DATA_DESC_SETELEM &&
10949 		    chain->flags & NFT_CHAIN_BINDING)
10950 			return -EINVAL;
10951 		if (!nft_use_inc(&chain->use))
10952 			return -EMFILE;
10953 
10954 		data->verdict.chain = chain;
10955 		break;
10956 	default:
10957 		return -EINVAL;
10958 	}
10959 
10960 	desc->len = sizeof(data->verdict);
10961 
10962 	return 0;
10963 }
10964 
nft_verdict_uninit(const struct nft_data * data)10965 static void nft_verdict_uninit(const struct nft_data *data)
10966 {
10967 	struct nft_chain *chain;
10968 
10969 	switch (data->verdict.code) {
10970 	case NFT_JUMP:
10971 	case NFT_GOTO:
10972 		chain = data->verdict.chain;
10973 		nft_use_dec(&chain->use);
10974 		break;
10975 	}
10976 }
10977 
nft_verdict_dump(struct sk_buff * skb,int type,const struct nft_verdict * v)10978 int nft_verdict_dump(struct sk_buff *skb, int type, const struct nft_verdict *v)
10979 {
10980 	struct nlattr *nest;
10981 
10982 	nest = nla_nest_start_noflag(skb, type);
10983 	if (!nest)
10984 		goto nla_put_failure;
10985 
10986 	if (nla_put_be32(skb, NFTA_VERDICT_CODE, htonl(v->code)))
10987 		goto nla_put_failure;
10988 
10989 	switch (v->code) {
10990 	case NFT_JUMP:
10991 	case NFT_GOTO:
10992 		if (nla_put_string(skb, NFTA_VERDICT_CHAIN,
10993 				   v->chain->name))
10994 			goto nla_put_failure;
10995 	}
10996 	nla_nest_end(skb, nest);
10997 	return 0;
10998 
10999 nla_put_failure:
11000 	return -1;
11001 }
11002 
nft_value_init(const struct nft_ctx * ctx,struct nft_data * data,struct nft_data_desc * desc,const struct nlattr * nla)11003 static int nft_value_init(const struct nft_ctx *ctx,
11004 			  struct nft_data *data, struct nft_data_desc *desc,
11005 			  const struct nlattr *nla)
11006 {
11007 	unsigned int len;
11008 
11009 	len = nla_len(nla);
11010 	if (len == 0)
11011 		return -EINVAL;
11012 	if (len > desc->size)
11013 		return -EOVERFLOW;
11014 	if (desc->len) {
11015 		if (len != desc->len)
11016 			return -EINVAL;
11017 	} else {
11018 		desc->len = len;
11019 	}
11020 
11021 	nla_memcpy(data->data, nla, len);
11022 
11023 	return 0;
11024 }
11025 
nft_value_dump(struct sk_buff * skb,const struct nft_data * data,unsigned int len)11026 static int nft_value_dump(struct sk_buff *skb, const struct nft_data *data,
11027 			  unsigned int len)
11028 {
11029 	return nla_put(skb, NFTA_DATA_VALUE, len, data->data);
11030 }
11031 
11032 static const struct nla_policy nft_data_policy[NFTA_DATA_MAX + 1] = {
11033 	[NFTA_DATA_VALUE]	= { .type = NLA_BINARY },
11034 	[NFTA_DATA_VERDICT]	= { .type = NLA_NESTED },
11035 };
11036 
11037 /**
11038  *	nft_data_init - parse nf_tables data netlink attributes
11039  *
11040  *	@ctx: context of the expression using the data
11041  *	@data: destination struct nft_data
11042  *	@desc: data description
11043  *	@nla: netlink attribute containing data
11044  *
11045  *	Parse the netlink data attributes and initialize a struct nft_data.
11046  *	The type and length of data are returned in the data description.
11047  *
11048  *	The caller can indicate that it only wants to accept data of type
11049  *	NFT_DATA_VALUE by passing NULL for the ctx argument.
11050  */
nft_data_init(const struct nft_ctx * ctx,struct nft_data * data,struct nft_data_desc * desc,const struct nlattr * nla)11051 int nft_data_init(const struct nft_ctx *ctx, struct nft_data *data,
11052 		  struct nft_data_desc *desc, const struct nlattr *nla)
11053 {
11054 	struct nlattr *tb[NFTA_DATA_MAX + 1];
11055 	int err;
11056 
11057 	if (WARN_ON_ONCE(!desc->size))
11058 		return -EINVAL;
11059 
11060 	err = nla_parse_nested_deprecated(tb, NFTA_DATA_MAX, nla,
11061 					  nft_data_policy, NULL);
11062 	if (err < 0)
11063 		return err;
11064 
11065 	if (tb[NFTA_DATA_VALUE]) {
11066 		if (desc->type != NFT_DATA_VALUE)
11067 			return -EINVAL;
11068 
11069 		err = nft_value_init(ctx, data, desc, tb[NFTA_DATA_VALUE]);
11070 	} else if (tb[NFTA_DATA_VERDICT] && ctx != NULL) {
11071 		if (desc->type != NFT_DATA_VERDICT)
11072 			return -EINVAL;
11073 
11074 		err = nft_verdict_init(ctx, data, desc, tb[NFTA_DATA_VERDICT]);
11075 	} else {
11076 		err = -EINVAL;
11077 	}
11078 
11079 	return err;
11080 }
11081 EXPORT_SYMBOL_GPL(nft_data_init);
11082 
11083 /**
11084  *	nft_data_release - release a nft_data item
11085  *
11086  *	@data: struct nft_data to release
11087  *	@type: type of data
11088  *
11089  *	Release a nft_data item. NFT_DATA_VALUE types can be silently discarded,
11090  *	all others need to be released by calling this function.
11091  */
nft_data_release(const struct nft_data * data,enum nft_data_types type)11092 void nft_data_release(const struct nft_data *data, enum nft_data_types type)
11093 {
11094 	if (type < NFT_DATA_VERDICT)
11095 		return;
11096 	switch (type) {
11097 	case NFT_DATA_VERDICT:
11098 		return nft_verdict_uninit(data);
11099 	default:
11100 		WARN_ON(1);
11101 	}
11102 }
11103 EXPORT_SYMBOL_GPL(nft_data_release);
11104 
nft_data_dump(struct sk_buff * skb,int attr,const struct nft_data * data,enum nft_data_types type,unsigned int len)11105 int nft_data_dump(struct sk_buff *skb, int attr, const struct nft_data *data,
11106 		  enum nft_data_types type, unsigned int len)
11107 {
11108 	struct nlattr *nest;
11109 	int err;
11110 
11111 	nest = nla_nest_start_noflag(skb, attr);
11112 	if (nest == NULL)
11113 		return -1;
11114 
11115 	switch (type) {
11116 	case NFT_DATA_VALUE:
11117 		err = nft_value_dump(skb, data, len);
11118 		break;
11119 	case NFT_DATA_VERDICT:
11120 		err = nft_verdict_dump(skb, NFTA_DATA_VERDICT, &data->verdict);
11121 		break;
11122 	default:
11123 		err = -EINVAL;
11124 		WARN_ON(1);
11125 	}
11126 
11127 	nla_nest_end(skb, nest);
11128 	return err;
11129 }
11130 EXPORT_SYMBOL_GPL(nft_data_dump);
11131 
__nft_release_basechain(struct nft_ctx * ctx)11132 int __nft_release_basechain(struct nft_ctx *ctx)
11133 {
11134 	struct nft_rule *rule, *nr;
11135 
11136 	if (WARN_ON(!nft_is_base_chain(ctx->chain)))
11137 		return 0;
11138 
11139 	nf_tables_unregister_hook(ctx->net, ctx->chain->table, ctx->chain);
11140 	list_for_each_entry_safe(rule, nr, &ctx->chain->rules, list) {
11141 		list_del(&rule->list);
11142 		nft_use_dec(&ctx->chain->use);
11143 		nf_tables_rule_release(ctx, rule);
11144 	}
11145 	nft_chain_del(ctx->chain);
11146 	nft_use_dec(&ctx->table->use);
11147 	nf_tables_chain_destroy(ctx);
11148 
11149 	return 0;
11150 }
11151 EXPORT_SYMBOL_GPL(__nft_release_basechain);
11152 
__nft_release_hook(struct net * net,struct nft_table * table)11153 static void __nft_release_hook(struct net *net, struct nft_table *table)
11154 {
11155 	struct nft_flowtable *flowtable;
11156 	struct nft_chain *chain;
11157 
11158 	list_for_each_entry(chain, &table->chains, list)
11159 		__nf_tables_unregister_hook(net, table, chain, true);
11160 	list_for_each_entry(flowtable, &table->flowtables, list)
11161 		__nft_unregister_flowtable_net_hooks(net, &flowtable->hook_list,
11162 						     true);
11163 }
11164 
__nft_release_hooks(struct net * net)11165 static void __nft_release_hooks(struct net *net)
11166 {
11167 	struct nftables_pernet *nft_net = nft_pernet(net);
11168 	struct nft_table *table;
11169 
11170 	list_for_each_entry(table, &nft_net->tables, list) {
11171 		if (nft_table_has_owner(table))
11172 			continue;
11173 
11174 		__nft_release_hook(net, table);
11175 	}
11176 }
11177 
__nft_release_table(struct net * net,struct nft_table * table)11178 static void __nft_release_table(struct net *net, struct nft_table *table)
11179 {
11180 	struct nft_flowtable *flowtable, *nf;
11181 	struct nft_chain *chain, *nc;
11182 	struct nft_object *obj, *ne;
11183 	struct nft_rule *rule, *nr;
11184 	struct nft_set *set, *ns;
11185 	struct nft_ctx ctx = {
11186 		.net	= net,
11187 		.family	= NFPROTO_NETDEV,
11188 	};
11189 
11190 	ctx.family = table->family;
11191 	ctx.table = table;
11192 	list_for_each_entry(chain, &table->chains, list) {
11193 		if (nft_chain_binding(chain))
11194 			continue;
11195 
11196 		ctx.chain = chain;
11197 		list_for_each_entry_safe(rule, nr, &chain->rules, list) {
11198 			list_del(&rule->list);
11199 			nft_use_dec(&chain->use);
11200 			nf_tables_rule_release(&ctx, rule);
11201 		}
11202 	}
11203 	list_for_each_entry_safe(flowtable, nf, &table->flowtables, list) {
11204 		list_del(&flowtable->list);
11205 		nft_use_dec(&table->use);
11206 		nf_tables_flowtable_destroy(flowtable);
11207 	}
11208 	list_for_each_entry_safe(set, ns, &table->sets, list) {
11209 		list_del(&set->list);
11210 		nft_use_dec(&table->use);
11211 		if (set->flags & (NFT_SET_MAP | NFT_SET_OBJECT))
11212 			nft_map_deactivate(&ctx, set);
11213 
11214 		nft_set_destroy(&ctx, set);
11215 	}
11216 	list_for_each_entry_safe(obj, ne, &table->objects, list) {
11217 		nft_obj_del(obj);
11218 		nft_use_dec(&table->use);
11219 		nft_obj_destroy(&ctx, obj);
11220 	}
11221 	list_for_each_entry_safe(chain, nc, &table->chains, list) {
11222 		ctx.chain = chain;
11223 		nft_chain_del(chain);
11224 		nft_use_dec(&table->use);
11225 		nf_tables_chain_destroy(&ctx);
11226 	}
11227 	nf_tables_table_destroy(&ctx);
11228 }
11229 
__nft_release_tables(struct net * net)11230 static void __nft_release_tables(struct net *net)
11231 {
11232 	struct nftables_pernet *nft_net = nft_pernet(net);
11233 	struct nft_table *table, *nt;
11234 
11235 	list_for_each_entry_safe(table, nt, &nft_net->tables, list) {
11236 		if (nft_table_has_owner(table))
11237 			continue;
11238 
11239 		list_del(&table->list);
11240 
11241 		__nft_release_table(net, table);
11242 	}
11243 }
11244 
nft_rcv_nl_event(struct notifier_block * this,unsigned long event,void * ptr)11245 static int nft_rcv_nl_event(struct notifier_block *this, unsigned long event,
11246 			    void *ptr)
11247 {
11248 	struct nft_table *table, *to_delete[8];
11249 	struct nftables_pernet *nft_net;
11250 	struct netlink_notify *n = ptr;
11251 	struct net *net = n->net;
11252 	unsigned int deleted;
11253 	bool restart = false;
11254 	unsigned int gc_seq;
11255 
11256 	if (event != NETLINK_URELEASE || n->protocol != NETLINK_NETFILTER)
11257 		return NOTIFY_DONE;
11258 
11259 	nft_net = nft_pernet(net);
11260 	deleted = 0;
11261 	mutex_lock(&nft_net->commit_mutex);
11262 
11263 	gc_seq = nft_gc_seq_begin(nft_net);
11264 
11265 	nf_tables_trans_destroy_flush_work();
11266 again:
11267 	list_for_each_entry(table, &nft_net->tables, list) {
11268 		if (nft_table_has_owner(table) &&
11269 		    n->portid == table->nlpid) {
11270 			__nft_release_hook(net, table);
11271 			list_del_rcu(&table->list);
11272 			to_delete[deleted++] = table;
11273 			if (deleted >= ARRAY_SIZE(to_delete))
11274 				break;
11275 		}
11276 	}
11277 	if (deleted) {
11278 		restart = deleted >= ARRAY_SIZE(to_delete);
11279 		synchronize_rcu();
11280 		while (deleted)
11281 			__nft_release_table(net, to_delete[--deleted]);
11282 
11283 		if (restart)
11284 			goto again;
11285 	}
11286 	nft_gc_seq_end(nft_net, gc_seq);
11287 
11288 	mutex_unlock(&nft_net->commit_mutex);
11289 
11290 	return NOTIFY_DONE;
11291 }
11292 
11293 static struct notifier_block nft_nl_notifier = {
11294 	.notifier_call  = nft_rcv_nl_event,
11295 };
11296 
nf_tables_init_net(struct net * net)11297 static int __net_init nf_tables_init_net(struct net *net)
11298 {
11299 	struct nftables_pernet *nft_net = nft_pernet(net);
11300 
11301 	INIT_LIST_HEAD(&nft_net->tables);
11302 	INIT_LIST_HEAD(&nft_net->commit_list);
11303 	INIT_LIST_HEAD(&nft_net->binding_list);
11304 	INIT_LIST_HEAD(&nft_net->module_list);
11305 	INIT_LIST_HEAD(&nft_net->notify_list);
11306 	mutex_init(&nft_net->commit_mutex);
11307 	nft_net->base_seq = 1;
11308 	nft_net->gc_seq = 0;
11309 	nft_net->validate_state = NFT_VALIDATE_SKIP;
11310 
11311 	return 0;
11312 }
11313 
nf_tables_pre_exit_net(struct net * net)11314 static void __net_exit nf_tables_pre_exit_net(struct net *net)
11315 {
11316 	struct nftables_pernet *nft_net = nft_pernet(net);
11317 
11318 	mutex_lock(&nft_net->commit_mutex);
11319 	__nft_release_hooks(net);
11320 	mutex_unlock(&nft_net->commit_mutex);
11321 }
11322 
nf_tables_exit_net(struct net * net)11323 static void __net_exit nf_tables_exit_net(struct net *net)
11324 {
11325 	struct nftables_pernet *nft_net = nft_pernet(net);
11326 	unsigned int gc_seq;
11327 
11328 	mutex_lock(&nft_net->commit_mutex);
11329 
11330 	gc_seq = nft_gc_seq_begin(nft_net);
11331 
11332 	WARN_ON_ONCE(!list_empty(&nft_net->commit_list));
11333 
11334 	if (!list_empty(&nft_net->module_list))
11335 		nf_tables_module_autoload_cleanup(net);
11336 
11337 	__nft_release_tables(net);
11338 
11339 	nft_gc_seq_end(nft_net, gc_seq);
11340 
11341 	mutex_unlock(&nft_net->commit_mutex);
11342 	WARN_ON_ONCE(!list_empty(&nft_net->tables));
11343 	WARN_ON_ONCE(!list_empty(&nft_net->module_list));
11344 	WARN_ON_ONCE(!list_empty(&nft_net->notify_list));
11345 }
11346 
nf_tables_exit_batch(struct list_head * net_exit_list)11347 static void nf_tables_exit_batch(struct list_head *net_exit_list)
11348 {
11349 	flush_work(&trans_gc_work);
11350 }
11351 
11352 static struct pernet_operations nf_tables_net_ops = {
11353 	.init		= nf_tables_init_net,
11354 	.pre_exit	= nf_tables_pre_exit_net,
11355 	.exit		= nf_tables_exit_net,
11356 	.exit_batch	= nf_tables_exit_batch,
11357 	.id		= &nf_tables_net_id,
11358 	.size		= sizeof(struct nftables_pernet),
11359 };
11360 
nf_tables_module_init(void)11361 static int __init nf_tables_module_init(void)
11362 {
11363 	int err;
11364 
11365 	err = register_pernet_subsys(&nf_tables_net_ops);
11366 	if (err < 0)
11367 		return err;
11368 
11369 	err = nft_chain_filter_init();
11370 	if (err < 0)
11371 		goto err_chain_filter;
11372 
11373 	err = nf_tables_core_module_init();
11374 	if (err < 0)
11375 		goto err_core_module;
11376 
11377 	err = register_netdevice_notifier(&nf_tables_flowtable_notifier);
11378 	if (err < 0)
11379 		goto err_netdev_notifier;
11380 
11381 	err = rhltable_init(&nft_objname_ht, &nft_objname_ht_params);
11382 	if (err < 0)
11383 		goto err_rht_objname;
11384 
11385 	err = nft_offload_init();
11386 	if (err < 0)
11387 		goto err_offload;
11388 
11389 	err = netlink_register_notifier(&nft_nl_notifier);
11390 	if (err < 0)
11391 		goto err_netlink_notifier;
11392 
11393 	/* must be last */
11394 	err = nfnetlink_subsys_register(&nf_tables_subsys);
11395 	if (err < 0)
11396 		goto err_nfnl_subsys;
11397 
11398 	nft_chain_route_init();
11399 
11400 	return err;
11401 
11402 err_nfnl_subsys:
11403 	netlink_unregister_notifier(&nft_nl_notifier);
11404 err_netlink_notifier:
11405 	nft_offload_exit();
11406 err_offload:
11407 	rhltable_destroy(&nft_objname_ht);
11408 err_rht_objname:
11409 	unregister_netdevice_notifier(&nf_tables_flowtable_notifier);
11410 err_netdev_notifier:
11411 	nf_tables_core_module_exit();
11412 err_core_module:
11413 	nft_chain_filter_fini();
11414 err_chain_filter:
11415 	unregister_pernet_subsys(&nf_tables_net_ops);
11416 	return err;
11417 }
11418 
nf_tables_module_exit(void)11419 static void __exit nf_tables_module_exit(void)
11420 {
11421 	nfnetlink_subsys_unregister(&nf_tables_subsys);
11422 	netlink_unregister_notifier(&nft_nl_notifier);
11423 	nft_offload_exit();
11424 	unregister_netdevice_notifier(&nf_tables_flowtable_notifier);
11425 	nft_chain_filter_fini();
11426 	nft_chain_route_fini();
11427 	nf_tables_trans_destroy_flush_work();
11428 	unregister_pernet_subsys(&nf_tables_net_ops);
11429 	cancel_work_sync(&trans_gc_work);
11430 	cancel_work_sync(&trans_destroy_work);
11431 	rcu_barrier();
11432 	rhltable_destroy(&nft_objname_ht);
11433 	nf_tables_core_module_exit();
11434 }
11435 
11436 module_init(nf_tables_module_init);
11437 module_exit(nf_tables_module_exit);
11438 
11439 MODULE_LICENSE("GPL");
11440 MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
11441 MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_NFTABLES);
11442