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