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