xref: /openbmc/linux/net/core/fib_rules.c (revision 217188d9)
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->suppress_ifgroup != -1 &&
420 		    r->suppress_ifgroup != rule->suppress_ifgroup)
421 			continue;
422 
423 		if (rule->suppress_prefixlen != -1 &&
424 		    r->suppress_prefixlen != rule->suppress_prefixlen)
425 			continue;
426 
427 		if (rule->mark_mask && r->mark_mask != rule->mark_mask)
428 			continue;
429 
430 		if (rule->tun_id && r->tun_id != rule->tun_id)
431 			continue;
432 
433 		if (r->fr_net != rule->fr_net)
434 			continue;
435 
436 		if (rule->l3mdev && r->l3mdev != rule->l3mdev)
437 			continue;
438 
439 		if (uid_range_set(&rule->uid_range) &&
440 		    (!uid_eq(r->uid_range.start, rule->uid_range.start) ||
441 		    !uid_eq(r->uid_range.end, rule->uid_range.end)))
442 			continue;
443 
444 		if (rule->ip_proto && r->ip_proto != rule->ip_proto)
445 			continue;
446 
447 		if (rule->proto && r->proto != rule->proto)
448 			continue;
449 
450 		if (fib_rule_port_range_set(&rule->sport_range) &&
451 		    !fib_rule_port_range_compare(&r->sport_range,
452 						 &rule->sport_range))
453 			continue;
454 
455 		if (fib_rule_port_range_set(&rule->dport_range) &&
456 		    !fib_rule_port_range_compare(&r->dport_range,
457 						 &rule->dport_range))
458 			continue;
459 
460 		if (!ops->compare(r, frh, tb))
461 			continue;
462 		return r;
463 	}
464 
465 	return NULL;
466 }
467 
468 #ifdef CONFIG_NET_L3_MASTER_DEV
469 static int fib_nl2rule_l3mdev(struct nlattr *nla, struct fib_rule *nlrule,
470 			      struct netlink_ext_ack *extack)
471 {
472 	nlrule->l3mdev = nla_get_u8(nla);
473 	if (nlrule->l3mdev != 1) {
474 		NL_SET_ERR_MSG(extack, "Invalid l3mdev attribute");
475 		return -1;
476 	}
477 
478 	return 0;
479 }
480 #else
481 static int fib_nl2rule_l3mdev(struct nlattr *nla, struct fib_rule *nlrule,
482 			      struct netlink_ext_ack *extack)
483 {
484 	NL_SET_ERR_MSG(extack, "l3mdev support is not enabled in kernel");
485 	return -1;
486 }
487 #endif
488 
489 static int fib_nl2rule(struct sk_buff *skb, struct nlmsghdr *nlh,
490 		       struct netlink_ext_ack *extack,
491 		       struct fib_rules_ops *ops,
492 		       struct nlattr *tb[],
493 		       struct fib_rule **rule,
494 		       bool *user_priority)
495 {
496 	struct net *net = sock_net(skb->sk);
497 	struct fib_rule_hdr *frh = nlmsg_data(nlh);
498 	struct fib_rule *nlrule = NULL;
499 	int err = -EINVAL;
500 
501 	if (frh->src_len)
502 		if (!tb[FRA_SRC] ||
503 		    frh->src_len > (ops->addr_size * 8) ||
504 		    nla_len(tb[FRA_SRC]) != ops->addr_size) {
505 			NL_SET_ERR_MSG(extack, "Invalid source address");
506 			goto errout;
507 	}
508 
509 	if (frh->dst_len)
510 		if (!tb[FRA_DST] ||
511 		    frh->dst_len > (ops->addr_size * 8) ||
512 		    nla_len(tb[FRA_DST]) != ops->addr_size) {
513 			NL_SET_ERR_MSG(extack, "Invalid dst address");
514 			goto errout;
515 	}
516 
517 	nlrule = kzalloc(ops->rule_size, GFP_KERNEL);
518 	if (!nlrule) {
519 		err = -ENOMEM;
520 		goto errout;
521 	}
522 	refcount_set(&nlrule->refcnt, 1);
523 	nlrule->fr_net = net;
524 
525 	if (tb[FRA_PRIORITY]) {
526 		nlrule->pref = nla_get_u32(tb[FRA_PRIORITY]);
527 		*user_priority = true;
528 	} else {
529 		nlrule->pref = fib_default_rule_pref(ops);
530 	}
531 
532 	nlrule->proto = tb[FRA_PROTOCOL] ?
533 		nla_get_u8(tb[FRA_PROTOCOL]) : RTPROT_UNSPEC;
534 
535 	if (tb[FRA_IIFNAME]) {
536 		struct net_device *dev;
537 
538 		nlrule->iifindex = -1;
539 		nla_strlcpy(nlrule->iifname, tb[FRA_IIFNAME], IFNAMSIZ);
540 		dev = __dev_get_by_name(net, nlrule->iifname);
541 		if (dev)
542 			nlrule->iifindex = dev->ifindex;
543 	}
544 
545 	if (tb[FRA_OIFNAME]) {
546 		struct net_device *dev;
547 
548 		nlrule->oifindex = -1;
549 		nla_strlcpy(nlrule->oifname, tb[FRA_OIFNAME], IFNAMSIZ);
550 		dev = __dev_get_by_name(net, nlrule->oifname);
551 		if (dev)
552 			nlrule->oifindex = dev->ifindex;
553 	}
554 
555 	if (tb[FRA_FWMARK]) {
556 		nlrule->mark = nla_get_u32(tb[FRA_FWMARK]);
557 		if (nlrule->mark)
558 			/* compatibility: if the mark value is non-zero all bits
559 			 * are compared unless a mask is explicitly specified.
560 			 */
561 			nlrule->mark_mask = 0xFFFFFFFF;
562 	}
563 
564 	if (tb[FRA_FWMASK])
565 		nlrule->mark_mask = nla_get_u32(tb[FRA_FWMASK]);
566 
567 	if (tb[FRA_TUN_ID])
568 		nlrule->tun_id = nla_get_be64(tb[FRA_TUN_ID]);
569 
570 	err = -EINVAL;
571 	if (tb[FRA_L3MDEV] &&
572 	    fib_nl2rule_l3mdev(tb[FRA_L3MDEV], nlrule, extack) < 0)
573 		goto errout_free;
574 
575 	nlrule->action = frh->action;
576 	nlrule->flags = frh->flags;
577 	nlrule->table = frh_get_table(frh, tb);
578 	if (tb[FRA_SUPPRESS_PREFIXLEN])
579 		nlrule->suppress_prefixlen = nla_get_u32(tb[FRA_SUPPRESS_PREFIXLEN]);
580 	else
581 		nlrule->suppress_prefixlen = -1;
582 
583 	if (tb[FRA_SUPPRESS_IFGROUP])
584 		nlrule->suppress_ifgroup = nla_get_u32(tb[FRA_SUPPRESS_IFGROUP]);
585 	else
586 		nlrule->suppress_ifgroup = -1;
587 
588 	if (tb[FRA_GOTO]) {
589 		if (nlrule->action != FR_ACT_GOTO) {
590 			NL_SET_ERR_MSG(extack, "Unexpected goto");
591 			goto errout_free;
592 		}
593 
594 		nlrule->target = nla_get_u32(tb[FRA_GOTO]);
595 		/* Backward jumps are prohibited to avoid endless loops */
596 		if (nlrule->target <= nlrule->pref) {
597 			NL_SET_ERR_MSG(extack, "Backward goto not supported");
598 			goto errout_free;
599 		}
600 	} else if (nlrule->action == FR_ACT_GOTO) {
601 		NL_SET_ERR_MSG(extack, "Missing goto target for action goto");
602 		goto errout_free;
603 	}
604 
605 	if (nlrule->l3mdev && nlrule->table) {
606 		NL_SET_ERR_MSG(extack, "l3mdev and table are mutually exclusive");
607 		goto errout_free;
608 	}
609 
610 	if (tb[FRA_UID_RANGE]) {
611 		if (current_user_ns() != net->user_ns) {
612 			err = -EPERM;
613 			NL_SET_ERR_MSG(extack, "No permission to set uid");
614 			goto errout_free;
615 		}
616 
617 		nlrule->uid_range = nla_get_kuid_range(tb);
618 
619 		if (!uid_range_set(&nlrule->uid_range) ||
620 		    !uid_lte(nlrule->uid_range.start, nlrule->uid_range.end)) {
621 			NL_SET_ERR_MSG(extack, "Invalid uid range");
622 			goto errout_free;
623 		}
624 	} else {
625 		nlrule->uid_range = fib_kuid_range_unset;
626 	}
627 
628 	if (tb[FRA_IP_PROTO])
629 		nlrule->ip_proto = nla_get_u8(tb[FRA_IP_PROTO]);
630 
631 	if (tb[FRA_SPORT_RANGE]) {
632 		err = nla_get_port_range(tb[FRA_SPORT_RANGE],
633 					 &nlrule->sport_range);
634 		if (err) {
635 			NL_SET_ERR_MSG(extack, "Invalid sport range");
636 			goto errout_free;
637 		}
638 	}
639 
640 	if (tb[FRA_DPORT_RANGE]) {
641 		err = nla_get_port_range(tb[FRA_DPORT_RANGE],
642 					 &nlrule->dport_range);
643 		if (err) {
644 			NL_SET_ERR_MSG(extack, "Invalid dport range");
645 			goto errout_free;
646 		}
647 	}
648 
649 	*rule = nlrule;
650 
651 	return 0;
652 
653 errout_free:
654 	kfree(nlrule);
655 errout:
656 	return err;
657 }
658 
659 static int rule_exists(struct fib_rules_ops *ops, struct fib_rule_hdr *frh,
660 		       struct nlattr **tb, struct fib_rule *rule)
661 {
662 	struct fib_rule *r;
663 
664 	list_for_each_entry(r, &ops->rules_list, list) {
665 		if (r->action != rule->action)
666 			continue;
667 
668 		if (r->table != rule->table)
669 			continue;
670 
671 		if (r->pref != rule->pref)
672 			continue;
673 
674 		if (memcmp(r->iifname, rule->iifname, IFNAMSIZ))
675 			continue;
676 
677 		if (memcmp(r->oifname, rule->oifname, IFNAMSIZ))
678 			continue;
679 
680 		if (r->mark != rule->mark)
681 			continue;
682 
683 		if (r->suppress_ifgroup != rule->suppress_ifgroup)
684 			continue;
685 
686 		if (r->suppress_prefixlen != rule->suppress_prefixlen)
687 			continue;
688 
689 		if (r->mark_mask != rule->mark_mask)
690 			continue;
691 
692 		if (r->tun_id != rule->tun_id)
693 			continue;
694 
695 		if (r->fr_net != rule->fr_net)
696 			continue;
697 
698 		if (r->l3mdev != rule->l3mdev)
699 			continue;
700 
701 		if (!uid_eq(r->uid_range.start, rule->uid_range.start) ||
702 		    !uid_eq(r->uid_range.end, rule->uid_range.end))
703 			continue;
704 
705 		if (r->ip_proto != rule->ip_proto)
706 			continue;
707 
708 		if (r->proto != rule->proto)
709 			continue;
710 
711 		if (!fib_rule_port_range_compare(&r->sport_range,
712 						 &rule->sport_range))
713 			continue;
714 
715 		if (!fib_rule_port_range_compare(&r->dport_range,
716 						 &rule->dport_range))
717 			continue;
718 
719 		if (!ops->compare(r, frh, tb))
720 			continue;
721 		return 1;
722 	}
723 	return 0;
724 }
725 
726 int fib_nl_newrule(struct sk_buff *skb, struct nlmsghdr *nlh,
727 		   struct netlink_ext_ack *extack)
728 {
729 	struct net *net = sock_net(skb->sk);
730 	struct fib_rule_hdr *frh = nlmsg_data(nlh);
731 	struct fib_rules_ops *ops = NULL;
732 	struct fib_rule *rule = NULL, *r, *last = NULL;
733 	struct nlattr *tb[FRA_MAX + 1];
734 	int err = -EINVAL, unresolved = 0;
735 	bool user_priority = false;
736 
737 	if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*frh))) {
738 		NL_SET_ERR_MSG(extack, "Invalid msg length");
739 		goto errout;
740 	}
741 
742 	ops = lookup_rules_ops(net, frh->family);
743 	if (!ops) {
744 		err = -EAFNOSUPPORT;
745 		NL_SET_ERR_MSG(extack, "Rule family not supported");
746 		goto errout;
747 	}
748 
749 	err = nlmsg_parse(nlh, sizeof(*frh), tb, FRA_MAX, ops->policy, extack);
750 	if (err < 0) {
751 		NL_SET_ERR_MSG(extack, "Error parsing msg");
752 		goto errout;
753 	}
754 
755 	err = fib_nl2rule(skb, nlh, extack, ops, tb, &rule, &user_priority);
756 	if (err)
757 		goto errout;
758 
759 	if ((nlh->nlmsg_flags & NLM_F_EXCL) &&
760 	    rule_exists(ops, frh, tb, rule)) {
761 		err = -EEXIST;
762 		goto errout_free;
763 	}
764 
765 	err = ops->configure(rule, skb, frh, tb, extack);
766 	if (err < 0)
767 		goto errout_free;
768 
769 	err = call_fib_rule_notifiers(net, FIB_EVENT_RULE_ADD, rule, ops,
770 				      extack);
771 	if (err < 0)
772 		goto errout_free;
773 
774 	list_for_each_entry(r, &ops->rules_list, list) {
775 		if (r->pref == rule->target) {
776 			RCU_INIT_POINTER(rule->ctarget, r);
777 			break;
778 		}
779 	}
780 
781 	if (rcu_dereference_protected(rule->ctarget, 1) == NULL)
782 		unresolved = 1;
783 
784 	list_for_each_entry(r, &ops->rules_list, list) {
785 		if (r->pref > rule->pref)
786 			break;
787 		last = r;
788 	}
789 
790 	if (last)
791 		list_add_rcu(&rule->list, &last->list);
792 	else
793 		list_add_rcu(&rule->list, &ops->rules_list);
794 
795 	if (ops->unresolved_rules) {
796 		/*
797 		 * There are unresolved goto rules in the list, check if
798 		 * any of them are pointing to this new rule.
799 		 */
800 		list_for_each_entry(r, &ops->rules_list, list) {
801 			if (r->action == FR_ACT_GOTO &&
802 			    r->target == rule->pref &&
803 			    rtnl_dereference(r->ctarget) == NULL) {
804 				rcu_assign_pointer(r->ctarget, rule);
805 				if (--ops->unresolved_rules == 0)
806 					break;
807 			}
808 		}
809 	}
810 
811 	if (rule->action == FR_ACT_GOTO)
812 		ops->nr_goto_rules++;
813 
814 	if (unresolved)
815 		ops->unresolved_rules++;
816 
817 	if (rule->tun_id)
818 		ip_tunnel_need_metadata();
819 
820 	notify_rule_change(RTM_NEWRULE, rule, ops, nlh, NETLINK_CB(skb).portid);
821 	flush_route_cache(ops);
822 	rules_ops_put(ops);
823 	return 0;
824 
825 errout_free:
826 	kfree(rule);
827 errout:
828 	rules_ops_put(ops);
829 	return err;
830 }
831 EXPORT_SYMBOL_GPL(fib_nl_newrule);
832 
833 int fib_nl_delrule(struct sk_buff *skb, struct nlmsghdr *nlh,
834 		   struct netlink_ext_ack *extack)
835 {
836 	struct net *net = sock_net(skb->sk);
837 	struct fib_rule_hdr *frh = nlmsg_data(nlh);
838 	struct fib_rules_ops *ops = NULL;
839 	struct fib_rule *rule = NULL, *r, *nlrule = NULL;
840 	struct nlattr *tb[FRA_MAX+1];
841 	int err = -EINVAL;
842 	bool user_priority = false;
843 
844 	if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*frh))) {
845 		NL_SET_ERR_MSG(extack, "Invalid msg length");
846 		goto errout;
847 	}
848 
849 	ops = lookup_rules_ops(net, frh->family);
850 	if (ops == NULL) {
851 		err = -EAFNOSUPPORT;
852 		NL_SET_ERR_MSG(extack, "Rule family not supported");
853 		goto errout;
854 	}
855 
856 	err = nlmsg_parse(nlh, sizeof(*frh), tb, FRA_MAX, ops->policy, extack);
857 	if (err < 0) {
858 		NL_SET_ERR_MSG(extack, "Error parsing msg");
859 		goto errout;
860 	}
861 
862 	err = fib_nl2rule(skb, nlh, extack, ops, tb, &nlrule, &user_priority);
863 	if (err)
864 		goto errout;
865 
866 	rule = rule_find(ops, frh, tb, nlrule, user_priority);
867 	if (!rule) {
868 		err = -ENOENT;
869 		goto errout;
870 	}
871 
872 	if (rule->flags & FIB_RULE_PERMANENT) {
873 		err = -EPERM;
874 		goto errout;
875 	}
876 
877 	if (ops->delete) {
878 		err = ops->delete(rule);
879 		if (err)
880 			goto errout;
881 	}
882 
883 	if (rule->tun_id)
884 		ip_tunnel_unneed_metadata();
885 
886 	list_del_rcu(&rule->list);
887 
888 	if (rule->action == FR_ACT_GOTO) {
889 		ops->nr_goto_rules--;
890 		if (rtnl_dereference(rule->ctarget) == NULL)
891 			ops->unresolved_rules--;
892 	}
893 
894 	/*
895 	 * Check if this rule is a target to any of them. If so,
896 	 * adjust to the next one with the same preference or
897 	 * disable them. As this operation is eventually very
898 	 * expensive, it is only performed if goto rules, except
899 	 * current if it is goto rule, have actually been added.
900 	 */
901 	if (ops->nr_goto_rules > 0) {
902 		struct fib_rule *n;
903 
904 		n = list_next_entry(rule, list);
905 		if (&n->list == &ops->rules_list || n->pref != rule->pref)
906 			n = NULL;
907 		list_for_each_entry(r, &ops->rules_list, list) {
908 			if (rtnl_dereference(r->ctarget) != rule)
909 				continue;
910 			rcu_assign_pointer(r->ctarget, n);
911 			if (!n)
912 				ops->unresolved_rules++;
913 		}
914 	}
915 
916 	call_fib_rule_notifiers(net, FIB_EVENT_RULE_DEL, rule, ops,
917 				NULL);
918 	notify_rule_change(RTM_DELRULE, rule, ops, nlh,
919 			   NETLINK_CB(skb).portid);
920 	fib_rule_put(rule);
921 	flush_route_cache(ops);
922 	rules_ops_put(ops);
923 	kfree(nlrule);
924 	return 0;
925 
926 errout:
927 	kfree(nlrule);
928 	rules_ops_put(ops);
929 	return err;
930 }
931 EXPORT_SYMBOL_GPL(fib_nl_delrule);
932 
933 static inline size_t fib_rule_nlmsg_size(struct fib_rules_ops *ops,
934 					 struct fib_rule *rule)
935 {
936 	size_t payload = NLMSG_ALIGN(sizeof(struct fib_rule_hdr))
937 			 + nla_total_size(IFNAMSIZ) /* FRA_IIFNAME */
938 			 + nla_total_size(IFNAMSIZ) /* FRA_OIFNAME */
939 			 + nla_total_size(4) /* FRA_PRIORITY */
940 			 + nla_total_size(4) /* FRA_TABLE */
941 			 + nla_total_size(4) /* FRA_SUPPRESS_PREFIXLEN */
942 			 + nla_total_size(4) /* FRA_SUPPRESS_IFGROUP */
943 			 + nla_total_size(4) /* FRA_FWMARK */
944 			 + nla_total_size(4) /* FRA_FWMASK */
945 			 + nla_total_size_64bit(8) /* FRA_TUN_ID */
946 			 + nla_total_size(sizeof(struct fib_kuid_range))
947 			 + nla_total_size(1) /* FRA_PROTOCOL */
948 			 + nla_total_size(1) /* FRA_IP_PROTO */
949 			 + nla_total_size(sizeof(struct fib_rule_port_range)) /* FRA_SPORT_RANGE */
950 			 + nla_total_size(sizeof(struct fib_rule_port_range)); /* FRA_DPORT_RANGE */
951 
952 	if (ops->nlmsg_payload)
953 		payload += ops->nlmsg_payload(rule);
954 
955 	return payload;
956 }
957 
958 static int fib_nl_fill_rule(struct sk_buff *skb, struct fib_rule *rule,
959 			    u32 pid, u32 seq, int type, int flags,
960 			    struct fib_rules_ops *ops)
961 {
962 	struct nlmsghdr *nlh;
963 	struct fib_rule_hdr *frh;
964 
965 	nlh = nlmsg_put(skb, pid, seq, type, sizeof(*frh), flags);
966 	if (nlh == NULL)
967 		return -EMSGSIZE;
968 
969 	frh = nlmsg_data(nlh);
970 	frh->family = ops->family;
971 	frh->table = rule->table;
972 	if (nla_put_u32(skb, FRA_TABLE, rule->table))
973 		goto nla_put_failure;
974 	if (nla_put_u32(skb, FRA_SUPPRESS_PREFIXLEN, rule->suppress_prefixlen))
975 		goto nla_put_failure;
976 	frh->res1 = 0;
977 	frh->res2 = 0;
978 	frh->action = rule->action;
979 	frh->flags = rule->flags;
980 
981 	if (nla_put_u8(skb, FRA_PROTOCOL, rule->proto))
982 		goto nla_put_failure;
983 
984 	if (rule->action == FR_ACT_GOTO &&
985 	    rcu_access_pointer(rule->ctarget) == NULL)
986 		frh->flags |= FIB_RULE_UNRESOLVED;
987 
988 	if (rule->iifname[0]) {
989 		if (nla_put_string(skb, FRA_IIFNAME, rule->iifname))
990 			goto nla_put_failure;
991 		if (rule->iifindex == -1)
992 			frh->flags |= FIB_RULE_IIF_DETACHED;
993 	}
994 
995 	if (rule->oifname[0]) {
996 		if (nla_put_string(skb, FRA_OIFNAME, rule->oifname))
997 			goto nla_put_failure;
998 		if (rule->oifindex == -1)
999 			frh->flags |= FIB_RULE_OIF_DETACHED;
1000 	}
1001 
1002 	if ((rule->pref &&
1003 	     nla_put_u32(skb, FRA_PRIORITY, rule->pref)) ||
1004 	    (rule->mark &&
1005 	     nla_put_u32(skb, FRA_FWMARK, rule->mark)) ||
1006 	    ((rule->mark_mask || rule->mark) &&
1007 	     nla_put_u32(skb, FRA_FWMASK, rule->mark_mask)) ||
1008 	    (rule->target &&
1009 	     nla_put_u32(skb, FRA_GOTO, rule->target)) ||
1010 	    (rule->tun_id &&
1011 	     nla_put_be64(skb, FRA_TUN_ID, rule->tun_id, FRA_PAD)) ||
1012 	    (rule->l3mdev &&
1013 	     nla_put_u8(skb, FRA_L3MDEV, rule->l3mdev)) ||
1014 	    (uid_range_set(&rule->uid_range) &&
1015 	     nla_put_uid_range(skb, &rule->uid_range)) ||
1016 	    (fib_rule_port_range_set(&rule->sport_range) &&
1017 	     nla_put_port_range(skb, FRA_SPORT_RANGE, &rule->sport_range)) ||
1018 	    (fib_rule_port_range_set(&rule->dport_range) &&
1019 	     nla_put_port_range(skb, FRA_DPORT_RANGE, &rule->dport_range)) ||
1020 	    (rule->ip_proto && nla_put_u8(skb, FRA_IP_PROTO, rule->ip_proto)))
1021 		goto nla_put_failure;
1022 
1023 	if (rule->suppress_ifgroup != -1) {
1024 		if (nla_put_u32(skb, FRA_SUPPRESS_IFGROUP, rule->suppress_ifgroup))
1025 			goto nla_put_failure;
1026 	}
1027 
1028 	if (ops->fill(rule, skb, frh) < 0)
1029 		goto nla_put_failure;
1030 
1031 	nlmsg_end(skb, nlh);
1032 	return 0;
1033 
1034 nla_put_failure:
1035 	nlmsg_cancel(skb, nlh);
1036 	return -EMSGSIZE;
1037 }
1038 
1039 static int dump_rules(struct sk_buff *skb, struct netlink_callback *cb,
1040 		      struct fib_rules_ops *ops)
1041 {
1042 	int idx = 0;
1043 	struct fib_rule *rule;
1044 	int err = 0;
1045 
1046 	rcu_read_lock();
1047 	list_for_each_entry_rcu(rule, &ops->rules_list, list) {
1048 		if (idx < cb->args[1])
1049 			goto skip;
1050 
1051 		err = fib_nl_fill_rule(skb, rule, NETLINK_CB(cb->skb).portid,
1052 				       cb->nlh->nlmsg_seq, RTM_NEWRULE,
1053 				       NLM_F_MULTI, ops);
1054 		if (err)
1055 			break;
1056 skip:
1057 		idx++;
1058 	}
1059 	rcu_read_unlock();
1060 	cb->args[1] = idx;
1061 	rules_ops_put(ops);
1062 
1063 	return err;
1064 }
1065 
1066 static int fib_nl_dumprule(struct sk_buff *skb, struct netlink_callback *cb)
1067 {
1068 	struct net *net = sock_net(skb->sk);
1069 	struct fib_rules_ops *ops;
1070 	int idx = 0, family;
1071 
1072 	family = rtnl_msg_family(cb->nlh);
1073 	if (family != AF_UNSPEC) {
1074 		/* Protocol specific dump request */
1075 		ops = lookup_rules_ops(net, family);
1076 		if (ops == NULL)
1077 			return -EAFNOSUPPORT;
1078 
1079 		dump_rules(skb, cb, ops);
1080 
1081 		return skb->len;
1082 	}
1083 
1084 	rcu_read_lock();
1085 	list_for_each_entry_rcu(ops, &net->rules_ops, list) {
1086 		if (idx < cb->args[0] || !try_module_get(ops->owner))
1087 			goto skip;
1088 
1089 		if (dump_rules(skb, cb, ops) < 0)
1090 			break;
1091 
1092 		cb->args[1] = 0;
1093 skip:
1094 		idx++;
1095 	}
1096 	rcu_read_unlock();
1097 	cb->args[0] = idx;
1098 
1099 	return skb->len;
1100 }
1101 
1102 static void notify_rule_change(int event, struct fib_rule *rule,
1103 			       struct fib_rules_ops *ops, struct nlmsghdr *nlh,
1104 			       u32 pid)
1105 {
1106 	struct net *net;
1107 	struct sk_buff *skb;
1108 	int err = -ENOBUFS;
1109 
1110 	net = ops->fro_net;
1111 	skb = nlmsg_new(fib_rule_nlmsg_size(ops, rule), GFP_KERNEL);
1112 	if (skb == NULL)
1113 		goto errout;
1114 
1115 	err = fib_nl_fill_rule(skb, rule, pid, nlh->nlmsg_seq, event, 0, ops);
1116 	if (err < 0) {
1117 		/* -EMSGSIZE implies BUG in fib_rule_nlmsg_size() */
1118 		WARN_ON(err == -EMSGSIZE);
1119 		kfree_skb(skb);
1120 		goto errout;
1121 	}
1122 
1123 	rtnl_notify(skb, net, pid, ops->nlgroup, nlh, GFP_KERNEL);
1124 	return;
1125 errout:
1126 	if (err < 0)
1127 		rtnl_set_sk_err(net, ops->nlgroup, err);
1128 }
1129 
1130 static void attach_rules(struct list_head *rules, struct net_device *dev)
1131 {
1132 	struct fib_rule *rule;
1133 
1134 	list_for_each_entry(rule, rules, list) {
1135 		if (rule->iifindex == -1 &&
1136 		    strcmp(dev->name, rule->iifname) == 0)
1137 			rule->iifindex = dev->ifindex;
1138 		if (rule->oifindex == -1 &&
1139 		    strcmp(dev->name, rule->oifname) == 0)
1140 			rule->oifindex = dev->ifindex;
1141 	}
1142 }
1143 
1144 static void detach_rules(struct list_head *rules, struct net_device *dev)
1145 {
1146 	struct fib_rule *rule;
1147 
1148 	list_for_each_entry(rule, rules, list) {
1149 		if (rule->iifindex == dev->ifindex)
1150 			rule->iifindex = -1;
1151 		if (rule->oifindex == dev->ifindex)
1152 			rule->oifindex = -1;
1153 	}
1154 }
1155 
1156 
1157 static int fib_rules_event(struct notifier_block *this, unsigned long event,
1158 			   void *ptr)
1159 {
1160 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1161 	struct net *net = dev_net(dev);
1162 	struct fib_rules_ops *ops;
1163 
1164 	ASSERT_RTNL();
1165 
1166 	switch (event) {
1167 	case NETDEV_REGISTER:
1168 		list_for_each_entry(ops, &net->rules_ops, list)
1169 			attach_rules(&ops->rules_list, dev);
1170 		break;
1171 
1172 	case NETDEV_CHANGENAME:
1173 		list_for_each_entry(ops, &net->rules_ops, list) {
1174 			detach_rules(&ops->rules_list, dev);
1175 			attach_rules(&ops->rules_list, dev);
1176 		}
1177 		break;
1178 
1179 	case NETDEV_UNREGISTER:
1180 		list_for_each_entry(ops, &net->rules_ops, list)
1181 			detach_rules(&ops->rules_list, dev);
1182 		break;
1183 	}
1184 
1185 	return NOTIFY_DONE;
1186 }
1187 
1188 static struct notifier_block fib_rules_notifier = {
1189 	.notifier_call = fib_rules_event,
1190 };
1191 
1192 static int __net_init fib_rules_net_init(struct net *net)
1193 {
1194 	INIT_LIST_HEAD(&net->rules_ops);
1195 	spin_lock_init(&net->rules_mod_lock);
1196 	return 0;
1197 }
1198 
1199 static void __net_exit fib_rules_net_exit(struct net *net)
1200 {
1201 	WARN_ON_ONCE(!list_empty(&net->rules_ops));
1202 }
1203 
1204 static struct pernet_operations fib_rules_net_ops = {
1205 	.init = fib_rules_net_init,
1206 	.exit = fib_rules_net_exit,
1207 };
1208 
1209 static int __init fib_rules_init(void)
1210 {
1211 	int err;
1212 	rtnl_register(PF_UNSPEC, RTM_NEWRULE, fib_nl_newrule, NULL, 0);
1213 	rtnl_register(PF_UNSPEC, RTM_DELRULE, fib_nl_delrule, NULL, 0);
1214 	rtnl_register(PF_UNSPEC, RTM_GETRULE, NULL, fib_nl_dumprule, 0);
1215 
1216 	err = register_pernet_subsys(&fib_rules_net_ops);
1217 	if (err < 0)
1218 		goto fail;
1219 
1220 	err = register_netdevice_notifier(&fib_rules_notifier);
1221 	if (err < 0)
1222 		goto fail_unregister;
1223 
1224 	return 0;
1225 
1226 fail_unregister:
1227 	unregister_pernet_subsys(&fib_rules_net_ops);
1228 fail:
1229 	rtnl_unregister(PF_UNSPEC, RTM_NEWRULE);
1230 	rtnl_unregister(PF_UNSPEC, RTM_DELRULE);
1231 	rtnl_unregister(PF_UNSPEC, RTM_GETRULE);
1232 	return err;
1233 }
1234 
1235 subsys_initcall(fib_rules_init);
1236