xref: /openbmc/linux/net/xfrm/xfrm_policy.c (revision c1530660)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * xfrm_policy.c
4  *
5  * Changes:
6  *	Mitsuru KANDA @USAGI
7  * 	Kazunori MIYAZAWA @USAGI
8  * 	Kunihiro Ishiguro <kunihiro@ipinfusion.com>
9  * 		IPv6 support
10  * 	Kazunori MIYAZAWA @USAGI
11  * 	YOSHIFUJI Hideaki
12  * 		Split up af-specific portion
13  *	Derek Atkins <derek@ihtfp.com>		Add the post_input processor
14  *
15  */
16 
17 #include <linux/err.h>
18 #include <linux/slab.h>
19 #include <linux/kmod.h>
20 #include <linux/list.h>
21 #include <linux/spinlock.h>
22 #include <linux/workqueue.h>
23 #include <linux/notifier.h>
24 #include <linux/netdevice.h>
25 #include <linux/netfilter.h>
26 #include <linux/module.h>
27 #include <linux/cache.h>
28 #include <linux/cpu.h>
29 #include <linux/audit.h>
30 #include <linux/rhashtable.h>
31 #include <linux/if_tunnel.h>
32 #include <net/dst.h>
33 #include <net/flow.h>
34 #include <net/inet_ecn.h>
35 #include <net/xfrm.h>
36 #include <net/ip.h>
37 #include <net/gre.h>
38 #if IS_ENABLED(CONFIG_IPV6_MIP6)
39 #include <net/mip6.h>
40 #endif
41 #ifdef CONFIG_XFRM_STATISTICS
42 #include <net/snmp.h>
43 #endif
44 #ifdef CONFIG_XFRM_ESPINTCP
45 #include <net/espintcp.h>
46 #endif
47 
48 #include "xfrm_hash.h"
49 
50 #define XFRM_QUEUE_TMO_MIN ((unsigned)(HZ/10))
51 #define XFRM_QUEUE_TMO_MAX ((unsigned)(60*HZ))
52 #define XFRM_MAX_QUEUE_LEN	100
53 
54 struct xfrm_flo {
55 	struct dst_entry *dst_orig;
56 	u8 flags;
57 };
58 
59 /* prefixes smaller than this are stored in lists, not trees. */
60 #define INEXACT_PREFIXLEN_IPV4	16
61 #define INEXACT_PREFIXLEN_IPV6	48
62 
63 struct xfrm_pol_inexact_node {
64 	struct rb_node node;
65 	union {
66 		xfrm_address_t addr;
67 		struct rcu_head rcu;
68 	};
69 	u8 prefixlen;
70 
71 	struct rb_root root;
72 
73 	/* the policies matching this node, can be empty list */
74 	struct hlist_head hhead;
75 };
76 
77 /* xfrm inexact policy search tree:
78  * xfrm_pol_inexact_bin = hash(dir,type,family,if_id);
79  *  |
80  * +---- root_d: sorted by daddr:prefix
81  * |                 |
82  * |        xfrm_pol_inexact_node
83  * |                 |
84  * |                 +- root: sorted by saddr/prefix
85  * |                 |              |
86  * |                 |         xfrm_pol_inexact_node
87  * |                 |              |
88  * |                 |              + root: unused
89  * |                 |              |
90  * |                 |              + hhead: saddr:daddr policies
91  * |                 |
92  * |                 +- coarse policies and all any:daddr policies
93  * |
94  * +---- root_s: sorted by saddr:prefix
95  * |                 |
96  * |        xfrm_pol_inexact_node
97  * |                 |
98  * |                 + root: unused
99  * |                 |
100  * |                 + hhead: saddr:any policies
101  * |
102  * +---- coarse policies and all any:any policies
103  *
104  * Lookups return four candidate lists:
105  * 1. any:any list from top-level xfrm_pol_inexact_bin
106  * 2. any:daddr list from daddr tree
107  * 3. saddr:daddr list from 2nd level daddr tree
108  * 4. saddr:any list from saddr tree
109  *
110  * This result set then needs to be searched for the policy with
111  * the lowest priority.  If two results have same prio, youngest one wins.
112  */
113 
114 struct xfrm_pol_inexact_key {
115 	possible_net_t net;
116 	u32 if_id;
117 	u16 family;
118 	u8 dir, type;
119 };
120 
121 struct xfrm_pol_inexact_bin {
122 	struct xfrm_pol_inexact_key k;
123 	struct rhash_head head;
124 	/* list containing '*:*' policies */
125 	struct hlist_head hhead;
126 
127 	seqcount_spinlock_t count;
128 	/* tree sorted by daddr/prefix */
129 	struct rb_root root_d;
130 
131 	/* tree sorted by saddr/prefix */
132 	struct rb_root root_s;
133 
134 	/* slow path below */
135 	struct list_head inexact_bins;
136 	struct rcu_head rcu;
137 };
138 
139 enum xfrm_pol_inexact_candidate_type {
140 	XFRM_POL_CAND_BOTH,
141 	XFRM_POL_CAND_SADDR,
142 	XFRM_POL_CAND_DADDR,
143 	XFRM_POL_CAND_ANY,
144 
145 	XFRM_POL_CAND_MAX,
146 };
147 
148 struct xfrm_pol_inexact_candidates {
149 	struct hlist_head *res[XFRM_POL_CAND_MAX];
150 };
151 
152 static DEFINE_SPINLOCK(xfrm_if_cb_lock);
153 static struct xfrm_if_cb const __rcu *xfrm_if_cb __read_mostly;
154 
155 static DEFINE_SPINLOCK(xfrm_policy_afinfo_lock);
156 static struct xfrm_policy_afinfo const __rcu *xfrm_policy_afinfo[AF_INET6 + 1]
157 						__read_mostly;
158 
159 static struct kmem_cache *xfrm_dst_cache __ro_after_init;
160 
161 static struct rhashtable xfrm_policy_inexact_table;
162 static const struct rhashtable_params xfrm_pol_inexact_params;
163 
164 static void xfrm_init_pmtu(struct xfrm_dst **bundle, int nr);
165 static int stale_bundle(struct dst_entry *dst);
166 static int xfrm_bundle_ok(struct xfrm_dst *xdst);
167 static void xfrm_policy_queue_process(struct timer_list *t);
168 
169 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir);
170 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
171 						int dir);
172 
173 static struct xfrm_pol_inexact_bin *
174 xfrm_policy_inexact_lookup(struct net *net, u8 type, u16 family, u8 dir,
175 			   u32 if_id);
176 
177 static struct xfrm_pol_inexact_bin *
178 xfrm_policy_inexact_lookup_rcu(struct net *net,
179 			       u8 type, u16 family, u8 dir, u32 if_id);
180 static struct xfrm_policy *
181 xfrm_policy_insert_list(struct hlist_head *chain, struct xfrm_policy *policy,
182 			bool excl);
183 static void xfrm_policy_insert_inexact_list(struct hlist_head *chain,
184 					    struct xfrm_policy *policy);
185 
186 static bool
187 xfrm_policy_find_inexact_candidates(struct xfrm_pol_inexact_candidates *cand,
188 				    struct xfrm_pol_inexact_bin *b,
189 				    const xfrm_address_t *saddr,
190 				    const xfrm_address_t *daddr);
191 
xfrm_pol_hold_rcu(struct xfrm_policy * policy)192 static inline bool xfrm_pol_hold_rcu(struct xfrm_policy *policy)
193 {
194 	return refcount_inc_not_zero(&policy->refcnt);
195 }
196 
197 static inline bool
__xfrm4_selector_match(const struct xfrm_selector * sel,const struct flowi * fl)198 __xfrm4_selector_match(const struct xfrm_selector *sel, const struct flowi *fl)
199 {
200 	const struct flowi4 *fl4 = &fl->u.ip4;
201 
202 	return  addr4_match(fl4->daddr, sel->daddr.a4, sel->prefixlen_d) &&
203 		addr4_match(fl4->saddr, sel->saddr.a4, sel->prefixlen_s) &&
204 		!((xfrm_flowi_dport(fl, &fl4->uli) ^ sel->dport) & sel->dport_mask) &&
205 		!((xfrm_flowi_sport(fl, &fl4->uli) ^ sel->sport) & sel->sport_mask) &&
206 		(fl4->flowi4_proto == sel->proto || !sel->proto) &&
207 		(fl4->flowi4_oif == sel->ifindex || !sel->ifindex);
208 }
209 
210 static inline bool
__xfrm6_selector_match(const struct xfrm_selector * sel,const struct flowi * fl)211 __xfrm6_selector_match(const struct xfrm_selector *sel, const struct flowi *fl)
212 {
213 	const struct flowi6 *fl6 = &fl->u.ip6;
214 
215 	return  addr_match(&fl6->daddr, &sel->daddr, sel->prefixlen_d) &&
216 		addr_match(&fl6->saddr, &sel->saddr, sel->prefixlen_s) &&
217 		!((xfrm_flowi_dport(fl, &fl6->uli) ^ sel->dport) & sel->dport_mask) &&
218 		!((xfrm_flowi_sport(fl, &fl6->uli) ^ sel->sport) & sel->sport_mask) &&
219 		(fl6->flowi6_proto == sel->proto || !sel->proto) &&
220 		(fl6->flowi6_oif == sel->ifindex || !sel->ifindex);
221 }
222 
xfrm_selector_match(const struct xfrm_selector * sel,const struct flowi * fl,unsigned short family)223 bool xfrm_selector_match(const struct xfrm_selector *sel, const struct flowi *fl,
224 			 unsigned short family)
225 {
226 	switch (family) {
227 	case AF_INET:
228 		return __xfrm4_selector_match(sel, fl);
229 	case AF_INET6:
230 		return __xfrm6_selector_match(sel, fl);
231 	}
232 	return false;
233 }
234 
xfrm_policy_get_afinfo(unsigned short family)235 static const struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family)
236 {
237 	const struct xfrm_policy_afinfo *afinfo;
238 
239 	if (unlikely(family >= ARRAY_SIZE(xfrm_policy_afinfo)))
240 		return NULL;
241 	rcu_read_lock();
242 	afinfo = rcu_dereference(xfrm_policy_afinfo[family]);
243 	if (unlikely(!afinfo))
244 		rcu_read_unlock();
245 	return afinfo;
246 }
247 
248 /* Called with rcu_read_lock(). */
xfrm_if_get_cb(void)249 static const struct xfrm_if_cb *xfrm_if_get_cb(void)
250 {
251 	return rcu_dereference(xfrm_if_cb);
252 }
253 
__xfrm_dst_lookup(int family,const struct xfrm_dst_lookup_params * params)254 struct dst_entry *__xfrm_dst_lookup(int family,
255 				    const struct xfrm_dst_lookup_params *params)
256 {
257 	const struct xfrm_policy_afinfo *afinfo;
258 	struct dst_entry *dst;
259 
260 	afinfo = xfrm_policy_get_afinfo(family);
261 	if (unlikely(afinfo == NULL))
262 		return ERR_PTR(-EAFNOSUPPORT);
263 
264 	dst = afinfo->dst_lookup(params);
265 
266 	rcu_read_unlock();
267 
268 	return dst;
269 }
270 EXPORT_SYMBOL(__xfrm_dst_lookup);
271 
xfrm_dst_lookup(struct xfrm_state * x,int tos,int oif,xfrm_address_t * prev_saddr,xfrm_address_t * prev_daddr,int family,u32 mark)272 static inline struct dst_entry *xfrm_dst_lookup(struct xfrm_state *x,
273 						int tos, int oif,
274 						xfrm_address_t *prev_saddr,
275 						xfrm_address_t *prev_daddr,
276 						int family, u32 mark)
277 {
278 	struct xfrm_dst_lookup_params params;
279 	struct net *net = xs_net(x);
280 	xfrm_address_t *saddr = &x->props.saddr;
281 	xfrm_address_t *daddr = &x->id.daddr;
282 	struct dst_entry *dst;
283 
284 	if (x->type->flags & XFRM_TYPE_LOCAL_COADDR) {
285 		saddr = x->coaddr;
286 		daddr = prev_daddr;
287 	}
288 	if (x->type->flags & XFRM_TYPE_REMOTE_COADDR) {
289 		saddr = prev_saddr;
290 		daddr = x->coaddr;
291 	}
292 
293 	params.net = net;
294 	params.saddr = saddr;
295 	params.daddr = daddr;
296 	params.tos = tos;
297 	params.oif = oif;
298 	params.mark = mark;
299 	params.ipproto = x->id.proto;
300 	if (x->encap) {
301 		switch (x->encap->encap_type) {
302 		case UDP_ENCAP_ESPINUDP:
303 			params.ipproto = IPPROTO_UDP;
304 			params.uli.ports.sport = x->encap->encap_sport;
305 			params.uli.ports.dport = x->encap->encap_dport;
306 			break;
307 		case TCP_ENCAP_ESPINTCP:
308 			params.ipproto = IPPROTO_TCP;
309 			params.uli.ports.sport = x->encap->encap_sport;
310 			params.uli.ports.dport = x->encap->encap_dport;
311 			break;
312 		}
313 	}
314 
315 	dst = __xfrm_dst_lookup(family, &params);
316 
317 	if (!IS_ERR(dst)) {
318 		if (prev_saddr != saddr)
319 			memcpy(prev_saddr, saddr,  sizeof(*prev_saddr));
320 		if (prev_daddr != daddr)
321 			memcpy(prev_daddr, daddr,  sizeof(*prev_daddr));
322 	}
323 
324 	return dst;
325 }
326 
make_jiffies(long secs)327 static inline unsigned long make_jiffies(long secs)
328 {
329 	if (secs >= (MAX_SCHEDULE_TIMEOUT-1)/HZ)
330 		return MAX_SCHEDULE_TIMEOUT-1;
331 	else
332 		return secs*HZ;
333 }
334 
xfrm_policy_timer(struct timer_list * t)335 static void xfrm_policy_timer(struct timer_list *t)
336 {
337 	struct xfrm_policy *xp = from_timer(xp, t, timer);
338 	time64_t now = ktime_get_real_seconds();
339 	time64_t next = TIME64_MAX;
340 	int warn = 0;
341 	int dir;
342 
343 	read_lock(&xp->lock);
344 
345 	if (unlikely(xp->walk.dead))
346 		goto out;
347 
348 	dir = xfrm_policy_id2dir(xp->index);
349 
350 	if (xp->lft.hard_add_expires_seconds) {
351 		time64_t tmo = xp->lft.hard_add_expires_seconds +
352 			xp->curlft.add_time - now;
353 		if (tmo <= 0)
354 			goto expired;
355 		if (tmo < next)
356 			next = tmo;
357 	}
358 	if (xp->lft.hard_use_expires_seconds) {
359 		time64_t tmo = xp->lft.hard_use_expires_seconds +
360 			(READ_ONCE(xp->curlft.use_time) ? : xp->curlft.add_time) - now;
361 		if (tmo <= 0)
362 			goto expired;
363 		if (tmo < next)
364 			next = tmo;
365 	}
366 	if (xp->lft.soft_add_expires_seconds) {
367 		time64_t tmo = xp->lft.soft_add_expires_seconds +
368 			xp->curlft.add_time - now;
369 		if (tmo <= 0) {
370 			warn = 1;
371 			tmo = XFRM_KM_TIMEOUT;
372 		}
373 		if (tmo < next)
374 			next = tmo;
375 	}
376 	if (xp->lft.soft_use_expires_seconds) {
377 		time64_t tmo = xp->lft.soft_use_expires_seconds +
378 			(READ_ONCE(xp->curlft.use_time) ? : xp->curlft.add_time) - now;
379 		if (tmo <= 0) {
380 			warn = 1;
381 			tmo = XFRM_KM_TIMEOUT;
382 		}
383 		if (tmo < next)
384 			next = tmo;
385 	}
386 
387 	if (warn)
388 		km_policy_expired(xp, dir, 0, 0);
389 	if (next != TIME64_MAX &&
390 	    !mod_timer(&xp->timer, jiffies + make_jiffies(next)))
391 		xfrm_pol_hold(xp);
392 
393 out:
394 	read_unlock(&xp->lock);
395 	xfrm_pol_put(xp);
396 	return;
397 
398 expired:
399 	read_unlock(&xp->lock);
400 	if (!xfrm_policy_delete(xp, dir))
401 		km_policy_expired(xp, dir, 1, 0);
402 	xfrm_pol_put(xp);
403 }
404 
405 /* Allocate xfrm_policy. Not used here, it is supposed to be used by pfkeyv2
406  * SPD calls.
407  */
408 
xfrm_policy_alloc(struct net * net,gfp_t gfp)409 struct xfrm_policy *xfrm_policy_alloc(struct net *net, gfp_t gfp)
410 {
411 	struct xfrm_policy *policy;
412 
413 	policy = kzalloc(sizeof(struct xfrm_policy), gfp);
414 
415 	if (policy) {
416 		write_pnet(&policy->xp_net, net);
417 		INIT_LIST_HEAD(&policy->walk.all);
418 		INIT_HLIST_NODE(&policy->bydst_inexact_list);
419 		INIT_HLIST_NODE(&policy->bydst);
420 		INIT_HLIST_NODE(&policy->byidx);
421 		rwlock_init(&policy->lock);
422 		refcount_set(&policy->refcnt, 1);
423 		skb_queue_head_init(&policy->polq.hold_queue);
424 		timer_setup(&policy->timer, xfrm_policy_timer, 0);
425 		timer_setup(&policy->polq.hold_timer,
426 			    xfrm_policy_queue_process, 0);
427 	}
428 	return policy;
429 }
430 EXPORT_SYMBOL(xfrm_policy_alloc);
431 
xfrm_policy_destroy_rcu(struct rcu_head * head)432 static void xfrm_policy_destroy_rcu(struct rcu_head *head)
433 {
434 	struct xfrm_policy *policy = container_of(head, struct xfrm_policy, rcu);
435 
436 	security_xfrm_policy_free(policy->security);
437 	kfree(policy);
438 }
439 
440 /* Destroy xfrm_policy: descendant resources must be released to this moment. */
441 
xfrm_policy_destroy(struct xfrm_policy * policy)442 void xfrm_policy_destroy(struct xfrm_policy *policy)
443 {
444 	BUG_ON(!policy->walk.dead);
445 
446 	if (del_timer(&policy->timer) || del_timer(&policy->polq.hold_timer))
447 		BUG();
448 
449 	xfrm_dev_policy_free(policy);
450 	call_rcu(&policy->rcu, xfrm_policy_destroy_rcu);
451 }
452 EXPORT_SYMBOL(xfrm_policy_destroy);
453 
454 /* Rule must be locked. Release descendant resources, announce
455  * entry dead. The rule must be unlinked from lists to the moment.
456  */
457 
xfrm_policy_kill(struct xfrm_policy * policy)458 static void xfrm_policy_kill(struct xfrm_policy *policy)
459 {
460 	xfrm_dev_policy_delete(policy);
461 
462 	write_lock_bh(&policy->lock);
463 	policy->walk.dead = 1;
464 	write_unlock_bh(&policy->lock);
465 
466 	atomic_inc(&policy->genid);
467 
468 	if (del_timer(&policy->polq.hold_timer))
469 		xfrm_pol_put(policy);
470 	skb_queue_purge(&policy->polq.hold_queue);
471 
472 	if (del_timer(&policy->timer))
473 		xfrm_pol_put(policy);
474 
475 	xfrm_pol_put(policy);
476 }
477 
478 static unsigned int xfrm_policy_hashmax __read_mostly = 1 * 1024 * 1024;
479 
idx_hash(struct net * net,u32 index)480 static inline unsigned int idx_hash(struct net *net, u32 index)
481 {
482 	return __idx_hash(index, net->xfrm.policy_idx_hmask);
483 }
484 
485 /* calculate policy hash thresholds */
__get_hash_thresh(struct net * net,unsigned short family,int dir,u8 * dbits,u8 * sbits)486 static void __get_hash_thresh(struct net *net,
487 			      unsigned short family, int dir,
488 			      u8 *dbits, u8 *sbits)
489 {
490 	switch (family) {
491 	case AF_INET:
492 		*dbits = net->xfrm.policy_bydst[dir].dbits4;
493 		*sbits = net->xfrm.policy_bydst[dir].sbits4;
494 		break;
495 
496 	case AF_INET6:
497 		*dbits = net->xfrm.policy_bydst[dir].dbits6;
498 		*sbits = net->xfrm.policy_bydst[dir].sbits6;
499 		break;
500 
501 	default:
502 		*dbits = 0;
503 		*sbits = 0;
504 	}
505 }
506 
policy_hash_bysel(struct net * net,const struct xfrm_selector * sel,unsigned short family,int dir)507 static struct hlist_head *policy_hash_bysel(struct net *net,
508 					    const struct xfrm_selector *sel,
509 					    unsigned short family, int dir)
510 {
511 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
512 	unsigned int hash;
513 	u8 dbits;
514 	u8 sbits;
515 
516 	__get_hash_thresh(net, family, dir, &dbits, &sbits);
517 	hash = __sel_hash(sel, family, hmask, dbits, sbits);
518 
519 	if (hash == hmask + 1)
520 		return NULL;
521 
522 	return rcu_dereference_check(net->xfrm.policy_bydst[dir].table,
523 		     lockdep_is_held(&net->xfrm.xfrm_policy_lock)) + hash;
524 }
525 
policy_hash_direct(struct net * net,const xfrm_address_t * daddr,const xfrm_address_t * saddr,unsigned short family,int dir)526 static struct hlist_head *policy_hash_direct(struct net *net,
527 					     const xfrm_address_t *daddr,
528 					     const xfrm_address_t *saddr,
529 					     unsigned short family, int dir)
530 {
531 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
532 	unsigned int hash;
533 	u8 dbits;
534 	u8 sbits;
535 
536 	__get_hash_thresh(net, family, dir, &dbits, &sbits);
537 	hash = __addr_hash(daddr, saddr, family, hmask, dbits, sbits);
538 
539 	return rcu_dereference_check(net->xfrm.policy_bydst[dir].table,
540 		     lockdep_is_held(&net->xfrm.xfrm_policy_lock)) + hash;
541 }
542 
xfrm_dst_hash_transfer(struct net * net,struct hlist_head * list,struct hlist_head * ndsttable,unsigned int nhashmask,int dir)543 static void xfrm_dst_hash_transfer(struct net *net,
544 				   struct hlist_head *list,
545 				   struct hlist_head *ndsttable,
546 				   unsigned int nhashmask,
547 				   int dir)
548 {
549 	struct hlist_node *tmp, *entry0 = NULL;
550 	struct xfrm_policy *pol;
551 	unsigned int h0 = 0;
552 	u8 dbits;
553 	u8 sbits;
554 
555 redo:
556 	hlist_for_each_entry_safe(pol, tmp, list, bydst) {
557 		unsigned int h;
558 
559 		__get_hash_thresh(net, pol->family, dir, &dbits, &sbits);
560 		h = __addr_hash(&pol->selector.daddr, &pol->selector.saddr,
561 				pol->family, nhashmask, dbits, sbits);
562 		if (!entry0 || pol->xdo.type == XFRM_DEV_OFFLOAD_PACKET) {
563 			hlist_del_rcu(&pol->bydst);
564 			hlist_add_head_rcu(&pol->bydst, ndsttable + h);
565 			h0 = h;
566 		} else {
567 			if (h != h0)
568 				continue;
569 			hlist_del_rcu(&pol->bydst);
570 			hlist_add_behind_rcu(&pol->bydst, entry0);
571 		}
572 		entry0 = &pol->bydst;
573 	}
574 	if (!hlist_empty(list)) {
575 		entry0 = NULL;
576 		goto redo;
577 	}
578 }
579 
xfrm_idx_hash_transfer(struct hlist_head * list,struct hlist_head * nidxtable,unsigned int nhashmask)580 static void xfrm_idx_hash_transfer(struct hlist_head *list,
581 				   struct hlist_head *nidxtable,
582 				   unsigned int nhashmask)
583 {
584 	struct hlist_node *tmp;
585 	struct xfrm_policy *pol;
586 
587 	hlist_for_each_entry_safe(pol, tmp, list, byidx) {
588 		unsigned int h;
589 
590 		h = __idx_hash(pol->index, nhashmask);
591 		hlist_add_head(&pol->byidx, nidxtable+h);
592 	}
593 }
594 
xfrm_new_hash_mask(unsigned int old_hmask)595 static unsigned long xfrm_new_hash_mask(unsigned int old_hmask)
596 {
597 	return ((old_hmask + 1) << 1) - 1;
598 }
599 
xfrm_bydst_resize(struct net * net,int dir)600 static void xfrm_bydst_resize(struct net *net, int dir)
601 {
602 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
603 	unsigned int nhashmask = xfrm_new_hash_mask(hmask);
604 	unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
605 	struct hlist_head *ndst = xfrm_hash_alloc(nsize);
606 	struct hlist_head *odst;
607 	int i;
608 
609 	if (!ndst)
610 		return;
611 
612 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
613 	write_seqcount_begin(&net->xfrm.xfrm_policy_hash_generation);
614 
615 	odst = rcu_dereference_protected(net->xfrm.policy_bydst[dir].table,
616 				lockdep_is_held(&net->xfrm.xfrm_policy_lock));
617 
618 	for (i = hmask; i >= 0; i--)
619 		xfrm_dst_hash_transfer(net, odst + i, ndst, nhashmask, dir);
620 
621 	rcu_assign_pointer(net->xfrm.policy_bydst[dir].table, ndst);
622 	net->xfrm.policy_bydst[dir].hmask = nhashmask;
623 
624 	write_seqcount_end(&net->xfrm.xfrm_policy_hash_generation);
625 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
626 
627 	synchronize_rcu();
628 
629 	xfrm_hash_free(odst, (hmask + 1) * sizeof(struct hlist_head));
630 }
631 
xfrm_byidx_resize(struct net * net)632 static void xfrm_byidx_resize(struct net *net)
633 {
634 	unsigned int hmask = net->xfrm.policy_idx_hmask;
635 	unsigned int nhashmask = xfrm_new_hash_mask(hmask);
636 	unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
637 	struct hlist_head *oidx = net->xfrm.policy_byidx;
638 	struct hlist_head *nidx = xfrm_hash_alloc(nsize);
639 	int i;
640 
641 	if (!nidx)
642 		return;
643 
644 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
645 
646 	for (i = hmask; i >= 0; i--)
647 		xfrm_idx_hash_transfer(oidx + i, nidx, nhashmask);
648 
649 	net->xfrm.policy_byidx = nidx;
650 	net->xfrm.policy_idx_hmask = nhashmask;
651 
652 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
653 
654 	xfrm_hash_free(oidx, (hmask + 1) * sizeof(struct hlist_head));
655 }
656 
xfrm_bydst_should_resize(struct net * net,int dir,int * total)657 static inline int xfrm_bydst_should_resize(struct net *net, int dir, int *total)
658 {
659 	unsigned int cnt = net->xfrm.policy_count[dir];
660 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
661 
662 	if (total)
663 		*total += cnt;
664 
665 	if ((hmask + 1) < xfrm_policy_hashmax &&
666 	    cnt > hmask)
667 		return 1;
668 
669 	return 0;
670 }
671 
xfrm_byidx_should_resize(struct net * net,int total)672 static inline int xfrm_byidx_should_resize(struct net *net, int total)
673 {
674 	unsigned int hmask = net->xfrm.policy_idx_hmask;
675 
676 	if ((hmask + 1) < xfrm_policy_hashmax &&
677 	    total > hmask)
678 		return 1;
679 
680 	return 0;
681 }
682 
xfrm_spd_getinfo(struct net * net,struct xfrmk_spdinfo * si)683 void xfrm_spd_getinfo(struct net *net, struct xfrmk_spdinfo *si)
684 {
685 	si->incnt = net->xfrm.policy_count[XFRM_POLICY_IN];
686 	si->outcnt = net->xfrm.policy_count[XFRM_POLICY_OUT];
687 	si->fwdcnt = net->xfrm.policy_count[XFRM_POLICY_FWD];
688 	si->inscnt = net->xfrm.policy_count[XFRM_POLICY_IN+XFRM_POLICY_MAX];
689 	si->outscnt = net->xfrm.policy_count[XFRM_POLICY_OUT+XFRM_POLICY_MAX];
690 	si->fwdscnt = net->xfrm.policy_count[XFRM_POLICY_FWD+XFRM_POLICY_MAX];
691 	si->spdhcnt = net->xfrm.policy_idx_hmask;
692 	si->spdhmcnt = xfrm_policy_hashmax;
693 }
694 EXPORT_SYMBOL(xfrm_spd_getinfo);
695 
696 static DEFINE_MUTEX(hash_resize_mutex);
xfrm_hash_resize(struct work_struct * work)697 static void xfrm_hash_resize(struct work_struct *work)
698 {
699 	struct net *net = container_of(work, struct net, xfrm.policy_hash_work);
700 	int dir, total;
701 
702 	mutex_lock(&hash_resize_mutex);
703 
704 	total = 0;
705 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
706 		if (xfrm_bydst_should_resize(net, dir, &total))
707 			xfrm_bydst_resize(net, dir);
708 	}
709 	if (xfrm_byidx_should_resize(net, total))
710 		xfrm_byidx_resize(net);
711 
712 	mutex_unlock(&hash_resize_mutex);
713 }
714 
715 /* Make sure *pol can be inserted into fastbin.
716  * Useful to check that later insert requests will be successful
717  * (provided xfrm_policy_lock is held throughout).
718  */
719 static struct xfrm_pol_inexact_bin *
xfrm_policy_inexact_alloc_bin(const struct xfrm_policy * pol,u8 dir)720 xfrm_policy_inexact_alloc_bin(const struct xfrm_policy *pol, u8 dir)
721 {
722 	struct xfrm_pol_inexact_bin *bin, *prev;
723 	struct xfrm_pol_inexact_key k = {
724 		.family = pol->family,
725 		.type = pol->type,
726 		.dir = dir,
727 		.if_id = pol->if_id,
728 	};
729 	struct net *net = xp_net(pol);
730 
731 	lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
732 
733 	write_pnet(&k.net, net);
734 	bin = rhashtable_lookup_fast(&xfrm_policy_inexact_table, &k,
735 				     xfrm_pol_inexact_params);
736 	if (bin)
737 		return bin;
738 
739 	bin = kzalloc(sizeof(*bin), GFP_ATOMIC);
740 	if (!bin)
741 		return NULL;
742 
743 	bin->k = k;
744 	INIT_HLIST_HEAD(&bin->hhead);
745 	bin->root_d = RB_ROOT;
746 	bin->root_s = RB_ROOT;
747 	seqcount_spinlock_init(&bin->count, &net->xfrm.xfrm_policy_lock);
748 
749 	prev = rhashtable_lookup_get_insert_key(&xfrm_policy_inexact_table,
750 						&bin->k, &bin->head,
751 						xfrm_pol_inexact_params);
752 	if (!prev) {
753 		list_add(&bin->inexact_bins, &net->xfrm.inexact_bins);
754 		return bin;
755 	}
756 
757 	kfree(bin);
758 
759 	return IS_ERR(prev) ? NULL : prev;
760 }
761 
xfrm_pol_inexact_addr_use_any_list(const xfrm_address_t * addr,int family,u8 prefixlen)762 static bool xfrm_pol_inexact_addr_use_any_list(const xfrm_address_t *addr,
763 					       int family, u8 prefixlen)
764 {
765 	if (xfrm_addr_any(addr, family))
766 		return true;
767 
768 	if (family == AF_INET6 && prefixlen < INEXACT_PREFIXLEN_IPV6)
769 		return true;
770 
771 	if (family == AF_INET && prefixlen < INEXACT_PREFIXLEN_IPV4)
772 		return true;
773 
774 	return false;
775 }
776 
777 static bool
xfrm_policy_inexact_insert_use_any_list(const struct xfrm_policy * policy)778 xfrm_policy_inexact_insert_use_any_list(const struct xfrm_policy *policy)
779 {
780 	const xfrm_address_t *addr;
781 	bool saddr_any, daddr_any;
782 	u8 prefixlen;
783 
784 	addr = &policy->selector.saddr;
785 	prefixlen = policy->selector.prefixlen_s;
786 
787 	saddr_any = xfrm_pol_inexact_addr_use_any_list(addr,
788 						       policy->family,
789 						       prefixlen);
790 	addr = &policy->selector.daddr;
791 	prefixlen = policy->selector.prefixlen_d;
792 	daddr_any = xfrm_pol_inexact_addr_use_any_list(addr,
793 						       policy->family,
794 						       prefixlen);
795 	return saddr_any && daddr_any;
796 }
797 
xfrm_pol_inexact_node_init(struct xfrm_pol_inexact_node * node,const xfrm_address_t * addr,u8 prefixlen)798 static void xfrm_pol_inexact_node_init(struct xfrm_pol_inexact_node *node,
799 				       const xfrm_address_t *addr, u8 prefixlen)
800 {
801 	node->addr = *addr;
802 	node->prefixlen = prefixlen;
803 }
804 
805 static struct xfrm_pol_inexact_node *
xfrm_pol_inexact_node_alloc(const xfrm_address_t * addr,u8 prefixlen)806 xfrm_pol_inexact_node_alloc(const xfrm_address_t *addr, u8 prefixlen)
807 {
808 	struct xfrm_pol_inexact_node *node;
809 
810 	node = kzalloc(sizeof(*node), GFP_ATOMIC);
811 	if (node)
812 		xfrm_pol_inexact_node_init(node, addr, prefixlen);
813 
814 	return node;
815 }
816 
xfrm_policy_addr_delta(const xfrm_address_t * a,const xfrm_address_t * b,u8 prefixlen,u16 family)817 static int xfrm_policy_addr_delta(const xfrm_address_t *a,
818 				  const xfrm_address_t *b,
819 				  u8 prefixlen, u16 family)
820 {
821 	u32 ma, mb, mask;
822 	unsigned int pdw, pbi;
823 	int delta = 0;
824 
825 	switch (family) {
826 	case AF_INET:
827 		if (prefixlen == 0)
828 			return 0;
829 		mask = ~0U << (32 - prefixlen);
830 		ma = ntohl(a->a4) & mask;
831 		mb = ntohl(b->a4) & mask;
832 		if (ma < mb)
833 			delta = -1;
834 		else if (ma > mb)
835 			delta = 1;
836 		break;
837 	case AF_INET6:
838 		pdw = prefixlen >> 5;
839 		pbi = prefixlen & 0x1f;
840 
841 		if (pdw) {
842 			delta = memcmp(a->a6, b->a6, pdw << 2);
843 			if (delta)
844 				return delta;
845 		}
846 		if (pbi) {
847 			mask = ~0U << (32 - pbi);
848 			ma = ntohl(a->a6[pdw]) & mask;
849 			mb = ntohl(b->a6[pdw]) & mask;
850 			if (ma < mb)
851 				delta = -1;
852 			else if (ma > mb)
853 				delta = 1;
854 		}
855 		break;
856 	default:
857 		break;
858 	}
859 
860 	return delta;
861 }
862 
xfrm_policy_inexact_list_reinsert(struct net * net,struct xfrm_pol_inexact_node * n,u16 family)863 static void xfrm_policy_inexact_list_reinsert(struct net *net,
864 					      struct xfrm_pol_inexact_node *n,
865 					      u16 family)
866 {
867 	unsigned int matched_s, matched_d;
868 	struct xfrm_policy *policy, *p;
869 
870 	matched_s = 0;
871 	matched_d = 0;
872 
873 	list_for_each_entry_reverse(policy, &net->xfrm.policy_all, walk.all) {
874 		struct hlist_node *newpos = NULL;
875 		bool matches_s, matches_d;
876 
877 		if (policy->walk.dead || !policy->bydst_reinsert)
878 			continue;
879 
880 		WARN_ON_ONCE(policy->family != family);
881 
882 		policy->bydst_reinsert = false;
883 		hlist_for_each_entry(p, &n->hhead, bydst) {
884 			if (policy->priority > p->priority)
885 				newpos = &p->bydst;
886 			else if (policy->priority == p->priority &&
887 				 policy->pos > p->pos)
888 				newpos = &p->bydst;
889 			else
890 				break;
891 		}
892 
893 		if (newpos && policy->xdo.type != XFRM_DEV_OFFLOAD_PACKET)
894 			hlist_add_behind_rcu(&policy->bydst, newpos);
895 		else
896 			hlist_add_head_rcu(&policy->bydst, &n->hhead);
897 
898 		/* paranoia checks follow.
899 		 * Check that the reinserted policy matches at least
900 		 * saddr or daddr for current node prefix.
901 		 *
902 		 * Matching both is fine, matching saddr in one policy
903 		 * (but not daddr) and then matching only daddr in another
904 		 * is a bug.
905 		 */
906 		matches_s = xfrm_policy_addr_delta(&policy->selector.saddr,
907 						   &n->addr,
908 						   n->prefixlen,
909 						   family) == 0;
910 		matches_d = xfrm_policy_addr_delta(&policy->selector.daddr,
911 						   &n->addr,
912 						   n->prefixlen,
913 						   family) == 0;
914 		if (matches_s && matches_d)
915 			continue;
916 
917 		WARN_ON_ONCE(!matches_s && !matches_d);
918 		if (matches_s)
919 			matched_s++;
920 		if (matches_d)
921 			matched_d++;
922 		WARN_ON_ONCE(matched_s && matched_d);
923 	}
924 }
925 
xfrm_policy_inexact_node_reinsert(struct net * net,struct xfrm_pol_inexact_node * n,struct rb_root * new,u16 family)926 static void xfrm_policy_inexact_node_reinsert(struct net *net,
927 					      struct xfrm_pol_inexact_node *n,
928 					      struct rb_root *new,
929 					      u16 family)
930 {
931 	struct xfrm_pol_inexact_node *node;
932 	struct rb_node **p, *parent;
933 
934 	/* we should not have another subtree here */
935 	WARN_ON_ONCE(!RB_EMPTY_ROOT(&n->root));
936 restart:
937 	parent = NULL;
938 	p = &new->rb_node;
939 	while (*p) {
940 		u8 prefixlen;
941 		int delta;
942 
943 		parent = *p;
944 		node = rb_entry(*p, struct xfrm_pol_inexact_node, node);
945 
946 		prefixlen = min(node->prefixlen, n->prefixlen);
947 
948 		delta = xfrm_policy_addr_delta(&n->addr, &node->addr,
949 					       prefixlen, family);
950 		if (delta < 0) {
951 			p = &parent->rb_left;
952 		} else if (delta > 0) {
953 			p = &parent->rb_right;
954 		} else {
955 			bool same_prefixlen = node->prefixlen == n->prefixlen;
956 			struct xfrm_policy *tmp;
957 
958 			hlist_for_each_entry(tmp, &n->hhead, bydst) {
959 				tmp->bydst_reinsert = true;
960 				hlist_del_rcu(&tmp->bydst);
961 			}
962 
963 			node->prefixlen = prefixlen;
964 
965 			xfrm_policy_inexact_list_reinsert(net, node, family);
966 
967 			if (same_prefixlen) {
968 				kfree_rcu(n, rcu);
969 				return;
970 			}
971 
972 			rb_erase(*p, new);
973 			kfree_rcu(n, rcu);
974 			n = node;
975 			goto restart;
976 		}
977 	}
978 
979 	rb_link_node_rcu(&n->node, parent, p);
980 	rb_insert_color(&n->node, new);
981 }
982 
983 /* merge nodes v and n */
xfrm_policy_inexact_node_merge(struct net * net,struct xfrm_pol_inexact_node * v,struct xfrm_pol_inexact_node * n,u16 family)984 static void xfrm_policy_inexact_node_merge(struct net *net,
985 					   struct xfrm_pol_inexact_node *v,
986 					   struct xfrm_pol_inexact_node *n,
987 					   u16 family)
988 {
989 	struct xfrm_pol_inexact_node *node;
990 	struct xfrm_policy *tmp;
991 	struct rb_node *rnode;
992 
993 	/* To-be-merged node v has a subtree.
994 	 *
995 	 * Dismantle it and insert its nodes to n->root.
996 	 */
997 	while ((rnode = rb_first(&v->root)) != NULL) {
998 		node = rb_entry(rnode, struct xfrm_pol_inexact_node, node);
999 		rb_erase(&node->node, &v->root);
1000 		xfrm_policy_inexact_node_reinsert(net, node, &n->root,
1001 						  family);
1002 	}
1003 
1004 	hlist_for_each_entry(tmp, &v->hhead, bydst) {
1005 		tmp->bydst_reinsert = true;
1006 		hlist_del_rcu(&tmp->bydst);
1007 	}
1008 
1009 	xfrm_policy_inexact_list_reinsert(net, n, family);
1010 }
1011 
1012 static struct xfrm_pol_inexact_node *
xfrm_policy_inexact_insert_node(struct net * net,struct rb_root * root,xfrm_address_t * addr,u16 family,u8 prefixlen,u8 dir)1013 xfrm_policy_inexact_insert_node(struct net *net,
1014 				struct rb_root *root,
1015 				xfrm_address_t *addr,
1016 				u16 family, u8 prefixlen, u8 dir)
1017 {
1018 	struct xfrm_pol_inexact_node *cached = NULL;
1019 	struct rb_node **p, *parent = NULL;
1020 	struct xfrm_pol_inexact_node *node;
1021 
1022 	p = &root->rb_node;
1023 	while (*p) {
1024 		int delta;
1025 
1026 		parent = *p;
1027 		node = rb_entry(*p, struct xfrm_pol_inexact_node, node);
1028 
1029 		delta = xfrm_policy_addr_delta(addr, &node->addr,
1030 					       node->prefixlen,
1031 					       family);
1032 		if (delta == 0 && prefixlen >= node->prefixlen) {
1033 			WARN_ON_ONCE(cached); /* ipsec policies got lost */
1034 			return node;
1035 		}
1036 
1037 		if (delta < 0)
1038 			p = &parent->rb_left;
1039 		else
1040 			p = &parent->rb_right;
1041 
1042 		if (prefixlen < node->prefixlen) {
1043 			delta = xfrm_policy_addr_delta(addr, &node->addr,
1044 						       prefixlen,
1045 						       family);
1046 			if (delta)
1047 				continue;
1048 
1049 			/* This node is a subnet of the new prefix. It needs
1050 			 * to be removed and re-inserted with the smaller
1051 			 * prefix and all nodes that are now also covered
1052 			 * by the reduced prefixlen.
1053 			 */
1054 			rb_erase(&node->node, root);
1055 
1056 			if (!cached) {
1057 				xfrm_pol_inexact_node_init(node, addr,
1058 							   prefixlen);
1059 				cached = node;
1060 			} else {
1061 				/* This node also falls within the new
1062 				 * prefixlen. Merge the to-be-reinserted
1063 				 * node and this one.
1064 				 */
1065 				xfrm_policy_inexact_node_merge(net, node,
1066 							       cached, family);
1067 				kfree_rcu(node, rcu);
1068 			}
1069 
1070 			/* restart */
1071 			p = &root->rb_node;
1072 			parent = NULL;
1073 		}
1074 	}
1075 
1076 	node = cached;
1077 	if (!node) {
1078 		node = xfrm_pol_inexact_node_alloc(addr, prefixlen);
1079 		if (!node)
1080 			return NULL;
1081 	}
1082 
1083 	rb_link_node_rcu(&node->node, parent, p);
1084 	rb_insert_color(&node->node, root);
1085 
1086 	return node;
1087 }
1088 
xfrm_policy_inexact_gc_tree(struct rb_root * r,bool rm)1089 static void xfrm_policy_inexact_gc_tree(struct rb_root *r, bool rm)
1090 {
1091 	struct xfrm_pol_inexact_node *node;
1092 	struct rb_node *rn = rb_first(r);
1093 
1094 	while (rn) {
1095 		node = rb_entry(rn, struct xfrm_pol_inexact_node, node);
1096 
1097 		xfrm_policy_inexact_gc_tree(&node->root, rm);
1098 		rn = rb_next(rn);
1099 
1100 		if (!hlist_empty(&node->hhead) || !RB_EMPTY_ROOT(&node->root)) {
1101 			WARN_ON_ONCE(rm);
1102 			continue;
1103 		}
1104 
1105 		rb_erase(&node->node, r);
1106 		kfree_rcu(node, rcu);
1107 	}
1108 }
1109 
__xfrm_policy_inexact_prune_bin(struct xfrm_pol_inexact_bin * b,bool net_exit)1110 static void __xfrm_policy_inexact_prune_bin(struct xfrm_pol_inexact_bin *b, bool net_exit)
1111 {
1112 	write_seqcount_begin(&b->count);
1113 	xfrm_policy_inexact_gc_tree(&b->root_d, net_exit);
1114 	xfrm_policy_inexact_gc_tree(&b->root_s, net_exit);
1115 	write_seqcount_end(&b->count);
1116 
1117 	if (!RB_EMPTY_ROOT(&b->root_d) || !RB_EMPTY_ROOT(&b->root_s) ||
1118 	    !hlist_empty(&b->hhead)) {
1119 		WARN_ON_ONCE(net_exit);
1120 		return;
1121 	}
1122 
1123 	if (rhashtable_remove_fast(&xfrm_policy_inexact_table, &b->head,
1124 				   xfrm_pol_inexact_params) == 0) {
1125 		list_del(&b->inexact_bins);
1126 		kfree_rcu(b, rcu);
1127 	}
1128 }
1129 
xfrm_policy_inexact_prune_bin(struct xfrm_pol_inexact_bin * b)1130 static void xfrm_policy_inexact_prune_bin(struct xfrm_pol_inexact_bin *b)
1131 {
1132 	struct net *net = read_pnet(&b->k.net);
1133 
1134 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1135 	__xfrm_policy_inexact_prune_bin(b, false);
1136 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1137 }
1138 
__xfrm_policy_inexact_flush(struct net * net)1139 static void __xfrm_policy_inexact_flush(struct net *net)
1140 {
1141 	struct xfrm_pol_inexact_bin *bin, *t;
1142 
1143 	lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1144 
1145 	list_for_each_entry_safe(bin, t, &net->xfrm.inexact_bins, inexact_bins)
1146 		__xfrm_policy_inexact_prune_bin(bin, false);
1147 }
1148 
1149 static struct hlist_head *
xfrm_policy_inexact_alloc_chain(struct xfrm_pol_inexact_bin * bin,struct xfrm_policy * policy,u8 dir)1150 xfrm_policy_inexact_alloc_chain(struct xfrm_pol_inexact_bin *bin,
1151 				struct xfrm_policy *policy, u8 dir)
1152 {
1153 	struct xfrm_pol_inexact_node *n;
1154 	struct net *net;
1155 
1156 	net = xp_net(policy);
1157 	lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1158 
1159 	if (xfrm_policy_inexact_insert_use_any_list(policy))
1160 		return &bin->hhead;
1161 
1162 	if (xfrm_pol_inexact_addr_use_any_list(&policy->selector.daddr,
1163 					       policy->family,
1164 					       policy->selector.prefixlen_d)) {
1165 		write_seqcount_begin(&bin->count);
1166 		n = xfrm_policy_inexact_insert_node(net,
1167 						    &bin->root_s,
1168 						    &policy->selector.saddr,
1169 						    policy->family,
1170 						    policy->selector.prefixlen_s,
1171 						    dir);
1172 		write_seqcount_end(&bin->count);
1173 		if (!n)
1174 			return NULL;
1175 
1176 		return &n->hhead;
1177 	}
1178 
1179 	/* daddr is fixed */
1180 	write_seqcount_begin(&bin->count);
1181 	n = xfrm_policy_inexact_insert_node(net,
1182 					    &bin->root_d,
1183 					    &policy->selector.daddr,
1184 					    policy->family,
1185 					    policy->selector.prefixlen_d, dir);
1186 	write_seqcount_end(&bin->count);
1187 	if (!n)
1188 		return NULL;
1189 
1190 	/* saddr is wildcard */
1191 	if (xfrm_pol_inexact_addr_use_any_list(&policy->selector.saddr,
1192 					       policy->family,
1193 					       policy->selector.prefixlen_s))
1194 		return &n->hhead;
1195 
1196 	write_seqcount_begin(&bin->count);
1197 	n = xfrm_policy_inexact_insert_node(net,
1198 					    &n->root,
1199 					    &policy->selector.saddr,
1200 					    policy->family,
1201 					    policy->selector.prefixlen_s, dir);
1202 	write_seqcount_end(&bin->count);
1203 	if (!n)
1204 		return NULL;
1205 
1206 	return &n->hhead;
1207 }
1208 
1209 static struct xfrm_policy *
xfrm_policy_inexact_insert(struct xfrm_policy * policy,u8 dir,int excl)1210 xfrm_policy_inexact_insert(struct xfrm_policy *policy, u8 dir, int excl)
1211 {
1212 	struct xfrm_pol_inexact_bin *bin;
1213 	struct xfrm_policy *delpol;
1214 	struct hlist_head *chain;
1215 	struct net *net;
1216 
1217 	bin = xfrm_policy_inexact_alloc_bin(policy, dir);
1218 	if (!bin)
1219 		return ERR_PTR(-ENOMEM);
1220 
1221 	net = xp_net(policy);
1222 	lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1223 
1224 	chain = xfrm_policy_inexact_alloc_chain(bin, policy, dir);
1225 	if (!chain) {
1226 		__xfrm_policy_inexact_prune_bin(bin, false);
1227 		return ERR_PTR(-ENOMEM);
1228 	}
1229 
1230 	delpol = xfrm_policy_insert_list(chain, policy, excl);
1231 	if (delpol && excl) {
1232 		__xfrm_policy_inexact_prune_bin(bin, false);
1233 		return ERR_PTR(-EEXIST);
1234 	}
1235 
1236 	chain = &net->xfrm.policy_inexact[dir];
1237 	xfrm_policy_insert_inexact_list(chain, policy);
1238 
1239 	if (delpol)
1240 		__xfrm_policy_inexact_prune_bin(bin, false);
1241 
1242 	return delpol;
1243 }
1244 
xfrm_hash_rebuild(struct work_struct * work)1245 static void xfrm_hash_rebuild(struct work_struct *work)
1246 {
1247 	struct net *net = container_of(work, struct net,
1248 				       xfrm.policy_hthresh.work);
1249 	unsigned int hmask;
1250 	struct xfrm_policy *pol;
1251 	struct xfrm_policy *policy;
1252 	struct hlist_head *chain;
1253 	struct hlist_head *odst;
1254 	struct hlist_node *newpos;
1255 	int i;
1256 	int dir;
1257 	unsigned seq;
1258 	u8 lbits4, rbits4, lbits6, rbits6;
1259 
1260 	mutex_lock(&hash_resize_mutex);
1261 
1262 	/* read selector prefixlen thresholds */
1263 	do {
1264 		seq = read_seqbegin(&net->xfrm.policy_hthresh.lock);
1265 
1266 		lbits4 = net->xfrm.policy_hthresh.lbits4;
1267 		rbits4 = net->xfrm.policy_hthresh.rbits4;
1268 		lbits6 = net->xfrm.policy_hthresh.lbits6;
1269 		rbits6 = net->xfrm.policy_hthresh.rbits6;
1270 	} while (read_seqretry(&net->xfrm.policy_hthresh.lock, seq));
1271 
1272 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1273 	write_seqcount_begin(&net->xfrm.xfrm_policy_hash_generation);
1274 
1275 	/* make sure that we can insert the indirect policies again before
1276 	 * we start with destructive action.
1277 	 */
1278 	list_for_each_entry(policy, &net->xfrm.policy_all, walk.all) {
1279 		struct xfrm_pol_inexact_bin *bin;
1280 		u8 dbits, sbits;
1281 
1282 		if (policy->walk.dead)
1283 			continue;
1284 
1285 		dir = xfrm_policy_id2dir(policy->index);
1286 		if (dir >= XFRM_POLICY_MAX)
1287 			continue;
1288 
1289 		if ((dir & XFRM_POLICY_MASK) == XFRM_POLICY_OUT) {
1290 			if (policy->family == AF_INET) {
1291 				dbits = rbits4;
1292 				sbits = lbits4;
1293 			} else {
1294 				dbits = rbits6;
1295 				sbits = lbits6;
1296 			}
1297 		} else {
1298 			if (policy->family == AF_INET) {
1299 				dbits = lbits4;
1300 				sbits = rbits4;
1301 			} else {
1302 				dbits = lbits6;
1303 				sbits = rbits6;
1304 			}
1305 		}
1306 
1307 		if (policy->selector.prefixlen_d < dbits ||
1308 		    policy->selector.prefixlen_s < sbits)
1309 			continue;
1310 
1311 		bin = xfrm_policy_inexact_alloc_bin(policy, dir);
1312 		if (!bin)
1313 			goto out_unlock;
1314 
1315 		if (!xfrm_policy_inexact_alloc_chain(bin, policy, dir))
1316 			goto out_unlock;
1317 	}
1318 
1319 	/* reset the bydst and inexact table in all directions */
1320 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
1321 		struct hlist_node *n;
1322 
1323 		hlist_for_each_entry_safe(policy, n,
1324 					  &net->xfrm.policy_inexact[dir],
1325 					  bydst_inexact_list) {
1326 			hlist_del_rcu(&policy->bydst);
1327 			hlist_del_init(&policy->bydst_inexact_list);
1328 		}
1329 
1330 		hmask = net->xfrm.policy_bydst[dir].hmask;
1331 		odst = net->xfrm.policy_bydst[dir].table;
1332 		for (i = hmask; i >= 0; i--) {
1333 			hlist_for_each_entry_safe(policy, n, odst + i, bydst)
1334 				hlist_del_rcu(&policy->bydst);
1335 		}
1336 		if ((dir & XFRM_POLICY_MASK) == XFRM_POLICY_OUT) {
1337 			/* dir out => dst = remote, src = local */
1338 			net->xfrm.policy_bydst[dir].dbits4 = rbits4;
1339 			net->xfrm.policy_bydst[dir].sbits4 = lbits4;
1340 			net->xfrm.policy_bydst[dir].dbits6 = rbits6;
1341 			net->xfrm.policy_bydst[dir].sbits6 = lbits6;
1342 		} else {
1343 			/* dir in/fwd => dst = local, src = remote */
1344 			net->xfrm.policy_bydst[dir].dbits4 = lbits4;
1345 			net->xfrm.policy_bydst[dir].sbits4 = rbits4;
1346 			net->xfrm.policy_bydst[dir].dbits6 = lbits6;
1347 			net->xfrm.policy_bydst[dir].sbits6 = rbits6;
1348 		}
1349 	}
1350 
1351 	/* re-insert all policies by order of creation */
1352 	list_for_each_entry_reverse(policy, &net->xfrm.policy_all, walk.all) {
1353 		if (policy->walk.dead)
1354 			continue;
1355 		dir = xfrm_policy_id2dir(policy->index);
1356 		if (dir >= XFRM_POLICY_MAX) {
1357 			/* skip socket policies */
1358 			continue;
1359 		}
1360 		newpos = NULL;
1361 		chain = policy_hash_bysel(net, &policy->selector,
1362 					  policy->family, dir);
1363 
1364 		if (!chain) {
1365 			void *p = xfrm_policy_inexact_insert(policy, dir, 0);
1366 
1367 			WARN_ONCE(IS_ERR(p), "reinsert: %ld\n", PTR_ERR(p));
1368 			continue;
1369 		}
1370 
1371 		hlist_for_each_entry(pol, chain, bydst) {
1372 			if (policy->priority >= pol->priority)
1373 				newpos = &pol->bydst;
1374 			else
1375 				break;
1376 		}
1377 		if (newpos && policy->xdo.type != XFRM_DEV_OFFLOAD_PACKET)
1378 			hlist_add_behind_rcu(&policy->bydst, newpos);
1379 		else
1380 			hlist_add_head_rcu(&policy->bydst, chain);
1381 	}
1382 
1383 out_unlock:
1384 	__xfrm_policy_inexact_flush(net);
1385 	write_seqcount_end(&net->xfrm.xfrm_policy_hash_generation);
1386 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1387 
1388 	mutex_unlock(&hash_resize_mutex);
1389 }
1390 
xfrm_policy_hash_rebuild(struct net * net)1391 void xfrm_policy_hash_rebuild(struct net *net)
1392 {
1393 	schedule_work(&net->xfrm.policy_hthresh.work);
1394 }
1395 EXPORT_SYMBOL(xfrm_policy_hash_rebuild);
1396 
1397 /* Generate new index... KAME seems to generate them ordered by cost
1398  * of an absolute inpredictability of ordering of rules. This will not pass. */
xfrm_gen_index(struct net * net,int dir,u32 index)1399 static u32 xfrm_gen_index(struct net *net, int dir, u32 index)
1400 {
1401 	for (;;) {
1402 		struct hlist_head *list;
1403 		struct xfrm_policy *p;
1404 		u32 idx;
1405 		int found;
1406 
1407 		if (!index) {
1408 			idx = (net->xfrm.idx_generator | dir);
1409 			net->xfrm.idx_generator += 8;
1410 		} else {
1411 			idx = index;
1412 			index = 0;
1413 		}
1414 
1415 		if (idx == 0)
1416 			idx = 8;
1417 		list = net->xfrm.policy_byidx + idx_hash(net, idx);
1418 		found = 0;
1419 		hlist_for_each_entry(p, list, byidx) {
1420 			if (p->index == idx) {
1421 				found = 1;
1422 				break;
1423 			}
1424 		}
1425 		if (!found)
1426 			return idx;
1427 	}
1428 }
1429 
selector_cmp(struct xfrm_selector * s1,struct xfrm_selector * s2)1430 static inline int selector_cmp(struct xfrm_selector *s1, struct xfrm_selector *s2)
1431 {
1432 	u32 *p1 = (u32 *) s1;
1433 	u32 *p2 = (u32 *) s2;
1434 	int len = sizeof(struct xfrm_selector) / sizeof(u32);
1435 	int i;
1436 
1437 	for (i = 0; i < len; i++) {
1438 		if (p1[i] != p2[i])
1439 			return 1;
1440 	}
1441 
1442 	return 0;
1443 }
1444 
xfrm_policy_requeue(struct xfrm_policy * old,struct xfrm_policy * new)1445 static void xfrm_policy_requeue(struct xfrm_policy *old,
1446 				struct xfrm_policy *new)
1447 {
1448 	struct xfrm_policy_queue *pq = &old->polq;
1449 	struct sk_buff_head list;
1450 
1451 	if (skb_queue_empty(&pq->hold_queue))
1452 		return;
1453 
1454 	__skb_queue_head_init(&list);
1455 
1456 	spin_lock_bh(&pq->hold_queue.lock);
1457 	skb_queue_splice_init(&pq->hold_queue, &list);
1458 	if (del_timer(&pq->hold_timer))
1459 		xfrm_pol_put(old);
1460 	spin_unlock_bh(&pq->hold_queue.lock);
1461 
1462 	pq = &new->polq;
1463 
1464 	spin_lock_bh(&pq->hold_queue.lock);
1465 	skb_queue_splice(&list, &pq->hold_queue);
1466 	pq->timeout = XFRM_QUEUE_TMO_MIN;
1467 	if (!mod_timer(&pq->hold_timer, jiffies))
1468 		xfrm_pol_hold(new);
1469 	spin_unlock_bh(&pq->hold_queue.lock);
1470 }
1471 
xfrm_policy_mark_match(const struct xfrm_mark * mark,struct xfrm_policy * pol)1472 static inline bool xfrm_policy_mark_match(const struct xfrm_mark *mark,
1473 					  struct xfrm_policy *pol)
1474 {
1475 	return mark->v == pol->mark.v && mark->m == pol->mark.m;
1476 }
1477 
xfrm_pol_bin_key(const void * data,u32 len,u32 seed)1478 static u32 xfrm_pol_bin_key(const void *data, u32 len, u32 seed)
1479 {
1480 	const struct xfrm_pol_inexact_key *k = data;
1481 	u32 a = k->type << 24 | k->dir << 16 | k->family;
1482 
1483 	return jhash_3words(a, k->if_id, net_hash_mix(read_pnet(&k->net)),
1484 			    seed);
1485 }
1486 
xfrm_pol_bin_obj(const void * data,u32 len,u32 seed)1487 static u32 xfrm_pol_bin_obj(const void *data, u32 len, u32 seed)
1488 {
1489 	const struct xfrm_pol_inexact_bin *b = data;
1490 
1491 	return xfrm_pol_bin_key(&b->k, 0, seed);
1492 }
1493 
xfrm_pol_bin_cmp(struct rhashtable_compare_arg * arg,const void * ptr)1494 static int xfrm_pol_bin_cmp(struct rhashtable_compare_arg *arg,
1495 			    const void *ptr)
1496 {
1497 	const struct xfrm_pol_inexact_key *key = arg->key;
1498 	const struct xfrm_pol_inexact_bin *b = ptr;
1499 	int ret;
1500 
1501 	if (!net_eq(read_pnet(&b->k.net), read_pnet(&key->net)))
1502 		return -1;
1503 
1504 	ret = b->k.dir ^ key->dir;
1505 	if (ret)
1506 		return ret;
1507 
1508 	ret = b->k.type ^ key->type;
1509 	if (ret)
1510 		return ret;
1511 
1512 	ret = b->k.family ^ key->family;
1513 	if (ret)
1514 		return ret;
1515 
1516 	return b->k.if_id ^ key->if_id;
1517 }
1518 
1519 static const struct rhashtable_params xfrm_pol_inexact_params = {
1520 	.head_offset		= offsetof(struct xfrm_pol_inexact_bin, head),
1521 	.hashfn			= xfrm_pol_bin_key,
1522 	.obj_hashfn		= xfrm_pol_bin_obj,
1523 	.obj_cmpfn		= xfrm_pol_bin_cmp,
1524 	.automatic_shrinking	= true,
1525 };
1526 
xfrm_policy_insert_inexact_list(struct hlist_head * chain,struct xfrm_policy * policy)1527 static void xfrm_policy_insert_inexact_list(struct hlist_head *chain,
1528 					    struct xfrm_policy *policy)
1529 {
1530 	struct xfrm_policy *pol, *delpol = NULL;
1531 	struct hlist_node *newpos = NULL;
1532 	int i = 0;
1533 
1534 	hlist_for_each_entry(pol, chain, bydst_inexact_list) {
1535 		if (pol->type == policy->type &&
1536 		    pol->if_id == policy->if_id &&
1537 		    !selector_cmp(&pol->selector, &policy->selector) &&
1538 		    xfrm_policy_mark_match(&policy->mark, pol) &&
1539 		    xfrm_sec_ctx_match(pol->security, policy->security) &&
1540 		    !WARN_ON(delpol)) {
1541 			delpol = pol;
1542 			if (policy->priority > pol->priority)
1543 				continue;
1544 		} else if (policy->priority >= pol->priority) {
1545 			newpos = &pol->bydst_inexact_list;
1546 			continue;
1547 		}
1548 		if (delpol)
1549 			break;
1550 	}
1551 
1552 	if (newpos && policy->xdo.type != XFRM_DEV_OFFLOAD_PACKET)
1553 		hlist_add_behind_rcu(&policy->bydst_inexact_list, newpos);
1554 	else
1555 		hlist_add_head_rcu(&policy->bydst_inexact_list, chain);
1556 
1557 	hlist_for_each_entry(pol, chain, bydst_inexact_list) {
1558 		pol->pos = i;
1559 		i++;
1560 	}
1561 }
1562 
xfrm_policy_insert_list(struct hlist_head * chain,struct xfrm_policy * policy,bool excl)1563 static struct xfrm_policy *xfrm_policy_insert_list(struct hlist_head *chain,
1564 						   struct xfrm_policy *policy,
1565 						   bool excl)
1566 {
1567 	struct xfrm_policy *pol, *newpos = NULL, *delpol = NULL;
1568 
1569 	hlist_for_each_entry(pol, chain, bydst) {
1570 		if (pol->type == policy->type &&
1571 		    pol->if_id == policy->if_id &&
1572 		    !selector_cmp(&pol->selector, &policy->selector) &&
1573 		    xfrm_policy_mark_match(&policy->mark, pol) &&
1574 		    xfrm_sec_ctx_match(pol->security, policy->security) &&
1575 		    !WARN_ON(delpol)) {
1576 			if (excl)
1577 				return ERR_PTR(-EEXIST);
1578 			delpol = pol;
1579 			if (policy->priority > pol->priority)
1580 				continue;
1581 		} else if (policy->priority >= pol->priority) {
1582 			newpos = pol;
1583 			continue;
1584 		}
1585 		if (delpol)
1586 			break;
1587 	}
1588 
1589 	if (newpos && policy->xdo.type != XFRM_DEV_OFFLOAD_PACKET)
1590 		hlist_add_behind_rcu(&policy->bydst, &newpos->bydst);
1591 	else
1592 		/* Packet offload policies enter to the head
1593 		 * to speed-up lookups.
1594 		 */
1595 		hlist_add_head_rcu(&policy->bydst, chain);
1596 
1597 	return delpol;
1598 }
1599 
xfrm_policy_insert(int dir,struct xfrm_policy * policy,int excl)1600 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
1601 {
1602 	struct net *net = xp_net(policy);
1603 	struct xfrm_policy *delpol;
1604 	struct hlist_head *chain;
1605 
1606 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1607 	chain = policy_hash_bysel(net, &policy->selector, policy->family, dir);
1608 	if (chain)
1609 		delpol = xfrm_policy_insert_list(chain, policy, excl);
1610 	else
1611 		delpol = xfrm_policy_inexact_insert(policy, dir, excl);
1612 
1613 	if (IS_ERR(delpol)) {
1614 		spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1615 		return PTR_ERR(delpol);
1616 	}
1617 
1618 	__xfrm_policy_link(policy, dir);
1619 
1620 	/* After previous checking, family can either be AF_INET or AF_INET6 */
1621 	if (policy->family == AF_INET)
1622 		rt_genid_bump_ipv4(net);
1623 	else
1624 		rt_genid_bump_ipv6(net);
1625 
1626 	if (delpol) {
1627 		xfrm_policy_requeue(delpol, policy);
1628 		__xfrm_policy_unlink(delpol, dir);
1629 	}
1630 	policy->index = delpol ? delpol->index : xfrm_gen_index(net, dir, policy->index);
1631 	hlist_add_head(&policy->byidx, net->xfrm.policy_byidx+idx_hash(net, policy->index));
1632 	policy->curlft.add_time = ktime_get_real_seconds();
1633 	policy->curlft.use_time = 0;
1634 	if (!mod_timer(&policy->timer, jiffies + HZ))
1635 		xfrm_pol_hold(policy);
1636 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1637 
1638 	if (delpol)
1639 		xfrm_policy_kill(delpol);
1640 	else if (xfrm_bydst_should_resize(net, dir, NULL))
1641 		schedule_work(&net->xfrm.policy_hash_work);
1642 
1643 	return 0;
1644 }
1645 EXPORT_SYMBOL(xfrm_policy_insert);
1646 
1647 static struct xfrm_policy *
__xfrm_policy_bysel_ctx(struct hlist_head * chain,const struct xfrm_mark * mark,u32 if_id,u8 type,int dir,struct xfrm_selector * sel,struct xfrm_sec_ctx * ctx)1648 __xfrm_policy_bysel_ctx(struct hlist_head *chain, const struct xfrm_mark *mark,
1649 			u32 if_id, u8 type, int dir, struct xfrm_selector *sel,
1650 			struct xfrm_sec_ctx *ctx)
1651 {
1652 	struct xfrm_policy *pol;
1653 
1654 	if (!chain)
1655 		return NULL;
1656 
1657 	hlist_for_each_entry(pol, chain, bydst) {
1658 		if (pol->type == type &&
1659 		    pol->if_id == if_id &&
1660 		    xfrm_policy_mark_match(mark, pol) &&
1661 		    !selector_cmp(sel, &pol->selector) &&
1662 		    xfrm_sec_ctx_match(ctx, pol->security))
1663 			return pol;
1664 	}
1665 
1666 	return NULL;
1667 }
1668 
1669 struct xfrm_policy *
xfrm_policy_bysel_ctx(struct net * net,const struct xfrm_mark * mark,u32 if_id,u8 type,int dir,struct xfrm_selector * sel,struct xfrm_sec_ctx * ctx,int delete,int * err)1670 xfrm_policy_bysel_ctx(struct net *net, const struct xfrm_mark *mark, u32 if_id,
1671 		      u8 type, int dir, struct xfrm_selector *sel,
1672 		      struct xfrm_sec_ctx *ctx, int delete, int *err)
1673 {
1674 	struct xfrm_pol_inexact_bin *bin = NULL;
1675 	struct xfrm_policy *pol, *ret = NULL;
1676 	struct hlist_head *chain;
1677 
1678 	*err = 0;
1679 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1680 	chain = policy_hash_bysel(net, sel, sel->family, dir);
1681 	if (!chain) {
1682 		struct xfrm_pol_inexact_candidates cand;
1683 		int i;
1684 
1685 		bin = xfrm_policy_inexact_lookup(net, type,
1686 						 sel->family, dir, if_id);
1687 		if (!bin) {
1688 			spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1689 			return NULL;
1690 		}
1691 
1692 		if (!xfrm_policy_find_inexact_candidates(&cand, bin,
1693 							 &sel->saddr,
1694 							 &sel->daddr)) {
1695 			spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1696 			return NULL;
1697 		}
1698 
1699 		pol = NULL;
1700 		for (i = 0; i < ARRAY_SIZE(cand.res); i++) {
1701 			struct xfrm_policy *tmp;
1702 
1703 			tmp = __xfrm_policy_bysel_ctx(cand.res[i], mark,
1704 						      if_id, type, dir,
1705 						      sel, ctx);
1706 			if (!tmp)
1707 				continue;
1708 
1709 			if (!pol || tmp->pos < pol->pos)
1710 				pol = tmp;
1711 		}
1712 	} else {
1713 		pol = __xfrm_policy_bysel_ctx(chain, mark, if_id, type, dir,
1714 					      sel, ctx);
1715 	}
1716 
1717 	if (pol) {
1718 		xfrm_pol_hold(pol);
1719 		if (delete) {
1720 			*err = security_xfrm_policy_delete(pol->security);
1721 			if (*err) {
1722 				spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1723 				return pol;
1724 			}
1725 			__xfrm_policy_unlink(pol, dir);
1726 		}
1727 		ret = pol;
1728 	}
1729 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1730 
1731 	if (ret && delete)
1732 		xfrm_policy_kill(ret);
1733 	if (bin && delete)
1734 		xfrm_policy_inexact_prune_bin(bin);
1735 	return ret;
1736 }
1737 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
1738 
1739 struct xfrm_policy *
xfrm_policy_byid(struct net * net,const struct xfrm_mark * mark,u32 if_id,u8 type,int dir,u32 id,int delete,int * err)1740 xfrm_policy_byid(struct net *net, const struct xfrm_mark *mark, u32 if_id,
1741 		 u8 type, int dir, u32 id, int delete, int *err)
1742 {
1743 	struct xfrm_policy *pol, *ret;
1744 	struct hlist_head *chain;
1745 
1746 	*err = -ENOENT;
1747 	if (xfrm_policy_id2dir(id) != dir)
1748 		return NULL;
1749 
1750 	*err = 0;
1751 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1752 	chain = net->xfrm.policy_byidx + idx_hash(net, id);
1753 	ret = NULL;
1754 	hlist_for_each_entry(pol, chain, byidx) {
1755 		if (pol->type == type && pol->index == id &&
1756 		    pol->if_id == if_id && xfrm_policy_mark_match(mark, pol)) {
1757 			xfrm_pol_hold(pol);
1758 			if (delete) {
1759 				*err = security_xfrm_policy_delete(
1760 								pol->security);
1761 				if (*err) {
1762 					spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1763 					return pol;
1764 				}
1765 				__xfrm_policy_unlink(pol, dir);
1766 			}
1767 			ret = pol;
1768 			break;
1769 		}
1770 	}
1771 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1772 
1773 	if (ret && delete)
1774 		xfrm_policy_kill(ret);
1775 	return ret;
1776 }
1777 EXPORT_SYMBOL(xfrm_policy_byid);
1778 
1779 #ifdef CONFIG_SECURITY_NETWORK_XFRM
1780 static inline int
xfrm_policy_flush_secctx_check(struct net * net,u8 type,bool task_valid)1781 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
1782 {
1783 	struct xfrm_policy *pol;
1784 	int err = 0;
1785 
1786 	list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1787 		if (pol->walk.dead ||
1788 		    xfrm_policy_id2dir(pol->index) >= XFRM_POLICY_MAX ||
1789 		    pol->type != type)
1790 			continue;
1791 
1792 		err = security_xfrm_policy_delete(pol->security);
1793 		if (err) {
1794 			xfrm_audit_policy_delete(pol, 0, task_valid);
1795 			return err;
1796 		}
1797 	}
1798 	return err;
1799 }
1800 
xfrm_dev_policy_flush_secctx_check(struct net * net,struct net_device * dev,bool task_valid)1801 static inline int xfrm_dev_policy_flush_secctx_check(struct net *net,
1802 						     struct net_device *dev,
1803 						     bool task_valid)
1804 {
1805 	struct xfrm_policy *pol;
1806 	int err = 0;
1807 
1808 	list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1809 		if (pol->walk.dead ||
1810 		    xfrm_policy_id2dir(pol->index) >= XFRM_POLICY_MAX ||
1811 		    pol->xdo.dev != dev)
1812 			continue;
1813 
1814 		err = security_xfrm_policy_delete(pol->security);
1815 		if (err) {
1816 			xfrm_audit_policy_delete(pol, 0, task_valid);
1817 			return err;
1818 		}
1819 	}
1820 	return err;
1821 }
1822 #else
1823 static inline int
xfrm_policy_flush_secctx_check(struct net * net,u8 type,bool task_valid)1824 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
1825 {
1826 	return 0;
1827 }
1828 
xfrm_dev_policy_flush_secctx_check(struct net * net,struct net_device * dev,bool task_valid)1829 static inline int xfrm_dev_policy_flush_secctx_check(struct net *net,
1830 						     struct net_device *dev,
1831 						     bool task_valid)
1832 {
1833 	return 0;
1834 }
1835 #endif
1836 
xfrm_policy_flush(struct net * net,u8 type,bool task_valid)1837 int xfrm_policy_flush(struct net *net, u8 type, bool task_valid)
1838 {
1839 	int dir, err = 0, cnt = 0;
1840 	struct xfrm_policy *pol;
1841 
1842 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1843 
1844 	err = xfrm_policy_flush_secctx_check(net, type, task_valid);
1845 	if (err)
1846 		goto out;
1847 
1848 again:
1849 	list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1850 		if (pol->walk.dead)
1851 			continue;
1852 
1853 		dir = xfrm_policy_id2dir(pol->index);
1854 		if (dir >= XFRM_POLICY_MAX ||
1855 		    pol->type != type)
1856 			continue;
1857 
1858 		__xfrm_policy_unlink(pol, dir);
1859 		spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1860 		cnt++;
1861 		xfrm_audit_policy_delete(pol, 1, task_valid);
1862 		xfrm_policy_kill(pol);
1863 		spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1864 		goto again;
1865 	}
1866 	if (cnt)
1867 		__xfrm_policy_inexact_flush(net);
1868 	else
1869 		err = -ESRCH;
1870 out:
1871 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1872 	return err;
1873 }
1874 EXPORT_SYMBOL(xfrm_policy_flush);
1875 
xfrm_dev_policy_flush(struct net * net,struct net_device * dev,bool task_valid)1876 int xfrm_dev_policy_flush(struct net *net, struct net_device *dev,
1877 			  bool task_valid)
1878 {
1879 	int dir, err = 0, cnt = 0;
1880 	struct xfrm_policy *pol;
1881 
1882 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1883 
1884 	err = xfrm_dev_policy_flush_secctx_check(net, dev, task_valid);
1885 	if (err)
1886 		goto out;
1887 
1888 again:
1889 	list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1890 		if (pol->walk.dead)
1891 			continue;
1892 
1893 		dir = xfrm_policy_id2dir(pol->index);
1894 		if (dir >= XFRM_POLICY_MAX ||
1895 		    pol->xdo.dev != dev)
1896 			continue;
1897 
1898 		__xfrm_policy_unlink(pol, dir);
1899 		spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1900 		cnt++;
1901 		xfrm_audit_policy_delete(pol, 1, task_valid);
1902 		xfrm_policy_kill(pol);
1903 		spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1904 		goto again;
1905 	}
1906 	if (cnt)
1907 		__xfrm_policy_inexact_flush(net);
1908 	else
1909 		err = -ESRCH;
1910 out:
1911 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1912 	return err;
1913 }
1914 EXPORT_SYMBOL(xfrm_dev_policy_flush);
1915 
xfrm_policy_walk(struct net * net,struct xfrm_policy_walk * walk,int (* func)(struct xfrm_policy *,int,int,void *),void * data)1916 int xfrm_policy_walk(struct net *net, struct xfrm_policy_walk *walk,
1917 		     int (*func)(struct xfrm_policy *, int, int, void*),
1918 		     void *data)
1919 {
1920 	struct xfrm_policy *pol;
1921 	struct xfrm_policy_walk_entry *x;
1922 	int error = 0;
1923 
1924 	if (walk->type >= XFRM_POLICY_TYPE_MAX &&
1925 	    walk->type != XFRM_POLICY_TYPE_ANY)
1926 		return -EINVAL;
1927 
1928 	if (list_empty(&walk->walk.all) && walk->seq != 0)
1929 		return 0;
1930 
1931 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1932 	if (list_empty(&walk->walk.all))
1933 		x = list_first_entry(&net->xfrm.policy_all, struct xfrm_policy_walk_entry, all);
1934 	else
1935 		x = list_first_entry(&walk->walk.all,
1936 				     struct xfrm_policy_walk_entry, all);
1937 
1938 	list_for_each_entry_from(x, &net->xfrm.policy_all, all) {
1939 		if (x->dead)
1940 			continue;
1941 		pol = container_of(x, struct xfrm_policy, walk);
1942 		if (walk->type != XFRM_POLICY_TYPE_ANY &&
1943 		    walk->type != pol->type)
1944 			continue;
1945 		error = func(pol, xfrm_policy_id2dir(pol->index),
1946 			     walk->seq, data);
1947 		if (error) {
1948 			list_move_tail(&walk->walk.all, &x->all);
1949 			goto out;
1950 		}
1951 		walk->seq++;
1952 	}
1953 	if (walk->seq == 0) {
1954 		error = -ENOENT;
1955 		goto out;
1956 	}
1957 	list_del_init(&walk->walk.all);
1958 out:
1959 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1960 	return error;
1961 }
1962 EXPORT_SYMBOL(xfrm_policy_walk);
1963 
xfrm_policy_walk_init(struct xfrm_policy_walk * walk,u8 type)1964 void xfrm_policy_walk_init(struct xfrm_policy_walk *walk, u8 type)
1965 {
1966 	INIT_LIST_HEAD(&walk->walk.all);
1967 	walk->walk.dead = 1;
1968 	walk->type = type;
1969 	walk->seq = 0;
1970 }
1971 EXPORT_SYMBOL(xfrm_policy_walk_init);
1972 
xfrm_policy_walk_done(struct xfrm_policy_walk * walk,struct net * net)1973 void xfrm_policy_walk_done(struct xfrm_policy_walk *walk, struct net *net)
1974 {
1975 	if (list_empty(&walk->walk.all))
1976 		return;
1977 
1978 	spin_lock_bh(&net->xfrm.xfrm_policy_lock); /*FIXME where is net? */
1979 	list_del(&walk->walk.all);
1980 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1981 }
1982 EXPORT_SYMBOL(xfrm_policy_walk_done);
1983 
1984 /*
1985  * Find policy to apply to this flow.
1986  *
1987  * Returns 0 if policy found, else an -errno.
1988  */
xfrm_policy_match(const struct xfrm_policy * pol,const struct flowi * fl,u8 type,u16 family,u32 if_id)1989 static int xfrm_policy_match(const struct xfrm_policy *pol,
1990 			     const struct flowi *fl,
1991 			     u8 type, u16 family, u32 if_id)
1992 {
1993 	const struct xfrm_selector *sel = &pol->selector;
1994 	int ret = -ESRCH;
1995 	bool match;
1996 
1997 	if (pol->family != family ||
1998 	    pol->if_id != if_id ||
1999 	    (fl->flowi_mark & pol->mark.m) != pol->mark.v ||
2000 	    pol->type != type)
2001 		return ret;
2002 
2003 	match = xfrm_selector_match(sel, fl, family);
2004 	if (match)
2005 		ret = security_xfrm_policy_lookup(pol->security, fl->flowi_secid);
2006 	return ret;
2007 }
2008 
2009 static struct xfrm_pol_inexact_node *
xfrm_policy_lookup_inexact_addr(const struct rb_root * r,seqcount_spinlock_t * count,const xfrm_address_t * addr,u16 family)2010 xfrm_policy_lookup_inexact_addr(const struct rb_root *r,
2011 				seqcount_spinlock_t *count,
2012 				const xfrm_address_t *addr, u16 family)
2013 {
2014 	const struct rb_node *parent;
2015 	int seq;
2016 
2017 again:
2018 	seq = read_seqcount_begin(count);
2019 
2020 	parent = rcu_dereference_raw(r->rb_node);
2021 	while (parent) {
2022 		struct xfrm_pol_inexact_node *node;
2023 		int delta;
2024 
2025 		node = rb_entry(parent, struct xfrm_pol_inexact_node, node);
2026 
2027 		delta = xfrm_policy_addr_delta(addr, &node->addr,
2028 					       node->prefixlen, family);
2029 		if (delta < 0) {
2030 			parent = rcu_dereference_raw(parent->rb_left);
2031 			continue;
2032 		} else if (delta > 0) {
2033 			parent = rcu_dereference_raw(parent->rb_right);
2034 			continue;
2035 		}
2036 
2037 		return node;
2038 	}
2039 
2040 	if (read_seqcount_retry(count, seq))
2041 		goto again;
2042 
2043 	return NULL;
2044 }
2045 
2046 static bool
xfrm_policy_find_inexact_candidates(struct xfrm_pol_inexact_candidates * cand,struct xfrm_pol_inexact_bin * b,const xfrm_address_t * saddr,const xfrm_address_t * daddr)2047 xfrm_policy_find_inexact_candidates(struct xfrm_pol_inexact_candidates *cand,
2048 				    struct xfrm_pol_inexact_bin *b,
2049 				    const xfrm_address_t *saddr,
2050 				    const xfrm_address_t *daddr)
2051 {
2052 	struct xfrm_pol_inexact_node *n;
2053 	u16 family;
2054 
2055 	if (!b)
2056 		return false;
2057 
2058 	family = b->k.family;
2059 	memset(cand, 0, sizeof(*cand));
2060 	cand->res[XFRM_POL_CAND_ANY] = &b->hhead;
2061 
2062 	n = xfrm_policy_lookup_inexact_addr(&b->root_d, &b->count, daddr,
2063 					    family);
2064 	if (n) {
2065 		cand->res[XFRM_POL_CAND_DADDR] = &n->hhead;
2066 		n = xfrm_policy_lookup_inexact_addr(&n->root, &b->count, saddr,
2067 						    family);
2068 		if (n)
2069 			cand->res[XFRM_POL_CAND_BOTH] = &n->hhead;
2070 	}
2071 
2072 	n = xfrm_policy_lookup_inexact_addr(&b->root_s, &b->count, saddr,
2073 					    family);
2074 	if (n)
2075 		cand->res[XFRM_POL_CAND_SADDR] = &n->hhead;
2076 
2077 	return true;
2078 }
2079 
2080 static struct xfrm_pol_inexact_bin *
xfrm_policy_inexact_lookup_rcu(struct net * net,u8 type,u16 family,u8 dir,u32 if_id)2081 xfrm_policy_inexact_lookup_rcu(struct net *net, u8 type, u16 family,
2082 			       u8 dir, u32 if_id)
2083 {
2084 	struct xfrm_pol_inexact_key k = {
2085 		.family = family,
2086 		.type = type,
2087 		.dir = dir,
2088 		.if_id = if_id,
2089 	};
2090 
2091 	write_pnet(&k.net, net);
2092 
2093 	return rhashtable_lookup(&xfrm_policy_inexact_table, &k,
2094 				 xfrm_pol_inexact_params);
2095 }
2096 
2097 static struct xfrm_pol_inexact_bin *
xfrm_policy_inexact_lookup(struct net * net,u8 type,u16 family,u8 dir,u32 if_id)2098 xfrm_policy_inexact_lookup(struct net *net, u8 type, u16 family,
2099 			   u8 dir, u32 if_id)
2100 {
2101 	struct xfrm_pol_inexact_bin *bin;
2102 
2103 	lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
2104 
2105 	rcu_read_lock();
2106 	bin = xfrm_policy_inexact_lookup_rcu(net, type, family, dir, if_id);
2107 	rcu_read_unlock();
2108 
2109 	return bin;
2110 }
2111 
2112 static struct xfrm_policy *
__xfrm_policy_eval_candidates(struct hlist_head * chain,struct xfrm_policy * prefer,const struct flowi * fl,u8 type,u16 family,u32 if_id)2113 __xfrm_policy_eval_candidates(struct hlist_head *chain,
2114 			      struct xfrm_policy *prefer,
2115 			      const struct flowi *fl,
2116 			      u8 type, u16 family, u32 if_id)
2117 {
2118 	u32 priority = prefer ? prefer->priority : ~0u;
2119 	struct xfrm_policy *pol;
2120 
2121 	if (!chain)
2122 		return NULL;
2123 
2124 	hlist_for_each_entry_rcu(pol, chain, bydst) {
2125 		int err;
2126 
2127 		if (pol->priority > priority)
2128 			break;
2129 
2130 		err = xfrm_policy_match(pol, fl, type, family, if_id);
2131 		if (err) {
2132 			if (err != -ESRCH)
2133 				return ERR_PTR(err);
2134 
2135 			continue;
2136 		}
2137 
2138 		if (prefer) {
2139 			/* matches.  Is it older than *prefer? */
2140 			if (pol->priority == priority &&
2141 			    prefer->pos < pol->pos)
2142 				return prefer;
2143 		}
2144 
2145 		return pol;
2146 	}
2147 
2148 	return NULL;
2149 }
2150 
2151 static struct xfrm_policy *
xfrm_policy_eval_candidates(struct xfrm_pol_inexact_candidates * cand,struct xfrm_policy * prefer,const struct flowi * fl,u8 type,u16 family,u32 if_id)2152 xfrm_policy_eval_candidates(struct xfrm_pol_inexact_candidates *cand,
2153 			    struct xfrm_policy *prefer,
2154 			    const struct flowi *fl,
2155 			    u8 type, u16 family, u32 if_id)
2156 {
2157 	struct xfrm_policy *tmp;
2158 	int i;
2159 
2160 	for (i = 0; i < ARRAY_SIZE(cand->res); i++) {
2161 		tmp = __xfrm_policy_eval_candidates(cand->res[i],
2162 						    prefer,
2163 						    fl, type, family, if_id);
2164 		if (!tmp)
2165 			continue;
2166 
2167 		if (IS_ERR(tmp))
2168 			return tmp;
2169 		prefer = tmp;
2170 	}
2171 
2172 	return prefer;
2173 }
2174 
xfrm_policy_lookup_bytype(struct net * net,u8 type,const struct flowi * fl,u16 family,u8 dir,u32 if_id)2175 static struct xfrm_policy *xfrm_policy_lookup_bytype(struct net *net, u8 type,
2176 						     const struct flowi *fl,
2177 						     u16 family, u8 dir,
2178 						     u32 if_id)
2179 {
2180 	struct xfrm_pol_inexact_candidates cand;
2181 	const xfrm_address_t *daddr, *saddr;
2182 	struct xfrm_pol_inexact_bin *bin;
2183 	struct xfrm_policy *pol, *ret;
2184 	struct hlist_head *chain;
2185 	unsigned int sequence;
2186 	int err;
2187 
2188 	daddr = xfrm_flowi_daddr(fl, family);
2189 	saddr = xfrm_flowi_saddr(fl, family);
2190 	if (unlikely(!daddr || !saddr))
2191 		return NULL;
2192 
2193 	rcu_read_lock();
2194  retry:
2195 	do {
2196 		sequence = read_seqcount_begin(&net->xfrm.xfrm_policy_hash_generation);
2197 		chain = policy_hash_direct(net, daddr, saddr, family, dir);
2198 	} while (read_seqcount_retry(&net->xfrm.xfrm_policy_hash_generation, sequence));
2199 
2200 	ret = NULL;
2201 	hlist_for_each_entry_rcu(pol, chain, bydst) {
2202 		err = xfrm_policy_match(pol, fl, type, family, if_id);
2203 		if (err) {
2204 			if (err == -ESRCH)
2205 				continue;
2206 			else {
2207 				ret = ERR_PTR(err);
2208 				goto fail;
2209 			}
2210 		} else {
2211 			ret = pol;
2212 			break;
2213 		}
2214 	}
2215 	if (ret && ret->xdo.type == XFRM_DEV_OFFLOAD_PACKET)
2216 		goto skip_inexact;
2217 
2218 	bin = xfrm_policy_inexact_lookup_rcu(net, type, family, dir, if_id);
2219 	if (!bin || !xfrm_policy_find_inexact_candidates(&cand, bin, saddr,
2220 							 daddr))
2221 		goto skip_inexact;
2222 
2223 	pol = xfrm_policy_eval_candidates(&cand, ret, fl, type,
2224 					  family, if_id);
2225 	if (pol) {
2226 		ret = pol;
2227 		if (IS_ERR(pol))
2228 			goto fail;
2229 	}
2230 
2231 skip_inexact:
2232 	if (read_seqcount_retry(&net->xfrm.xfrm_policy_hash_generation, sequence))
2233 		goto retry;
2234 
2235 	if (ret && !xfrm_pol_hold_rcu(ret))
2236 		goto retry;
2237 fail:
2238 	rcu_read_unlock();
2239 
2240 	return ret;
2241 }
2242 
xfrm_policy_lookup(struct net * net,const struct flowi * fl,u16 family,u8 dir,u32 if_id)2243 static struct xfrm_policy *xfrm_policy_lookup(struct net *net,
2244 					      const struct flowi *fl,
2245 					      u16 family, u8 dir, u32 if_id)
2246 {
2247 #ifdef CONFIG_XFRM_SUB_POLICY
2248 	struct xfrm_policy *pol;
2249 
2250 	pol = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_SUB, fl, family,
2251 					dir, if_id);
2252 	if (pol != NULL)
2253 		return pol;
2254 #endif
2255 	return xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN, fl, family,
2256 					 dir, if_id);
2257 }
2258 
xfrm_sk_policy_lookup(const struct sock * sk,int dir,const struct flowi * fl,u16 family,u32 if_id)2259 static struct xfrm_policy *xfrm_sk_policy_lookup(const struct sock *sk, int dir,
2260 						 const struct flowi *fl,
2261 						 u16 family, u32 if_id)
2262 {
2263 	struct xfrm_policy *pol;
2264 
2265 	rcu_read_lock();
2266  again:
2267 	pol = rcu_dereference(sk->sk_policy[dir]);
2268 	if (pol != NULL) {
2269 		bool match;
2270 		int err = 0;
2271 
2272 		if (pol->family != family) {
2273 			pol = NULL;
2274 			goto out;
2275 		}
2276 
2277 		match = xfrm_selector_match(&pol->selector, fl, family);
2278 		if (match) {
2279 			if ((READ_ONCE(sk->sk_mark) & pol->mark.m) != pol->mark.v ||
2280 			    pol->if_id != if_id) {
2281 				pol = NULL;
2282 				goto out;
2283 			}
2284 			err = security_xfrm_policy_lookup(pol->security,
2285 						      fl->flowi_secid);
2286 			if (!err) {
2287 				if (!xfrm_pol_hold_rcu(pol))
2288 					goto again;
2289 			} else if (err == -ESRCH) {
2290 				pol = NULL;
2291 			} else {
2292 				pol = ERR_PTR(err);
2293 			}
2294 		} else
2295 			pol = NULL;
2296 	}
2297 out:
2298 	rcu_read_unlock();
2299 	return pol;
2300 }
2301 
__xfrm_policy_link(struct xfrm_policy * pol,int dir)2302 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
2303 {
2304 	struct net *net = xp_net(pol);
2305 
2306 	list_add(&pol->walk.all, &net->xfrm.policy_all);
2307 	net->xfrm.policy_count[dir]++;
2308 	xfrm_pol_hold(pol);
2309 }
2310 
__xfrm_policy_unlink(struct xfrm_policy * pol,int dir)2311 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
2312 						int dir)
2313 {
2314 	struct net *net = xp_net(pol);
2315 
2316 	if (list_empty(&pol->walk.all))
2317 		return NULL;
2318 
2319 	/* Socket policies are not hashed. */
2320 	if (!hlist_unhashed(&pol->bydst)) {
2321 		hlist_del_rcu(&pol->bydst);
2322 		hlist_del_init(&pol->bydst_inexact_list);
2323 		hlist_del(&pol->byidx);
2324 	}
2325 
2326 	list_del_init(&pol->walk.all);
2327 	net->xfrm.policy_count[dir]--;
2328 
2329 	return pol;
2330 }
2331 
xfrm_sk_policy_link(struct xfrm_policy * pol,int dir)2332 static void xfrm_sk_policy_link(struct xfrm_policy *pol, int dir)
2333 {
2334 	__xfrm_policy_link(pol, XFRM_POLICY_MAX + dir);
2335 }
2336 
xfrm_sk_policy_unlink(struct xfrm_policy * pol,int dir)2337 static void xfrm_sk_policy_unlink(struct xfrm_policy *pol, int dir)
2338 {
2339 	__xfrm_policy_unlink(pol, XFRM_POLICY_MAX + dir);
2340 }
2341 
xfrm_policy_delete(struct xfrm_policy * pol,int dir)2342 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
2343 {
2344 	struct net *net = xp_net(pol);
2345 
2346 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2347 	pol = __xfrm_policy_unlink(pol, dir);
2348 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2349 	if (pol) {
2350 		xfrm_policy_kill(pol);
2351 		return 0;
2352 	}
2353 	return -ENOENT;
2354 }
2355 EXPORT_SYMBOL(xfrm_policy_delete);
2356 
xfrm_sk_policy_insert(struct sock * sk,int dir,struct xfrm_policy * pol)2357 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
2358 {
2359 	struct net *net = sock_net(sk);
2360 	struct xfrm_policy *old_pol;
2361 
2362 #ifdef CONFIG_XFRM_SUB_POLICY
2363 	if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
2364 		return -EINVAL;
2365 #endif
2366 
2367 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2368 	old_pol = rcu_dereference_protected(sk->sk_policy[dir],
2369 				lockdep_is_held(&net->xfrm.xfrm_policy_lock));
2370 	if (pol) {
2371 		pol->curlft.add_time = ktime_get_real_seconds();
2372 		pol->index = xfrm_gen_index(net, XFRM_POLICY_MAX+dir, 0);
2373 		xfrm_sk_policy_link(pol, dir);
2374 	}
2375 	rcu_assign_pointer(sk->sk_policy[dir], pol);
2376 	if (old_pol) {
2377 		if (pol)
2378 			xfrm_policy_requeue(old_pol, pol);
2379 
2380 		/* Unlinking succeeds always. This is the only function
2381 		 * allowed to delete or replace socket policy.
2382 		 */
2383 		xfrm_sk_policy_unlink(old_pol, dir);
2384 	}
2385 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2386 
2387 	if (old_pol) {
2388 		xfrm_policy_kill(old_pol);
2389 	}
2390 	return 0;
2391 }
2392 
clone_policy(const struct xfrm_policy * old,int dir)2393 static struct xfrm_policy *clone_policy(const struct xfrm_policy *old, int dir)
2394 {
2395 	struct xfrm_policy *newp = xfrm_policy_alloc(xp_net(old), GFP_ATOMIC);
2396 	struct net *net = xp_net(old);
2397 
2398 	if (newp) {
2399 		newp->selector = old->selector;
2400 		if (security_xfrm_policy_clone(old->security,
2401 					       &newp->security)) {
2402 			kfree(newp);
2403 			return NULL;  /* ENOMEM */
2404 		}
2405 		newp->lft = old->lft;
2406 		newp->curlft = old->curlft;
2407 		newp->mark = old->mark;
2408 		newp->if_id = old->if_id;
2409 		newp->action = old->action;
2410 		newp->flags = old->flags;
2411 		newp->xfrm_nr = old->xfrm_nr;
2412 		newp->index = old->index;
2413 		newp->type = old->type;
2414 		newp->family = old->family;
2415 		memcpy(newp->xfrm_vec, old->xfrm_vec,
2416 		       newp->xfrm_nr*sizeof(struct xfrm_tmpl));
2417 		spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2418 		xfrm_sk_policy_link(newp, dir);
2419 		spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2420 		xfrm_pol_put(newp);
2421 	}
2422 	return newp;
2423 }
2424 
__xfrm_sk_clone_policy(struct sock * sk,const struct sock * osk)2425 int __xfrm_sk_clone_policy(struct sock *sk, const struct sock *osk)
2426 {
2427 	const struct xfrm_policy *p;
2428 	struct xfrm_policy *np;
2429 	int i, ret = 0;
2430 
2431 	rcu_read_lock();
2432 	for (i = 0; i < 2; i++) {
2433 		p = rcu_dereference(osk->sk_policy[i]);
2434 		if (p) {
2435 			np = clone_policy(p, i);
2436 			if (unlikely(!np)) {
2437 				ret = -ENOMEM;
2438 				break;
2439 			}
2440 			rcu_assign_pointer(sk->sk_policy[i], np);
2441 		}
2442 	}
2443 	rcu_read_unlock();
2444 	return ret;
2445 }
2446 
2447 static int
xfrm_get_saddr(unsigned short family,xfrm_address_t * saddr,const struct xfrm_dst_lookup_params * params)2448 xfrm_get_saddr(unsigned short family, xfrm_address_t *saddr,
2449 	       const struct xfrm_dst_lookup_params *params)
2450 {
2451 	int err;
2452 	const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2453 
2454 	if (unlikely(afinfo == NULL))
2455 		return -EINVAL;
2456 	err = afinfo->get_saddr(saddr, params);
2457 	rcu_read_unlock();
2458 	return err;
2459 }
2460 
2461 /* Resolve list of templates for the flow, given policy. */
2462 
2463 static int
xfrm_tmpl_resolve_one(struct xfrm_policy * policy,const struct flowi * fl,struct xfrm_state ** xfrm,unsigned short family)2464 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, const struct flowi *fl,
2465 		      struct xfrm_state **xfrm, unsigned short family)
2466 {
2467 	struct net *net = xp_net(policy);
2468 	int nx;
2469 	int i, error;
2470 	xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
2471 	xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
2472 	xfrm_address_t tmp;
2473 
2474 	for (nx = 0, i = 0; i < policy->xfrm_nr; i++) {
2475 		struct xfrm_state *x;
2476 		xfrm_address_t *remote = daddr;
2477 		xfrm_address_t *local  = saddr;
2478 		struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
2479 
2480 		if (tmpl->mode == XFRM_MODE_TUNNEL ||
2481 		    tmpl->mode == XFRM_MODE_BEET) {
2482 			remote = &tmpl->id.daddr;
2483 			local = &tmpl->saddr;
2484 			if (xfrm_addr_any(local, tmpl->encap_family)) {
2485 				struct xfrm_dst_lookup_params params;
2486 
2487 				memset(&params, 0, sizeof(params));
2488 				params.net = net;
2489 				params.oif = fl->flowi_oif;
2490 				params.daddr = remote;
2491 				error = xfrm_get_saddr(tmpl->encap_family, &tmp,
2492 						       &params);
2493 				if (error)
2494 					goto fail;
2495 				local = &tmp;
2496 			}
2497 		}
2498 
2499 		x = xfrm_state_find(remote, local, fl, tmpl, policy, &error,
2500 				    family, policy->if_id);
2501 
2502 		if (x && x->km.state == XFRM_STATE_VALID) {
2503 			xfrm[nx++] = x;
2504 			daddr = remote;
2505 			saddr = local;
2506 			continue;
2507 		}
2508 		if (x) {
2509 			error = (x->km.state == XFRM_STATE_ERROR ?
2510 				 -EINVAL : -EAGAIN);
2511 			xfrm_state_put(x);
2512 		} else if (error == -ESRCH) {
2513 			error = -EAGAIN;
2514 		}
2515 
2516 		if (!tmpl->optional)
2517 			goto fail;
2518 	}
2519 	return nx;
2520 
2521 fail:
2522 	for (nx--; nx >= 0; nx--)
2523 		xfrm_state_put(xfrm[nx]);
2524 	return error;
2525 }
2526 
2527 static int
xfrm_tmpl_resolve(struct xfrm_policy ** pols,int npols,const struct flowi * fl,struct xfrm_state ** xfrm,unsigned short family)2528 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, const struct flowi *fl,
2529 		  struct xfrm_state **xfrm, unsigned short family)
2530 {
2531 	struct xfrm_state *tp[XFRM_MAX_DEPTH];
2532 	struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
2533 	int cnx = 0;
2534 	int error;
2535 	int ret;
2536 	int i;
2537 
2538 	for (i = 0; i < npols; i++) {
2539 		if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
2540 			error = -ENOBUFS;
2541 			goto fail;
2542 		}
2543 
2544 		ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
2545 		if (ret < 0) {
2546 			error = ret;
2547 			goto fail;
2548 		} else
2549 			cnx += ret;
2550 	}
2551 
2552 	/* found states are sorted for outbound processing */
2553 	if (npols > 1)
2554 		xfrm_state_sort(xfrm, tpp, cnx, family);
2555 
2556 	return cnx;
2557 
2558  fail:
2559 	for (cnx--; cnx >= 0; cnx--)
2560 		xfrm_state_put(tpp[cnx]);
2561 	return error;
2562 
2563 }
2564 
xfrm_get_tos(const struct flowi * fl,int family)2565 static int xfrm_get_tos(const struct flowi *fl, int family)
2566 {
2567 	if (family == AF_INET)
2568 		return IPTOS_RT_MASK & fl->u.ip4.flowi4_tos;
2569 
2570 	return 0;
2571 }
2572 
xfrm_alloc_dst(struct net * net,int family)2573 static inline struct xfrm_dst *xfrm_alloc_dst(struct net *net, int family)
2574 {
2575 	const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2576 	struct dst_ops *dst_ops;
2577 	struct xfrm_dst *xdst;
2578 
2579 	if (!afinfo)
2580 		return ERR_PTR(-EINVAL);
2581 
2582 	switch (family) {
2583 	case AF_INET:
2584 		dst_ops = &net->xfrm.xfrm4_dst_ops;
2585 		break;
2586 #if IS_ENABLED(CONFIG_IPV6)
2587 	case AF_INET6:
2588 		dst_ops = &net->xfrm.xfrm6_dst_ops;
2589 		break;
2590 #endif
2591 	default:
2592 		BUG();
2593 	}
2594 	xdst = dst_alloc(dst_ops, NULL, 1, DST_OBSOLETE_NONE, 0);
2595 
2596 	if (likely(xdst)) {
2597 		memset_after(xdst, 0, u.dst);
2598 	} else
2599 		xdst = ERR_PTR(-ENOBUFS);
2600 
2601 	rcu_read_unlock();
2602 
2603 	return xdst;
2604 }
2605 
xfrm_init_path(struct xfrm_dst * path,struct dst_entry * dst,int nfheader_len)2606 static void xfrm_init_path(struct xfrm_dst *path, struct dst_entry *dst,
2607 			   int nfheader_len)
2608 {
2609 	if (dst->ops->family == AF_INET6) {
2610 		struct rt6_info *rt = (struct rt6_info *)dst;
2611 		path->path_cookie = rt6_get_cookie(rt);
2612 		path->u.rt6.rt6i_nfheader_len = nfheader_len;
2613 	}
2614 }
2615 
xfrm_fill_dst(struct xfrm_dst * xdst,struct net_device * dev,const struct flowi * fl)2616 static inline int xfrm_fill_dst(struct xfrm_dst *xdst, struct net_device *dev,
2617 				const struct flowi *fl)
2618 {
2619 	const struct xfrm_policy_afinfo *afinfo =
2620 		xfrm_policy_get_afinfo(xdst->u.dst.ops->family);
2621 	int err;
2622 
2623 	if (!afinfo)
2624 		return -EINVAL;
2625 
2626 	err = afinfo->fill_dst(xdst, dev, fl);
2627 
2628 	rcu_read_unlock();
2629 
2630 	return err;
2631 }
2632 
2633 
2634 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
2635  * all the metrics... Shortly, bundle a bundle.
2636  */
2637 
xfrm_bundle_create(struct xfrm_policy * policy,struct xfrm_state ** xfrm,struct xfrm_dst ** bundle,int nx,const struct flowi * fl,struct dst_entry * dst)2638 static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy,
2639 					    struct xfrm_state **xfrm,
2640 					    struct xfrm_dst **bundle,
2641 					    int nx,
2642 					    const struct flowi *fl,
2643 					    struct dst_entry *dst)
2644 {
2645 	const struct xfrm_state_afinfo *afinfo;
2646 	const struct xfrm_mode *inner_mode;
2647 	struct net *net = xp_net(policy);
2648 	unsigned long now = jiffies;
2649 	struct net_device *dev;
2650 	struct xfrm_dst *xdst_prev = NULL;
2651 	struct xfrm_dst *xdst0 = NULL;
2652 	int i = 0;
2653 	int err;
2654 	int header_len = 0;
2655 	int nfheader_len = 0;
2656 	int trailer_len = 0;
2657 	int tos;
2658 	int family = policy->selector.family;
2659 	xfrm_address_t saddr, daddr;
2660 
2661 	xfrm_flowi_addr_get(fl, &saddr, &daddr, family);
2662 
2663 	tos = xfrm_get_tos(fl, family);
2664 
2665 	dst_hold(dst);
2666 
2667 	for (; i < nx; i++) {
2668 		struct xfrm_dst *xdst = xfrm_alloc_dst(net, family);
2669 		struct dst_entry *dst1 = &xdst->u.dst;
2670 
2671 		err = PTR_ERR(xdst);
2672 		if (IS_ERR(xdst)) {
2673 			dst_release(dst);
2674 			goto put_states;
2675 		}
2676 
2677 		bundle[i] = xdst;
2678 		if (!xdst_prev)
2679 			xdst0 = xdst;
2680 		else
2681 			/* Ref count is taken during xfrm_alloc_dst()
2682 			 * No need to do dst_clone() on dst1
2683 			 */
2684 			xfrm_dst_set_child(xdst_prev, &xdst->u.dst);
2685 
2686 		if (xfrm[i]->sel.family == AF_UNSPEC) {
2687 			inner_mode = xfrm_ip2inner_mode(xfrm[i],
2688 							xfrm_af2proto(family));
2689 			if (!inner_mode) {
2690 				err = -EAFNOSUPPORT;
2691 				dst_release(dst);
2692 				goto put_states;
2693 			}
2694 		} else
2695 			inner_mode = &xfrm[i]->inner_mode;
2696 
2697 		xdst->route = dst;
2698 		dst_copy_metrics(dst1, dst);
2699 
2700 		if (xfrm[i]->props.mode != XFRM_MODE_TRANSPORT) {
2701 			__u32 mark = 0;
2702 			int oif;
2703 
2704 			if (xfrm[i]->props.smark.v || xfrm[i]->props.smark.m)
2705 				mark = xfrm_smark_get(fl->flowi_mark, xfrm[i]);
2706 
2707 			if (xfrm[i]->xso.type != XFRM_DEV_OFFLOAD_PACKET)
2708 				family = xfrm[i]->props.family;
2709 
2710 			oif = fl->flowi_oif ? : fl->flowi_l3mdev;
2711 			dst = xfrm_dst_lookup(xfrm[i], tos, oif,
2712 					      &saddr, &daddr, family, mark);
2713 			err = PTR_ERR(dst);
2714 			if (IS_ERR(dst))
2715 				goto put_states;
2716 		} else
2717 			dst_hold(dst);
2718 
2719 		dst1->xfrm = xfrm[i];
2720 		xdst->xfrm_genid = xfrm[i]->genid;
2721 
2722 		dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2723 		dst1->lastuse = now;
2724 
2725 		dst1->input = dst_discard;
2726 
2727 		rcu_read_lock();
2728 		afinfo = xfrm_state_afinfo_get_rcu(inner_mode->family);
2729 		if (likely(afinfo))
2730 			dst1->output = afinfo->output;
2731 		else
2732 			dst1->output = dst_discard_out;
2733 		rcu_read_unlock();
2734 
2735 		xdst_prev = xdst;
2736 
2737 		header_len += xfrm[i]->props.header_len;
2738 		if (xfrm[i]->type->flags & XFRM_TYPE_NON_FRAGMENT)
2739 			nfheader_len += xfrm[i]->props.header_len;
2740 		trailer_len += xfrm[i]->props.trailer_len;
2741 	}
2742 
2743 	xfrm_dst_set_child(xdst_prev, dst);
2744 	xdst0->path = dst;
2745 
2746 	err = -ENODEV;
2747 	dev = dst->dev;
2748 	if (!dev)
2749 		goto free_dst;
2750 
2751 	xfrm_init_path(xdst0, dst, nfheader_len);
2752 	xfrm_init_pmtu(bundle, nx);
2753 
2754 	for (xdst_prev = xdst0; xdst_prev != (struct xfrm_dst *)dst;
2755 	     xdst_prev = (struct xfrm_dst *) xfrm_dst_child(&xdst_prev->u.dst)) {
2756 		err = xfrm_fill_dst(xdst_prev, dev, fl);
2757 		if (err)
2758 			goto free_dst;
2759 
2760 		xdst_prev->u.dst.header_len = header_len;
2761 		xdst_prev->u.dst.trailer_len = trailer_len;
2762 		header_len -= xdst_prev->u.dst.xfrm->props.header_len;
2763 		trailer_len -= xdst_prev->u.dst.xfrm->props.trailer_len;
2764 	}
2765 
2766 	return &xdst0->u.dst;
2767 
2768 put_states:
2769 	for (; i < nx; i++)
2770 		xfrm_state_put(xfrm[i]);
2771 free_dst:
2772 	if (xdst0)
2773 		dst_release_immediate(&xdst0->u.dst);
2774 
2775 	return ERR_PTR(err);
2776 }
2777 
xfrm_expand_policies(const struct flowi * fl,u16 family,struct xfrm_policy ** pols,int * num_pols,int * num_xfrms)2778 static int xfrm_expand_policies(const struct flowi *fl, u16 family,
2779 				struct xfrm_policy **pols,
2780 				int *num_pols, int *num_xfrms)
2781 {
2782 	int i;
2783 
2784 	if (*num_pols == 0 || !pols[0]) {
2785 		*num_pols = 0;
2786 		*num_xfrms = 0;
2787 		return 0;
2788 	}
2789 	if (IS_ERR(pols[0])) {
2790 		*num_pols = 0;
2791 		return PTR_ERR(pols[0]);
2792 	}
2793 
2794 	*num_xfrms = pols[0]->xfrm_nr;
2795 
2796 #ifdef CONFIG_XFRM_SUB_POLICY
2797 	if (pols[0]->action == XFRM_POLICY_ALLOW &&
2798 	    pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
2799 		pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
2800 						    XFRM_POLICY_TYPE_MAIN,
2801 						    fl, family,
2802 						    XFRM_POLICY_OUT,
2803 						    pols[0]->if_id);
2804 		if (pols[1]) {
2805 			if (IS_ERR(pols[1])) {
2806 				xfrm_pols_put(pols, *num_pols);
2807 				*num_pols = 0;
2808 				return PTR_ERR(pols[1]);
2809 			}
2810 			(*num_pols)++;
2811 			(*num_xfrms) += pols[1]->xfrm_nr;
2812 		}
2813 	}
2814 #endif
2815 	for (i = 0; i < *num_pols; i++) {
2816 		if (pols[i]->action != XFRM_POLICY_ALLOW) {
2817 			*num_xfrms = -1;
2818 			break;
2819 		}
2820 	}
2821 
2822 	return 0;
2823 
2824 }
2825 
2826 static struct xfrm_dst *
xfrm_resolve_and_create_bundle(struct xfrm_policy ** pols,int num_pols,const struct flowi * fl,u16 family,struct dst_entry * dst_orig)2827 xfrm_resolve_and_create_bundle(struct xfrm_policy **pols, int num_pols,
2828 			       const struct flowi *fl, u16 family,
2829 			       struct dst_entry *dst_orig)
2830 {
2831 	struct net *net = xp_net(pols[0]);
2832 	struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
2833 	struct xfrm_dst *bundle[XFRM_MAX_DEPTH];
2834 	struct xfrm_dst *xdst;
2835 	struct dst_entry *dst;
2836 	int err;
2837 
2838 	/* Try to instantiate a bundle */
2839 	err = xfrm_tmpl_resolve(pols, num_pols, fl, xfrm, family);
2840 	if (err <= 0) {
2841 		if (err == 0)
2842 			return NULL;
2843 
2844 		if (err != -EAGAIN)
2845 			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
2846 		return ERR_PTR(err);
2847 	}
2848 
2849 	dst = xfrm_bundle_create(pols[0], xfrm, bundle, err, fl, dst_orig);
2850 	if (IS_ERR(dst)) {
2851 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLEGENERROR);
2852 		return ERR_CAST(dst);
2853 	}
2854 
2855 	xdst = (struct xfrm_dst *)dst;
2856 	xdst->num_xfrms = err;
2857 	xdst->num_pols = num_pols;
2858 	memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
2859 	xdst->policy_genid = atomic_read(&pols[0]->genid);
2860 
2861 	return xdst;
2862 }
2863 
xfrm_policy_queue_process(struct timer_list * t)2864 static void xfrm_policy_queue_process(struct timer_list *t)
2865 {
2866 	struct sk_buff *skb;
2867 	struct sock *sk;
2868 	struct dst_entry *dst;
2869 	struct xfrm_policy *pol = from_timer(pol, t, polq.hold_timer);
2870 	struct net *net = xp_net(pol);
2871 	struct xfrm_policy_queue *pq = &pol->polq;
2872 	struct flowi fl;
2873 	struct sk_buff_head list;
2874 	__u32 skb_mark;
2875 
2876 	spin_lock(&pq->hold_queue.lock);
2877 	skb = skb_peek(&pq->hold_queue);
2878 	if (!skb) {
2879 		spin_unlock(&pq->hold_queue.lock);
2880 		goto out;
2881 	}
2882 	dst = skb_dst(skb);
2883 	sk = skb->sk;
2884 
2885 	/* Fixup the mark to support VTI. */
2886 	skb_mark = skb->mark;
2887 	skb->mark = pol->mark.v;
2888 	xfrm_decode_session(skb, &fl, dst->ops->family);
2889 	skb->mark = skb_mark;
2890 	spin_unlock(&pq->hold_queue.lock);
2891 
2892 	dst_hold(xfrm_dst_path(dst));
2893 	dst = xfrm_lookup(net, xfrm_dst_path(dst), &fl, sk, XFRM_LOOKUP_QUEUE);
2894 	if (IS_ERR(dst))
2895 		goto purge_queue;
2896 
2897 	if (dst->flags & DST_XFRM_QUEUE) {
2898 		dst_release(dst);
2899 
2900 		if (pq->timeout >= XFRM_QUEUE_TMO_MAX)
2901 			goto purge_queue;
2902 
2903 		pq->timeout = pq->timeout << 1;
2904 		if (!mod_timer(&pq->hold_timer, jiffies + pq->timeout))
2905 			xfrm_pol_hold(pol);
2906 		goto out;
2907 	}
2908 
2909 	dst_release(dst);
2910 
2911 	__skb_queue_head_init(&list);
2912 
2913 	spin_lock(&pq->hold_queue.lock);
2914 	pq->timeout = 0;
2915 	skb_queue_splice_init(&pq->hold_queue, &list);
2916 	spin_unlock(&pq->hold_queue.lock);
2917 
2918 	while (!skb_queue_empty(&list)) {
2919 		skb = __skb_dequeue(&list);
2920 
2921 		/* Fixup the mark to support VTI. */
2922 		skb_mark = skb->mark;
2923 		skb->mark = pol->mark.v;
2924 		xfrm_decode_session(skb, &fl, skb_dst(skb)->ops->family);
2925 		skb->mark = skb_mark;
2926 
2927 		dst_hold(xfrm_dst_path(skb_dst(skb)));
2928 		dst = xfrm_lookup(net, xfrm_dst_path(skb_dst(skb)), &fl, skb->sk, 0);
2929 		if (IS_ERR(dst)) {
2930 			kfree_skb(skb);
2931 			continue;
2932 		}
2933 
2934 		nf_reset_ct(skb);
2935 		skb_dst_drop(skb);
2936 		skb_dst_set(skb, dst);
2937 
2938 		dst_output(net, skb->sk, skb);
2939 	}
2940 
2941 out:
2942 	xfrm_pol_put(pol);
2943 	return;
2944 
2945 purge_queue:
2946 	pq->timeout = 0;
2947 	skb_queue_purge(&pq->hold_queue);
2948 	xfrm_pol_put(pol);
2949 }
2950 
xdst_queue_output(struct net * net,struct sock * sk,struct sk_buff * skb)2951 static int xdst_queue_output(struct net *net, struct sock *sk, struct sk_buff *skb)
2952 {
2953 	unsigned long sched_next;
2954 	struct dst_entry *dst = skb_dst(skb);
2955 	struct xfrm_dst *xdst = (struct xfrm_dst *) dst;
2956 	struct xfrm_policy *pol = xdst->pols[0];
2957 	struct xfrm_policy_queue *pq = &pol->polq;
2958 
2959 	if (unlikely(skb_fclone_busy(sk, skb))) {
2960 		kfree_skb(skb);
2961 		return 0;
2962 	}
2963 
2964 	if (pq->hold_queue.qlen > XFRM_MAX_QUEUE_LEN) {
2965 		kfree_skb(skb);
2966 		return -EAGAIN;
2967 	}
2968 
2969 	skb_dst_force(skb);
2970 
2971 	spin_lock_bh(&pq->hold_queue.lock);
2972 
2973 	if (!pq->timeout)
2974 		pq->timeout = XFRM_QUEUE_TMO_MIN;
2975 
2976 	sched_next = jiffies + pq->timeout;
2977 
2978 	if (del_timer(&pq->hold_timer)) {
2979 		if (time_before(pq->hold_timer.expires, sched_next))
2980 			sched_next = pq->hold_timer.expires;
2981 		xfrm_pol_put(pol);
2982 	}
2983 
2984 	__skb_queue_tail(&pq->hold_queue, skb);
2985 	if (!mod_timer(&pq->hold_timer, sched_next))
2986 		xfrm_pol_hold(pol);
2987 
2988 	spin_unlock_bh(&pq->hold_queue.lock);
2989 
2990 	return 0;
2991 }
2992 
xfrm_create_dummy_bundle(struct net * net,struct xfrm_flo * xflo,const struct flowi * fl,int num_xfrms,u16 family)2993 static struct xfrm_dst *xfrm_create_dummy_bundle(struct net *net,
2994 						 struct xfrm_flo *xflo,
2995 						 const struct flowi *fl,
2996 						 int num_xfrms,
2997 						 u16 family)
2998 {
2999 	int err;
3000 	struct net_device *dev;
3001 	struct dst_entry *dst;
3002 	struct dst_entry *dst1;
3003 	struct xfrm_dst *xdst;
3004 
3005 	xdst = xfrm_alloc_dst(net, family);
3006 	if (IS_ERR(xdst))
3007 		return xdst;
3008 
3009 	if (!(xflo->flags & XFRM_LOOKUP_QUEUE) ||
3010 	    net->xfrm.sysctl_larval_drop ||
3011 	    num_xfrms <= 0)
3012 		return xdst;
3013 
3014 	dst = xflo->dst_orig;
3015 	dst1 = &xdst->u.dst;
3016 	dst_hold(dst);
3017 	xdst->route = dst;
3018 
3019 	dst_copy_metrics(dst1, dst);
3020 
3021 	dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
3022 	dst1->flags |= DST_XFRM_QUEUE;
3023 	dst1->lastuse = jiffies;
3024 
3025 	dst1->input = dst_discard;
3026 	dst1->output = xdst_queue_output;
3027 
3028 	dst_hold(dst);
3029 	xfrm_dst_set_child(xdst, dst);
3030 	xdst->path = dst;
3031 
3032 	xfrm_init_path((struct xfrm_dst *)dst1, dst, 0);
3033 
3034 	err = -ENODEV;
3035 	dev = dst->dev;
3036 	if (!dev)
3037 		goto free_dst;
3038 
3039 	err = xfrm_fill_dst(xdst, dev, fl);
3040 	if (err)
3041 		goto free_dst;
3042 
3043 out:
3044 	return xdst;
3045 
3046 free_dst:
3047 	dst_release(dst1);
3048 	xdst = ERR_PTR(err);
3049 	goto out;
3050 }
3051 
xfrm_bundle_lookup(struct net * net,const struct flowi * fl,u16 family,u8 dir,struct xfrm_flo * xflo,u32 if_id)3052 static struct xfrm_dst *xfrm_bundle_lookup(struct net *net,
3053 					   const struct flowi *fl,
3054 					   u16 family, u8 dir,
3055 					   struct xfrm_flo *xflo, u32 if_id)
3056 {
3057 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3058 	int num_pols = 0, num_xfrms = 0, err;
3059 	struct xfrm_dst *xdst;
3060 
3061 	/* Resolve policies to use if we couldn't get them from
3062 	 * previous cache entry */
3063 	num_pols = 1;
3064 	pols[0] = xfrm_policy_lookup(net, fl, family, dir, if_id);
3065 	err = xfrm_expand_policies(fl, family, pols,
3066 					   &num_pols, &num_xfrms);
3067 	if (err < 0)
3068 		goto inc_error;
3069 	if (num_pols == 0)
3070 		return NULL;
3071 	if (num_xfrms <= 0)
3072 		goto make_dummy_bundle;
3073 
3074 	xdst = xfrm_resolve_and_create_bundle(pols, num_pols, fl, family,
3075 					      xflo->dst_orig);
3076 	if (IS_ERR(xdst)) {
3077 		err = PTR_ERR(xdst);
3078 		if (err == -EREMOTE) {
3079 			xfrm_pols_put(pols, num_pols);
3080 			return NULL;
3081 		}
3082 
3083 		if (err != -EAGAIN)
3084 			goto error;
3085 		goto make_dummy_bundle;
3086 	} else if (xdst == NULL) {
3087 		num_xfrms = 0;
3088 		goto make_dummy_bundle;
3089 	}
3090 
3091 	return xdst;
3092 
3093 make_dummy_bundle:
3094 	/* We found policies, but there's no bundles to instantiate:
3095 	 * either because the policy blocks, has no transformations or
3096 	 * we could not build template (no xfrm_states).*/
3097 	xdst = xfrm_create_dummy_bundle(net, xflo, fl, num_xfrms, family);
3098 	if (IS_ERR(xdst)) {
3099 		xfrm_pols_put(pols, num_pols);
3100 		return ERR_CAST(xdst);
3101 	}
3102 	xdst->num_pols = num_pols;
3103 	xdst->num_xfrms = num_xfrms;
3104 	memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
3105 
3106 	return xdst;
3107 
3108 inc_error:
3109 	XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
3110 error:
3111 	xfrm_pols_put(pols, num_pols);
3112 	return ERR_PTR(err);
3113 }
3114 
make_blackhole(struct net * net,u16 family,struct dst_entry * dst_orig)3115 static struct dst_entry *make_blackhole(struct net *net, u16 family,
3116 					struct dst_entry *dst_orig)
3117 {
3118 	const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
3119 	struct dst_entry *ret;
3120 
3121 	if (!afinfo) {
3122 		dst_release(dst_orig);
3123 		return ERR_PTR(-EINVAL);
3124 	} else {
3125 		ret = afinfo->blackhole_route(net, dst_orig);
3126 	}
3127 	rcu_read_unlock();
3128 
3129 	return ret;
3130 }
3131 
3132 /* Finds/creates a bundle for given flow and if_id
3133  *
3134  * At the moment we eat a raw IP route. Mostly to speed up lookups
3135  * on interfaces with disabled IPsec.
3136  *
3137  * xfrm_lookup uses an if_id of 0 by default, and is provided for
3138  * compatibility
3139  */
xfrm_lookup_with_ifid(struct net * net,struct dst_entry * dst_orig,const struct flowi * fl,const struct sock * sk,int flags,u32 if_id)3140 struct dst_entry *xfrm_lookup_with_ifid(struct net *net,
3141 					struct dst_entry *dst_orig,
3142 					const struct flowi *fl,
3143 					const struct sock *sk,
3144 					int flags, u32 if_id)
3145 {
3146 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3147 	struct xfrm_dst *xdst;
3148 	struct dst_entry *dst, *route;
3149 	u16 family = dst_orig->ops->family;
3150 	u8 dir = XFRM_POLICY_OUT;
3151 	int i, err, num_pols, num_xfrms = 0, drop_pols = 0;
3152 
3153 	dst = NULL;
3154 	xdst = NULL;
3155 	route = NULL;
3156 
3157 	sk = sk_const_to_full_sk(sk);
3158 	if (sk && sk->sk_policy[XFRM_POLICY_OUT]) {
3159 		num_pols = 1;
3160 		pols[0] = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl, family,
3161 						if_id);
3162 		err = xfrm_expand_policies(fl, family, pols,
3163 					   &num_pols, &num_xfrms);
3164 		if (err < 0)
3165 			goto dropdst;
3166 
3167 		if (num_pols) {
3168 			if (num_xfrms <= 0) {
3169 				drop_pols = num_pols;
3170 				goto no_transform;
3171 			}
3172 
3173 			xdst = xfrm_resolve_and_create_bundle(
3174 					pols, num_pols, fl,
3175 					family, dst_orig);
3176 
3177 			if (IS_ERR(xdst)) {
3178 				xfrm_pols_put(pols, num_pols);
3179 				err = PTR_ERR(xdst);
3180 				if (err == -EREMOTE)
3181 					goto nopol;
3182 
3183 				goto dropdst;
3184 			} else if (xdst == NULL) {
3185 				num_xfrms = 0;
3186 				drop_pols = num_pols;
3187 				goto no_transform;
3188 			}
3189 
3190 			route = xdst->route;
3191 		}
3192 	}
3193 
3194 	if (xdst == NULL) {
3195 		struct xfrm_flo xflo;
3196 
3197 		xflo.dst_orig = dst_orig;
3198 		xflo.flags = flags;
3199 
3200 		/* To accelerate a bit...  */
3201 		if (!if_id && ((dst_orig->flags & DST_NOXFRM) ||
3202 			       !net->xfrm.policy_count[XFRM_POLICY_OUT]))
3203 			goto nopol;
3204 
3205 		xdst = xfrm_bundle_lookup(net, fl, family, dir, &xflo, if_id);
3206 		if (xdst == NULL)
3207 			goto nopol;
3208 		if (IS_ERR(xdst)) {
3209 			err = PTR_ERR(xdst);
3210 			goto dropdst;
3211 		}
3212 
3213 		num_pols = xdst->num_pols;
3214 		num_xfrms = xdst->num_xfrms;
3215 		memcpy(pols, xdst->pols, sizeof(struct xfrm_policy *) * num_pols);
3216 		route = xdst->route;
3217 	}
3218 
3219 	dst = &xdst->u.dst;
3220 	if (route == NULL && num_xfrms > 0) {
3221 		/* The only case when xfrm_bundle_lookup() returns a
3222 		 * bundle with null route, is when the template could
3223 		 * not be resolved. It means policies are there, but
3224 		 * bundle could not be created, since we don't yet
3225 		 * have the xfrm_state's. We need to wait for KM to
3226 		 * negotiate new SA's or bail out with error.*/
3227 		if (net->xfrm.sysctl_larval_drop) {
3228 			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
3229 			err = -EREMOTE;
3230 			goto error;
3231 		}
3232 
3233 		err = -EAGAIN;
3234 
3235 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
3236 		goto error;
3237 	}
3238 
3239 no_transform:
3240 	if (num_pols == 0)
3241 		goto nopol;
3242 
3243 	if ((flags & XFRM_LOOKUP_ICMP) &&
3244 	    !(pols[0]->flags & XFRM_POLICY_ICMP)) {
3245 		err = -ENOENT;
3246 		goto error;
3247 	}
3248 
3249 	for (i = 0; i < num_pols; i++)
3250 		WRITE_ONCE(pols[i]->curlft.use_time, ktime_get_real_seconds());
3251 
3252 	if (num_xfrms < 0) {
3253 		/* Prohibit the flow */
3254 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLBLOCK);
3255 		err = -EPERM;
3256 		goto error;
3257 	} else if (num_xfrms > 0) {
3258 		/* Flow transformed */
3259 		dst_release(dst_orig);
3260 	} else {
3261 		/* Flow passes untransformed */
3262 		dst_release(dst);
3263 		dst = dst_orig;
3264 	}
3265 ok:
3266 	xfrm_pols_put(pols, drop_pols);
3267 	if (dst && dst->xfrm &&
3268 	    dst->xfrm->props.mode == XFRM_MODE_TUNNEL)
3269 		dst->flags |= DST_XFRM_TUNNEL;
3270 	return dst;
3271 
3272 nopol:
3273 	if ((!dst_orig->dev || !(dst_orig->dev->flags & IFF_LOOPBACK)) &&
3274 	    net->xfrm.policy_default[dir] == XFRM_USERPOLICY_BLOCK) {
3275 		err = -EPERM;
3276 		goto error;
3277 	}
3278 	if (!(flags & XFRM_LOOKUP_ICMP)) {
3279 		dst = dst_orig;
3280 		goto ok;
3281 	}
3282 	err = -ENOENT;
3283 error:
3284 	dst_release(dst);
3285 dropdst:
3286 	if (!(flags & XFRM_LOOKUP_KEEP_DST_REF))
3287 		dst_release(dst_orig);
3288 	xfrm_pols_put(pols, drop_pols);
3289 	return ERR_PTR(err);
3290 }
3291 EXPORT_SYMBOL(xfrm_lookup_with_ifid);
3292 
3293 /* Main function: finds/creates a bundle for given flow.
3294  *
3295  * At the moment we eat a raw IP route. Mostly to speed up lookups
3296  * on interfaces with disabled IPsec.
3297  */
xfrm_lookup(struct net * net,struct dst_entry * dst_orig,const struct flowi * fl,const struct sock * sk,int flags)3298 struct dst_entry *xfrm_lookup(struct net *net, struct dst_entry *dst_orig,
3299 			      const struct flowi *fl, const struct sock *sk,
3300 			      int flags)
3301 {
3302 	return xfrm_lookup_with_ifid(net, dst_orig, fl, sk, flags, 0);
3303 }
3304 EXPORT_SYMBOL(xfrm_lookup);
3305 
3306 /* Callers of xfrm_lookup_route() must ensure a call to dst_output().
3307  * Otherwise we may send out blackholed packets.
3308  */
xfrm_lookup_route(struct net * net,struct dst_entry * dst_orig,const struct flowi * fl,const struct sock * sk,int flags)3309 struct dst_entry *xfrm_lookup_route(struct net *net, struct dst_entry *dst_orig,
3310 				    const struct flowi *fl,
3311 				    const struct sock *sk, int flags)
3312 {
3313 	struct dst_entry *dst = xfrm_lookup(net, dst_orig, fl, sk,
3314 					    flags | XFRM_LOOKUP_QUEUE |
3315 					    XFRM_LOOKUP_KEEP_DST_REF);
3316 
3317 	if (PTR_ERR(dst) == -EREMOTE)
3318 		return make_blackhole(net, dst_orig->ops->family, dst_orig);
3319 
3320 	if (IS_ERR(dst))
3321 		dst_release(dst_orig);
3322 
3323 	return dst;
3324 }
3325 EXPORT_SYMBOL(xfrm_lookup_route);
3326 
3327 static inline int
xfrm_secpath_reject(int idx,struct sk_buff * skb,const struct flowi * fl)3328 xfrm_secpath_reject(int idx, struct sk_buff *skb, const struct flowi *fl)
3329 {
3330 	struct sec_path *sp = skb_sec_path(skb);
3331 	struct xfrm_state *x;
3332 
3333 	if (!sp || idx < 0 || idx >= sp->len)
3334 		return 0;
3335 	x = sp->xvec[idx];
3336 	if (!x->type->reject)
3337 		return 0;
3338 	return x->type->reject(x, skb, fl);
3339 }
3340 
3341 /* When skb is transformed back to its "native" form, we have to
3342  * check policy restrictions. At the moment we make this in maximally
3343  * stupid way. Shame on me. :-) Of course, connected sockets must
3344  * have policy cached at them.
3345  */
3346 
3347 static inline int
xfrm_state_ok(const struct xfrm_tmpl * tmpl,const struct xfrm_state * x,unsigned short family,u32 if_id)3348 xfrm_state_ok(const struct xfrm_tmpl *tmpl, const struct xfrm_state *x,
3349 	      unsigned short family, u32 if_id)
3350 {
3351 	if (xfrm_state_kern(x))
3352 		return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
3353 	return	x->id.proto == tmpl->id.proto &&
3354 		(x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
3355 		(x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
3356 		x->props.mode == tmpl->mode &&
3357 		(tmpl->allalgs || (tmpl->aalgos & (1<<x->props.aalgo)) ||
3358 		 !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
3359 		!(x->props.mode != XFRM_MODE_TRANSPORT &&
3360 		  xfrm_state_addr_cmp(tmpl, x, family)) &&
3361 		(if_id == 0 || if_id == x->if_id);
3362 }
3363 
3364 /*
3365  * 0 or more than 0 is returned when validation is succeeded (either bypass
3366  * because of optional transport mode, or next index of the matched secpath
3367  * state with the template.
3368  * -1 is returned when no matching template is found.
3369  * Otherwise "-2 - errored_index" is returned.
3370  */
3371 static inline int
xfrm_policy_ok(const struct xfrm_tmpl * tmpl,const struct sec_path * sp,int start,unsigned short family,u32 if_id)3372 xfrm_policy_ok(const struct xfrm_tmpl *tmpl, const struct sec_path *sp, int start,
3373 	       unsigned short family, u32 if_id)
3374 {
3375 	int idx = start;
3376 
3377 	if (tmpl->optional) {
3378 		if (tmpl->mode == XFRM_MODE_TRANSPORT)
3379 			return start;
3380 	} else
3381 		start = -1;
3382 	for (; idx < sp->len; idx++) {
3383 		if (xfrm_state_ok(tmpl, sp->xvec[idx], family, if_id))
3384 			return ++idx;
3385 		if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
3386 			if (idx < sp->verified_cnt) {
3387 				/* Secpath entry previously verified, consider optional and
3388 				 * continue searching
3389 				 */
3390 				continue;
3391 			}
3392 
3393 			if (start == -1)
3394 				start = -2-idx;
3395 			break;
3396 		}
3397 	}
3398 	return start;
3399 }
3400 
3401 static void
decode_session4(struct sk_buff * skb,struct flowi * fl,bool reverse)3402 decode_session4(struct sk_buff *skb, struct flowi *fl, bool reverse)
3403 {
3404 	const struct iphdr *iph = ip_hdr(skb);
3405 	int ihl = iph->ihl;
3406 	u8 *xprth = skb_network_header(skb) + ihl * 4;
3407 	struct flowi4 *fl4 = &fl->u.ip4;
3408 	int oif = 0;
3409 
3410 	if (skb_dst(skb) && skb_dst(skb)->dev)
3411 		oif = skb_dst(skb)->dev->ifindex;
3412 
3413 	memset(fl4, 0, sizeof(struct flowi4));
3414 	fl4->flowi4_mark = skb->mark;
3415 	fl4->flowi4_oif = reverse ? skb->skb_iif : oif;
3416 
3417 	fl4->flowi4_proto = iph->protocol;
3418 	fl4->daddr = reverse ? iph->saddr : iph->daddr;
3419 	fl4->saddr = reverse ? iph->daddr : iph->saddr;
3420 	fl4->flowi4_tos = iph->tos & ~INET_ECN_MASK;
3421 
3422 	if (!ip_is_fragment(iph)) {
3423 		switch (iph->protocol) {
3424 		case IPPROTO_UDP:
3425 		case IPPROTO_UDPLITE:
3426 		case IPPROTO_TCP:
3427 		case IPPROTO_SCTP:
3428 		case IPPROTO_DCCP:
3429 			if (xprth + 4 < skb->data ||
3430 			    pskb_may_pull(skb, xprth + 4 - skb->data)) {
3431 				__be16 *ports;
3432 
3433 				xprth = skb_network_header(skb) + ihl * 4;
3434 				ports = (__be16 *)xprth;
3435 
3436 				fl4->fl4_sport = ports[!!reverse];
3437 				fl4->fl4_dport = ports[!reverse];
3438 			}
3439 			break;
3440 		case IPPROTO_ICMP:
3441 			if (xprth + 2 < skb->data ||
3442 			    pskb_may_pull(skb, xprth + 2 - skb->data)) {
3443 				u8 *icmp;
3444 
3445 				xprth = skb_network_header(skb) + ihl * 4;
3446 				icmp = xprth;
3447 
3448 				fl4->fl4_icmp_type = icmp[0];
3449 				fl4->fl4_icmp_code = icmp[1];
3450 			}
3451 			break;
3452 		case IPPROTO_GRE:
3453 			if (xprth + 12 < skb->data ||
3454 			    pskb_may_pull(skb, xprth + 12 - skb->data)) {
3455 				__be16 *greflags;
3456 				__be32 *gre_hdr;
3457 
3458 				xprth = skb_network_header(skb) + ihl * 4;
3459 				greflags = (__be16 *)xprth;
3460 				gre_hdr = (__be32 *)xprth;
3461 
3462 				if (greflags[0] & GRE_KEY) {
3463 					if (greflags[0] & GRE_CSUM)
3464 						gre_hdr++;
3465 					fl4->fl4_gre_key = gre_hdr[1];
3466 				}
3467 			}
3468 			break;
3469 		default:
3470 			break;
3471 		}
3472 	}
3473 }
3474 
3475 #if IS_ENABLED(CONFIG_IPV6)
3476 static void
decode_session6(struct sk_buff * skb,struct flowi * fl,bool reverse)3477 decode_session6(struct sk_buff *skb, struct flowi *fl, bool reverse)
3478 {
3479 	struct flowi6 *fl6 = &fl->u.ip6;
3480 	int onlyproto = 0;
3481 	const struct ipv6hdr *hdr = ipv6_hdr(skb);
3482 	u32 offset = sizeof(*hdr);
3483 	struct ipv6_opt_hdr *exthdr;
3484 	const unsigned char *nh = skb_network_header(skb);
3485 	u16 nhoff = IP6CB(skb)->nhoff;
3486 	int oif = 0;
3487 	u8 nexthdr;
3488 
3489 	if (!nhoff)
3490 		nhoff = offsetof(struct ipv6hdr, nexthdr);
3491 
3492 	nexthdr = nh[nhoff];
3493 
3494 	if (skb_dst(skb) && skb_dst(skb)->dev)
3495 		oif = skb_dst(skb)->dev->ifindex;
3496 
3497 	memset(fl6, 0, sizeof(struct flowi6));
3498 	fl6->flowi6_mark = skb->mark;
3499 	fl6->flowi6_oif = reverse ? skb->skb_iif : oif;
3500 
3501 	fl6->daddr = reverse ? hdr->saddr : hdr->daddr;
3502 	fl6->saddr = reverse ? hdr->daddr : hdr->saddr;
3503 
3504 	while (nh + offset + sizeof(*exthdr) < skb->data ||
3505 	       pskb_may_pull(skb, nh + offset + sizeof(*exthdr) - skb->data)) {
3506 		nh = skb_network_header(skb);
3507 		exthdr = (struct ipv6_opt_hdr *)(nh + offset);
3508 
3509 		switch (nexthdr) {
3510 		case NEXTHDR_FRAGMENT:
3511 			onlyproto = 1;
3512 			fallthrough;
3513 		case NEXTHDR_ROUTING:
3514 		case NEXTHDR_HOP:
3515 		case NEXTHDR_DEST:
3516 			offset += ipv6_optlen(exthdr);
3517 			nexthdr = exthdr->nexthdr;
3518 			break;
3519 		case IPPROTO_UDP:
3520 		case IPPROTO_UDPLITE:
3521 		case IPPROTO_TCP:
3522 		case IPPROTO_SCTP:
3523 		case IPPROTO_DCCP:
3524 			if (!onlyproto && (nh + offset + 4 < skb->data ||
3525 			     pskb_may_pull(skb, nh + offset + 4 - skb->data))) {
3526 				__be16 *ports;
3527 
3528 				nh = skb_network_header(skb);
3529 				ports = (__be16 *)(nh + offset);
3530 				fl6->fl6_sport = ports[!!reverse];
3531 				fl6->fl6_dport = ports[!reverse];
3532 			}
3533 			fl6->flowi6_proto = nexthdr;
3534 			return;
3535 		case IPPROTO_ICMPV6:
3536 			if (!onlyproto && (nh + offset + 2 < skb->data ||
3537 			    pskb_may_pull(skb, nh + offset + 2 - skb->data))) {
3538 				u8 *icmp;
3539 
3540 				nh = skb_network_header(skb);
3541 				icmp = (u8 *)(nh + offset);
3542 				fl6->fl6_icmp_type = icmp[0];
3543 				fl6->fl6_icmp_code = icmp[1];
3544 			}
3545 			fl6->flowi6_proto = nexthdr;
3546 			return;
3547 		case IPPROTO_GRE:
3548 			if (!onlyproto &&
3549 			    (nh + offset + 12 < skb->data ||
3550 			     pskb_may_pull(skb, nh + offset + 12 - skb->data))) {
3551 				struct gre_base_hdr *gre_hdr;
3552 				__be32 *gre_key;
3553 
3554 				nh = skb_network_header(skb);
3555 				gre_hdr = (struct gre_base_hdr *)(nh + offset);
3556 				gre_key = (__be32 *)(gre_hdr + 1);
3557 
3558 				if (gre_hdr->flags & GRE_KEY) {
3559 					if (gre_hdr->flags & GRE_CSUM)
3560 						gre_key++;
3561 					fl6->fl6_gre_key = *gre_key;
3562 				}
3563 			}
3564 			fl6->flowi6_proto = nexthdr;
3565 			return;
3566 
3567 #if IS_ENABLED(CONFIG_IPV6_MIP6)
3568 		case IPPROTO_MH:
3569 			offset += ipv6_optlen(exthdr);
3570 			if (!onlyproto && (nh + offset + 3 < skb->data ||
3571 			    pskb_may_pull(skb, nh + offset + 3 - skb->data))) {
3572 				struct ip6_mh *mh;
3573 
3574 				nh = skb_network_header(skb);
3575 				mh = (struct ip6_mh *)(nh + offset);
3576 				fl6->fl6_mh_type = mh->ip6mh_type;
3577 			}
3578 			fl6->flowi6_proto = nexthdr;
3579 			return;
3580 #endif
3581 		default:
3582 			fl6->flowi6_proto = nexthdr;
3583 			return;
3584 		}
3585 	}
3586 }
3587 #endif
3588 
__xfrm_decode_session(struct sk_buff * skb,struct flowi * fl,unsigned int family,int reverse)3589 int __xfrm_decode_session(struct sk_buff *skb, struct flowi *fl,
3590 			  unsigned int family, int reverse)
3591 {
3592 	switch (family) {
3593 	case AF_INET:
3594 		decode_session4(skb, fl, reverse);
3595 		break;
3596 #if IS_ENABLED(CONFIG_IPV6)
3597 	case AF_INET6:
3598 		decode_session6(skb, fl, reverse);
3599 		break;
3600 #endif
3601 	default:
3602 		return -EAFNOSUPPORT;
3603 	}
3604 
3605 	return security_xfrm_decode_session(skb, &fl->flowi_secid);
3606 }
3607 EXPORT_SYMBOL(__xfrm_decode_session);
3608 
secpath_has_nontransport(const struct sec_path * sp,int k,int * idxp)3609 static inline int secpath_has_nontransport(const struct sec_path *sp, int k, int *idxp)
3610 {
3611 	for (; k < sp->len; k++) {
3612 		if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
3613 			*idxp = k;
3614 			return 1;
3615 		}
3616 	}
3617 
3618 	return 0;
3619 }
3620 
__xfrm_policy_check(struct sock * sk,int dir,struct sk_buff * skb,unsigned short family)3621 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
3622 			unsigned short family)
3623 {
3624 	struct net *net = dev_net(skb->dev);
3625 	struct xfrm_policy *pol;
3626 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3627 	int npols = 0;
3628 	int xfrm_nr;
3629 	int pi;
3630 	int reverse;
3631 	struct flowi fl;
3632 	int xerr_idx = -1;
3633 	const struct xfrm_if_cb *ifcb;
3634 	struct sec_path *sp;
3635 	u32 if_id = 0;
3636 
3637 	rcu_read_lock();
3638 	ifcb = xfrm_if_get_cb();
3639 
3640 	if (ifcb) {
3641 		struct xfrm_if_decode_session_result r;
3642 
3643 		if (ifcb->decode_session(skb, family, &r)) {
3644 			if_id = r.if_id;
3645 			net = r.net;
3646 		}
3647 	}
3648 	rcu_read_unlock();
3649 
3650 	reverse = dir & ~XFRM_POLICY_MASK;
3651 	dir &= XFRM_POLICY_MASK;
3652 
3653 	if (__xfrm_decode_session(skb, &fl, family, reverse) < 0) {
3654 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
3655 		return 0;
3656 	}
3657 
3658 	nf_nat_decode_session(skb, &fl, family);
3659 
3660 	/* First, check used SA against their selectors. */
3661 	sp = skb_sec_path(skb);
3662 	if (sp) {
3663 		int i;
3664 
3665 		for (i = sp->len - 1; i >= 0; i--) {
3666 			struct xfrm_state *x = sp->xvec[i];
3667 			if (!xfrm_selector_match(&x->sel, &fl, family)) {
3668 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINSTATEMISMATCH);
3669 				return 0;
3670 			}
3671 		}
3672 	}
3673 
3674 	pol = NULL;
3675 	sk = sk_to_full_sk(sk);
3676 	if (sk && sk->sk_policy[dir]) {
3677 		pol = xfrm_sk_policy_lookup(sk, dir, &fl, family, if_id);
3678 		if (IS_ERR(pol)) {
3679 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3680 			return 0;
3681 		}
3682 	}
3683 
3684 	if (!pol)
3685 		pol = xfrm_policy_lookup(net, &fl, family, dir, if_id);
3686 
3687 	if (IS_ERR(pol)) {
3688 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3689 		return 0;
3690 	}
3691 
3692 	if (!pol) {
3693 		if (net->xfrm.policy_default[dir] == XFRM_USERPOLICY_BLOCK) {
3694 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
3695 			return 0;
3696 		}
3697 
3698 		if (sp && secpath_has_nontransport(sp, 0, &xerr_idx)) {
3699 			xfrm_secpath_reject(xerr_idx, skb, &fl);
3700 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
3701 			return 0;
3702 		}
3703 		return 1;
3704 	}
3705 
3706 	/* This lockless write can happen from different cpus. */
3707 	WRITE_ONCE(pol->curlft.use_time, ktime_get_real_seconds());
3708 
3709 	pols[0] = pol;
3710 	npols++;
3711 #ifdef CONFIG_XFRM_SUB_POLICY
3712 	if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
3713 		pols[1] = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN,
3714 						    &fl, family,
3715 						    XFRM_POLICY_IN, if_id);
3716 		if (pols[1]) {
3717 			if (IS_ERR(pols[1])) {
3718 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3719 				xfrm_pol_put(pols[0]);
3720 				return 0;
3721 			}
3722 			/* This write can happen from different cpus. */
3723 			WRITE_ONCE(pols[1]->curlft.use_time,
3724 				   ktime_get_real_seconds());
3725 			npols++;
3726 		}
3727 	}
3728 #endif
3729 
3730 	if (pol->action == XFRM_POLICY_ALLOW) {
3731 		static struct sec_path dummy;
3732 		struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
3733 		struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
3734 		struct xfrm_tmpl **tpp = tp;
3735 		int ti = 0;
3736 		int i, k;
3737 
3738 		sp = skb_sec_path(skb);
3739 		if (!sp)
3740 			sp = &dummy;
3741 
3742 		for (pi = 0; pi < npols; pi++) {
3743 			if (pols[pi] != pol &&
3744 			    pols[pi]->action != XFRM_POLICY_ALLOW) {
3745 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
3746 				goto reject;
3747 			}
3748 			if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH) {
3749 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
3750 				goto reject_error;
3751 			}
3752 			for (i = 0; i < pols[pi]->xfrm_nr; i++)
3753 				tpp[ti++] = &pols[pi]->xfrm_vec[i];
3754 		}
3755 		xfrm_nr = ti;
3756 
3757 		if (npols > 1) {
3758 			xfrm_tmpl_sort(stp, tpp, xfrm_nr, family);
3759 			tpp = stp;
3760 		}
3761 
3762 		/* For each tunnel xfrm, find the first matching tmpl.
3763 		 * For each tmpl before that, find corresponding xfrm.
3764 		 * Order is _important_. Later we will implement
3765 		 * some barriers, but at the moment barriers
3766 		 * are implied between each two transformations.
3767 		 * Upon success, marks secpath entries as having been
3768 		 * verified to allow them to be skipped in future policy
3769 		 * checks (e.g. nested tunnels).
3770 		 */
3771 		for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
3772 			k = xfrm_policy_ok(tpp[i], sp, k, family, if_id);
3773 			if (k < 0) {
3774 				if (k < -1)
3775 					/* "-2 - errored_index" returned */
3776 					xerr_idx = -(2+k);
3777 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
3778 				goto reject;
3779 			}
3780 		}
3781 
3782 		if (secpath_has_nontransport(sp, k, &xerr_idx)) {
3783 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
3784 			goto reject;
3785 		}
3786 
3787 		xfrm_pols_put(pols, npols);
3788 		sp->verified_cnt = k;
3789 
3790 		return 1;
3791 	}
3792 	XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
3793 
3794 reject:
3795 	xfrm_secpath_reject(xerr_idx, skb, &fl);
3796 reject_error:
3797 	xfrm_pols_put(pols, npols);
3798 	return 0;
3799 }
3800 EXPORT_SYMBOL(__xfrm_policy_check);
3801 
__xfrm_route_forward(struct sk_buff * skb,unsigned short family)3802 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
3803 {
3804 	struct net *net = dev_net(skb->dev);
3805 	struct flowi fl;
3806 	struct dst_entry *dst;
3807 	int res = 1;
3808 
3809 	if (xfrm_decode_session(skb, &fl, family) < 0) {
3810 		XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
3811 		return 0;
3812 	}
3813 
3814 	skb_dst_force(skb);
3815 	if (!skb_dst(skb)) {
3816 		XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
3817 		return 0;
3818 	}
3819 
3820 	dst = xfrm_lookup(net, skb_dst(skb), &fl, NULL, XFRM_LOOKUP_QUEUE);
3821 	if (IS_ERR(dst)) {
3822 		res = 0;
3823 		dst = NULL;
3824 	}
3825 	skb_dst_set(skb, dst);
3826 	return res;
3827 }
3828 EXPORT_SYMBOL(__xfrm_route_forward);
3829 
3830 /* Optimize later using cookies and generation ids. */
3831 
xfrm_dst_check(struct dst_entry * dst,u32 cookie)3832 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
3833 {
3834 	/* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
3835 	 * to DST_OBSOLETE_FORCE_CHK to force all XFRM destinations to
3836 	 * get validated by dst_ops->check on every use.  We do this
3837 	 * because when a normal route referenced by an XFRM dst is
3838 	 * obsoleted we do not go looking around for all parent
3839 	 * referencing XFRM dsts so that we can invalidate them.  It
3840 	 * is just too much work.  Instead we make the checks here on
3841 	 * every use.  For example:
3842 	 *
3843 	 *	XFRM dst A --> IPv4 dst X
3844 	 *
3845 	 * X is the "xdst->route" of A (X is also the "dst->path" of A
3846 	 * in this example).  If X is marked obsolete, "A" will not
3847 	 * notice.  That's what we are validating here via the
3848 	 * stale_bundle() check.
3849 	 *
3850 	 * When a dst is removed from the fib tree, DST_OBSOLETE_DEAD will
3851 	 * be marked on it.
3852 	 * This will force stale_bundle() to fail on any xdst bundle with
3853 	 * this dst linked in it.
3854 	 */
3855 	if (dst->obsolete < 0 && !stale_bundle(dst))
3856 		return dst;
3857 
3858 	return NULL;
3859 }
3860 
stale_bundle(struct dst_entry * dst)3861 static int stale_bundle(struct dst_entry *dst)
3862 {
3863 	return !xfrm_bundle_ok((struct xfrm_dst *)dst);
3864 }
3865 
xfrm_dst_ifdown(struct dst_entry * dst,struct net_device * dev)3866 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
3867 {
3868 	while ((dst = xfrm_dst_child(dst)) && dst->xfrm && dst->dev == dev) {
3869 		dst->dev = blackhole_netdev;
3870 		dev_hold(dst->dev);
3871 		dev_put(dev);
3872 	}
3873 }
3874 EXPORT_SYMBOL(xfrm_dst_ifdown);
3875 
xfrm_link_failure(struct sk_buff * skb)3876 static void xfrm_link_failure(struct sk_buff *skb)
3877 {
3878 	/* Impossible. Such dst must be popped before reaches point of failure. */
3879 }
3880 
xfrm_negative_advice(struct sock * sk,struct dst_entry * dst)3881 static void xfrm_negative_advice(struct sock *sk, struct dst_entry *dst)
3882 {
3883 	if (dst->obsolete)
3884 		sk_dst_reset(sk);
3885 }
3886 
xfrm_init_pmtu(struct xfrm_dst ** bundle,int nr)3887 static void xfrm_init_pmtu(struct xfrm_dst **bundle, int nr)
3888 {
3889 	while (nr--) {
3890 		struct xfrm_dst *xdst = bundle[nr];
3891 		u32 pmtu, route_mtu_cached;
3892 		struct dst_entry *dst;
3893 
3894 		dst = &xdst->u.dst;
3895 		pmtu = dst_mtu(xfrm_dst_child(dst));
3896 		xdst->child_mtu_cached = pmtu;
3897 
3898 		pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
3899 
3900 		route_mtu_cached = dst_mtu(xdst->route);
3901 		xdst->route_mtu_cached = route_mtu_cached;
3902 
3903 		if (pmtu > route_mtu_cached)
3904 			pmtu = route_mtu_cached;
3905 
3906 		dst_metric_set(dst, RTAX_MTU, pmtu);
3907 	}
3908 }
3909 
3910 /* Check that the bundle accepts the flow and its components are
3911  * still valid.
3912  */
3913 
xfrm_bundle_ok(struct xfrm_dst * first)3914 static int xfrm_bundle_ok(struct xfrm_dst *first)
3915 {
3916 	struct xfrm_dst *bundle[XFRM_MAX_DEPTH];
3917 	struct dst_entry *dst = &first->u.dst;
3918 	struct xfrm_dst *xdst;
3919 	int start_from, nr;
3920 	u32 mtu;
3921 
3922 	if (!dst_check(xfrm_dst_path(dst), ((struct xfrm_dst *)dst)->path_cookie) ||
3923 	    (dst->dev && !netif_running(dst->dev)))
3924 		return 0;
3925 
3926 	if (dst->flags & DST_XFRM_QUEUE)
3927 		return 1;
3928 
3929 	start_from = nr = 0;
3930 	do {
3931 		struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
3932 
3933 		if (dst->xfrm->km.state != XFRM_STATE_VALID)
3934 			return 0;
3935 		if (xdst->xfrm_genid != dst->xfrm->genid)
3936 			return 0;
3937 		if (xdst->num_pols > 0 &&
3938 		    xdst->policy_genid != atomic_read(&xdst->pols[0]->genid))
3939 			return 0;
3940 
3941 		bundle[nr++] = xdst;
3942 
3943 		mtu = dst_mtu(xfrm_dst_child(dst));
3944 		if (xdst->child_mtu_cached != mtu) {
3945 			start_from = nr;
3946 			xdst->child_mtu_cached = mtu;
3947 		}
3948 
3949 		if (!dst_check(xdst->route, xdst->route_cookie))
3950 			return 0;
3951 		mtu = dst_mtu(xdst->route);
3952 		if (xdst->route_mtu_cached != mtu) {
3953 			start_from = nr;
3954 			xdst->route_mtu_cached = mtu;
3955 		}
3956 
3957 		dst = xfrm_dst_child(dst);
3958 	} while (dst->xfrm);
3959 
3960 	if (likely(!start_from))
3961 		return 1;
3962 
3963 	xdst = bundle[start_from - 1];
3964 	mtu = xdst->child_mtu_cached;
3965 	while (start_from--) {
3966 		dst = &xdst->u.dst;
3967 
3968 		mtu = xfrm_state_mtu(dst->xfrm, mtu);
3969 		if (mtu > xdst->route_mtu_cached)
3970 			mtu = xdst->route_mtu_cached;
3971 		dst_metric_set(dst, RTAX_MTU, mtu);
3972 		if (!start_from)
3973 			break;
3974 
3975 		xdst = bundle[start_from - 1];
3976 		xdst->child_mtu_cached = mtu;
3977 	}
3978 
3979 	return 1;
3980 }
3981 
xfrm_default_advmss(const struct dst_entry * dst)3982 static unsigned int xfrm_default_advmss(const struct dst_entry *dst)
3983 {
3984 	return dst_metric_advmss(xfrm_dst_path(dst));
3985 }
3986 
xfrm_mtu(const struct dst_entry * dst)3987 static unsigned int xfrm_mtu(const struct dst_entry *dst)
3988 {
3989 	unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
3990 
3991 	return mtu ? : dst_mtu(xfrm_dst_path(dst));
3992 }
3993 
xfrm_get_dst_nexthop(const struct dst_entry * dst,const void * daddr)3994 static const void *xfrm_get_dst_nexthop(const struct dst_entry *dst,
3995 					const void *daddr)
3996 {
3997 	while (dst->xfrm) {
3998 		const struct xfrm_state *xfrm = dst->xfrm;
3999 
4000 		dst = xfrm_dst_child(dst);
4001 
4002 		if (xfrm->props.mode == XFRM_MODE_TRANSPORT)
4003 			continue;
4004 		if (xfrm->type->flags & XFRM_TYPE_REMOTE_COADDR)
4005 			daddr = xfrm->coaddr;
4006 		else if (!(xfrm->type->flags & XFRM_TYPE_LOCAL_COADDR))
4007 			daddr = &xfrm->id.daddr;
4008 	}
4009 	return daddr;
4010 }
4011 
xfrm_neigh_lookup(const struct dst_entry * dst,struct sk_buff * skb,const void * daddr)4012 static struct neighbour *xfrm_neigh_lookup(const struct dst_entry *dst,
4013 					   struct sk_buff *skb,
4014 					   const void *daddr)
4015 {
4016 	const struct dst_entry *path = xfrm_dst_path(dst);
4017 
4018 	if (!skb)
4019 		daddr = xfrm_get_dst_nexthop(dst, daddr);
4020 	return path->ops->neigh_lookup(path, skb, daddr);
4021 }
4022 
xfrm_confirm_neigh(const struct dst_entry * dst,const void * daddr)4023 static void xfrm_confirm_neigh(const struct dst_entry *dst, const void *daddr)
4024 {
4025 	const struct dst_entry *path = xfrm_dst_path(dst);
4026 
4027 	daddr = xfrm_get_dst_nexthop(dst, daddr);
4028 	path->ops->confirm_neigh(path, daddr);
4029 }
4030 
xfrm_policy_register_afinfo(const struct xfrm_policy_afinfo * afinfo,int family)4031 int xfrm_policy_register_afinfo(const struct xfrm_policy_afinfo *afinfo, int family)
4032 {
4033 	int err = 0;
4034 
4035 	if (WARN_ON(family >= ARRAY_SIZE(xfrm_policy_afinfo)))
4036 		return -EAFNOSUPPORT;
4037 
4038 	spin_lock(&xfrm_policy_afinfo_lock);
4039 	if (unlikely(xfrm_policy_afinfo[family] != NULL))
4040 		err = -EEXIST;
4041 	else {
4042 		struct dst_ops *dst_ops = afinfo->dst_ops;
4043 		if (likely(dst_ops->kmem_cachep == NULL))
4044 			dst_ops->kmem_cachep = xfrm_dst_cache;
4045 		if (likely(dst_ops->check == NULL))
4046 			dst_ops->check = xfrm_dst_check;
4047 		if (likely(dst_ops->default_advmss == NULL))
4048 			dst_ops->default_advmss = xfrm_default_advmss;
4049 		if (likely(dst_ops->mtu == NULL))
4050 			dst_ops->mtu = xfrm_mtu;
4051 		if (likely(dst_ops->negative_advice == NULL))
4052 			dst_ops->negative_advice = xfrm_negative_advice;
4053 		if (likely(dst_ops->link_failure == NULL))
4054 			dst_ops->link_failure = xfrm_link_failure;
4055 		if (likely(dst_ops->neigh_lookup == NULL))
4056 			dst_ops->neigh_lookup = xfrm_neigh_lookup;
4057 		if (likely(!dst_ops->confirm_neigh))
4058 			dst_ops->confirm_neigh = xfrm_confirm_neigh;
4059 		rcu_assign_pointer(xfrm_policy_afinfo[family], afinfo);
4060 	}
4061 	spin_unlock(&xfrm_policy_afinfo_lock);
4062 
4063 	return err;
4064 }
4065 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
4066 
xfrm_policy_unregister_afinfo(const struct xfrm_policy_afinfo * afinfo)4067 void xfrm_policy_unregister_afinfo(const struct xfrm_policy_afinfo *afinfo)
4068 {
4069 	struct dst_ops *dst_ops = afinfo->dst_ops;
4070 	int i;
4071 
4072 	for (i = 0; i < ARRAY_SIZE(xfrm_policy_afinfo); i++) {
4073 		if (xfrm_policy_afinfo[i] != afinfo)
4074 			continue;
4075 		RCU_INIT_POINTER(xfrm_policy_afinfo[i], NULL);
4076 		break;
4077 	}
4078 
4079 	synchronize_rcu();
4080 
4081 	dst_ops->kmem_cachep = NULL;
4082 	dst_ops->check = NULL;
4083 	dst_ops->negative_advice = NULL;
4084 	dst_ops->link_failure = NULL;
4085 }
4086 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
4087 
xfrm_if_register_cb(const struct xfrm_if_cb * ifcb)4088 void xfrm_if_register_cb(const struct xfrm_if_cb *ifcb)
4089 {
4090 	spin_lock(&xfrm_if_cb_lock);
4091 	rcu_assign_pointer(xfrm_if_cb, ifcb);
4092 	spin_unlock(&xfrm_if_cb_lock);
4093 }
4094 EXPORT_SYMBOL(xfrm_if_register_cb);
4095 
xfrm_if_unregister_cb(void)4096 void xfrm_if_unregister_cb(void)
4097 {
4098 	RCU_INIT_POINTER(xfrm_if_cb, NULL);
4099 	synchronize_rcu();
4100 }
4101 EXPORT_SYMBOL(xfrm_if_unregister_cb);
4102 
4103 #ifdef CONFIG_XFRM_STATISTICS
xfrm_statistics_init(struct net * net)4104 static int __net_init xfrm_statistics_init(struct net *net)
4105 {
4106 	int rv;
4107 	net->mib.xfrm_statistics = alloc_percpu(struct linux_xfrm_mib);
4108 	if (!net->mib.xfrm_statistics)
4109 		return -ENOMEM;
4110 	rv = xfrm_proc_init(net);
4111 	if (rv < 0)
4112 		free_percpu(net->mib.xfrm_statistics);
4113 	return rv;
4114 }
4115 
xfrm_statistics_fini(struct net * net)4116 static void xfrm_statistics_fini(struct net *net)
4117 {
4118 	xfrm_proc_fini(net);
4119 	free_percpu(net->mib.xfrm_statistics);
4120 }
4121 #else
xfrm_statistics_init(struct net * net)4122 static int __net_init xfrm_statistics_init(struct net *net)
4123 {
4124 	return 0;
4125 }
4126 
xfrm_statistics_fini(struct net * net)4127 static void xfrm_statistics_fini(struct net *net)
4128 {
4129 }
4130 #endif
4131 
xfrm_policy_init(struct net * net)4132 static int __net_init xfrm_policy_init(struct net *net)
4133 {
4134 	unsigned int hmask, sz;
4135 	int dir, err;
4136 
4137 	if (net_eq(net, &init_net)) {
4138 		xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
4139 					   sizeof(struct xfrm_dst),
4140 					   0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4141 					   NULL);
4142 		err = rhashtable_init(&xfrm_policy_inexact_table,
4143 				      &xfrm_pol_inexact_params);
4144 		BUG_ON(err);
4145 	}
4146 
4147 	hmask = 8 - 1;
4148 	sz = (hmask+1) * sizeof(struct hlist_head);
4149 
4150 	net->xfrm.policy_byidx = xfrm_hash_alloc(sz);
4151 	if (!net->xfrm.policy_byidx)
4152 		goto out_byidx;
4153 	net->xfrm.policy_idx_hmask = hmask;
4154 
4155 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
4156 		struct xfrm_policy_hash *htab;
4157 
4158 		net->xfrm.policy_count[dir] = 0;
4159 		net->xfrm.policy_count[XFRM_POLICY_MAX + dir] = 0;
4160 		INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
4161 
4162 		htab = &net->xfrm.policy_bydst[dir];
4163 		htab->table = xfrm_hash_alloc(sz);
4164 		if (!htab->table)
4165 			goto out_bydst;
4166 		htab->hmask = hmask;
4167 		htab->dbits4 = 32;
4168 		htab->sbits4 = 32;
4169 		htab->dbits6 = 128;
4170 		htab->sbits6 = 128;
4171 	}
4172 	net->xfrm.policy_hthresh.lbits4 = 32;
4173 	net->xfrm.policy_hthresh.rbits4 = 32;
4174 	net->xfrm.policy_hthresh.lbits6 = 128;
4175 	net->xfrm.policy_hthresh.rbits6 = 128;
4176 
4177 	seqlock_init(&net->xfrm.policy_hthresh.lock);
4178 
4179 	INIT_LIST_HEAD(&net->xfrm.policy_all);
4180 	INIT_LIST_HEAD(&net->xfrm.inexact_bins);
4181 	INIT_WORK(&net->xfrm.policy_hash_work, xfrm_hash_resize);
4182 	INIT_WORK(&net->xfrm.policy_hthresh.work, xfrm_hash_rebuild);
4183 	return 0;
4184 
4185 out_bydst:
4186 	for (dir--; dir >= 0; dir--) {
4187 		struct xfrm_policy_hash *htab;
4188 
4189 		htab = &net->xfrm.policy_bydst[dir];
4190 		xfrm_hash_free(htab->table, sz);
4191 	}
4192 	xfrm_hash_free(net->xfrm.policy_byidx, sz);
4193 out_byidx:
4194 	return -ENOMEM;
4195 }
4196 
xfrm_policy_fini(struct net * net)4197 static void xfrm_policy_fini(struct net *net)
4198 {
4199 	struct xfrm_pol_inexact_bin *b, *t;
4200 	unsigned int sz;
4201 	int dir;
4202 
4203 	flush_work(&net->xfrm.policy_hash_work);
4204 #ifdef CONFIG_XFRM_SUB_POLICY
4205 	xfrm_policy_flush(net, XFRM_POLICY_TYPE_SUB, false);
4206 #endif
4207 	xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, false);
4208 
4209 	WARN_ON(!list_empty(&net->xfrm.policy_all));
4210 
4211 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
4212 		struct xfrm_policy_hash *htab;
4213 
4214 		WARN_ON(!hlist_empty(&net->xfrm.policy_inexact[dir]));
4215 
4216 		htab = &net->xfrm.policy_bydst[dir];
4217 		sz = (htab->hmask + 1) * sizeof(struct hlist_head);
4218 		WARN_ON(!hlist_empty(htab->table));
4219 		xfrm_hash_free(htab->table, sz);
4220 	}
4221 
4222 	sz = (net->xfrm.policy_idx_hmask + 1) * sizeof(struct hlist_head);
4223 	WARN_ON(!hlist_empty(net->xfrm.policy_byidx));
4224 	xfrm_hash_free(net->xfrm.policy_byidx, sz);
4225 
4226 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
4227 	list_for_each_entry_safe(b, t, &net->xfrm.inexact_bins, inexact_bins)
4228 		__xfrm_policy_inexact_prune_bin(b, true);
4229 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
4230 }
4231 
xfrm_net_init(struct net * net)4232 static int __net_init xfrm_net_init(struct net *net)
4233 {
4234 	int rv;
4235 
4236 	/* Initialize the per-net locks here */
4237 	spin_lock_init(&net->xfrm.xfrm_state_lock);
4238 	spin_lock_init(&net->xfrm.xfrm_policy_lock);
4239 	seqcount_spinlock_init(&net->xfrm.xfrm_policy_hash_generation, &net->xfrm.xfrm_policy_lock);
4240 	mutex_init(&net->xfrm.xfrm_cfg_mutex);
4241 	net->xfrm.policy_default[XFRM_POLICY_IN] = XFRM_USERPOLICY_ACCEPT;
4242 	net->xfrm.policy_default[XFRM_POLICY_FWD] = XFRM_USERPOLICY_ACCEPT;
4243 	net->xfrm.policy_default[XFRM_POLICY_OUT] = XFRM_USERPOLICY_ACCEPT;
4244 
4245 	rv = xfrm_statistics_init(net);
4246 	if (rv < 0)
4247 		goto out_statistics;
4248 	rv = xfrm_state_init(net);
4249 	if (rv < 0)
4250 		goto out_state;
4251 	rv = xfrm_policy_init(net);
4252 	if (rv < 0)
4253 		goto out_policy;
4254 	rv = xfrm_sysctl_init(net);
4255 	if (rv < 0)
4256 		goto out_sysctl;
4257 
4258 	return 0;
4259 
4260 out_sysctl:
4261 	xfrm_policy_fini(net);
4262 out_policy:
4263 	xfrm_state_fini(net);
4264 out_state:
4265 	xfrm_statistics_fini(net);
4266 out_statistics:
4267 	return rv;
4268 }
4269 
xfrm_net_exit(struct net * net)4270 static void __net_exit xfrm_net_exit(struct net *net)
4271 {
4272 	xfrm_sysctl_fini(net);
4273 	xfrm_policy_fini(net);
4274 	xfrm_state_fini(net);
4275 	xfrm_statistics_fini(net);
4276 }
4277 
4278 static struct pernet_operations __net_initdata xfrm_net_ops = {
4279 	.init = xfrm_net_init,
4280 	.exit = xfrm_net_exit,
4281 };
4282 
xfrm_init(void)4283 void __init xfrm_init(void)
4284 {
4285 	register_pernet_subsys(&xfrm_net_ops);
4286 	xfrm_dev_init();
4287 	xfrm_input_init();
4288 
4289 #ifdef CONFIG_XFRM_ESPINTCP
4290 	espintcp_init();
4291 #endif
4292 }
4293 
4294 #ifdef CONFIG_AUDITSYSCALL
xfrm_audit_common_policyinfo(struct xfrm_policy * xp,struct audit_buffer * audit_buf)4295 static void xfrm_audit_common_policyinfo(struct xfrm_policy *xp,
4296 					 struct audit_buffer *audit_buf)
4297 {
4298 	struct xfrm_sec_ctx *ctx = xp->security;
4299 	struct xfrm_selector *sel = &xp->selector;
4300 
4301 	if (ctx)
4302 		audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
4303 				 ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
4304 
4305 	switch (sel->family) {
4306 	case AF_INET:
4307 		audit_log_format(audit_buf, " src=%pI4", &sel->saddr.a4);
4308 		if (sel->prefixlen_s != 32)
4309 			audit_log_format(audit_buf, " src_prefixlen=%d",
4310 					 sel->prefixlen_s);
4311 		audit_log_format(audit_buf, " dst=%pI4", &sel->daddr.a4);
4312 		if (sel->prefixlen_d != 32)
4313 			audit_log_format(audit_buf, " dst_prefixlen=%d",
4314 					 sel->prefixlen_d);
4315 		break;
4316 	case AF_INET6:
4317 		audit_log_format(audit_buf, " src=%pI6", sel->saddr.a6);
4318 		if (sel->prefixlen_s != 128)
4319 			audit_log_format(audit_buf, " src_prefixlen=%d",
4320 					 sel->prefixlen_s);
4321 		audit_log_format(audit_buf, " dst=%pI6", sel->daddr.a6);
4322 		if (sel->prefixlen_d != 128)
4323 			audit_log_format(audit_buf, " dst_prefixlen=%d",
4324 					 sel->prefixlen_d);
4325 		break;
4326 	}
4327 }
4328 
xfrm_audit_policy_add(struct xfrm_policy * xp,int result,bool task_valid)4329 void xfrm_audit_policy_add(struct xfrm_policy *xp, int result, bool task_valid)
4330 {
4331 	struct audit_buffer *audit_buf;
4332 
4333 	audit_buf = xfrm_audit_start("SPD-add");
4334 	if (audit_buf == NULL)
4335 		return;
4336 	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
4337 	audit_log_format(audit_buf, " res=%u", result);
4338 	xfrm_audit_common_policyinfo(xp, audit_buf);
4339 	audit_log_end(audit_buf);
4340 }
4341 EXPORT_SYMBOL_GPL(xfrm_audit_policy_add);
4342 
xfrm_audit_policy_delete(struct xfrm_policy * xp,int result,bool task_valid)4343 void xfrm_audit_policy_delete(struct xfrm_policy *xp, int result,
4344 			      bool task_valid)
4345 {
4346 	struct audit_buffer *audit_buf;
4347 
4348 	audit_buf = xfrm_audit_start("SPD-delete");
4349 	if (audit_buf == NULL)
4350 		return;
4351 	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
4352 	audit_log_format(audit_buf, " res=%u", result);
4353 	xfrm_audit_common_policyinfo(xp, audit_buf);
4354 	audit_log_end(audit_buf);
4355 }
4356 EXPORT_SYMBOL_GPL(xfrm_audit_policy_delete);
4357 #endif
4358 
4359 #ifdef CONFIG_XFRM_MIGRATE
xfrm_migrate_selector_match(const struct xfrm_selector * sel_cmp,const struct xfrm_selector * sel_tgt)4360 static bool xfrm_migrate_selector_match(const struct xfrm_selector *sel_cmp,
4361 					const struct xfrm_selector *sel_tgt)
4362 {
4363 	if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
4364 		if (sel_tgt->family == sel_cmp->family &&
4365 		    xfrm_addr_equal(&sel_tgt->daddr, &sel_cmp->daddr,
4366 				    sel_cmp->family) &&
4367 		    xfrm_addr_equal(&sel_tgt->saddr, &sel_cmp->saddr,
4368 				    sel_cmp->family) &&
4369 		    sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
4370 		    sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
4371 			return true;
4372 		}
4373 	} else {
4374 		if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
4375 			return true;
4376 		}
4377 	}
4378 	return false;
4379 }
4380 
xfrm_migrate_policy_find(const struct xfrm_selector * sel,u8 dir,u8 type,struct net * net,u32 if_id)4381 static struct xfrm_policy *xfrm_migrate_policy_find(const struct xfrm_selector *sel,
4382 						    u8 dir, u8 type, struct net *net, u32 if_id)
4383 {
4384 	struct xfrm_policy *pol, *ret = NULL;
4385 	struct hlist_head *chain;
4386 	u32 priority = ~0U;
4387 
4388 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
4389 	chain = policy_hash_direct(net, &sel->daddr, &sel->saddr, sel->family, dir);
4390 	hlist_for_each_entry(pol, chain, bydst) {
4391 		if ((if_id == 0 || pol->if_id == if_id) &&
4392 		    xfrm_migrate_selector_match(sel, &pol->selector) &&
4393 		    pol->type == type) {
4394 			ret = pol;
4395 			priority = ret->priority;
4396 			break;
4397 		}
4398 	}
4399 	chain = &net->xfrm.policy_inexact[dir];
4400 	hlist_for_each_entry(pol, chain, bydst_inexact_list) {
4401 		if ((pol->priority >= priority) && ret)
4402 			break;
4403 
4404 		if ((if_id == 0 || pol->if_id == if_id) &&
4405 		    xfrm_migrate_selector_match(sel, &pol->selector) &&
4406 		    pol->type == type) {
4407 			ret = pol;
4408 			break;
4409 		}
4410 	}
4411 
4412 	xfrm_pol_hold(ret);
4413 
4414 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
4415 
4416 	return ret;
4417 }
4418 
migrate_tmpl_match(const struct xfrm_migrate * m,const struct xfrm_tmpl * t)4419 static int migrate_tmpl_match(const struct xfrm_migrate *m, const struct xfrm_tmpl *t)
4420 {
4421 	int match = 0;
4422 
4423 	if (t->mode == m->mode && t->id.proto == m->proto &&
4424 	    (m->reqid == 0 || t->reqid == m->reqid)) {
4425 		switch (t->mode) {
4426 		case XFRM_MODE_TUNNEL:
4427 		case XFRM_MODE_BEET:
4428 			if (xfrm_addr_equal(&t->id.daddr, &m->old_daddr,
4429 					    m->old_family) &&
4430 			    xfrm_addr_equal(&t->saddr, &m->old_saddr,
4431 					    m->old_family)) {
4432 				match = 1;
4433 			}
4434 			break;
4435 		case XFRM_MODE_TRANSPORT:
4436 			/* in case of transport mode, template does not store
4437 			   any IP addresses, hence we just compare mode and
4438 			   protocol */
4439 			match = 1;
4440 			break;
4441 		default:
4442 			break;
4443 		}
4444 	}
4445 	return match;
4446 }
4447 
4448 /* update endpoint address(es) of template(s) */
xfrm_policy_migrate(struct xfrm_policy * pol,struct xfrm_migrate * m,int num_migrate,struct netlink_ext_ack * extack)4449 static int xfrm_policy_migrate(struct xfrm_policy *pol,
4450 			       struct xfrm_migrate *m, int num_migrate,
4451 			       struct netlink_ext_ack *extack)
4452 {
4453 	struct xfrm_migrate *mp;
4454 	int i, j, n = 0;
4455 
4456 	write_lock_bh(&pol->lock);
4457 	if (unlikely(pol->walk.dead)) {
4458 		/* target policy has been deleted */
4459 		NL_SET_ERR_MSG(extack, "Target policy not found");
4460 		write_unlock_bh(&pol->lock);
4461 		return -ENOENT;
4462 	}
4463 
4464 	for (i = 0; i < pol->xfrm_nr; i++) {
4465 		for (j = 0, mp = m; j < num_migrate; j++, mp++) {
4466 			if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
4467 				continue;
4468 			n++;
4469 			if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL &&
4470 			    pol->xfrm_vec[i].mode != XFRM_MODE_BEET)
4471 				continue;
4472 			/* update endpoints */
4473 			memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
4474 			       sizeof(pol->xfrm_vec[i].id.daddr));
4475 			memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
4476 			       sizeof(pol->xfrm_vec[i].saddr));
4477 			pol->xfrm_vec[i].encap_family = mp->new_family;
4478 			/* flush bundles */
4479 			atomic_inc(&pol->genid);
4480 		}
4481 	}
4482 
4483 	write_unlock_bh(&pol->lock);
4484 
4485 	if (!n)
4486 		return -ENODATA;
4487 
4488 	return 0;
4489 }
4490 
xfrm_migrate_check(const struct xfrm_migrate * m,int num_migrate,struct netlink_ext_ack * extack)4491 static int xfrm_migrate_check(const struct xfrm_migrate *m, int num_migrate,
4492 			      struct netlink_ext_ack *extack)
4493 {
4494 	int i, j;
4495 
4496 	if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH) {
4497 		NL_SET_ERR_MSG(extack, "Invalid number of SAs to migrate, must be 0 < num <= XFRM_MAX_DEPTH (6)");
4498 		return -EINVAL;
4499 	}
4500 
4501 	for (i = 0; i < num_migrate; i++) {
4502 		if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
4503 		    xfrm_addr_any(&m[i].new_saddr, m[i].new_family)) {
4504 			NL_SET_ERR_MSG(extack, "Addresses in the MIGRATE attribute's list cannot be null");
4505 			return -EINVAL;
4506 		}
4507 
4508 		/* check if there is any duplicated entry */
4509 		for (j = i + 1; j < num_migrate; j++) {
4510 			if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
4511 				    sizeof(m[i].old_daddr)) &&
4512 			    !memcmp(&m[i].old_saddr, &m[j].old_saddr,
4513 				    sizeof(m[i].old_saddr)) &&
4514 			    m[i].proto == m[j].proto &&
4515 			    m[i].mode == m[j].mode &&
4516 			    m[i].reqid == m[j].reqid &&
4517 			    m[i].old_family == m[j].old_family) {
4518 				NL_SET_ERR_MSG(extack, "Entries in the MIGRATE attribute's list must be unique");
4519 				return -EINVAL;
4520 			}
4521 		}
4522 	}
4523 
4524 	return 0;
4525 }
4526 
xfrm_migrate(const struct xfrm_selector * sel,u8 dir,u8 type,struct xfrm_migrate * m,int num_migrate,struct xfrm_kmaddress * k,struct net * net,struct xfrm_encap_tmpl * encap,u32 if_id,struct netlink_ext_ack * extack)4527 int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
4528 		 struct xfrm_migrate *m, int num_migrate,
4529 		 struct xfrm_kmaddress *k, struct net *net,
4530 		 struct xfrm_encap_tmpl *encap, u32 if_id,
4531 		 struct netlink_ext_ack *extack)
4532 {
4533 	int i, err, nx_cur = 0, nx_new = 0;
4534 	struct xfrm_policy *pol = NULL;
4535 	struct xfrm_state *x, *xc;
4536 	struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
4537 	struct xfrm_state *x_new[XFRM_MAX_DEPTH];
4538 	struct xfrm_migrate *mp;
4539 
4540 	/* Stage 0 - sanity checks */
4541 	err = xfrm_migrate_check(m, num_migrate, extack);
4542 	if (err < 0)
4543 		goto out;
4544 
4545 	if (dir >= XFRM_POLICY_MAX) {
4546 		NL_SET_ERR_MSG(extack, "Invalid policy direction");
4547 		err = -EINVAL;
4548 		goto out;
4549 	}
4550 
4551 	/* Stage 1 - find policy */
4552 	pol = xfrm_migrate_policy_find(sel, dir, type, net, if_id);
4553 	if (!pol) {
4554 		NL_SET_ERR_MSG(extack, "Target policy not found");
4555 		err = -ENOENT;
4556 		goto out;
4557 	}
4558 
4559 	/* Stage 2 - find and update state(s) */
4560 	for (i = 0, mp = m; i < num_migrate; i++, mp++) {
4561 		if ((x = xfrm_migrate_state_find(mp, net, if_id))) {
4562 			x_cur[nx_cur] = x;
4563 			nx_cur++;
4564 			xc = xfrm_state_migrate(x, mp, encap);
4565 			if (xc) {
4566 				x_new[nx_new] = xc;
4567 				nx_new++;
4568 			} else {
4569 				err = -ENODATA;
4570 				goto restore_state;
4571 			}
4572 		}
4573 	}
4574 
4575 	/* Stage 3 - update policy */
4576 	err = xfrm_policy_migrate(pol, m, num_migrate, extack);
4577 	if (err < 0)
4578 		goto restore_state;
4579 
4580 	/* Stage 4 - delete old state(s) */
4581 	if (nx_cur) {
4582 		xfrm_states_put(x_cur, nx_cur);
4583 		xfrm_states_delete(x_cur, nx_cur);
4584 	}
4585 
4586 	/* Stage 5 - announce */
4587 	km_migrate(sel, dir, type, m, num_migrate, k, encap);
4588 
4589 	xfrm_pol_put(pol);
4590 
4591 	return 0;
4592 out:
4593 	return err;
4594 
4595 restore_state:
4596 	if (pol)
4597 		xfrm_pol_put(pol);
4598 	if (nx_cur)
4599 		xfrm_states_put(x_cur, nx_cur);
4600 	if (nx_new)
4601 		xfrm_states_delete(x_new, nx_new);
4602 
4603 	return err;
4604 }
4605 EXPORT_SYMBOL(xfrm_migrate);
4606 #endif
4607