xref: /linux/net/core/fib_rules.c (revision 791d3ef2e11100449837dc0b6fe884e60ca3a484)
1 /*
2  * net/core/fib_rules.c		Generic Routing Rules
3  *
4  *	This program is free software; you can redistribute it and/or
5  *	modify it under the terms of the GNU General Public License as
6  *	published by the Free Software Foundation, version 2.
7  *
8  * Authors:	Thomas Graf <tgraf@suug.ch>
9  */
10 
11 #include <linux/types.h>
12 #include <linux/kernel.h>
13 #include <linux/slab.h>
14 #include <linux/list.h>
15 #include <linux/module.h>
16 #include <net/net_namespace.h>
17 #include <net/sock.h>
18 #include <net/fib_rules.h>
19 #include <net/ip_tunnels.h>
20 
21 static const struct fib_kuid_range fib_kuid_range_unset = {
22 	KUIDT_INIT(0),
23 	KUIDT_INIT(~0),
24 };
25 
26 bool fib_rule_matchall(const struct fib_rule *rule)
27 {
28 	if (rule->iifindex || rule->oifindex || rule->mark || rule->tun_id ||
29 	    rule->flags)
30 		return false;
31 	if (rule->suppress_ifgroup != -1 || rule->suppress_prefixlen != -1)
32 		return false;
33 	if (!uid_eq(rule->uid_range.start, fib_kuid_range_unset.start) ||
34 	    !uid_eq(rule->uid_range.end, fib_kuid_range_unset.end))
35 		return false;
36 	if (fib_rule_port_range_set(&rule->sport_range))
37 		return false;
38 	if (fib_rule_port_range_set(&rule->dport_range))
39 		return false;
40 	return true;
41 }
42 EXPORT_SYMBOL_GPL(fib_rule_matchall);
43 
44 int fib_default_rule_add(struct fib_rules_ops *ops,
45 			 u32 pref, u32 table, u32 flags)
46 {
47 	struct fib_rule *r;
48 
49 	r = kzalloc(ops->rule_size, GFP_KERNEL);
50 	if (r == NULL)
51 		return -ENOMEM;
52 
53 	refcount_set(&r->refcnt, 1);
54 	r->action = FR_ACT_TO_TBL;
55 	r->pref = pref;
56 	r->table = table;
57 	r->flags = flags;
58 	r->proto = RTPROT_KERNEL;
59 	r->fr_net = ops->fro_net;
60 	r->uid_range = fib_kuid_range_unset;
61 
62 	r->suppress_prefixlen = -1;
63 	r->suppress_ifgroup = -1;
64 
65 	/* The lock is not required here, the list in unreacheable
66 	 * at the moment this function is called */
67 	list_add_tail(&r->list, &ops->rules_list);
68 	return 0;
69 }
70 EXPORT_SYMBOL(fib_default_rule_add);
71 
72 static u32 fib_default_rule_pref(struct fib_rules_ops *ops)
73 {
74 	struct list_head *pos;
75 	struct fib_rule *rule;
76 
77 	if (!list_empty(&ops->rules_list)) {
78 		pos = ops->rules_list.next;
79 		if (pos->next != &ops->rules_list) {
80 			rule = list_entry(pos->next, struct fib_rule, list);
81 			if (rule->pref)
82 				return rule->pref - 1;
83 		}
84 	}
85 
86 	return 0;
87 }
88 
89 static void notify_rule_change(int event, struct fib_rule *rule,
90 			       struct fib_rules_ops *ops, struct nlmsghdr *nlh,
91 			       u32 pid);
92 
93 static struct fib_rules_ops *lookup_rules_ops(struct net *net, int family)
94 {
95 	struct fib_rules_ops *ops;
96 
97 	rcu_read_lock();
98 	list_for_each_entry_rcu(ops, &net->rules_ops, list) {
99 		if (ops->family == family) {
100 			if (!try_module_get(ops->owner))
101 				ops = NULL;
102 			rcu_read_unlock();
103 			return ops;
104 		}
105 	}
106 	rcu_read_unlock();
107 
108 	return NULL;
109 }
110 
111 static void rules_ops_put(struct fib_rules_ops *ops)
112 {
113 	if (ops)
114 		module_put(ops->owner);
115 }
116 
117 static void flush_route_cache(struct fib_rules_ops *ops)
118 {
119 	if (ops->flush_cache)
120 		ops->flush_cache(ops);
121 }
122 
123 static int __fib_rules_register(struct fib_rules_ops *ops)
124 {
125 	int err = -EEXIST;
126 	struct fib_rules_ops *o;
127 	struct net *net;
128 
129 	net = ops->fro_net;
130 
131 	if (ops->rule_size < sizeof(struct fib_rule))
132 		return -EINVAL;
133 
134 	if (ops->match == NULL || ops->configure == NULL ||
135 	    ops->compare == NULL || ops->fill == NULL ||
136 	    ops->action == NULL)
137 		return -EINVAL;
138 
139 	spin_lock(&net->rules_mod_lock);
140 	list_for_each_entry(o, &net->rules_ops, list)
141 		if (ops->family == o->family)
142 			goto errout;
143 
144 	list_add_tail_rcu(&ops->list, &net->rules_ops);
145 	err = 0;
146 errout:
147 	spin_unlock(&net->rules_mod_lock);
148 
149 	return err;
150 }
151 
152 struct fib_rules_ops *
153 fib_rules_register(const struct fib_rules_ops *tmpl, struct net *net)
154 {
155 	struct fib_rules_ops *ops;
156 	int err;
157 
158 	ops = kmemdup(tmpl, sizeof(*ops), GFP_KERNEL);
159 	if (ops == NULL)
160 		return ERR_PTR(-ENOMEM);
161 
162 	INIT_LIST_HEAD(&ops->rules_list);
163 	ops->fro_net = net;
164 
165 	err = __fib_rules_register(ops);
166 	if (err) {
167 		kfree(ops);
168 		ops = ERR_PTR(err);
169 	}
170 
171 	return ops;
172 }
173 EXPORT_SYMBOL_GPL(fib_rules_register);
174 
175 static void fib_rules_cleanup_ops(struct fib_rules_ops *ops)
176 {
177 	struct fib_rule *rule, *tmp;
178 
179 	list_for_each_entry_safe(rule, tmp, &ops->rules_list, list) {
180 		list_del_rcu(&rule->list);
181 		if (ops->delete)
182 			ops->delete(rule);
183 		fib_rule_put(rule);
184 	}
185 }
186 
187 void fib_rules_unregister(struct fib_rules_ops *ops)
188 {
189 	struct net *net = ops->fro_net;
190 
191 	spin_lock(&net->rules_mod_lock);
192 	list_del_rcu(&ops->list);
193 	spin_unlock(&net->rules_mod_lock);
194 
195 	fib_rules_cleanup_ops(ops);
196 	kfree_rcu(ops, rcu);
197 }
198 EXPORT_SYMBOL_GPL(fib_rules_unregister);
199 
200 static int uid_range_set(struct fib_kuid_range *range)
201 {
202 	return uid_valid(range->start) && uid_valid(range->end);
203 }
204 
205 static struct fib_kuid_range nla_get_kuid_range(struct nlattr **tb)
206 {
207 	struct fib_rule_uid_range *in;
208 	struct fib_kuid_range out;
209 
210 	in = (struct fib_rule_uid_range *)nla_data(tb[FRA_UID_RANGE]);
211 
212 	out.start = make_kuid(current_user_ns(), in->start);
213 	out.end = make_kuid(current_user_ns(), in->end);
214 
215 	return out;
216 }
217 
218 static int nla_put_uid_range(struct sk_buff *skb, struct fib_kuid_range *range)
219 {
220 	struct fib_rule_uid_range out = {
221 		from_kuid_munged(current_user_ns(), range->start),
222 		from_kuid_munged(current_user_ns(), range->end)
223 	};
224 
225 	return nla_put(skb, FRA_UID_RANGE, sizeof(out), &out);
226 }
227 
228 static int nla_get_port_range(struct nlattr *pattr,
229 			      struct fib_rule_port_range *port_range)
230 {
231 	const struct fib_rule_port_range *pr = nla_data(pattr);
232 
233 	if (!fib_rule_port_range_valid(pr))
234 		return -EINVAL;
235 
236 	port_range->start = pr->start;
237 	port_range->end = pr->end;
238 
239 	return 0;
240 }
241 
242 static int nla_put_port_range(struct sk_buff *skb, int attrtype,
243 			      struct fib_rule_port_range *range)
244 {
245 	return nla_put(skb, attrtype, sizeof(*range), range);
246 }
247 
248 static int fib_rule_match(struct fib_rule *rule, struct fib_rules_ops *ops,
249 			  struct flowi *fl, int flags,
250 			  struct fib_lookup_arg *arg)
251 {
252 	int ret = 0;
253 
254 	if (rule->iifindex && (rule->iifindex != fl->flowi_iif))
255 		goto out;
256 
257 	if (rule->oifindex && (rule->oifindex != fl->flowi_oif))
258 		goto out;
259 
260 	if ((rule->mark ^ fl->flowi_mark) & rule->mark_mask)
261 		goto out;
262 
263 	if (rule->tun_id && (rule->tun_id != fl->flowi_tun_key.tun_id))
264 		goto out;
265 
266 	if (rule->l3mdev && !l3mdev_fib_rule_match(rule->fr_net, fl, arg))
267 		goto out;
268 
269 	if (uid_lt(fl->flowi_uid, rule->uid_range.start) ||
270 	    uid_gt(fl->flowi_uid, rule->uid_range.end))
271 		goto out;
272 
273 	ret = ops->match(rule, fl, flags);
274 out:
275 	return (rule->flags & FIB_RULE_INVERT) ? !ret : ret;
276 }
277 
278 int fib_rules_lookup(struct fib_rules_ops *ops, struct flowi *fl,
279 		     int flags, struct fib_lookup_arg *arg)
280 {
281 	struct fib_rule *rule;
282 	int err;
283 
284 	rcu_read_lock();
285 
286 	list_for_each_entry_rcu(rule, &ops->rules_list, list) {
287 jumped:
288 		if (!fib_rule_match(rule, ops, fl, flags, arg))
289 			continue;
290 
291 		if (rule->action == FR_ACT_GOTO) {
292 			struct fib_rule *target;
293 
294 			target = rcu_dereference(rule->ctarget);
295 			if (target == NULL) {
296 				continue;
297 			} else {
298 				rule = target;
299 				goto jumped;
300 			}
301 		} else if (rule->action == FR_ACT_NOP)
302 			continue;
303 		else
304 			err = ops->action(rule, fl, flags, arg);
305 
306 		if (!err && ops->suppress && ops->suppress(rule, arg))
307 			continue;
308 
309 		if (err != -EAGAIN) {
310 			if ((arg->flags & FIB_LOOKUP_NOREF) ||
311 			    likely(refcount_inc_not_zero(&rule->refcnt))) {
312 				arg->rule = rule;
313 				goto out;
314 			}
315 			break;
316 		}
317 	}
318 
319 	err = -ESRCH;
320 out:
321 	rcu_read_unlock();
322 
323 	return err;
324 }
325 EXPORT_SYMBOL_GPL(fib_rules_lookup);
326 
327 static int call_fib_rule_notifier(struct notifier_block *nb, struct net *net,
328 				  enum fib_event_type event_type,
329 				  struct fib_rule *rule, int family)
330 {
331 	struct fib_rule_notifier_info info = {
332 		.info.family = family,
333 		.rule = rule,
334 	};
335 
336 	return call_fib_notifier(nb, net, event_type, &info.info);
337 }
338 
339 static int call_fib_rule_notifiers(struct net *net,
340 				   enum fib_event_type event_type,
341 				   struct fib_rule *rule,
342 				   struct fib_rules_ops *ops,
343 				   struct netlink_ext_ack *extack)
344 {
345 	struct fib_rule_notifier_info info = {
346 		.info.family = ops->family,
347 		.info.extack = extack,
348 		.rule = rule,
349 	};
350 
351 	ops->fib_rules_seq++;
352 	return call_fib_notifiers(net, event_type, &info.info);
353 }
354 
355 /* Called with rcu_read_lock() */
356 int fib_rules_dump(struct net *net, struct notifier_block *nb, int family)
357 {
358 	struct fib_rules_ops *ops;
359 	struct fib_rule *rule;
360 
361 	ops = lookup_rules_ops(net, family);
362 	if (!ops)
363 		return -EAFNOSUPPORT;
364 	list_for_each_entry_rcu(rule, &ops->rules_list, list)
365 		call_fib_rule_notifier(nb, net, FIB_EVENT_RULE_ADD, rule,
366 				       family);
367 	rules_ops_put(ops);
368 
369 	return 0;
370 }
371 EXPORT_SYMBOL_GPL(fib_rules_dump);
372 
373 unsigned int fib_rules_seq_read(struct net *net, int family)
374 {
375 	unsigned int fib_rules_seq;
376 	struct fib_rules_ops *ops;
377 
378 	ASSERT_RTNL();
379 
380 	ops = lookup_rules_ops(net, family);
381 	if (!ops)
382 		return 0;
383 	fib_rules_seq = ops->fib_rules_seq;
384 	rules_ops_put(ops);
385 
386 	return fib_rules_seq;
387 }
388 EXPORT_SYMBOL_GPL(fib_rules_seq_read);
389 
390 static struct fib_rule *rule_find(struct fib_rules_ops *ops,
391 				  struct fib_rule_hdr *frh,
392 				  struct nlattr **tb,
393 				  struct fib_rule *rule,
394 				  bool user_priority)
395 {
396 	struct fib_rule *r;
397 
398 	list_for_each_entry(r, &ops->rules_list, list) {
399 		if (rule->action && r->action != rule->action)
400 			continue;
401 
402 		if (rule->table && r->table != rule->table)
403 			continue;
404 
405 		if (user_priority && r->pref != rule->pref)
406 			continue;
407 
408 		if (rule->iifname[0] &&
409 		    memcmp(r->iifname, rule->iifname, IFNAMSIZ))
410 			continue;
411 
412 		if (rule->oifname[0] &&
413 		    memcmp(r->oifname, rule->oifname, IFNAMSIZ))
414 			continue;
415 
416 		if (rule->mark && r->mark != rule->mark)
417 			continue;
418 
419 		if (rule->mark_mask && r->mark_mask != rule->mark_mask)
420 			continue;
421 
422 		if (rule->tun_id && r->tun_id != rule->tun_id)
423 			continue;
424 
425 		if (r->fr_net != rule->fr_net)
426 			continue;
427 
428 		if (rule->l3mdev && r->l3mdev != rule->l3mdev)
429 			continue;
430 
431 		if (uid_range_set(&rule->uid_range) &&
432 		    (!uid_eq(r->uid_range.start, rule->uid_range.start) ||
433 		    !uid_eq(r->uid_range.end, rule->uid_range.end)))
434 			continue;
435 
436 		if (rule->ip_proto && r->ip_proto != rule->ip_proto)
437 			continue;
438 
439 		if (fib_rule_port_range_set(&rule->sport_range) &&
440 		    !fib_rule_port_range_compare(&r->sport_range,
441 						 &rule->sport_range))
442 			continue;
443 
444 		if (fib_rule_port_range_set(&rule->dport_range) &&
445 		    !fib_rule_port_range_compare(&r->dport_range,
446 						 &rule->dport_range))
447 			continue;
448 
449 		if (!ops->compare(r, frh, tb))
450 			continue;
451 		return r;
452 	}
453 
454 	return NULL;
455 }
456 
457 #ifdef CONFIG_NET_L3_MASTER_DEV
458 static int fib_nl2rule_l3mdev(struct nlattr *nla, struct fib_rule *nlrule,
459 			      struct netlink_ext_ack *extack)
460 {
461 	nlrule->l3mdev = nla_get_u8(nla);
462 	if (nlrule->l3mdev != 1) {
463 		NL_SET_ERR_MSG(extack, "Invalid l3mdev attribute");
464 		return -1;
465 	}
466 
467 	return 0;
468 }
469 #else
470 static int fib_nl2rule_l3mdev(struct nlattr *nla, struct fib_rule *nlrule,
471 			      struct netlink_ext_ack *extack)
472 {
473 	NL_SET_ERR_MSG(extack, "l3mdev support is not enabled in kernel");
474 	return -1;
475 }
476 #endif
477 
478 static int fib_nl2rule(struct sk_buff *skb, struct nlmsghdr *nlh,
479 		       struct netlink_ext_ack *extack,
480 		       struct fib_rules_ops *ops,
481 		       struct nlattr *tb[],
482 		       struct fib_rule **rule,
483 		       bool *user_priority)
484 {
485 	struct net *net = sock_net(skb->sk);
486 	struct fib_rule_hdr *frh = nlmsg_data(nlh);
487 	struct fib_rule *nlrule = NULL;
488 	int err = -EINVAL;
489 
490 	if (frh->src_len)
491 		if (!tb[FRA_SRC] ||
492 		    frh->src_len > (ops->addr_size * 8) ||
493 		    nla_len(tb[FRA_SRC]) != ops->addr_size) {
494 			NL_SET_ERR_MSG(extack, "Invalid source address");
495 			goto errout;
496 	}
497 
498 	if (frh->dst_len)
499 		if (!tb[FRA_DST] ||
500 		    frh->dst_len > (ops->addr_size * 8) ||
501 		    nla_len(tb[FRA_DST]) != ops->addr_size) {
502 			NL_SET_ERR_MSG(extack, "Invalid dst address");
503 			goto errout;
504 	}
505 
506 	nlrule = kzalloc(ops->rule_size, GFP_KERNEL);
507 	if (!nlrule) {
508 		err = -ENOMEM;
509 		goto errout;
510 	}
511 	refcount_set(&nlrule->refcnt, 1);
512 	nlrule->fr_net = net;
513 
514 	if (tb[FRA_PRIORITY]) {
515 		nlrule->pref = nla_get_u32(tb[FRA_PRIORITY]);
516 		*user_priority = true;
517 	} else {
518 		nlrule->pref = fib_default_rule_pref(ops);
519 	}
520 
521 	nlrule->proto = tb[FRA_PROTOCOL] ?
522 		nla_get_u8(tb[FRA_PROTOCOL]) : RTPROT_UNSPEC;
523 
524 	if (tb[FRA_IIFNAME]) {
525 		struct net_device *dev;
526 
527 		nlrule->iifindex = -1;
528 		nla_strlcpy(nlrule->iifname, tb[FRA_IIFNAME], IFNAMSIZ);
529 		dev = __dev_get_by_name(net, nlrule->iifname);
530 		if (dev)
531 			nlrule->iifindex = dev->ifindex;
532 	}
533 
534 	if (tb[FRA_OIFNAME]) {
535 		struct net_device *dev;
536 
537 		nlrule->oifindex = -1;
538 		nla_strlcpy(nlrule->oifname, tb[FRA_OIFNAME], IFNAMSIZ);
539 		dev = __dev_get_by_name(net, nlrule->oifname);
540 		if (dev)
541 			nlrule->oifindex = dev->ifindex;
542 	}
543 
544 	if (tb[FRA_FWMARK]) {
545 		nlrule->mark = nla_get_u32(tb[FRA_FWMARK]);
546 		if (nlrule->mark)
547 			/* compatibility: if the mark value is non-zero all bits
548 			 * are compared unless a mask is explicitly specified.
549 			 */
550 			nlrule->mark_mask = 0xFFFFFFFF;
551 	}
552 
553 	if (tb[FRA_FWMASK])
554 		nlrule->mark_mask = nla_get_u32(tb[FRA_FWMASK]);
555 
556 	if (tb[FRA_TUN_ID])
557 		nlrule->tun_id = nla_get_be64(tb[FRA_TUN_ID]);
558 
559 	err = -EINVAL;
560 	if (tb[FRA_L3MDEV] &&
561 	    fib_nl2rule_l3mdev(tb[FRA_L3MDEV], nlrule, extack) < 0)
562 		goto errout_free;
563 
564 	nlrule->action = frh->action;
565 	nlrule->flags = frh->flags;
566 	nlrule->table = frh_get_table(frh, tb);
567 	if (tb[FRA_SUPPRESS_PREFIXLEN])
568 		nlrule->suppress_prefixlen = nla_get_u32(tb[FRA_SUPPRESS_PREFIXLEN]);
569 	else
570 		nlrule->suppress_prefixlen = -1;
571 
572 	if (tb[FRA_SUPPRESS_IFGROUP])
573 		nlrule->suppress_ifgroup = nla_get_u32(tb[FRA_SUPPRESS_IFGROUP]);
574 	else
575 		nlrule->suppress_ifgroup = -1;
576 
577 	if (tb[FRA_GOTO]) {
578 		if (nlrule->action != FR_ACT_GOTO) {
579 			NL_SET_ERR_MSG(extack, "Unexpected goto");
580 			goto errout_free;
581 		}
582 
583 		nlrule->target = nla_get_u32(tb[FRA_GOTO]);
584 		/* Backward jumps are prohibited to avoid endless loops */
585 		if (nlrule->target <= nlrule->pref) {
586 			NL_SET_ERR_MSG(extack, "Backward goto not supported");
587 			goto errout_free;
588 		}
589 	} else if (nlrule->action == FR_ACT_GOTO) {
590 		NL_SET_ERR_MSG(extack, "Missing goto target for action goto");
591 		goto errout_free;
592 	}
593 
594 	if (nlrule->l3mdev && nlrule->table) {
595 		NL_SET_ERR_MSG(extack, "l3mdev and table are mutually exclusive");
596 		goto errout_free;
597 	}
598 
599 	if (tb[FRA_UID_RANGE]) {
600 		if (current_user_ns() != net->user_ns) {
601 			err = -EPERM;
602 			NL_SET_ERR_MSG(extack, "No permission to set uid");
603 			goto errout_free;
604 		}
605 
606 		nlrule->uid_range = nla_get_kuid_range(tb);
607 
608 		if (!uid_range_set(&nlrule->uid_range) ||
609 		    !uid_lte(nlrule->uid_range.start, nlrule->uid_range.end)) {
610 			NL_SET_ERR_MSG(extack, "Invalid uid range");
611 			goto errout_free;
612 		}
613 	} else {
614 		nlrule->uid_range = fib_kuid_range_unset;
615 	}
616 
617 	if (tb[FRA_IP_PROTO])
618 		nlrule->ip_proto = nla_get_u8(tb[FRA_IP_PROTO]);
619 
620 	if (tb[FRA_SPORT_RANGE]) {
621 		err = nla_get_port_range(tb[FRA_SPORT_RANGE],
622 					 &nlrule->sport_range);
623 		if (err) {
624 			NL_SET_ERR_MSG(extack, "Invalid sport range");
625 			goto errout_free;
626 		}
627 	}
628 
629 	if (tb[FRA_DPORT_RANGE]) {
630 		err = nla_get_port_range(tb[FRA_DPORT_RANGE],
631 					 &nlrule->dport_range);
632 		if (err) {
633 			NL_SET_ERR_MSG(extack, "Invalid dport range");
634 			goto errout_free;
635 		}
636 	}
637 
638 	*rule = nlrule;
639 
640 	return 0;
641 
642 errout_free:
643 	kfree(nlrule);
644 errout:
645 	return err;
646 }
647 
648 int fib_nl_newrule(struct sk_buff *skb, struct nlmsghdr *nlh,
649 		   struct netlink_ext_ack *extack)
650 {
651 	struct net *net = sock_net(skb->sk);
652 	struct fib_rule_hdr *frh = nlmsg_data(nlh);
653 	struct fib_rules_ops *ops = NULL;
654 	struct fib_rule *rule = NULL, *r, *last = NULL;
655 	struct nlattr *tb[FRA_MAX + 1];
656 	int err = -EINVAL, unresolved = 0;
657 	bool user_priority = false;
658 
659 	if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*frh))) {
660 		NL_SET_ERR_MSG(extack, "Invalid msg length");
661 		goto errout;
662 	}
663 
664 	ops = lookup_rules_ops(net, frh->family);
665 	if (!ops) {
666 		err = -EAFNOSUPPORT;
667 		NL_SET_ERR_MSG(extack, "Rule family not supported");
668 		goto errout;
669 	}
670 
671 	err = nlmsg_parse(nlh, sizeof(*frh), tb, FRA_MAX, ops->policy, extack);
672 	if (err < 0) {
673 		NL_SET_ERR_MSG(extack, "Error parsing msg");
674 		goto errout;
675 	}
676 
677 	err = fib_nl2rule(skb, nlh, extack, ops, tb, &rule, &user_priority);
678 	if (err)
679 		goto errout;
680 
681 	if ((nlh->nlmsg_flags & NLM_F_EXCL) &&
682 	    rule_find(ops, frh, tb, rule, user_priority)) {
683 		err = -EEXIST;
684 		goto errout_free;
685 	}
686 
687 	err = ops->configure(rule, skb, frh, tb, extack);
688 	if (err < 0)
689 		goto errout_free;
690 
691 	err = call_fib_rule_notifiers(net, FIB_EVENT_RULE_ADD, rule, ops,
692 				      extack);
693 	if (err < 0)
694 		goto errout_free;
695 
696 	list_for_each_entry(r, &ops->rules_list, list) {
697 		if (r->pref == rule->target) {
698 			RCU_INIT_POINTER(rule->ctarget, r);
699 			break;
700 		}
701 	}
702 
703 	if (rcu_dereference_protected(rule->ctarget, 1) == NULL)
704 		unresolved = 1;
705 
706 	list_for_each_entry(r, &ops->rules_list, list) {
707 		if (r->pref > rule->pref)
708 			break;
709 		last = r;
710 	}
711 
712 	if (last)
713 		list_add_rcu(&rule->list, &last->list);
714 	else
715 		list_add_rcu(&rule->list, &ops->rules_list);
716 
717 	if (ops->unresolved_rules) {
718 		/*
719 		 * There are unresolved goto rules in the list, check if
720 		 * any of them are pointing to this new rule.
721 		 */
722 		list_for_each_entry(r, &ops->rules_list, list) {
723 			if (r->action == FR_ACT_GOTO &&
724 			    r->target == rule->pref &&
725 			    rtnl_dereference(r->ctarget) == NULL) {
726 				rcu_assign_pointer(r->ctarget, rule);
727 				if (--ops->unresolved_rules == 0)
728 					break;
729 			}
730 		}
731 	}
732 
733 	if (rule->action == FR_ACT_GOTO)
734 		ops->nr_goto_rules++;
735 
736 	if (unresolved)
737 		ops->unresolved_rules++;
738 
739 	if (rule->tun_id)
740 		ip_tunnel_need_metadata();
741 
742 	notify_rule_change(RTM_NEWRULE, rule, ops, nlh, NETLINK_CB(skb).portid);
743 	flush_route_cache(ops);
744 	rules_ops_put(ops);
745 	return 0;
746 
747 errout_free:
748 	kfree(rule);
749 errout:
750 	rules_ops_put(ops);
751 	return err;
752 }
753 EXPORT_SYMBOL_GPL(fib_nl_newrule);
754 
755 int fib_nl_delrule(struct sk_buff *skb, struct nlmsghdr *nlh,
756 		   struct netlink_ext_ack *extack)
757 {
758 	struct net *net = sock_net(skb->sk);
759 	struct fib_rule_hdr *frh = nlmsg_data(nlh);
760 	struct fib_rules_ops *ops = NULL;
761 	struct fib_rule *rule = NULL, *r, *nlrule = NULL;
762 	struct nlattr *tb[FRA_MAX+1];
763 	int err = -EINVAL;
764 	bool user_priority = false;
765 
766 	if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*frh))) {
767 		NL_SET_ERR_MSG(extack, "Invalid msg length");
768 		goto errout;
769 	}
770 
771 	ops = lookup_rules_ops(net, frh->family);
772 	if (ops == NULL) {
773 		err = -EAFNOSUPPORT;
774 		NL_SET_ERR_MSG(extack, "Rule family not supported");
775 		goto errout;
776 	}
777 
778 	err = nlmsg_parse(nlh, sizeof(*frh), tb, FRA_MAX, ops->policy, extack);
779 	if (err < 0) {
780 		NL_SET_ERR_MSG(extack, "Error parsing msg");
781 		goto errout;
782 	}
783 
784 	err = fib_nl2rule(skb, nlh, extack, ops, tb, &nlrule, &user_priority);
785 	if (err)
786 		goto errout;
787 
788 	rule = rule_find(ops, frh, tb, nlrule, user_priority);
789 	if (!rule) {
790 		err = -ENOENT;
791 		goto errout;
792 	}
793 
794 	if (rule->flags & FIB_RULE_PERMANENT) {
795 		err = -EPERM;
796 		goto errout;
797 	}
798 
799 	if (ops->delete) {
800 		err = ops->delete(rule);
801 		if (err)
802 			goto errout;
803 	}
804 
805 	if (rule->tun_id)
806 		ip_tunnel_unneed_metadata();
807 
808 	list_del_rcu(&rule->list);
809 
810 	if (rule->action == FR_ACT_GOTO) {
811 		ops->nr_goto_rules--;
812 		if (rtnl_dereference(rule->ctarget) == NULL)
813 			ops->unresolved_rules--;
814 	}
815 
816 	/*
817 	 * Check if this rule is a target to any of them. If so,
818 	 * adjust to the next one with the same preference or
819 	 * disable them. As this operation is eventually very
820 	 * expensive, it is only performed if goto rules, except
821 	 * current if it is goto rule, have actually been added.
822 	 */
823 	if (ops->nr_goto_rules > 0) {
824 		struct fib_rule *n;
825 
826 		n = list_next_entry(rule, list);
827 		if (&n->list == &ops->rules_list || n->pref != rule->pref)
828 			n = NULL;
829 		list_for_each_entry(r, &ops->rules_list, list) {
830 			if (rtnl_dereference(r->ctarget) != rule)
831 				continue;
832 			rcu_assign_pointer(r->ctarget, n);
833 			if (!n)
834 				ops->unresolved_rules++;
835 		}
836 	}
837 
838 	call_fib_rule_notifiers(net, FIB_EVENT_RULE_DEL, rule, ops,
839 				NULL);
840 	notify_rule_change(RTM_DELRULE, rule, ops, nlh,
841 			   NETLINK_CB(skb).portid);
842 	fib_rule_put(rule);
843 	flush_route_cache(ops);
844 	rules_ops_put(ops);
845 	kfree(nlrule);
846 	return 0;
847 
848 errout:
849 	if (nlrule)
850 		kfree(nlrule);
851 	rules_ops_put(ops);
852 	return err;
853 }
854 EXPORT_SYMBOL_GPL(fib_nl_delrule);
855 
856 static inline size_t fib_rule_nlmsg_size(struct fib_rules_ops *ops,
857 					 struct fib_rule *rule)
858 {
859 	size_t payload = NLMSG_ALIGN(sizeof(struct fib_rule_hdr))
860 			 + nla_total_size(IFNAMSIZ) /* FRA_IIFNAME */
861 			 + nla_total_size(IFNAMSIZ) /* FRA_OIFNAME */
862 			 + nla_total_size(4) /* FRA_PRIORITY */
863 			 + nla_total_size(4) /* FRA_TABLE */
864 			 + nla_total_size(4) /* FRA_SUPPRESS_PREFIXLEN */
865 			 + nla_total_size(4) /* FRA_SUPPRESS_IFGROUP */
866 			 + nla_total_size(4) /* FRA_FWMARK */
867 			 + nla_total_size(4) /* FRA_FWMASK */
868 			 + nla_total_size_64bit(8) /* FRA_TUN_ID */
869 			 + nla_total_size(sizeof(struct fib_kuid_range))
870 			 + nla_total_size(1) /* FRA_PROTOCOL */
871 			 + nla_total_size(1) /* FRA_IP_PROTO */
872 			 + nla_total_size(sizeof(struct fib_rule_port_range)) /* FRA_SPORT_RANGE */
873 			 + nla_total_size(sizeof(struct fib_rule_port_range)); /* FRA_DPORT_RANGE */
874 
875 	if (ops->nlmsg_payload)
876 		payload += ops->nlmsg_payload(rule);
877 
878 	return payload;
879 }
880 
881 static int fib_nl_fill_rule(struct sk_buff *skb, struct fib_rule *rule,
882 			    u32 pid, u32 seq, int type, int flags,
883 			    struct fib_rules_ops *ops)
884 {
885 	struct nlmsghdr *nlh;
886 	struct fib_rule_hdr *frh;
887 
888 	nlh = nlmsg_put(skb, pid, seq, type, sizeof(*frh), flags);
889 	if (nlh == NULL)
890 		return -EMSGSIZE;
891 
892 	frh = nlmsg_data(nlh);
893 	frh->family = ops->family;
894 	frh->table = rule->table;
895 	if (nla_put_u32(skb, FRA_TABLE, rule->table))
896 		goto nla_put_failure;
897 	if (nla_put_u32(skb, FRA_SUPPRESS_PREFIXLEN, rule->suppress_prefixlen))
898 		goto nla_put_failure;
899 	frh->res1 = 0;
900 	frh->res2 = 0;
901 	frh->action = rule->action;
902 	frh->flags = rule->flags;
903 
904 	if (nla_put_u8(skb, FRA_PROTOCOL, rule->proto))
905 		goto nla_put_failure;
906 
907 	if (rule->action == FR_ACT_GOTO &&
908 	    rcu_access_pointer(rule->ctarget) == NULL)
909 		frh->flags |= FIB_RULE_UNRESOLVED;
910 
911 	if (rule->iifname[0]) {
912 		if (nla_put_string(skb, FRA_IIFNAME, rule->iifname))
913 			goto nla_put_failure;
914 		if (rule->iifindex == -1)
915 			frh->flags |= FIB_RULE_IIF_DETACHED;
916 	}
917 
918 	if (rule->oifname[0]) {
919 		if (nla_put_string(skb, FRA_OIFNAME, rule->oifname))
920 			goto nla_put_failure;
921 		if (rule->oifindex == -1)
922 			frh->flags |= FIB_RULE_OIF_DETACHED;
923 	}
924 
925 	if ((rule->pref &&
926 	     nla_put_u32(skb, FRA_PRIORITY, rule->pref)) ||
927 	    (rule->mark &&
928 	     nla_put_u32(skb, FRA_FWMARK, rule->mark)) ||
929 	    ((rule->mark_mask || rule->mark) &&
930 	     nla_put_u32(skb, FRA_FWMASK, rule->mark_mask)) ||
931 	    (rule->target &&
932 	     nla_put_u32(skb, FRA_GOTO, rule->target)) ||
933 	    (rule->tun_id &&
934 	     nla_put_be64(skb, FRA_TUN_ID, rule->tun_id, FRA_PAD)) ||
935 	    (rule->l3mdev &&
936 	     nla_put_u8(skb, FRA_L3MDEV, rule->l3mdev)) ||
937 	    (uid_range_set(&rule->uid_range) &&
938 	     nla_put_uid_range(skb, &rule->uid_range)) ||
939 	    (fib_rule_port_range_set(&rule->sport_range) &&
940 	     nla_put_port_range(skb, FRA_SPORT_RANGE, &rule->sport_range)) ||
941 	    (fib_rule_port_range_set(&rule->dport_range) &&
942 	     nla_put_port_range(skb, FRA_DPORT_RANGE, &rule->dport_range)) ||
943 	    (rule->ip_proto && nla_put_u8(skb, FRA_IP_PROTO, rule->ip_proto)))
944 		goto nla_put_failure;
945 
946 	if (rule->suppress_ifgroup != -1) {
947 		if (nla_put_u32(skb, FRA_SUPPRESS_IFGROUP, rule->suppress_ifgroup))
948 			goto nla_put_failure;
949 	}
950 
951 	if (ops->fill(rule, skb, frh) < 0)
952 		goto nla_put_failure;
953 
954 	nlmsg_end(skb, nlh);
955 	return 0;
956 
957 nla_put_failure:
958 	nlmsg_cancel(skb, nlh);
959 	return -EMSGSIZE;
960 }
961 
962 static int dump_rules(struct sk_buff *skb, struct netlink_callback *cb,
963 		      struct fib_rules_ops *ops)
964 {
965 	int idx = 0;
966 	struct fib_rule *rule;
967 	int err = 0;
968 
969 	rcu_read_lock();
970 	list_for_each_entry_rcu(rule, &ops->rules_list, list) {
971 		if (idx < cb->args[1])
972 			goto skip;
973 
974 		err = fib_nl_fill_rule(skb, rule, NETLINK_CB(cb->skb).portid,
975 				       cb->nlh->nlmsg_seq, RTM_NEWRULE,
976 				       NLM_F_MULTI, ops);
977 		if (err)
978 			break;
979 skip:
980 		idx++;
981 	}
982 	rcu_read_unlock();
983 	cb->args[1] = idx;
984 	rules_ops_put(ops);
985 
986 	return err;
987 }
988 
989 static int fib_nl_dumprule(struct sk_buff *skb, struct netlink_callback *cb)
990 {
991 	struct net *net = sock_net(skb->sk);
992 	struct fib_rules_ops *ops;
993 	int idx = 0, family;
994 
995 	family = rtnl_msg_family(cb->nlh);
996 	if (family != AF_UNSPEC) {
997 		/* Protocol specific dump request */
998 		ops = lookup_rules_ops(net, family);
999 		if (ops == NULL)
1000 			return -EAFNOSUPPORT;
1001 
1002 		dump_rules(skb, cb, ops);
1003 
1004 		return skb->len;
1005 	}
1006 
1007 	rcu_read_lock();
1008 	list_for_each_entry_rcu(ops, &net->rules_ops, list) {
1009 		if (idx < cb->args[0] || !try_module_get(ops->owner))
1010 			goto skip;
1011 
1012 		if (dump_rules(skb, cb, ops) < 0)
1013 			break;
1014 
1015 		cb->args[1] = 0;
1016 skip:
1017 		idx++;
1018 	}
1019 	rcu_read_unlock();
1020 	cb->args[0] = idx;
1021 
1022 	return skb->len;
1023 }
1024 
1025 static void notify_rule_change(int event, struct fib_rule *rule,
1026 			       struct fib_rules_ops *ops, struct nlmsghdr *nlh,
1027 			       u32 pid)
1028 {
1029 	struct net *net;
1030 	struct sk_buff *skb;
1031 	int err = -ENOBUFS;
1032 
1033 	net = ops->fro_net;
1034 	skb = nlmsg_new(fib_rule_nlmsg_size(ops, rule), GFP_KERNEL);
1035 	if (skb == NULL)
1036 		goto errout;
1037 
1038 	err = fib_nl_fill_rule(skb, rule, pid, nlh->nlmsg_seq, event, 0, ops);
1039 	if (err < 0) {
1040 		/* -EMSGSIZE implies BUG in fib_rule_nlmsg_size() */
1041 		WARN_ON(err == -EMSGSIZE);
1042 		kfree_skb(skb);
1043 		goto errout;
1044 	}
1045 
1046 	rtnl_notify(skb, net, pid, ops->nlgroup, nlh, GFP_KERNEL);
1047 	return;
1048 errout:
1049 	if (err < 0)
1050 		rtnl_set_sk_err(net, ops->nlgroup, err);
1051 }
1052 
1053 static void attach_rules(struct list_head *rules, struct net_device *dev)
1054 {
1055 	struct fib_rule *rule;
1056 
1057 	list_for_each_entry(rule, rules, list) {
1058 		if (rule->iifindex == -1 &&
1059 		    strcmp(dev->name, rule->iifname) == 0)
1060 			rule->iifindex = dev->ifindex;
1061 		if (rule->oifindex == -1 &&
1062 		    strcmp(dev->name, rule->oifname) == 0)
1063 			rule->oifindex = dev->ifindex;
1064 	}
1065 }
1066 
1067 static void detach_rules(struct list_head *rules, struct net_device *dev)
1068 {
1069 	struct fib_rule *rule;
1070 
1071 	list_for_each_entry(rule, rules, list) {
1072 		if (rule->iifindex == dev->ifindex)
1073 			rule->iifindex = -1;
1074 		if (rule->oifindex == dev->ifindex)
1075 			rule->oifindex = -1;
1076 	}
1077 }
1078 
1079 
1080 static int fib_rules_event(struct notifier_block *this, unsigned long event,
1081 			   void *ptr)
1082 {
1083 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1084 	struct net *net = dev_net(dev);
1085 	struct fib_rules_ops *ops;
1086 
1087 	ASSERT_RTNL();
1088 
1089 	switch (event) {
1090 	case NETDEV_REGISTER:
1091 		list_for_each_entry(ops, &net->rules_ops, list)
1092 			attach_rules(&ops->rules_list, dev);
1093 		break;
1094 
1095 	case NETDEV_CHANGENAME:
1096 		list_for_each_entry(ops, &net->rules_ops, list) {
1097 			detach_rules(&ops->rules_list, dev);
1098 			attach_rules(&ops->rules_list, dev);
1099 		}
1100 		break;
1101 
1102 	case NETDEV_UNREGISTER:
1103 		list_for_each_entry(ops, &net->rules_ops, list)
1104 			detach_rules(&ops->rules_list, dev);
1105 		break;
1106 	}
1107 
1108 	return NOTIFY_DONE;
1109 }
1110 
1111 static struct notifier_block fib_rules_notifier = {
1112 	.notifier_call = fib_rules_event,
1113 };
1114 
1115 static int __net_init fib_rules_net_init(struct net *net)
1116 {
1117 	INIT_LIST_HEAD(&net->rules_ops);
1118 	spin_lock_init(&net->rules_mod_lock);
1119 	return 0;
1120 }
1121 
1122 static void __net_exit fib_rules_net_exit(struct net *net)
1123 {
1124 	WARN_ON_ONCE(!list_empty(&net->rules_ops));
1125 }
1126 
1127 static struct pernet_operations fib_rules_net_ops = {
1128 	.init = fib_rules_net_init,
1129 	.exit = fib_rules_net_exit,
1130 };
1131 
1132 static int __init fib_rules_init(void)
1133 {
1134 	int err;
1135 	rtnl_register(PF_UNSPEC, RTM_NEWRULE, fib_nl_newrule, NULL, 0);
1136 	rtnl_register(PF_UNSPEC, RTM_DELRULE, fib_nl_delrule, NULL, 0);
1137 	rtnl_register(PF_UNSPEC, RTM_GETRULE, NULL, fib_nl_dumprule, 0);
1138 
1139 	err = register_pernet_subsys(&fib_rules_net_ops);
1140 	if (err < 0)
1141 		goto fail;
1142 
1143 	err = register_netdevice_notifier(&fib_rules_notifier);
1144 	if (err < 0)
1145 		goto fail_unregister;
1146 
1147 	return 0;
1148 
1149 fail_unregister:
1150 	unregister_pernet_subsys(&fib_rules_net_ops);
1151 fail:
1152 	rtnl_unregister(PF_UNSPEC, RTM_NEWRULE);
1153 	rtnl_unregister(PF_UNSPEC, RTM_DELRULE);
1154 	rtnl_unregister(PF_UNSPEC, RTM_GETRULE);
1155 	return err;
1156 }
1157 
1158 subsys_initcall(fib_rules_init);
1159