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