• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * xfrm_state.c
4  *
5  * Changes:
6  *	Mitsuru KANDA @USAGI
7  * 	Kazunori MIYAZAWA @USAGI
8  * 	Kunihiro Ishiguro <kunihiro@ipinfusion.com>
9  * 		IPv6 support
10  * 	YOSHIFUJI Hideaki @USAGI
11  * 		Split up af-specific functions
12  *	Derek Atkins <derek@ihtfp.com>
13  *		Add UDP Encapsulation
14  *
15  */
16 
17 #include <linux/workqueue.h>
18 #include <net/xfrm.h>
19 #include <linux/pfkeyv2.h>
20 #include <linux/ipsec.h>
21 #include <linux/module.h>
22 #include <linux/cache.h>
23 #include <linux/audit.h>
24 #include <linux/uaccess.h>
25 #include <linux/ktime.h>
26 #include <linux/slab.h>
27 #include <linux/interrupt.h>
28 #include <linux/kernel.h>
29 
30 #include <crypto/aead.h>
31 
32 #include "xfrm_hash.h"
33 
34 #define xfrm_state_deref_prot(table, net) \
35 	rcu_dereference_protected((table), lockdep_is_held(&(net)->xfrm.xfrm_state_lock))
36 
37 static void xfrm_state_gc_task(struct work_struct *work);
38 
39 /* Each xfrm_state may be linked to two tables:
40 
41    1. Hash table by (spi,daddr,ah/esp) to find SA by SPI. (input,ctl)
42    2. Hash table by (daddr,family,reqid) to find what SAs exist for given
43       destination/tunnel endpoint. (output)
44  */
45 
46 static unsigned int xfrm_state_hashmax __read_mostly = 1 * 1024 * 1024;
47 static struct kmem_cache *xfrm_state_cache __ro_after_init;
48 
49 static DECLARE_WORK(xfrm_state_gc_work, xfrm_state_gc_task);
50 static HLIST_HEAD(xfrm_state_gc_list);
51 
xfrm_state_hold_rcu(struct xfrm_state __rcu * x)52 static inline bool xfrm_state_hold_rcu(struct xfrm_state __rcu *x)
53 {
54 	return refcount_inc_not_zero(&x->refcnt);
55 }
56 
xfrm_dst_hash(struct net * net,const xfrm_address_t * daddr,const xfrm_address_t * saddr,u32 reqid,unsigned short family)57 static inline unsigned int xfrm_dst_hash(struct net *net,
58 					 const xfrm_address_t *daddr,
59 					 const xfrm_address_t *saddr,
60 					 u32 reqid,
61 					 unsigned short family)
62 {
63 	return __xfrm_dst_hash(daddr, saddr, reqid, family, net->xfrm.state_hmask);
64 }
65 
xfrm_src_hash(struct net * net,const xfrm_address_t * daddr,const xfrm_address_t * saddr,unsigned short family)66 static inline unsigned int xfrm_src_hash(struct net *net,
67 					 const xfrm_address_t *daddr,
68 					 const xfrm_address_t *saddr,
69 					 unsigned short family)
70 {
71 	return __xfrm_src_hash(daddr, saddr, family, net->xfrm.state_hmask);
72 }
73 
74 static inline unsigned int
xfrm_spi_hash(struct net * net,const xfrm_address_t * daddr,__be32 spi,u8 proto,unsigned short family)75 xfrm_spi_hash(struct net *net, const xfrm_address_t *daddr,
76 	      __be32 spi, u8 proto, unsigned short family)
77 {
78 	return __xfrm_spi_hash(daddr, spi, proto, family, net->xfrm.state_hmask);
79 }
80 
xfrm_hash_transfer(struct hlist_head * list,struct hlist_head * ndsttable,struct hlist_head * nsrctable,struct hlist_head * nspitable,unsigned int nhashmask)81 static void xfrm_hash_transfer(struct hlist_head *list,
82 			       struct hlist_head *ndsttable,
83 			       struct hlist_head *nsrctable,
84 			       struct hlist_head *nspitable,
85 			       unsigned int nhashmask)
86 {
87 	struct hlist_node *tmp;
88 	struct xfrm_state *x;
89 
90 	hlist_for_each_entry_safe(x, tmp, list, bydst) {
91 		unsigned int h;
92 
93 		h = __xfrm_dst_hash(&x->id.daddr, &x->props.saddr,
94 				    x->props.reqid, x->props.family,
95 				    nhashmask);
96 		hlist_add_head_rcu(&x->bydst, ndsttable + h);
97 
98 		h = __xfrm_src_hash(&x->id.daddr, &x->props.saddr,
99 				    x->props.family,
100 				    nhashmask);
101 		hlist_add_head_rcu(&x->bysrc, nsrctable + h);
102 
103 		if (x->id.spi) {
104 			h = __xfrm_spi_hash(&x->id.daddr, x->id.spi,
105 					    x->id.proto, x->props.family,
106 					    nhashmask);
107 			hlist_add_head_rcu(&x->byspi, nspitable + h);
108 		}
109 	}
110 }
111 
xfrm_hash_new_size(unsigned int state_hmask)112 static unsigned long xfrm_hash_new_size(unsigned int state_hmask)
113 {
114 	return ((state_hmask + 1) << 1) * sizeof(struct hlist_head);
115 }
116 
xfrm_hash_resize(struct work_struct * work)117 static void xfrm_hash_resize(struct work_struct *work)
118 {
119 	struct net *net = container_of(work, struct net, xfrm.state_hash_work);
120 	struct hlist_head *ndst, *nsrc, *nspi, *odst, *osrc, *ospi;
121 	unsigned long nsize, osize;
122 	unsigned int nhashmask, ohashmask;
123 	int i;
124 
125 	nsize = xfrm_hash_new_size(net->xfrm.state_hmask);
126 	ndst = xfrm_hash_alloc(nsize);
127 	if (!ndst)
128 		return;
129 	nsrc = xfrm_hash_alloc(nsize);
130 	if (!nsrc) {
131 		xfrm_hash_free(ndst, nsize);
132 		return;
133 	}
134 	nspi = xfrm_hash_alloc(nsize);
135 	if (!nspi) {
136 		xfrm_hash_free(ndst, nsize);
137 		xfrm_hash_free(nsrc, nsize);
138 		return;
139 	}
140 
141 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
142 	write_seqcount_begin(&net->xfrm.xfrm_state_hash_generation);
143 
144 	nhashmask = (nsize / sizeof(struct hlist_head)) - 1U;
145 	odst = xfrm_state_deref_prot(net->xfrm.state_bydst, net);
146 	for (i = net->xfrm.state_hmask; i >= 0; i--)
147 		xfrm_hash_transfer(odst + i, ndst, nsrc, nspi, nhashmask);
148 
149 	osrc = xfrm_state_deref_prot(net->xfrm.state_bysrc, net);
150 	ospi = xfrm_state_deref_prot(net->xfrm.state_byspi, net);
151 	ohashmask = net->xfrm.state_hmask;
152 
153 	rcu_assign_pointer(net->xfrm.state_bydst, ndst);
154 	rcu_assign_pointer(net->xfrm.state_bysrc, nsrc);
155 	rcu_assign_pointer(net->xfrm.state_byspi, nspi);
156 	net->xfrm.state_hmask = nhashmask;
157 
158 	write_seqcount_end(&net->xfrm.xfrm_state_hash_generation);
159 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
160 
161 	osize = (ohashmask + 1) * sizeof(struct hlist_head);
162 
163 	synchronize_rcu();
164 
165 	xfrm_hash_free(odst, osize);
166 	xfrm_hash_free(osrc, osize);
167 	xfrm_hash_free(ospi, osize);
168 }
169 
170 static DEFINE_SPINLOCK(xfrm_state_afinfo_lock);
171 static struct xfrm_state_afinfo __rcu *xfrm_state_afinfo[NPROTO];
172 
173 static DEFINE_SPINLOCK(xfrm_state_gc_lock);
174 
175 int __xfrm_state_delete(struct xfrm_state *x);
176 
177 int km_query(struct xfrm_state *x, struct xfrm_tmpl *t, struct xfrm_policy *pol);
178 static bool km_is_alive(const struct km_event *c);
179 void km_state_expired(struct xfrm_state *x, int hard, u32 portid);
180 
xfrm_register_type(const struct xfrm_type * type,unsigned short family)181 int xfrm_register_type(const struct xfrm_type *type, unsigned short family)
182 {
183 	struct xfrm_state_afinfo *afinfo = xfrm_state_get_afinfo(family);
184 	int err = 0;
185 
186 	if (!afinfo)
187 		return -EAFNOSUPPORT;
188 
189 #define X(afi, T, name) do {			\
190 		WARN_ON((afi)->type_ ## name);	\
191 		(afi)->type_ ## name = (T);	\
192 	} while (0)
193 
194 	switch (type->proto) {
195 	case IPPROTO_COMP:
196 		X(afinfo, type, comp);
197 		break;
198 	case IPPROTO_AH:
199 		X(afinfo, type, ah);
200 		break;
201 	case IPPROTO_ESP:
202 		X(afinfo, type, esp);
203 		break;
204 	case IPPROTO_IPIP:
205 		X(afinfo, type, ipip);
206 		break;
207 	case IPPROTO_DSTOPTS:
208 		X(afinfo, type, dstopts);
209 		break;
210 	case IPPROTO_ROUTING:
211 		X(afinfo, type, routing);
212 		break;
213 	case IPPROTO_IPV6:
214 		X(afinfo, type, ipip6);
215 		break;
216 	default:
217 		WARN_ON(1);
218 		err = -EPROTONOSUPPORT;
219 		break;
220 	}
221 #undef X
222 	rcu_read_unlock();
223 	return err;
224 }
225 EXPORT_SYMBOL(xfrm_register_type);
226 
xfrm_unregister_type(const struct xfrm_type * type,unsigned short family)227 void xfrm_unregister_type(const struct xfrm_type *type, unsigned short family)
228 {
229 	struct xfrm_state_afinfo *afinfo = xfrm_state_get_afinfo(family);
230 
231 	if (unlikely(afinfo == NULL))
232 		return;
233 
234 #define X(afi, T, name) do {				\
235 		WARN_ON((afi)->type_ ## name != (T));	\
236 		(afi)->type_ ## name = NULL;		\
237 	} while (0)
238 
239 	switch (type->proto) {
240 	case IPPROTO_COMP:
241 		X(afinfo, type, comp);
242 		break;
243 	case IPPROTO_AH:
244 		X(afinfo, type, ah);
245 		break;
246 	case IPPROTO_ESP:
247 		X(afinfo, type, esp);
248 		break;
249 	case IPPROTO_IPIP:
250 		X(afinfo, type, ipip);
251 		break;
252 	case IPPROTO_DSTOPTS:
253 		X(afinfo, type, dstopts);
254 		break;
255 	case IPPROTO_ROUTING:
256 		X(afinfo, type, routing);
257 		break;
258 	case IPPROTO_IPV6:
259 		X(afinfo, type, ipip6);
260 		break;
261 	default:
262 		WARN_ON(1);
263 		break;
264 	}
265 #undef X
266 	rcu_read_unlock();
267 }
268 EXPORT_SYMBOL(xfrm_unregister_type);
269 
xfrm_get_type(u8 proto,unsigned short family)270 static const struct xfrm_type *xfrm_get_type(u8 proto, unsigned short family)
271 {
272 	const struct xfrm_type *type = NULL;
273 	struct xfrm_state_afinfo *afinfo;
274 	int modload_attempted = 0;
275 
276 retry:
277 	afinfo = xfrm_state_get_afinfo(family);
278 	if (unlikely(afinfo == NULL))
279 		return NULL;
280 
281 	switch (proto) {
282 	case IPPROTO_COMP:
283 		type = afinfo->type_comp;
284 		break;
285 	case IPPROTO_AH:
286 		type = afinfo->type_ah;
287 		break;
288 	case IPPROTO_ESP:
289 		type = afinfo->type_esp;
290 		break;
291 	case IPPROTO_IPIP:
292 		type = afinfo->type_ipip;
293 		break;
294 	case IPPROTO_DSTOPTS:
295 		type = afinfo->type_dstopts;
296 		break;
297 	case IPPROTO_ROUTING:
298 		type = afinfo->type_routing;
299 		break;
300 	case IPPROTO_IPV6:
301 		type = afinfo->type_ipip6;
302 		break;
303 	default:
304 		break;
305 	}
306 
307 	if (unlikely(type && !try_module_get(type->owner)))
308 		type = NULL;
309 
310 	rcu_read_unlock();
311 
312 	if (!type && !modload_attempted) {
313 		request_module("xfrm-type-%d-%d", family, proto);
314 		modload_attempted = 1;
315 		goto retry;
316 	}
317 
318 	return type;
319 }
320 
xfrm_put_type(const struct xfrm_type * type)321 static void xfrm_put_type(const struct xfrm_type *type)
322 {
323 	module_put(type->owner);
324 }
325 
xfrm_register_type_offload(const struct xfrm_type_offload * type,unsigned short family)326 int xfrm_register_type_offload(const struct xfrm_type_offload *type,
327 			       unsigned short family)
328 {
329 	struct xfrm_state_afinfo *afinfo = xfrm_state_get_afinfo(family);
330 	int err = 0;
331 
332 	if (unlikely(afinfo == NULL))
333 		return -EAFNOSUPPORT;
334 
335 	switch (type->proto) {
336 	case IPPROTO_ESP:
337 		WARN_ON(afinfo->type_offload_esp);
338 		afinfo->type_offload_esp = type;
339 		break;
340 	default:
341 		WARN_ON(1);
342 		err = -EPROTONOSUPPORT;
343 		break;
344 	}
345 
346 	rcu_read_unlock();
347 	return err;
348 }
349 EXPORT_SYMBOL(xfrm_register_type_offload);
350 
xfrm_unregister_type_offload(const struct xfrm_type_offload * type,unsigned short family)351 void xfrm_unregister_type_offload(const struct xfrm_type_offload *type,
352 				  unsigned short family)
353 {
354 	struct xfrm_state_afinfo *afinfo = xfrm_state_get_afinfo(family);
355 
356 	if (unlikely(afinfo == NULL))
357 		return;
358 
359 	switch (type->proto) {
360 	case IPPROTO_ESP:
361 		WARN_ON(afinfo->type_offload_esp != type);
362 		afinfo->type_offload_esp = NULL;
363 		break;
364 	default:
365 		WARN_ON(1);
366 		break;
367 	}
368 	rcu_read_unlock();
369 }
370 EXPORT_SYMBOL(xfrm_unregister_type_offload);
371 
372 static const struct xfrm_type_offload *
xfrm_get_type_offload(u8 proto,unsigned short family,bool try_load)373 xfrm_get_type_offload(u8 proto, unsigned short family, bool try_load)
374 {
375 	const struct xfrm_type_offload *type = NULL;
376 	struct xfrm_state_afinfo *afinfo;
377 
378 retry:
379 	afinfo = xfrm_state_get_afinfo(family);
380 	if (unlikely(afinfo == NULL))
381 		return NULL;
382 
383 	switch (proto) {
384 	case IPPROTO_ESP:
385 		type = afinfo->type_offload_esp;
386 		break;
387 	default:
388 		break;
389 	}
390 
391 	if ((type && !try_module_get(type->owner)))
392 		type = NULL;
393 
394 	rcu_read_unlock();
395 
396 	if (!type && try_load) {
397 		request_module("xfrm-offload-%d-%d", family, proto);
398 		try_load = false;
399 		goto retry;
400 	}
401 
402 	return type;
403 }
404 
xfrm_put_type_offload(const struct xfrm_type_offload * type)405 static void xfrm_put_type_offload(const struct xfrm_type_offload *type)
406 {
407 	module_put(type->owner);
408 }
409 
410 static const struct xfrm_mode xfrm4_mode_map[XFRM_MODE_MAX] = {
411 	[XFRM_MODE_BEET] = {
412 		.encap = XFRM_MODE_BEET,
413 		.flags = XFRM_MODE_FLAG_TUNNEL,
414 		.family = AF_INET,
415 	},
416 	[XFRM_MODE_TRANSPORT] = {
417 		.encap = XFRM_MODE_TRANSPORT,
418 		.family = AF_INET,
419 	},
420 	[XFRM_MODE_TUNNEL] = {
421 		.encap = XFRM_MODE_TUNNEL,
422 		.flags = XFRM_MODE_FLAG_TUNNEL,
423 		.family = AF_INET,
424 	},
425 };
426 
427 static const struct xfrm_mode xfrm6_mode_map[XFRM_MODE_MAX] = {
428 	[XFRM_MODE_BEET] = {
429 		.encap = XFRM_MODE_BEET,
430 		.flags = XFRM_MODE_FLAG_TUNNEL,
431 		.family = AF_INET6,
432 	},
433 	[XFRM_MODE_ROUTEOPTIMIZATION] = {
434 		.encap = XFRM_MODE_ROUTEOPTIMIZATION,
435 		.family = AF_INET6,
436 	},
437 	[XFRM_MODE_TRANSPORT] = {
438 		.encap = XFRM_MODE_TRANSPORT,
439 		.family = AF_INET6,
440 	},
441 	[XFRM_MODE_TUNNEL] = {
442 		.encap = XFRM_MODE_TUNNEL,
443 		.flags = XFRM_MODE_FLAG_TUNNEL,
444 		.family = AF_INET6,
445 	},
446 };
447 
xfrm_get_mode(unsigned int encap,int family)448 static const struct xfrm_mode *xfrm_get_mode(unsigned int encap, int family)
449 {
450 	const struct xfrm_mode *mode;
451 
452 	if (unlikely(encap >= XFRM_MODE_MAX))
453 		return NULL;
454 
455 	switch (family) {
456 	case AF_INET:
457 		mode = &xfrm4_mode_map[encap];
458 		if (mode->family == family)
459 			return mode;
460 		break;
461 	case AF_INET6:
462 		mode = &xfrm6_mode_map[encap];
463 		if (mode->family == family)
464 			return mode;
465 		break;
466 	default:
467 		break;
468 	}
469 
470 	return NULL;
471 }
472 
xfrm_state_free(struct xfrm_state * x)473 void xfrm_state_free(struct xfrm_state *x)
474 {
475 	kmem_cache_free(xfrm_state_cache, x);
476 }
477 EXPORT_SYMBOL(xfrm_state_free);
478 
___xfrm_state_destroy(struct xfrm_state * x)479 static void ___xfrm_state_destroy(struct xfrm_state *x)
480 {
481 	hrtimer_cancel(&x->mtimer);
482 	del_timer_sync(&x->rtimer);
483 	kfree(x->aead);
484 	kfree(x->aalg);
485 	kfree(x->ealg);
486 	kfree(x->calg);
487 	kfree(x->encap);
488 	kfree(x->coaddr);
489 	kfree(x->replay_esn);
490 	kfree(x->preplay_esn);
491 	if (x->type_offload)
492 		xfrm_put_type_offload(x->type_offload);
493 	if (x->type) {
494 		x->type->destructor(x);
495 		xfrm_put_type(x->type);
496 	}
497 	if (x->xfrag.page)
498 		put_page(x->xfrag.page);
499 	xfrm_dev_state_free(x);
500 	security_xfrm_state_free(x);
501 	xfrm_state_free(x);
502 }
503 
xfrm_state_gc_task(struct work_struct * work)504 static void xfrm_state_gc_task(struct work_struct *work)
505 {
506 	struct xfrm_state *x;
507 	struct hlist_node *tmp;
508 	struct hlist_head gc_list;
509 
510 	spin_lock_bh(&xfrm_state_gc_lock);
511 	hlist_move_list(&xfrm_state_gc_list, &gc_list);
512 	spin_unlock_bh(&xfrm_state_gc_lock);
513 
514 	synchronize_rcu();
515 
516 	hlist_for_each_entry_safe(x, tmp, &gc_list, gclist)
517 		___xfrm_state_destroy(x);
518 }
519 
xfrm_timer_handler(struct hrtimer * me)520 static enum hrtimer_restart xfrm_timer_handler(struct hrtimer *me)
521 {
522 	struct xfrm_state *x = container_of(me, struct xfrm_state, mtimer);
523 	enum hrtimer_restart ret = HRTIMER_NORESTART;
524 	time64_t now = ktime_get_real_seconds();
525 	time64_t next = TIME64_MAX;
526 	int warn = 0;
527 	int err = 0;
528 
529 	spin_lock(&x->lock);
530 	if (x->km.state == XFRM_STATE_DEAD)
531 		goto out;
532 	if (x->km.state == XFRM_STATE_EXPIRED)
533 		goto expired;
534 	if (x->lft.hard_add_expires_seconds) {
535 		long tmo = x->lft.hard_add_expires_seconds +
536 			x->curlft.add_time - now;
537 		if (tmo <= 0) {
538 			if (x->xflags & XFRM_SOFT_EXPIRE) {
539 				/* enter hard expire without soft expire first?!
540 				 * setting a new date could trigger this.
541 				 * workaround: fix x->curflt.add_time by below:
542 				 */
543 				x->curlft.add_time = now - x->saved_tmo - 1;
544 				tmo = x->lft.hard_add_expires_seconds - x->saved_tmo;
545 			} else
546 				goto expired;
547 		}
548 		if (tmo < next)
549 			next = tmo;
550 	}
551 	if (x->lft.hard_use_expires_seconds) {
552 		long tmo = x->lft.hard_use_expires_seconds +
553 			(x->curlft.use_time ? : now) - now;
554 		if (tmo <= 0)
555 			goto expired;
556 		if (tmo < next)
557 			next = tmo;
558 	}
559 	if (x->km.dying)
560 		goto resched;
561 	if (x->lft.soft_add_expires_seconds) {
562 		long tmo = x->lft.soft_add_expires_seconds +
563 			x->curlft.add_time - now;
564 		if (tmo <= 0) {
565 			warn = 1;
566 			x->xflags &= ~XFRM_SOFT_EXPIRE;
567 		} else if (tmo < next) {
568 			next = tmo;
569 			x->xflags |= XFRM_SOFT_EXPIRE;
570 			x->saved_tmo = tmo;
571 		}
572 	}
573 	if (x->lft.soft_use_expires_seconds) {
574 		long tmo = x->lft.soft_use_expires_seconds +
575 			(x->curlft.use_time ? : now) - now;
576 		if (tmo <= 0)
577 			warn = 1;
578 		else if (tmo < next)
579 			next = tmo;
580 	}
581 
582 	x->km.dying = warn;
583 	if (warn)
584 		km_state_expired(x, 0, 0);
585 resched:
586 	if (next != TIME64_MAX) {
587 		hrtimer_forward_now(&x->mtimer, ktime_set(next, 0));
588 		ret = HRTIMER_RESTART;
589 	}
590 
591 	goto out;
592 
593 expired:
594 	if (x->km.state == XFRM_STATE_ACQ && x->id.spi == 0)
595 		x->km.state = XFRM_STATE_EXPIRED;
596 
597 	err = __xfrm_state_delete(x);
598 	if (!err)
599 		km_state_expired(x, 1, 0);
600 
601 	xfrm_audit_state_delete(x, err ? 0 : 1, true);
602 
603 out:
604 	spin_unlock(&x->lock);
605 	return ret;
606 }
607 
608 static void xfrm_replay_timer_handler(struct timer_list *t);
609 
xfrm_state_alloc(struct net * net)610 struct xfrm_state *xfrm_state_alloc(struct net *net)
611 {
612 	struct xfrm_state *x;
613 
614 	x = kmem_cache_zalloc(xfrm_state_cache, GFP_ATOMIC);
615 
616 	if (x) {
617 		write_pnet(&x->xs_net, net);
618 		refcount_set(&x->refcnt, 1);
619 		atomic_set(&x->tunnel_users, 0);
620 		INIT_LIST_HEAD(&x->km.all);
621 		INIT_HLIST_NODE(&x->bydst);
622 		INIT_HLIST_NODE(&x->bysrc);
623 		INIT_HLIST_NODE(&x->byspi);
624 		hrtimer_init(&x->mtimer, CLOCK_BOOTTIME, HRTIMER_MODE_ABS_SOFT);
625 		x->mtimer.function = xfrm_timer_handler;
626 		timer_setup(&x->rtimer, xfrm_replay_timer_handler, 0);
627 		x->curlft.add_time = ktime_get_real_seconds();
628 		x->lft.soft_byte_limit = XFRM_INF;
629 		x->lft.soft_packet_limit = XFRM_INF;
630 		x->lft.hard_byte_limit = XFRM_INF;
631 		x->lft.hard_packet_limit = XFRM_INF;
632 		x->replay_maxage = 0;
633 		x->replay_maxdiff = 0;
634 		spin_lock_init(&x->lock);
635 	}
636 	return x;
637 }
638 EXPORT_SYMBOL(xfrm_state_alloc);
639 
__xfrm_state_destroy(struct xfrm_state * x,bool sync)640 void __xfrm_state_destroy(struct xfrm_state *x, bool sync)
641 {
642 	WARN_ON(x->km.state != XFRM_STATE_DEAD);
643 
644 	if (sync) {
645 		synchronize_rcu();
646 		___xfrm_state_destroy(x);
647 	} else {
648 		spin_lock_bh(&xfrm_state_gc_lock);
649 		hlist_add_head(&x->gclist, &xfrm_state_gc_list);
650 		spin_unlock_bh(&xfrm_state_gc_lock);
651 		schedule_work(&xfrm_state_gc_work);
652 	}
653 }
654 EXPORT_SYMBOL(__xfrm_state_destroy);
655 
__xfrm_state_delete(struct xfrm_state * x)656 int __xfrm_state_delete(struct xfrm_state *x)
657 {
658 	struct net *net = xs_net(x);
659 	int err = -ESRCH;
660 
661 	if (x->km.state != XFRM_STATE_DEAD) {
662 		x->km.state = XFRM_STATE_DEAD;
663 		spin_lock(&net->xfrm.xfrm_state_lock);
664 		list_del(&x->km.all);
665 		hlist_del_rcu(&x->bydst);
666 		hlist_del_rcu(&x->bysrc);
667 		if (x->id.spi)
668 			hlist_del_rcu(&x->byspi);
669 		net->xfrm.state_num--;
670 		spin_unlock(&net->xfrm.xfrm_state_lock);
671 
672 		if (x->encap_sk)
673 			sock_put(rcu_dereference_raw(x->encap_sk));
674 
675 		xfrm_dev_state_delete(x);
676 
677 		/* All xfrm_state objects are created by xfrm_state_alloc.
678 		 * The xfrm_state_alloc call gives a reference, and that
679 		 * is what we are dropping here.
680 		 */
681 		xfrm_state_put(x);
682 		err = 0;
683 	}
684 
685 	return err;
686 }
687 EXPORT_SYMBOL(__xfrm_state_delete);
688 
xfrm_state_delete(struct xfrm_state * x)689 int xfrm_state_delete(struct xfrm_state *x)
690 {
691 	int err;
692 
693 	spin_lock_bh(&x->lock);
694 	err = __xfrm_state_delete(x);
695 	spin_unlock_bh(&x->lock);
696 
697 	return err;
698 }
699 EXPORT_SYMBOL(xfrm_state_delete);
700 
701 #ifdef CONFIG_SECURITY_NETWORK_XFRM
702 static inline int
xfrm_state_flush_secctx_check(struct net * net,u8 proto,bool task_valid)703 xfrm_state_flush_secctx_check(struct net *net, u8 proto, bool task_valid)
704 {
705 	int i, err = 0;
706 
707 	for (i = 0; i <= net->xfrm.state_hmask; i++) {
708 		struct xfrm_state *x;
709 
710 		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
711 			if (xfrm_id_proto_match(x->id.proto, proto) &&
712 			   (err = security_xfrm_state_delete(x)) != 0) {
713 				xfrm_audit_state_delete(x, 0, task_valid);
714 				return err;
715 			}
716 		}
717 	}
718 
719 	return err;
720 }
721 
722 static inline int
xfrm_dev_state_flush_secctx_check(struct net * net,struct net_device * dev,bool task_valid)723 xfrm_dev_state_flush_secctx_check(struct net *net, struct net_device *dev, bool task_valid)
724 {
725 	int i, err = 0;
726 
727 	for (i = 0; i <= net->xfrm.state_hmask; i++) {
728 		struct xfrm_state *x;
729 		struct xfrm_state_offload *xso;
730 
731 		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
732 			xso = &x->xso;
733 
734 			if (xso->dev == dev &&
735 			   (err = security_xfrm_state_delete(x)) != 0) {
736 				xfrm_audit_state_delete(x, 0, task_valid);
737 				return err;
738 			}
739 		}
740 	}
741 
742 	return err;
743 }
744 #else
745 static inline int
xfrm_state_flush_secctx_check(struct net * net,u8 proto,bool task_valid)746 xfrm_state_flush_secctx_check(struct net *net, u8 proto, bool task_valid)
747 {
748 	return 0;
749 }
750 
751 static inline int
xfrm_dev_state_flush_secctx_check(struct net * net,struct net_device * dev,bool task_valid)752 xfrm_dev_state_flush_secctx_check(struct net *net, struct net_device *dev, bool task_valid)
753 {
754 	return 0;
755 }
756 #endif
757 
xfrm_state_flush(struct net * net,u8 proto,bool task_valid,bool sync)758 int xfrm_state_flush(struct net *net, u8 proto, bool task_valid, bool sync)
759 {
760 	int i, err = 0, cnt = 0;
761 
762 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
763 	err = xfrm_state_flush_secctx_check(net, proto, task_valid);
764 	if (err)
765 		goto out;
766 
767 	err = -ESRCH;
768 	for (i = 0; i <= net->xfrm.state_hmask; i++) {
769 		struct xfrm_state *x;
770 restart:
771 		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
772 			if (!xfrm_state_kern(x) &&
773 			    xfrm_id_proto_match(x->id.proto, proto)) {
774 				xfrm_state_hold(x);
775 				spin_unlock_bh(&net->xfrm.xfrm_state_lock);
776 
777 				err = xfrm_state_delete(x);
778 				xfrm_audit_state_delete(x, err ? 0 : 1,
779 							task_valid);
780 				if (sync)
781 					xfrm_state_put_sync(x);
782 				else
783 					xfrm_state_put(x);
784 				if (!err)
785 					cnt++;
786 
787 				spin_lock_bh(&net->xfrm.xfrm_state_lock);
788 				goto restart;
789 			}
790 		}
791 	}
792 out:
793 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
794 	if (cnt)
795 		err = 0;
796 
797 	return err;
798 }
799 EXPORT_SYMBOL(xfrm_state_flush);
800 
xfrm_dev_state_flush(struct net * net,struct net_device * dev,bool task_valid)801 int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_valid)
802 {
803 	int i, err = 0, cnt = 0;
804 
805 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
806 	err = xfrm_dev_state_flush_secctx_check(net, dev, task_valid);
807 	if (err)
808 		goto out;
809 
810 	err = -ESRCH;
811 	for (i = 0; i <= net->xfrm.state_hmask; i++) {
812 		struct xfrm_state *x;
813 		struct xfrm_state_offload *xso;
814 restart:
815 		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
816 			xso = &x->xso;
817 
818 			if (!xfrm_state_kern(x) && xso->dev == dev) {
819 				xfrm_state_hold(x);
820 				spin_unlock_bh(&net->xfrm.xfrm_state_lock);
821 
822 				err = xfrm_state_delete(x);
823 				xfrm_audit_state_delete(x, err ? 0 : 1,
824 							task_valid);
825 				xfrm_state_put(x);
826 				if (!err)
827 					cnt++;
828 
829 				spin_lock_bh(&net->xfrm.xfrm_state_lock);
830 				goto restart;
831 			}
832 		}
833 	}
834 	if (cnt)
835 		err = 0;
836 
837 out:
838 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
839 	return err;
840 }
841 EXPORT_SYMBOL(xfrm_dev_state_flush);
842 
xfrm_sad_getinfo(struct net * net,struct xfrmk_sadinfo * si)843 void xfrm_sad_getinfo(struct net *net, struct xfrmk_sadinfo *si)
844 {
845 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
846 	si->sadcnt = net->xfrm.state_num;
847 	si->sadhcnt = net->xfrm.state_hmask + 1;
848 	si->sadhmcnt = xfrm_state_hashmax;
849 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
850 }
851 EXPORT_SYMBOL(xfrm_sad_getinfo);
852 
853 static void
__xfrm4_init_tempsel(struct xfrm_selector * sel,const struct flowi * fl)854 __xfrm4_init_tempsel(struct xfrm_selector *sel, const struct flowi *fl)
855 {
856 	const struct flowi4 *fl4 = &fl->u.ip4;
857 
858 	sel->daddr.a4 = fl4->daddr;
859 	sel->saddr.a4 = fl4->saddr;
860 	sel->dport = xfrm_flowi_dport(fl, &fl4->uli);
861 	sel->dport_mask = htons(0xffff);
862 	sel->sport = xfrm_flowi_sport(fl, &fl4->uli);
863 	sel->sport_mask = htons(0xffff);
864 	sel->family = AF_INET;
865 	sel->prefixlen_d = 32;
866 	sel->prefixlen_s = 32;
867 	sel->proto = fl4->flowi4_proto;
868 	sel->ifindex = fl4->flowi4_oif;
869 }
870 
871 static void
__xfrm6_init_tempsel(struct xfrm_selector * sel,const struct flowi * fl)872 __xfrm6_init_tempsel(struct xfrm_selector *sel, const struct flowi *fl)
873 {
874 	const struct flowi6 *fl6 = &fl->u.ip6;
875 
876 	/* Initialize temporary selector matching only to current session. */
877 	*(struct in6_addr *)&sel->daddr = fl6->daddr;
878 	*(struct in6_addr *)&sel->saddr = fl6->saddr;
879 	sel->dport = xfrm_flowi_dport(fl, &fl6->uli);
880 	sel->dport_mask = htons(0xffff);
881 	sel->sport = xfrm_flowi_sport(fl, &fl6->uli);
882 	sel->sport_mask = htons(0xffff);
883 	sel->family = AF_INET6;
884 	sel->prefixlen_d = 128;
885 	sel->prefixlen_s = 128;
886 	sel->proto = fl6->flowi6_proto;
887 	sel->ifindex = fl6->flowi6_oif;
888 }
889 
890 static void
xfrm_init_tempstate(struct xfrm_state * x,const struct flowi * fl,const struct xfrm_tmpl * tmpl,const xfrm_address_t * daddr,const xfrm_address_t * saddr,unsigned short family)891 xfrm_init_tempstate(struct xfrm_state *x, const struct flowi *fl,
892 		    const struct xfrm_tmpl *tmpl,
893 		    const xfrm_address_t *daddr, const xfrm_address_t *saddr,
894 		    unsigned short family)
895 {
896 	switch (family) {
897 	case AF_INET:
898 		__xfrm4_init_tempsel(&x->sel, fl);
899 		break;
900 	case AF_INET6:
901 		__xfrm6_init_tempsel(&x->sel, fl);
902 		break;
903 	}
904 
905 	x->id = tmpl->id;
906 
907 	switch (tmpl->encap_family) {
908 	case AF_INET:
909 		if (x->id.daddr.a4 == 0)
910 			x->id.daddr.a4 = daddr->a4;
911 		x->props.saddr = tmpl->saddr;
912 		if (x->props.saddr.a4 == 0)
913 			x->props.saddr.a4 = saddr->a4;
914 		break;
915 	case AF_INET6:
916 		if (ipv6_addr_any((struct in6_addr *)&x->id.daddr))
917 			memcpy(&x->id.daddr, daddr, sizeof(x->sel.daddr));
918 		memcpy(&x->props.saddr, &tmpl->saddr, sizeof(x->props.saddr));
919 		if (ipv6_addr_any((struct in6_addr *)&x->props.saddr))
920 			memcpy(&x->props.saddr, saddr, sizeof(x->props.saddr));
921 		break;
922 	}
923 
924 	x->props.mode = tmpl->mode;
925 	x->props.reqid = tmpl->reqid;
926 	x->props.family = tmpl->encap_family;
927 }
928 
__xfrm_state_lookup(struct net * net,u32 mark,const xfrm_address_t * daddr,__be32 spi,u8 proto,unsigned short family)929 static struct xfrm_state *__xfrm_state_lookup(struct net *net, u32 mark,
930 					      const xfrm_address_t *daddr,
931 					      __be32 spi, u8 proto,
932 					      unsigned short family)
933 {
934 	unsigned int h = xfrm_spi_hash(net, daddr, spi, proto, family);
935 	struct xfrm_state *x;
936 
937 	hlist_for_each_entry_rcu(x, net->xfrm.state_byspi + h, byspi) {
938 		if (x->props.family != family ||
939 		    x->id.spi       != spi ||
940 		    x->id.proto     != proto ||
941 		    !xfrm_addr_equal(&x->id.daddr, daddr, family))
942 			continue;
943 
944 		if ((mark & x->mark.m) != x->mark.v)
945 			continue;
946 		if (!xfrm_state_hold_rcu(x))
947 			continue;
948 		return x;
949 	}
950 
951 	return NULL;
952 }
953 
__xfrm_state_lookup_byaddr(struct net * net,u32 mark,const xfrm_address_t * daddr,const xfrm_address_t * saddr,u8 proto,unsigned short family)954 static struct xfrm_state *__xfrm_state_lookup_byaddr(struct net *net, u32 mark,
955 						     const xfrm_address_t *daddr,
956 						     const xfrm_address_t *saddr,
957 						     u8 proto, unsigned short family)
958 {
959 	unsigned int h = xfrm_src_hash(net, daddr, saddr, family);
960 	struct xfrm_state *x;
961 
962 	hlist_for_each_entry_rcu(x, net->xfrm.state_bysrc + h, bysrc) {
963 		if (x->props.family != family ||
964 		    x->id.proto     != proto ||
965 		    !xfrm_addr_equal(&x->id.daddr, daddr, family) ||
966 		    !xfrm_addr_equal(&x->props.saddr, saddr, family))
967 			continue;
968 
969 		if ((mark & x->mark.m) != x->mark.v)
970 			continue;
971 		if (!xfrm_state_hold_rcu(x))
972 			continue;
973 		return x;
974 	}
975 
976 	return NULL;
977 }
978 
979 static inline struct xfrm_state *
__xfrm_state_locate(struct xfrm_state * x,int use_spi,int family)980 __xfrm_state_locate(struct xfrm_state *x, int use_spi, int family)
981 {
982 	struct net *net = xs_net(x);
983 	u32 mark = x->mark.v & x->mark.m;
984 
985 	if (use_spi)
986 		return __xfrm_state_lookup(net, mark, &x->id.daddr,
987 					   x->id.spi, x->id.proto, family);
988 	else
989 		return __xfrm_state_lookup_byaddr(net, mark,
990 						  &x->id.daddr,
991 						  &x->props.saddr,
992 						  x->id.proto, family);
993 }
994 
xfrm_hash_grow_check(struct net * net,int have_hash_collision)995 static void xfrm_hash_grow_check(struct net *net, int have_hash_collision)
996 {
997 	if (have_hash_collision &&
998 	    (net->xfrm.state_hmask + 1) < xfrm_state_hashmax &&
999 	    net->xfrm.state_num > net->xfrm.state_hmask)
1000 		schedule_work(&net->xfrm.state_hash_work);
1001 }
1002 
xfrm_state_look_at(struct xfrm_policy * pol,struct xfrm_state * x,const struct flowi * fl,unsigned short family,struct xfrm_state ** best,int * acq_in_progress,int * error)1003 static void xfrm_state_look_at(struct xfrm_policy *pol, struct xfrm_state *x,
1004 			       const struct flowi *fl, unsigned short family,
1005 			       struct xfrm_state **best, int *acq_in_progress,
1006 			       int *error)
1007 {
1008 	/* Resolution logic:
1009 	 * 1. There is a valid state with matching selector. Done.
1010 	 * 2. Valid state with inappropriate selector. Skip.
1011 	 *
1012 	 * Entering area of "sysdeps".
1013 	 *
1014 	 * 3. If state is not valid, selector is temporary, it selects
1015 	 *    only session which triggered previous resolution. Key
1016 	 *    manager will do something to install a state with proper
1017 	 *    selector.
1018 	 */
1019 	if (x->km.state == XFRM_STATE_VALID) {
1020 		if ((x->sel.family &&
1021 		     (x->sel.family != family ||
1022 		      !xfrm_selector_match(&x->sel, fl, family))) ||
1023 		    !security_xfrm_state_pol_flow_match(x, pol,
1024 							&fl->u.__fl_common))
1025 			return;
1026 
1027 		if (!*best ||
1028 		    (*best)->km.dying > x->km.dying ||
1029 		    ((*best)->km.dying == x->km.dying &&
1030 		     (*best)->curlft.add_time < x->curlft.add_time))
1031 			*best = x;
1032 	} else if (x->km.state == XFRM_STATE_ACQ) {
1033 		*acq_in_progress = 1;
1034 	} else if (x->km.state == XFRM_STATE_ERROR ||
1035 		   x->km.state == XFRM_STATE_EXPIRED) {
1036 		if ((!x->sel.family ||
1037 		     (x->sel.family == family &&
1038 		      xfrm_selector_match(&x->sel, fl, family))) &&
1039 		    security_xfrm_state_pol_flow_match(x, pol,
1040 						       &fl->u.__fl_common))
1041 			*error = -ESRCH;
1042 	}
1043 }
1044 
1045 struct xfrm_state *
xfrm_state_find(const xfrm_address_t * daddr,const xfrm_address_t * saddr,const struct flowi * fl,struct xfrm_tmpl * tmpl,struct xfrm_policy * pol,int * err,unsigned short family,u32 if_id)1046 xfrm_state_find(const xfrm_address_t *daddr, const xfrm_address_t *saddr,
1047 		const struct flowi *fl, struct xfrm_tmpl *tmpl,
1048 		struct xfrm_policy *pol, int *err,
1049 		unsigned short family, u32 if_id)
1050 {
1051 	static xfrm_address_t saddr_wildcard = { };
1052 	struct net *net = xp_net(pol);
1053 	unsigned int h, h_wildcard;
1054 	struct xfrm_state *x, *x0, *to_put;
1055 	int acquire_in_progress = 0;
1056 	int error = 0;
1057 	struct xfrm_state *best = NULL;
1058 	u32 mark = pol->mark.v & pol->mark.m;
1059 	unsigned short encap_family = tmpl->encap_family;
1060 	unsigned int sequence;
1061 	struct km_event c;
1062 
1063 	to_put = NULL;
1064 
1065 	sequence = read_seqcount_begin(&net->xfrm.xfrm_state_hash_generation);
1066 
1067 	rcu_read_lock();
1068 	h = xfrm_dst_hash(net, daddr, saddr, tmpl->reqid, encap_family);
1069 	hlist_for_each_entry_rcu(x, net->xfrm.state_bydst + h, bydst) {
1070 		if (x->props.family == encap_family &&
1071 		    x->props.reqid == tmpl->reqid &&
1072 		    (mark & x->mark.m) == x->mark.v &&
1073 		    x->if_id == if_id &&
1074 		    !(x->props.flags & XFRM_STATE_WILDRECV) &&
1075 		    xfrm_state_addr_check(x, daddr, saddr, encap_family) &&
1076 		    tmpl->mode == x->props.mode &&
1077 		    tmpl->id.proto == x->id.proto &&
1078 		    (tmpl->id.spi == x->id.spi || !tmpl->id.spi))
1079 			xfrm_state_look_at(pol, x, fl, family,
1080 					   &best, &acquire_in_progress, &error);
1081 	}
1082 	if (best || acquire_in_progress)
1083 		goto found;
1084 
1085 	h_wildcard = xfrm_dst_hash(net, daddr, &saddr_wildcard, tmpl->reqid, encap_family);
1086 	hlist_for_each_entry_rcu(x, net->xfrm.state_bydst + h_wildcard, bydst) {
1087 		if (x->props.family == encap_family &&
1088 		    x->props.reqid == tmpl->reqid &&
1089 		    (mark & x->mark.m) == x->mark.v &&
1090 		    x->if_id == if_id &&
1091 		    !(x->props.flags & XFRM_STATE_WILDRECV) &&
1092 		    xfrm_addr_equal(&x->id.daddr, daddr, encap_family) &&
1093 		    tmpl->mode == x->props.mode &&
1094 		    tmpl->id.proto == x->id.proto &&
1095 		    (tmpl->id.spi == x->id.spi || !tmpl->id.spi))
1096 			xfrm_state_look_at(pol, x, fl, family,
1097 					   &best, &acquire_in_progress, &error);
1098 	}
1099 
1100 found:
1101 	x = best;
1102 	if (!x && !error && !acquire_in_progress) {
1103 		if (tmpl->id.spi &&
1104 		    (x0 = __xfrm_state_lookup(net, mark, daddr, tmpl->id.spi,
1105 					      tmpl->id.proto, encap_family)) != NULL) {
1106 			to_put = x0;
1107 			error = -EEXIST;
1108 			goto out;
1109 		}
1110 
1111 		c.net = net;
1112 		/* If the KMs have no listeners (yet...), avoid allocating an SA
1113 		 * for each and every packet - garbage collection might not
1114 		 * handle the flood.
1115 		 */
1116 		if (!km_is_alive(&c)) {
1117 			error = -ESRCH;
1118 			goto out;
1119 		}
1120 
1121 		x = xfrm_state_alloc(net);
1122 		if (x == NULL) {
1123 			error = -ENOMEM;
1124 			goto out;
1125 		}
1126 		/* Initialize temporary state matching only
1127 		 * to current session. */
1128 		xfrm_init_tempstate(x, fl, tmpl, daddr, saddr, family);
1129 		memcpy(&x->mark, &pol->mark, sizeof(x->mark));
1130 		x->if_id = if_id;
1131 
1132 		error = security_xfrm_state_alloc_acquire(x, pol->security, fl->flowi_secid);
1133 		if (error) {
1134 			x->km.state = XFRM_STATE_DEAD;
1135 			to_put = x;
1136 			x = NULL;
1137 			goto out;
1138 		}
1139 
1140 		if (km_query(x, tmpl, pol) == 0) {
1141 			spin_lock_bh(&net->xfrm.xfrm_state_lock);
1142 			x->km.state = XFRM_STATE_ACQ;
1143 			list_add(&x->km.all, &net->xfrm.state_all);
1144 			hlist_add_head_rcu(&x->bydst, net->xfrm.state_bydst + h);
1145 			h = xfrm_src_hash(net, daddr, saddr, encap_family);
1146 			hlist_add_head_rcu(&x->bysrc, net->xfrm.state_bysrc + h);
1147 			if (x->id.spi) {
1148 				h = xfrm_spi_hash(net, &x->id.daddr, x->id.spi, x->id.proto, encap_family);
1149 				hlist_add_head_rcu(&x->byspi, net->xfrm.state_byspi + h);
1150 			}
1151 			x->lft.hard_add_expires_seconds = net->xfrm.sysctl_acq_expires;
1152 			hrtimer_start(&x->mtimer,
1153 				      ktime_set(net->xfrm.sysctl_acq_expires, 0),
1154 				      HRTIMER_MODE_REL_SOFT);
1155 			net->xfrm.state_num++;
1156 			xfrm_hash_grow_check(net, x->bydst.next != NULL);
1157 			spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1158 		} else {
1159 			x->km.state = XFRM_STATE_DEAD;
1160 			to_put = x;
1161 			x = NULL;
1162 			error = -ESRCH;
1163 		}
1164 	}
1165 out:
1166 	if (x) {
1167 		if (!xfrm_state_hold_rcu(x)) {
1168 			*err = -EAGAIN;
1169 			x = NULL;
1170 		}
1171 	} else {
1172 		*err = acquire_in_progress ? -EAGAIN : error;
1173 	}
1174 	rcu_read_unlock();
1175 	if (to_put)
1176 		xfrm_state_put(to_put);
1177 
1178 	if (read_seqcount_retry(&net->xfrm.xfrm_state_hash_generation, sequence)) {
1179 		*err = -EAGAIN;
1180 		if (x) {
1181 			xfrm_state_put(x);
1182 			x = NULL;
1183 		}
1184 	}
1185 
1186 	return x;
1187 }
1188 
1189 struct xfrm_state *
xfrm_stateonly_find(struct net * net,u32 mark,u32 if_id,xfrm_address_t * daddr,xfrm_address_t * saddr,unsigned short family,u8 mode,u8 proto,u32 reqid)1190 xfrm_stateonly_find(struct net *net, u32 mark, u32 if_id,
1191 		    xfrm_address_t *daddr, xfrm_address_t *saddr,
1192 		    unsigned short family, u8 mode, u8 proto, u32 reqid)
1193 {
1194 	unsigned int h;
1195 	struct xfrm_state *rx = NULL, *x = NULL;
1196 
1197 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1198 	h = xfrm_dst_hash(net, daddr, saddr, reqid, family);
1199 	hlist_for_each_entry(x, net->xfrm.state_bydst+h, bydst) {
1200 		if (x->props.family == family &&
1201 		    x->props.reqid == reqid &&
1202 		    (mark & x->mark.m) == x->mark.v &&
1203 		    x->if_id == if_id &&
1204 		    !(x->props.flags & XFRM_STATE_WILDRECV) &&
1205 		    xfrm_state_addr_check(x, daddr, saddr, family) &&
1206 		    mode == x->props.mode &&
1207 		    proto == x->id.proto &&
1208 		    x->km.state == XFRM_STATE_VALID) {
1209 			rx = x;
1210 			break;
1211 		}
1212 	}
1213 
1214 	if (rx)
1215 		xfrm_state_hold(rx);
1216 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1217 
1218 
1219 	return rx;
1220 }
1221 EXPORT_SYMBOL(xfrm_stateonly_find);
1222 
xfrm_state_lookup_byspi(struct net * net,__be32 spi,unsigned short family)1223 struct xfrm_state *xfrm_state_lookup_byspi(struct net *net, __be32 spi,
1224 					      unsigned short family)
1225 {
1226 	struct xfrm_state *x;
1227 	struct xfrm_state_walk *w;
1228 
1229 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1230 	list_for_each_entry(w, &net->xfrm.state_all, all) {
1231 		x = container_of(w, struct xfrm_state, km);
1232 		if (x->props.family != family ||
1233 			x->id.spi != spi)
1234 			continue;
1235 
1236 		xfrm_state_hold(x);
1237 		spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1238 		return x;
1239 	}
1240 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1241 	return NULL;
1242 }
1243 EXPORT_SYMBOL(xfrm_state_lookup_byspi);
1244 
__xfrm_state_insert(struct xfrm_state * x)1245 static void __xfrm_state_insert(struct xfrm_state *x)
1246 {
1247 	struct net *net = xs_net(x);
1248 	unsigned int h;
1249 
1250 	list_add(&x->km.all, &net->xfrm.state_all);
1251 
1252 	h = xfrm_dst_hash(net, &x->id.daddr, &x->props.saddr,
1253 			  x->props.reqid, x->props.family);
1254 	hlist_add_head_rcu(&x->bydst, net->xfrm.state_bydst + h);
1255 
1256 	h = xfrm_src_hash(net, &x->id.daddr, &x->props.saddr, x->props.family);
1257 	hlist_add_head_rcu(&x->bysrc, net->xfrm.state_bysrc + h);
1258 
1259 	if (x->id.spi) {
1260 		h = xfrm_spi_hash(net, &x->id.daddr, x->id.spi, x->id.proto,
1261 				  x->props.family);
1262 
1263 		hlist_add_head_rcu(&x->byspi, net->xfrm.state_byspi + h);
1264 	}
1265 
1266 	hrtimer_start(&x->mtimer, ktime_set(1, 0), HRTIMER_MODE_REL_SOFT);
1267 	if (x->replay_maxage)
1268 		mod_timer(&x->rtimer, jiffies + x->replay_maxage);
1269 
1270 	net->xfrm.state_num++;
1271 
1272 	xfrm_hash_grow_check(net, x->bydst.next != NULL);
1273 }
1274 
1275 /* net->xfrm.xfrm_state_lock is held */
__xfrm_state_bump_genids(struct xfrm_state * xnew)1276 static void __xfrm_state_bump_genids(struct xfrm_state *xnew)
1277 {
1278 	struct net *net = xs_net(xnew);
1279 	unsigned short family = xnew->props.family;
1280 	u32 reqid = xnew->props.reqid;
1281 	struct xfrm_state *x;
1282 	unsigned int h;
1283 	u32 mark = xnew->mark.v & xnew->mark.m;
1284 	u32 if_id = xnew->if_id;
1285 
1286 	h = xfrm_dst_hash(net, &xnew->id.daddr, &xnew->props.saddr, reqid, family);
1287 	hlist_for_each_entry(x, net->xfrm.state_bydst+h, bydst) {
1288 		if (x->props.family	== family &&
1289 		    x->props.reqid	== reqid &&
1290 		    x->if_id		== if_id &&
1291 		    (mark & x->mark.m) == x->mark.v &&
1292 		    xfrm_addr_equal(&x->id.daddr, &xnew->id.daddr, family) &&
1293 		    xfrm_addr_equal(&x->props.saddr, &xnew->props.saddr, family))
1294 			x->genid++;
1295 	}
1296 }
1297 
xfrm_state_insert(struct xfrm_state * x)1298 void xfrm_state_insert(struct xfrm_state *x)
1299 {
1300 	struct net *net = xs_net(x);
1301 
1302 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1303 	__xfrm_state_bump_genids(x);
1304 	__xfrm_state_insert(x);
1305 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1306 }
1307 EXPORT_SYMBOL(xfrm_state_insert);
1308 
1309 /* net->xfrm.xfrm_state_lock is held */
__find_acq_core(struct net * net,const struct xfrm_mark * m,unsigned short family,u8 mode,u32 reqid,u32 if_id,u8 proto,const xfrm_address_t * daddr,const xfrm_address_t * saddr,int create)1310 static struct xfrm_state *__find_acq_core(struct net *net,
1311 					  const struct xfrm_mark *m,
1312 					  unsigned short family, u8 mode,
1313 					  u32 reqid, u32 if_id, u8 proto,
1314 					  const xfrm_address_t *daddr,
1315 					  const xfrm_address_t *saddr,
1316 					  int create)
1317 {
1318 	unsigned int h = xfrm_dst_hash(net, daddr, saddr, reqid, family);
1319 	struct xfrm_state *x;
1320 	u32 mark = m->v & m->m;
1321 
1322 	hlist_for_each_entry(x, net->xfrm.state_bydst+h, bydst) {
1323 		if (x->props.reqid  != reqid ||
1324 		    x->props.mode   != mode ||
1325 		    x->props.family != family ||
1326 		    x->km.state     != XFRM_STATE_ACQ ||
1327 		    x->id.spi       != 0 ||
1328 		    x->id.proto	    != proto ||
1329 		    (mark & x->mark.m) != x->mark.v ||
1330 		    !xfrm_addr_equal(&x->id.daddr, daddr, family) ||
1331 		    !xfrm_addr_equal(&x->props.saddr, saddr, family))
1332 			continue;
1333 
1334 		xfrm_state_hold(x);
1335 		return x;
1336 	}
1337 
1338 	if (!create)
1339 		return NULL;
1340 
1341 	x = xfrm_state_alloc(net);
1342 	if (likely(x)) {
1343 		switch (family) {
1344 		case AF_INET:
1345 			x->sel.daddr.a4 = daddr->a4;
1346 			x->sel.saddr.a4 = saddr->a4;
1347 			x->sel.prefixlen_d = 32;
1348 			x->sel.prefixlen_s = 32;
1349 			x->props.saddr.a4 = saddr->a4;
1350 			x->id.daddr.a4 = daddr->a4;
1351 			break;
1352 
1353 		case AF_INET6:
1354 			x->sel.daddr.in6 = daddr->in6;
1355 			x->sel.saddr.in6 = saddr->in6;
1356 			x->sel.prefixlen_d = 128;
1357 			x->sel.prefixlen_s = 128;
1358 			x->props.saddr.in6 = saddr->in6;
1359 			x->id.daddr.in6 = daddr->in6;
1360 			break;
1361 		}
1362 
1363 		x->km.state = XFRM_STATE_ACQ;
1364 		x->id.proto = proto;
1365 		x->props.family = family;
1366 		x->props.mode = mode;
1367 		x->props.reqid = reqid;
1368 		x->if_id = if_id;
1369 		x->mark.v = m->v;
1370 		x->mark.m = m->m;
1371 		x->lft.hard_add_expires_seconds = net->xfrm.sysctl_acq_expires;
1372 		xfrm_state_hold(x);
1373 		hrtimer_start(&x->mtimer,
1374 			      ktime_set(net->xfrm.sysctl_acq_expires, 0),
1375 			      HRTIMER_MODE_REL_SOFT);
1376 		list_add(&x->km.all, &net->xfrm.state_all);
1377 		hlist_add_head_rcu(&x->bydst, net->xfrm.state_bydst + h);
1378 		h = xfrm_src_hash(net, daddr, saddr, family);
1379 		hlist_add_head_rcu(&x->bysrc, net->xfrm.state_bysrc + h);
1380 
1381 		net->xfrm.state_num++;
1382 
1383 		xfrm_hash_grow_check(net, x->bydst.next != NULL);
1384 	}
1385 
1386 	return x;
1387 }
1388 
1389 static struct xfrm_state *__xfrm_find_acq_byseq(struct net *net, u32 mark, u32 seq);
1390 
xfrm_state_add(struct xfrm_state * x)1391 int xfrm_state_add(struct xfrm_state *x)
1392 {
1393 	struct net *net = xs_net(x);
1394 	struct xfrm_state *x1, *to_put;
1395 	int family;
1396 	int err;
1397 	u32 mark = x->mark.v & x->mark.m;
1398 	int use_spi = xfrm_id_proto_match(x->id.proto, IPSEC_PROTO_ANY);
1399 
1400 	family = x->props.family;
1401 
1402 	to_put = NULL;
1403 
1404 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1405 
1406 	x1 = __xfrm_state_locate(x, use_spi, family);
1407 	if (x1) {
1408 		to_put = x1;
1409 		x1 = NULL;
1410 		err = -EEXIST;
1411 		goto out;
1412 	}
1413 
1414 	if (use_spi && x->km.seq) {
1415 		x1 = __xfrm_find_acq_byseq(net, mark, x->km.seq);
1416 		if (x1 && ((x1->id.proto != x->id.proto) ||
1417 		    !xfrm_addr_equal(&x1->id.daddr, &x->id.daddr, family))) {
1418 			to_put = x1;
1419 			x1 = NULL;
1420 		}
1421 	}
1422 
1423 	if (use_spi && !x1)
1424 		x1 = __find_acq_core(net, &x->mark, family, x->props.mode,
1425 				     x->props.reqid, x->if_id, x->id.proto,
1426 				     &x->id.daddr, &x->props.saddr, 0);
1427 
1428 	__xfrm_state_bump_genids(x);
1429 	__xfrm_state_insert(x);
1430 	err = 0;
1431 
1432 out:
1433 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1434 
1435 	if (x1) {
1436 		xfrm_state_delete(x1);
1437 		xfrm_state_put(x1);
1438 	}
1439 
1440 	if (to_put)
1441 		xfrm_state_put(to_put);
1442 
1443 	return err;
1444 }
1445 EXPORT_SYMBOL(xfrm_state_add);
1446 
1447 #ifdef CONFIG_XFRM_MIGRATE
clone_security(struct xfrm_state * x,struct xfrm_sec_ctx * security)1448 static inline int clone_security(struct xfrm_state *x, struct xfrm_sec_ctx *security)
1449 {
1450 	struct xfrm_user_sec_ctx *uctx;
1451 	int size = sizeof(*uctx) + security->ctx_len;
1452 	int err;
1453 
1454 	uctx = kmalloc(size, GFP_KERNEL);
1455 	if (!uctx)
1456 		return -ENOMEM;
1457 
1458 	uctx->exttype = XFRMA_SEC_CTX;
1459 	uctx->len = size;
1460 	uctx->ctx_doi = security->ctx_doi;
1461 	uctx->ctx_alg = security->ctx_alg;
1462 	uctx->ctx_len = security->ctx_len;
1463 	memcpy(uctx + 1, security->ctx_str, security->ctx_len);
1464 	err = security_xfrm_state_alloc(x, uctx);
1465 	kfree(uctx);
1466 	if (err)
1467 		return err;
1468 
1469 	return 0;
1470 }
1471 
xfrm_state_clone(struct xfrm_state * orig,struct xfrm_encap_tmpl * encap)1472 static struct xfrm_state *xfrm_state_clone(struct xfrm_state *orig,
1473 					   struct xfrm_encap_tmpl *encap)
1474 {
1475 	struct net *net = xs_net(orig);
1476 	struct xfrm_state *x = xfrm_state_alloc(net);
1477 	if (!x)
1478 		goto out;
1479 
1480 	memcpy(&x->id, &orig->id, sizeof(x->id));
1481 	memcpy(&x->sel, &orig->sel, sizeof(x->sel));
1482 	memcpy(&x->lft, &orig->lft, sizeof(x->lft));
1483 	x->props.mode = orig->props.mode;
1484 	x->props.replay_window = orig->props.replay_window;
1485 	x->props.reqid = orig->props.reqid;
1486 	x->props.family = orig->props.family;
1487 	x->props.saddr = orig->props.saddr;
1488 
1489 	if (orig->aalg) {
1490 		x->aalg = xfrm_algo_auth_clone(orig->aalg);
1491 		if (!x->aalg)
1492 			goto error;
1493 	}
1494 	x->props.aalgo = orig->props.aalgo;
1495 
1496 	if (orig->aead) {
1497 		x->aead = xfrm_algo_aead_clone(orig->aead);
1498 		x->geniv = orig->geniv;
1499 		if (!x->aead)
1500 			goto error;
1501 	}
1502 	if (orig->ealg) {
1503 		x->ealg = xfrm_algo_clone(orig->ealg);
1504 		if (!x->ealg)
1505 			goto error;
1506 	}
1507 	x->props.ealgo = orig->props.ealgo;
1508 
1509 	if (orig->calg) {
1510 		x->calg = xfrm_algo_clone(orig->calg);
1511 		if (!x->calg)
1512 			goto error;
1513 	}
1514 	x->props.calgo = orig->props.calgo;
1515 
1516 	if (encap || orig->encap) {
1517 		if (encap)
1518 			x->encap = kmemdup(encap, sizeof(*x->encap),
1519 					GFP_KERNEL);
1520 		else
1521 			x->encap = kmemdup(orig->encap, sizeof(*x->encap),
1522 					GFP_KERNEL);
1523 
1524 		if (!x->encap)
1525 			goto error;
1526 	}
1527 
1528 	if (orig->security)
1529 		if (clone_security(x, orig->security))
1530 			goto error;
1531 
1532 	if (orig->coaddr) {
1533 		x->coaddr = kmemdup(orig->coaddr, sizeof(*x->coaddr),
1534 				    GFP_KERNEL);
1535 		if (!x->coaddr)
1536 			goto error;
1537 	}
1538 
1539 	if (orig->replay_esn) {
1540 		if (xfrm_replay_clone(x, orig))
1541 			goto error;
1542 	}
1543 
1544 	memcpy(&x->mark, &orig->mark, sizeof(x->mark));
1545 	memcpy(&x->props.smark, &orig->props.smark, sizeof(x->props.smark));
1546 
1547 	x->props.flags = orig->props.flags;
1548 	x->props.extra_flags = orig->props.extra_flags;
1549 
1550 	x->if_id = orig->if_id;
1551 	x->tfcpad = orig->tfcpad;
1552 	x->replay_maxdiff = orig->replay_maxdiff;
1553 	x->replay_maxage = orig->replay_maxage;
1554 	memcpy(&x->curlft, &orig->curlft, sizeof(x->curlft));
1555 	x->km.state = orig->km.state;
1556 	x->km.seq = orig->km.seq;
1557 	x->replay = orig->replay;
1558 	x->preplay = orig->preplay;
1559 	x->lastused = orig->lastused;
1560 
1561 	return x;
1562 
1563  error:
1564 	xfrm_state_put(x);
1565 out:
1566 	return NULL;
1567 }
1568 
xfrm_migrate_state_find(struct xfrm_migrate * m,struct net * net,u32 if_id)1569 struct xfrm_state *xfrm_migrate_state_find(struct xfrm_migrate *m, struct net *net,
1570 						u32 if_id)
1571 {
1572 	unsigned int h;
1573 	struct xfrm_state *x = NULL;
1574 
1575 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1576 
1577 	if (m->reqid) {
1578 		h = xfrm_dst_hash(net, &m->old_daddr, &m->old_saddr,
1579 				  m->reqid, m->old_family);
1580 		hlist_for_each_entry(x, net->xfrm.state_bydst+h, bydst) {
1581 			if (x->props.mode != m->mode ||
1582 			    x->id.proto != m->proto)
1583 				continue;
1584 			if (m->reqid && x->props.reqid != m->reqid)
1585 				continue;
1586 			if (if_id != 0 && x->if_id != if_id)
1587 				continue;
1588 			if (!xfrm_addr_equal(&x->id.daddr, &m->old_daddr,
1589 					     m->old_family) ||
1590 			    !xfrm_addr_equal(&x->props.saddr, &m->old_saddr,
1591 					     m->old_family))
1592 				continue;
1593 			xfrm_state_hold(x);
1594 			break;
1595 		}
1596 	} else {
1597 		h = xfrm_src_hash(net, &m->old_daddr, &m->old_saddr,
1598 				  m->old_family);
1599 		hlist_for_each_entry(x, net->xfrm.state_bysrc+h, bysrc) {
1600 			if (x->props.mode != m->mode ||
1601 			    x->id.proto != m->proto)
1602 				continue;
1603 			if (if_id != 0 && x->if_id != if_id)
1604 				continue;
1605 			if (!xfrm_addr_equal(&x->id.daddr, &m->old_daddr,
1606 					     m->old_family) ||
1607 			    !xfrm_addr_equal(&x->props.saddr, &m->old_saddr,
1608 					     m->old_family))
1609 				continue;
1610 			xfrm_state_hold(x);
1611 			break;
1612 		}
1613 	}
1614 
1615 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1616 
1617 	return x;
1618 }
1619 EXPORT_SYMBOL(xfrm_migrate_state_find);
1620 
xfrm_state_migrate(struct xfrm_state * x,struct xfrm_migrate * m,struct xfrm_encap_tmpl * encap)1621 struct xfrm_state *xfrm_state_migrate(struct xfrm_state *x,
1622 				      struct xfrm_migrate *m,
1623 				      struct xfrm_encap_tmpl *encap)
1624 {
1625 	struct xfrm_state *xc;
1626 
1627 	xc = xfrm_state_clone(x, encap);
1628 	if (!xc)
1629 		return NULL;
1630 
1631 	xc->props.family = m->new_family;
1632 
1633 	if (xfrm_init_state(xc) < 0)
1634 		goto error;
1635 
1636 	memcpy(&xc->id.daddr, &m->new_daddr, sizeof(xc->id.daddr));
1637 	memcpy(&xc->props.saddr, &m->new_saddr, sizeof(xc->props.saddr));
1638 
1639 	/* add state */
1640 	if (xfrm_addr_equal(&x->id.daddr, &m->new_daddr, m->new_family)) {
1641 		/* a care is needed when the destination address of the
1642 		   state is to be updated as it is a part of triplet */
1643 		xfrm_state_insert(xc);
1644 	} else {
1645 		if (xfrm_state_add(xc) < 0)
1646 			goto error;
1647 	}
1648 
1649 	return xc;
1650 error:
1651 	xfrm_state_put(xc);
1652 	return NULL;
1653 }
1654 EXPORT_SYMBOL(xfrm_state_migrate);
1655 #endif
1656 
xfrm_state_update(struct xfrm_state * x)1657 int xfrm_state_update(struct xfrm_state *x)
1658 {
1659 	struct xfrm_state *x1, *to_put;
1660 	int err;
1661 	int use_spi = xfrm_id_proto_match(x->id.proto, IPSEC_PROTO_ANY);
1662 	struct net *net = xs_net(x);
1663 
1664 	to_put = NULL;
1665 
1666 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1667 	x1 = __xfrm_state_locate(x, use_spi, x->props.family);
1668 
1669 	err = -ESRCH;
1670 	if (!x1)
1671 		goto out;
1672 
1673 	if (xfrm_state_kern(x1)) {
1674 		to_put = x1;
1675 		err = -EEXIST;
1676 		goto out;
1677 	}
1678 
1679 	if (x1->km.state == XFRM_STATE_ACQ) {
1680 		__xfrm_state_insert(x);
1681 		x = NULL;
1682 	}
1683 	err = 0;
1684 
1685 out:
1686 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1687 
1688 	if (to_put)
1689 		xfrm_state_put(to_put);
1690 
1691 	if (err)
1692 		return err;
1693 
1694 	if (!x) {
1695 		xfrm_state_delete(x1);
1696 		xfrm_state_put(x1);
1697 		return 0;
1698 	}
1699 
1700 	err = -EINVAL;
1701 	spin_lock_bh(&x1->lock);
1702 	if (likely(x1->km.state == XFRM_STATE_VALID)) {
1703 		if (x->encap && x1->encap &&
1704 		    x->encap->encap_type == x1->encap->encap_type)
1705 			memcpy(x1->encap, x->encap, sizeof(*x1->encap));
1706 		else if (x->encap || x1->encap)
1707 			goto fail;
1708 
1709 		if (x->coaddr && x1->coaddr) {
1710 			memcpy(x1->coaddr, x->coaddr, sizeof(*x1->coaddr));
1711 		}
1712 		if (!use_spi && memcmp(&x1->sel, &x->sel, sizeof(x1->sel)))
1713 			memcpy(&x1->sel, &x->sel, sizeof(x1->sel));
1714 		memcpy(&x1->lft, &x->lft, sizeof(x1->lft));
1715 		x1->km.dying = 0;
1716 
1717 		hrtimer_start(&x1->mtimer, ktime_set(1, 0),
1718 			      HRTIMER_MODE_REL_SOFT);
1719 		if (x1->curlft.use_time)
1720 			xfrm_state_check_expire(x1);
1721 
1722 		if (x->props.smark.m || x->props.smark.v || x->if_id) {
1723 			spin_lock_bh(&net->xfrm.xfrm_state_lock);
1724 
1725 			if (x->props.smark.m || x->props.smark.v)
1726 				x1->props.smark = x->props.smark;
1727 
1728 			if (x->if_id)
1729 				x1->if_id = x->if_id;
1730 
1731 			__xfrm_state_bump_genids(x1);
1732 			spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1733 		}
1734 
1735 		err = 0;
1736 		x->km.state = XFRM_STATE_DEAD;
1737 		__xfrm_state_put(x);
1738 	}
1739 
1740 fail:
1741 	spin_unlock_bh(&x1->lock);
1742 
1743 	xfrm_state_put(x1);
1744 
1745 	return err;
1746 }
1747 EXPORT_SYMBOL(xfrm_state_update);
1748 
xfrm_state_check_expire(struct xfrm_state * x)1749 int xfrm_state_check_expire(struct xfrm_state *x)
1750 {
1751 	if (!x->curlft.use_time)
1752 		x->curlft.use_time = ktime_get_real_seconds();
1753 
1754 	if (x->curlft.bytes >= x->lft.hard_byte_limit ||
1755 	    x->curlft.packets >= x->lft.hard_packet_limit) {
1756 		x->km.state = XFRM_STATE_EXPIRED;
1757 		hrtimer_start(&x->mtimer, 0, HRTIMER_MODE_REL_SOFT);
1758 		return -EINVAL;
1759 	}
1760 
1761 	if (!x->km.dying &&
1762 	    (x->curlft.bytes >= x->lft.soft_byte_limit ||
1763 	     x->curlft.packets >= x->lft.soft_packet_limit)) {
1764 		x->km.dying = 1;
1765 		km_state_expired(x, 0, 0);
1766 	}
1767 	return 0;
1768 }
1769 EXPORT_SYMBOL(xfrm_state_check_expire);
1770 
1771 struct xfrm_state *
xfrm_state_lookup(struct net * net,u32 mark,const xfrm_address_t * daddr,__be32 spi,u8 proto,unsigned short family)1772 xfrm_state_lookup(struct net *net, u32 mark, const xfrm_address_t *daddr, __be32 spi,
1773 		  u8 proto, unsigned short family)
1774 {
1775 	struct xfrm_state *x;
1776 
1777 	rcu_read_lock();
1778 	x = __xfrm_state_lookup(net, mark, daddr, spi, proto, family);
1779 	rcu_read_unlock();
1780 	return x;
1781 }
1782 EXPORT_SYMBOL(xfrm_state_lookup);
1783 
1784 struct xfrm_state *
xfrm_state_lookup_byaddr(struct net * net,u32 mark,const xfrm_address_t * daddr,const xfrm_address_t * saddr,u8 proto,unsigned short family)1785 xfrm_state_lookup_byaddr(struct net *net, u32 mark,
1786 			 const xfrm_address_t *daddr, const xfrm_address_t *saddr,
1787 			 u8 proto, unsigned short family)
1788 {
1789 	struct xfrm_state *x;
1790 
1791 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1792 	x = __xfrm_state_lookup_byaddr(net, mark, daddr, saddr, proto, family);
1793 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1794 	return x;
1795 }
1796 EXPORT_SYMBOL(xfrm_state_lookup_byaddr);
1797 
1798 struct xfrm_state *
xfrm_find_acq(struct net * net,const struct xfrm_mark * mark,u8 mode,u32 reqid,u32 if_id,u8 proto,const xfrm_address_t * daddr,const xfrm_address_t * saddr,int create,unsigned short family)1799 xfrm_find_acq(struct net *net, const struct xfrm_mark *mark, u8 mode, u32 reqid,
1800 	      u32 if_id, u8 proto, const xfrm_address_t *daddr,
1801 	      const xfrm_address_t *saddr, int create, unsigned short family)
1802 {
1803 	struct xfrm_state *x;
1804 
1805 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1806 	x = __find_acq_core(net, mark, family, mode, reqid, if_id, proto, daddr, saddr, create);
1807 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1808 
1809 	return x;
1810 }
1811 EXPORT_SYMBOL(xfrm_find_acq);
1812 
1813 #ifdef CONFIG_XFRM_SUB_POLICY
1814 #if IS_ENABLED(CONFIG_IPV6)
1815 /* distribution counting sort function for xfrm_state and xfrm_tmpl */
1816 static void
__xfrm6_sort(void ** dst,void ** src,int n,int (* cmp)(const void * p),int maxclass)1817 __xfrm6_sort(void **dst, void **src, int n,
1818 	     int (*cmp)(const void *p), int maxclass)
1819 {
1820 	int count[XFRM_MAX_DEPTH] = { };
1821 	int class[XFRM_MAX_DEPTH];
1822 	int i;
1823 
1824 	for (i = 0; i < n; i++) {
1825 		int c = cmp(src[i]);
1826 
1827 		class[i] = c;
1828 		count[c]++;
1829 	}
1830 
1831 	for (i = 2; i < maxclass; i++)
1832 		count[i] += count[i - 1];
1833 
1834 	for (i = 0; i < n; i++) {
1835 		dst[count[class[i] - 1]++] = src[i];
1836 		src[i] = NULL;
1837 	}
1838 }
1839 
1840 /* Rule for xfrm_state:
1841  *
1842  * rule 1: select IPsec transport except AH
1843  * rule 2: select MIPv6 RO or inbound trigger
1844  * rule 3: select IPsec transport AH
1845  * rule 4: select IPsec tunnel
1846  * rule 5: others
1847  */
__xfrm6_state_sort_cmp(const void * p)1848 static int __xfrm6_state_sort_cmp(const void *p)
1849 {
1850 	const struct xfrm_state *v = p;
1851 
1852 	switch (v->props.mode) {
1853 	case XFRM_MODE_TRANSPORT:
1854 		if (v->id.proto != IPPROTO_AH)
1855 			return 1;
1856 		else
1857 			return 3;
1858 #if IS_ENABLED(CONFIG_IPV6_MIP6)
1859 	case XFRM_MODE_ROUTEOPTIMIZATION:
1860 	case XFRM_MODE_IN_TRIGGER:
1861 		return 2;
1862 #endif
1863 	case XFRM_MODE_TUNNEL:
1864 	case XFRM_MODE_BEET:
1865 		return 4;
1866 	}
1867 	return 5;
1868 }
1869 
1870 /* Rule for xfrm_tmpl:
1871  *
1872  * rule 1: select IPsec transport
1873  * rule 2: select MIPv6 RO or inbound trigger
1874  * rule 3: select IPsec tunnel
1875  * rule 4: others
1876  */
__xfrm6_tmpl_sort_cmp(const void * p)1877 static int __xfrm6_tmpl_sort_cmp(const void *p)
1878 {
1879 	const struct xfrm_tmpl *v = p;
1880 
1881 	switch (v->mode) {
1882 	case XFRM_MODE_TRANSPORT:
1883 		return 1;
1884 #if IS_ENABLED(CONFIG_IPV6_MIP6)
1885 	case XFRM_MODE_ROUTEOPTIMIZATION:
1886 	case XFRM_MODE_IN_TRIGGER:
1887 		return 2;
1888 #endif
1889 	case XFRM_MODE_TUNNEL:
1890 	case XFRM_MODE_BEET:
1891 		return 3;
1892 	}
1893 	return 4;
1894 }
1895 #else
__xfrm6_state_sort_cmp(const void * p)1896 static inline int __xfrm6_state_sort_cmp(const void *p) { return 5; }
__xfrm6_tmpl_sort_cmp(const void * p)1897 static inline int __xfrm6_tmpl_sort_cmp(const void *p) { return 4; }
1898 
1899 static inline void
__xfrm6_sort(void ** dst,void ** src,int n,int (* cmp)(const void * p),int maxclass)1900 __xfrm6_sort(void **dst, void **src, int n,
1901 	     int (*cmp)(const void *p), int maxclass)
1902 {
1903 	int i;
1904 
1905 	for (i = 0; i < n; i++)
1906 		dst[i] = src[i];
1907 }
1908 #endif /* CONFIG_IPV6 */
1909 
1910 void
xfrm_tmpl_sort(struct xfrm_tmpl ** dst,struct xfrm_tmpl ** src,int n,unsigned short family)1911 xfrm_tmpl_sort(struct xfrm_tmpl **dst, struct xfrm_tmpl **src, int n,
1912 	       unsigned short family)
1913 {
1914 	int i;
1915 
1916 	if (family == AF_INET6)
1917 		__xfrm6_sort((void **)dst, (void **)src, n,
1918 			     __xfrm6_tmpl_sort_cmp, 5);
1919 	else
1920 		for (i = 0; i < n; i++)
1921 			dst[i] = src[i];
1922 }
1923 
1924 void
xfrm_state_sort(struct xfrm_state ** dst,struct xfrm_state ** src,int n,unsigned short family)1925 xfrm_state_sort(struct xfrm_state **dst, struct xfrm_state **src, int n,
1926 		unsigned short family)
1927 {
1928 	int i;
1929 
1930 	if (family == AF_INET6)
1931 		__xfrm6_sort((void **)dst, (void **)src, n,
1932 			     __xfrm6_state_sort_cmp, 6);
1933 	else
1934 		for (i = 0; i < n; i++)
1935 			dst[i] = src[i];
1936 }
1937 #endif
1938 
1939 /* Silly enough, but I'm lazy to build resolution list */
1940 
__xfrm_find_acq_byseq(struct net * net,u32 mark,u32 seq)1941 static struct xfrm_state *__xfrm_find_acq_byseq(struct net *net, u32 mark, u32 seq)
1942 {
1943 	int i;
1944 
1945 	for (i = 0; i <= net->xfrm.state_hmask; i++) {
1946 		struct xfrm_state *x;
1947 
1948 		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
1949 			if (x->km.seq == seq &&
1950 			    (mark & x->mark.m) == x->mark.v &&
1951 			    x->km.state == XFRM_STATE_ACQ) {
1952 				xfrm_state_hold(x);
1953 				return x;
1954 			}
1955 		}
1956 	}
1957 	return NULL;
1958 }
1959 
xfrm_find_acq_byseq(struct net * net,u32 mark,u32 seq)1960 struct xfrm_state *xfrm_find_acq_byseq(struct net *net, u32 mark, u32 seq)
1961 {
1962 	struct xfrm_state *x;
1963 
1964 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1965 	x = __xfrm_find_acq_byseq(net, mark, seq);
1966 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1967 	return x;
1968 }
1969 EXPORT_SYMBOL(xfrm_find_acq_byseq);
1970 
xfrm_get_acqseq(void)1971 u32 xfrm_get_acqseq(void)
1972 {
1973 	u32 res;
1974 	static atomic_t acqseq;
1975 
1976 	do {
1977 		res = atomic_inc_return(&acqseq);
1978 	} while (!res);
1979 
1980 	return res;
1981 }
1982 EXPORT_SYMBOL(xfrm_get_acqseq);
1983 
verify_spi_info(u8 proto,u32 min,u32 max)1984 int verify_spi_info(u8 proto, u32 min, u32 max)
1985 {
1986 	switch (proto) {
1987 	case IPPROTO_AH:
1988 	case IPPROTO_ESP:
1989 		break;
1990 
1991 	case IPPROTO_COMP:
1992 		/* IPCOMP spi is 16-bits. */
1993 		if (max >= 0x10000)
1994 			return -EINVAL;
1995 		break;
1996 
1997 	default:
1998 		return -EINVAL;
1999 	}
2000 
2001 	if (min > max)
2002 		return -EINVAL;
2003 
2004 	return 0;
2005 }
2006 EXPORT_SYMBOL(verify_spi_info);
2007 
xfrm_alloc_spi(struct xfrm_state * x,u32 low,u32 high)2008 int xfrm_alloc_spi(struct xfrm_state *x, u32 low, u32 high)
2009 {
2010 	struct net *net = xs_net(x);
2011 	unsigned int h;
2012 	struct xfrm_state *x0;
2013 	int err = -ENOENT;
2014 	__be32 minspi = htonl(low);
2015 	__be32 maxspi = htonl(high);
2016 	__be32 newspi = 0;
2017 	u32 mark = x->mark.v & x->mark.m;
2018 
2019 	spin_lock_bh(&x->lock);
2020 	if (x->km.state == XFRM_STATE_DEAD)
2021 		goto unlock;
2022 
2023 	err = 0;
2024 	if (x->id.spi)
2025 		goto unlock;
2026 
2027 	err = -ENOENT;
2028 
2029 	if (minspi == maxspi) {
2030 		x0 = xfrm_state_lookup(net, mark, &x->id.daddr, minspi, x->id.proto, x->props.family);
2031 		if (x0) {
2032 			xfrm_state_put(x0);
2033 			goto unlock;
2034 		}
2035 		newspi = minspi;
2036 	} else {
2037 		u32 spi = 0;
2038 		for (h = 0; h < high-low+1; h++) {
2039 			spi = low + prandom_u32()%(high-low+1);
2040 			x0 = xfrm_state_lookup(net, mark, &x->id.daddr, htonl(spi), x->id.proto, x->props.family);
2041 			if (x0 == NULL) {
2042 				newspi = htonl(spi);
2043 				break;
2044 			}
2045 			xfrm_state_put(x0);
2046 		}
2047 	}
2048 	if (newspi) {
2049 		spin_lock_bh(&net->xfrm.xfrm_state_lock);
2050 		x->id.spi = newspi;
2051 		h = xfrm_spi_hash(net, &x->id.daddr, x->id.spi, x->id.proto, x->props.family);
2052 		hlist_add_head_rcu(&x->byspi, net->xfrm.state_byspi + h);
2053 		spin_unlock_bh(&net->xfrm.xfrm_state_lock);
2054 
2055 		err = 0;
2056 	}
2057 
2058 unlock:
2059 	spin_unlock_bh(&x->lock);
2060 
2061 	return err;
2062 }
2063 EXPORT_SYMBOL(xfrm_alloc_spi);
2064 
__xfrm_state_filter_match(struct xfrm_state * x,struct xfrm_address_filter * filter)2065 static bool __xfrm_state_filter_match(struct xfrm_state *x,
2066 				      struct xfrm_address_filter *filter)
2067 {
2068 	if (filter) {
2069 		if ((filter->family == AF_INET ||
2070 		     filter->family == AF_INET6) &&
2071 		    x->props.family != filter->family)
2072 			return false;
2073 
2074 		return addr_match(&x->props.saddr, &filter->saddr,
2075 				  filter->splen) &&
2076 		       addr_match(&x->id.daddr, &filter->daddr,
2077 				  filter->dplen);
2078 	}
2079 	return true;
2080 }
2081 
xfrm_state_walk(struct net * net,struct xfrm_state_walk * walk,int (* func)(struct xfrm_state *,int,void *),void * data)2082 int xfrm_state_walk(struct net *net, struct xfrm_state_walk *walk,
2083 		    int (*func)(struct xfrm_state *, int, void*),
2084 		    void *data)
2085 {
2086 	struct xfrm_state *state;
2087 	struct xfrm_state_walk *x;
2088 	int err = 0;
2089 
2090 	if (walk->seq != 0 && list_empty(&walk->all))
2091 		return 0;
2092 
2093 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
2094 	if (list_empty(&walk->all))
2095 		x = list_first_entry(&net->xfrm.state_all, struct xfrm_state_walk, all);
2096 	else
2097 		x = list_first_entry(&walk->all, struct xfrm_state_walk, all);
2098 	list_for_each_entry_from(x, &net->xfrm.state_all, all) {
2099 		if (x->state == XFRM_STATE_DEAD)
2100 			continue;
2101 		state = container_of(x, struct xfrm_state, km);
2102 		if (!xfrm_id_proto_match(state->id.proto, walk->proto))
2103 			continue;
2104 		if (!__xfrm_state_filter_match(state, walk->filter))
2105 			continue;
2106 		err = func(state, walk->seq, data);
2107 		if (err) {
2108 			list_move_tail(&walk->all, &x->all);
2109 			goto out;
2110 		}
2111 		walk->seq++;
2112 	}
2113 	if (walk->seq == 0) {
2114 		err = -ENOENT;
2115 		goto out;
2116 	}
2117 	list_del_init(&walk->all);
2118 out:
2119 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
2120 	return err;
2121 }
2122 EXPORT_SYMBOL(xfrm_state_walk);
2123 
xfrm_state_walk_init(struct xfrm_state_walk * walk,u8 proto,struct xfrm_address_filter * filter)2124 void xfrm_state_walk_init(struct xfrm_state_walk *walk, u8 proto,
2125 			  struct xfrm_address_filter *filter)
2126 {
2127 	INIT_LIST_HEAD(&walk->all);
2128 	walk->proto = proto;
2129 	walk->state = XFRM_STATE_DEAD;
2130 	walk->seq = 0;
2131 	walk->filter = filter;
2132 }
2133 EXPORT_SYMBOL(xfrm_state_walk_init);
2134 
xfrm_state_walk_done(struct xfrm_state_walk * walk,struct net * net)2135 void xfrm_state_walk_done(struct xfrm_state_walk *walk, struct net *net)
2136 {
2137 	kfree(walk->filter);
2138 
2139 	if (list_empty(&walk->all))
2140 		return;
2141 
2142 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
2143 	list_del(&walk->all);
2144 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
2145 }
2146 EXPORT_SYMBOL(xfrm_state_walk_done);
2147 
xfrm_replay_timer_handler(struct timer_list * t)2148 static void xfrm_replay_timer_handler(struct timer_list *t)
2149 {
2150 	struct xfrm_state *x = from_timer(x, t, rtimer);
2151 
2152 	spin_lock(&x->lock);
2153 
2154 	if (x->km.state == XFRM_STATE_VALID) {
2155 		if (xfrm_aevent_is_on(xs_net(x)))
2156 			x->repl->notify(x, XFRM_REPLAY_TIMEOUT);
2157 		else
2158 			x->xflags |= XFRM_TIME_DEFER;
2159 	}
2160 
2161 	spin_unlock(&x->lock);
2162 }
2163 
2164 static LIST_HEAD(xfrm_km_list);
2165 
km_policy_notify(struct xfrm_policy * xp,int dir,const struct km_event * c)2166 void km_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
2167 {
2168 	struct xfrm_mgr *km;
2169 
2170 	rcu_read_lock();
2171 	list_for_each_entry_rcu(km, &xfrm_km_list, list)
2172 		if (km->notify_policy)
2173 			km->notify_policy(xp, dir, c);
2174 	rcu_read_unlock();
2175 }
2176 
km_state_notify(struct xfrm_state * x,const struct km_event * c)2177 void km_state_notify(struct xfrm_state *x, const struct km_event *c)
2178 {
2179 	struct xfrm_mgr *km;
2180 	rcu_read_lock();
2181 	list_for_each_entry_rcu(km, &xfrm_km_list, list)
2182 		if (km->notify)
2183 			km->notify(x, c);
2184 	rcu_read_unlock();
2185 }
2186 
2187 EXPORT_SYMBOL(km_policy_notify);
2188 EXPORT_SYMBOL(km_state_notify);
2189 
km_state_expired(struct xfrm_state * x,int hard,u32 portid)2190 void km_state_expired(struct xfrm_state *x, int hard, u32 portid)
2191 {
2192 	struct km_event c;
2193 
2194 	c.data.hard = hard;
2195 	c.portid = portid;
2196 	c.event = XFRM_MSG_EXPIRE;
2197 	km_state_notify(x, &c);
2198 }
2199 
2200 EXPORT_SYMBOL(km_state_expired);
2201 /*
2202  * We send to all registered managers regardless of failure
2203  * We are happy with one success
2204 */
km_query(struct xfrm_state * x,struct xfrm_tmpl * t,struct xfrm_policy * pol)2205 int km_query(struct xfrm_state *x, struct xfrm_tmpl *t, struct xfrm_policy *pol)
2206 {
2207 	int err = -EINVAL, acqret;
2208 	struct xfrm_mgr *km;
2209 
2210 	rcu_read_lock();
2211 	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2212 		acqret = km->acquire(x, t, pol);
2213 		if (!acqret)
2214 			err = acqret;
2215 	}
2216 	rcu_read_unlock();
2217 	return err;
2218 }
2219 EXPORT_SYMBOL(km_query);
2220 
km_new_mapping(struct xfrm_state * x,xfrm_address_t * ipaddr,__be16 sport)2221 int km_new_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr, __be16 sport)
2222 {
2223 	int err = -EINVAL;
2224 	struct xfrm_mgr *km;
2225 
2226 	rcu_read_lock();
2227 	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2228 		if (km->new_mapping)
2229 			err = km->new_mapping(x, ipaddr, sport);
2230 		if (!err)
2231 			break;
2232 	}
2233 	rcu_read_unlock();
2234 	return err;
2235 }
2236 EXPORT_SYMBOL(km_new_mapping);
2237 
km_policy_expired(struct xfrm_policy * pol,int dir,int hard,u32 portid)2238 void km_policy_expired(struct xfrm_policy *pol, int dir, int hard, u32 portid)
2239 {
2240 	struct km_event c;
2241 
2242 	c.data.hard = hard;
2243 	c.portid = portid;
2244 	c.event = XFRM_MSG_POLEXPIRE;
2245 	km_policy_notify(pol, dir, &c);
2246 }
2247 EXPORT_SYMBOL(km_policy_expired);
2248 
2249 #ifdef CONFIG_XFRM_MIGRATE
km_migrate(const struct xfrm_selector * sel,u8 dir,u8 type,const struct xfrm_migrate * m,int num_migrate,const struct xfrm_kmaddress * k,const struct xfrm_encap_tmpl * encap)2250 int km_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
2251 	       const struct xfrm_migrate *m, int num_migrate,
2252 	       const struct xfrm_kmaddress *k,
2253 	       const struct xfrm_encap_tmpl *encap)
2254 {
2255 	int err = -EINVAL;
2256 	int ret;
2257 	struct xfrm_mgr *km;
2258 
2259 	rcu_read_lock();
2260 	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2261 		if (km->migrate) {
2262 			ret = km->migrate(sel, dir, type, m, num_migrate, k,
2263 					  encap);
2264 			if (!ret)
2265 				err = ret;
2266 		}
2267 	}
2268 	rcu_read_unlock();
2269 	return err;
2270 }
2271 EXPORT_SYMBOL(km_migrate);
2272 #endif
2273 
km_report(struct net * net,u8 proto,struct xfrm_selector * sel,xfrm_address_t * addr)2274 int km_report(struct net *net, u8 proto, struct xfrm_selector *sel, xfrm_address_t *addr)
2275 {
2276 	int err = -EINVAL;
2277 	int ret;
2278 	struct xfrm_mgr *km;
2279 
2280 	rcu_read_lock();
2281 	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2282 		if (km->report) {
2283 			ret = km->report(net, proto, sel, addr);
2284 			if (!ret)
2285 				err = ret;
2286 		}
2287 	}
2288 	rcu_read_unlock();
2289 	return err;
2290 }
2291 EXPORT_SYMBOL(km_report);
2292 
km_is_alive(const struct km_event * c)2293 static bool km_is_alive(const struct km_event *c)
2294 {
2295 	struct xfrm_mgr *km;
2296 	bool is_alive = false;
2297 
2298 	rcu_read_lock();
2299 	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2300 		if (km->is_alive && km->is_alive(c)) {
2301 			is_alive = true;
2302 			break;
2303 		}
2304 	}
2305 	rcu_read_unlock();
2306 
2307 	return is_alive;
2308 }
2309 
2310 #if IS_ENABLED(CONFIG_XFRM_USER_COMPAT)
2311 static DEFINE_SPINLOCK(xfrm_translator_lock);
2312 static struct xfrm_translator __rcu *xfrm_translator;
2313 
xfrm_get_translator(void)2314 struct xfrm_translator *xfrm_get_translator(void)
2315 {
2316 	struct xfrm_translator *xtr;
2317 
2318 	rcu_read_lock();
2319 	xtr = rcu_dereference(xfrm_translator);
2320 	if (unlikely(!xtr))
2321 		goto out;
2322 	if (!try_module_get(xtr->owner))
2323 		xtr = NULL;
2324 out:
2325 	rcu_read_unlock();
2326 	return xtr;
2327 }
2328 EXPORT_SYMBOL_GPL(xfrm_get_translator);
2329 
xfrm_put_translator(struct xfrm_translator * xtr)2330 void xfrm_put_translator(struct xfrm_translator *xtr)
2331 {
2332 	module_put(xtr->owner);
2333 }
2334 EXPORT_SYMBOL_GPL(xfrm_put_translator);
2335 
xfrm_register_translator(struct xfrm_translator * xtr)2336 int xfrm_register_translator(struct xfrm_translator *xtr)
2337 {
2338 	int err = 0;
2339 
2340 	spin_lock_bh(&xfrm_translator_lock);
2341 	if (unlikely(xfrm_translator != NULL))
2342 		err = -EEXIST;
2343 	else
2344 		rcu_assign_pointer(xfrm_translator, xtr);
2345 	spin_unlock_bh(&xfrm_translator_lock);
2346 
2347 	return err;
2348 }
2349 EXPORT_SYMBOL_GPL(xfrm_register_translator);
2350 
xfrm_unregister_translator(struct xfrm_translator * xtr)2351 int xfrm_unregister_translator(struct xfrm_translator *xtr)
2352 {
2353 	int err = 0;
2354 
2355 	spin_lock_bh(&xfrm_translator_lock);
2356 	if (likely(xfrm_translator != NULL)) {
2357 		if (rcu_access_pointer(xfrm_translator) != xtr)
2358 			err = -EINVAL;
2359 		else
2360 			RCU_INIT_POINTER(xfrm_translator, NULL);
2361 	}
2362 	spin_unlock_bh(&xfrm_translator_lock);
2363 	synchronize_rcu();
2364 
2365 	return err;
2366 }
2367 EXPORT_SYMBOL_GPL(xfrm_unregister_translator);
2368 #endif
2369 
xfrm_user_policy(struct sock * sk,int optname,sockptr_t optval,int optlen)2370 int xfrm_user_policy(struct sock *sk, int optname, sockptr_t optval, int optlen)
2371 {
2372 	int err;
2373 	u8 *data;
2374 	struct xfrm_mgr *km;
2375 	struct xfrm_policy *pol = NULL;
2376 
2377 	if (sockptr_is_null(optval) && !optlen) {
2378 		xfrm_sk_policy_insert(sk, XFRM_POLICY_IN, NULL);
2379 		xfrm_sk_policy_insert(sk, XFRM_POLICY_OUT, NULL);
2380 		__sk_dst_reset(sk);
2381 		return 0;
2382 	}
2383 
2384 	if (optlen <= 0 || optlen > PAGE_SIZE)
2385 		return -EMSGSIZE;
2386 
2387 	data = memdup_sockptr(optval, optlen);
2388 	if (IS_ERR(data))
2389 		return PTR_ERR(data);
2390 
2391 	/* Use the 64-bit / untranslated format on Android, even for compat */
2392 	if (!IS_ENABLED(CONFIG_ANDROID) || IS_ENABLED(CONFIG_XFRM_USER_COMPAT)) {
2393 		if (in_compat_syscall()) {
2394 			struct xfrm_translator *xtr = xfrm_get_translator();
2395 
2396 			if (!xtr) {
2397 				kfree(data);
2398 				return -EOPNOTSUPP;
2399 			}
2400 
2401 			err = xtr->xlate_user_policy_sockptr(&data, optlen);
2402 			xfrm_put_translator(xtr);
2403 			if (err) {
2404 				kfree(data);
2405 				return err;
2406 			}
2407 		}
2408 	}
2409 
2410 	err = -EINVAL;
2411 	rcu_read_lock();
2412 	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2413 		pol = km->compile_policy(sk, optname, data,
2414 					 optlen, &err);
2415 		if (err >= 0)
2416 			break;
2417 	}
2418 	rcu_read_unlock();
2419 
2420 	if (err >= 0) {
2421 		xfrm_sk_policy_insert(sk, err, pol);
2422 		xfrm_pol_put(pol);
2423 		__sk_dst_reset(sk);
2424 		err = 0;
2425 	}
2426 
2427 	kfree(data);
2428 	return err;
2429 }
2430 EXPORT_SYMBOL(xfrm_user_policy);
2431 
2432 static DEFINE_SPINLOCK(xfrm_km_lock);
2433 
xfrm_register_km(struct xfrm_mgr * km)2434 int xfrm_register_km(struct xfrm_mgr *km)
2435 {
2436 	spin_lock_bh(&xfrm_km_lock);
2437 	list_add_tail_rcu(&km->list, &xfrm_km_list);
2438 	spin_unlock_bh(&xfrm_km_lock);
2439 	return 0;
2440 }
2441 EXPORT_SYMBOL(xfrm_register_km);
2442 
xfrm_unregister_km(struct xfrm_mgr * km)2443 int xfrm_unregister_km(struct xfrm_mgr *km)
2444 {
2445 	spin_lock_bh(&xfrm_km_lock);
2446 	list_del_rcu(&km->list);
2447 	spin_unlock_bh(&xfrm_km_lock);
2448 	synchronize_rcu();
2449 	return 0;
2450 }
2451 EXPORT_SYMBOL(xfrm_unregister_km);
2452 
xfrm_state_register_afinfo(struct xfrm_state_afinfo * afinfo)2453 int xfrm_state_register_afinfo(struct xfrm_state_afinfo *afinfo)
2454 {
2455 	int err = 0;
2456 
2457 	if (WARN_ON(afinfo->family >= NPROTO))
2458 		return -EAFNOSUPPORT;
2459 
2460 	spin_lock_bh(&xfrm_state_afinfo_lock);
2461 	if (unlikely(xfrm_state_afinfo[afinfo->family] != NULL))
2462 		err = -EEXIST;
2463 	else
2464 		rcu_assign_pointer(xfrm_state_afinfo[afinfo->family], afinfo);
2465 	spin_unlock_bh(&xfrm_state_afinfo_lock);
2466 	return err;
2467 }
2468 EXPORT_SYMBOL(xfrm_state_register_afinfo);
2469 
xfrm_state_unregister_afinfo(struct xfrm_state_afinfo * afinfo)2470 int xfrm_state_unregister_afinfo(struct xfrm_state_afinfo *afinfo)
2471 {
2472 	int err = 0, family = afinfo->family;
2473 
2474 	if (WARN_ON(family >= NPROTO))
2475 		return -EAFNOSUPPORT;
2476 
2477 	spin_lock_bh(&xfrm_state_afinfo_lock);
2478 	if (likely(xfrm_state_afinfo[afinfo->family] != NULL)) {
2479 		if (rcu_access_pointer(xfrm_state_afinfo[family]) != afinfo)
2480 			err = -EINVAL;
2481 		else
2482 			RCU_INIT_POINTER(xfrm_state_afinfo[afinfo->family], NULL);
2483 	}
2484 	spin_unlock_bh(&xfrm_state_afinfo_lock);
2485 	synchronize_rcu();
2486 	return err;
2487 }
2488 EXPORT_SYMBOL(xfrm_state_unregister_afinfo);
2489 
xfrm_state_afinfo_get_rcu(unsigned int family)2490 struct xfrm_state_afinfo *xfrm_state_afinfo_get_rcu(unsigned int family)
2491 {
2492 	if (unlikely(family >= NPROTO))
2493 		return NULL;
2494 
2495 	return rcu_dereference(xfrm_state_afinfo[family]);
2496 }
2497 EXPORT_SYMBOL_GPL(xfrm_state_afinfo_get_rcu);
2498 
xfrm_state_get_afinfo(unsigned int family)2499 struct xfrm_state_afinfo *xfrm_state_get_afinfo(unsigned int family)
2500 {
2501 	struct xfrm_state_afinfo *afinfo;
2502 	if (unlikely(family >= NPROTO))
2503 		return NULL;
2504 	rcu_read_lock();
2505 	afinfo = rcu_dereference(xfrm_state_afinfo[family]);
2506 	if (unlikely(!afinfo))
2507 		rcu_read_unlock();
2508 	return afinfo;
2509 }
2510 
xfrm_flush_gc(void)2511 void xfrm_flush_gc(void)
2512 {
2513 	flush_work(&xfrm_state_gc_work);
2514 }
2515 EXPORT_SYMBOL(xfrm_flush_gc);
2516 
2517 /* Temporarily located here until net/xfrm/xfrm_tunnel.c is created */
xfrm_state_delete_tunnel(struct xfrm_state * x)2518 void xfrm_state_delete_tunnel(struct xfrm_state *x)
2519 {
2520 	if (x->tunnel) {
2521 		struct xfrm_state *t = x->tunnel;
2522 
2523 		if (atomic_read(&t->tunnel_users) == 2)
2524 			xfrm_state_delete(t);
2525 		atomic_dec(&t->tunnel_users);
2526 		xfrm_state_put_sync(t);
2527 		x->tunnel = NULL;
2528 	}
2529 }
2530 EXPORT_SYMBOL(xfrm_state_delete_tunnel);
2531 
xfrm_state_mtu(struct xfrm_state * x,int mtu)2532 u32 xfrm_state_mtu(struct xfrm_state *x, int mtu)
2533 {
2534 	const struct xfrm_type *type = READ_ONCE(x->type);
2535 	struct crypto_aead *aead;
2536 	u32 blksize, net_adj = 0;
2537 
2538 	if (x->km.state != XFRM_STATE_VALID ||
2539 	    !type || type->proto != IPPROTO_ESP)
2540 		return mtu - x->props.header_len;
2541 
2542 	aead = x->data;
2543 	blksize = ALIGN(crypto_aead_blocksize(aead), 4);
2544 
2545 	switch (x->props.mode) {
2546 	case XFRM_MODE_TRANSPORT:
2547 	case XFRM_MODE_BEET:
2548 		if (x->props.family == AF_INET)
2549 			net_adj = sizeof(struct iphdr);
2550 		else if (x->props.family == AF_INET6)
2551 			net_adj = sizeof(struct ipv6hdr);
2552 		break;
2553 	case XFRM_MODE_TUNNEL:
2554 		break;
2555 	default:
2556 		WARN_ON_ONCE(1);
2557 		break;
2558 	}
2559 
2560 	return ((mtu - x->props.header_len - crypto_aead_authsize(aead) -
2561 		 net_adj) & ~(blksize - 1)) + net_adj - 2;
2562 }
2563 EXPORT_SYMBOL_GPL(xfrm_state_mtu);
2564 
__xfrm_init_state(struct xfrm_state * x,bool init_replay,bool offload)2565 int __xfrm_init_state(struct xfrm_state *x, bool init_replay, bool offload)
2566 {
2567 	const struct xfrm_mode *inner_mode;
2568 	const struct xfrm_mode *outer_mode;
2569 	int family = x->props.family;
2570 	int err;
2571 
2572 	if (family == AF_INET &&
2573 	    READ_ONCE(xs_net(x)->ipv4.sysctl_ip_no_pmtu_disc))
2574 		x->props.flags |= XFRM_STATE_NOPMTUDISC;
2575 
2576 	err = -EPROTONOSUPPORT;
2577 
2578 	if (x->sel.family != AF_UNSPEC) {
2579 		inner_mode = xfrm_get_mode(x->props.mode, x->sel.family);
2580 		if (inner_mode == NULL)
2581 			goto error;
2582 
2583 		if (!(inner_mode->flags & XFRM_MODE_FLAG_TUNNEL) &&
2584 		    family != x->sel.family)
2585 			goto error;
2586 
2587 		x->inner_mode = *inner_mode;
2588 	} else {
2589 		const struct xfrm_mode *inner_mode_iaf;
2590 		int iafamily = AF_INET;
2591 
2592 		inner_mode = xfrm_get_mode(x->props.mode, x->props.family);
2593 		if (inner_mode == NULL)
2594 			goto error;
2595 
2596 		x->inner_mode = *inner_mode;
2597 
2598 		if (x->props.family == AF_INET)
2599 			iafamily = AF_INET6;
2600 
2601 		inner_mode_iaf = xfrm_get_mode(x->props.mode, iafamily);
2602 		if (inner_mode_iaf) {
2603 			if (inner_mode_iaf->flags & XFRM_MODE_FLAG_TUNNEL)
2604 				x->inner_mode_iaf = *inner_mode_iaf;
2605 		}
2606 	}
2607 
2608 	x->type = xfrm_get_type(x->id.proto, family);
2609 	if (x->type == NULL)
2610 		goto error;
2611 
2612 	x->type_offload = xfrm_get_type_offload(x->id.proto, family, offload);
2613 
2614 	err = x->type->init_state(x);
2615 	if (err)
2616 		goto error;
2617 
2618 	outer_mode = xfrm_get_mode(x->props.mode, family);
2619 	if (!outer_mode) {
2620 		err = -EPROTONOSUPPORT;
2621 		goto error;
2622 	}
2623 
2624 	x->outer_mode = *outer_mode;
2625 	if (init_replay) {
2626 		err = xfrm_init_replay(x);
2627 		if (err)
2628 			goto error;
2629 	}
2630 
2631 error:
2632 	return err;
2633 }
2634 
2635 EXPORT_SYMBOL(__xfrm_init_state);
2636 
xfrm_init_state(struct xfrm_state * x)2637 int xfrm_init_state(struct xfrm_state *x)
2638 {
2639 	int err;
2640 
2641 	err = __xfrm_init_state(x, true, false);
2642 	if (!err)
2643 		x->km.state = XFRM_STATE_VALID;
2644 
2645 	return err;
2646 }
2647 
2648 EXPORT_SYMBOL(xfrm_init_state);
2649 
xfrm_state_init(struct net * net)2650 int __net_init xfrm_state_init(struct net *net)
2651 {
2652 	unsigned int sz;
2653 
2654 	if (net_eq(net, &init_net))
2655 		xfrm_state_cache = KMEM_CACHE(xfrm_state,
2656 					      SLAB_HWCACHE_ALIGN | SLAB_PANIC);
2657 
2658 	INIT_LIST_HEAD(&net->xfrm.state_all);
2659 
2660 	sz = sizeof(struct hlist_head) * 8;
2661 
2662 	net->xfrm.state_bydst = xfrm_hash_alloc(sz);
2663 	if (!net->xfrm.state_bydst)
2664 		goto out_bydst;
2665 	net->xfrm.state_bysrc = xfrm_hash_alloc(sz);
2666 	if (!net->xfrm.state_bysrc)
2667 		goto out_bysrc;
2668 	net->xfrm.state_byspi = xfrm_hash_alloc(sz);
2669 	if (!net->xfrm.state_byspi)
2670 		goto out_byspi;
2671 	net->xfrm.state_hmask = ((sz / sizeof(struct hlist_head)) - 1);
2672 
2673 	net->xfrm.state_num = 0;
2674 	INIT_WORK(&net->xfrm.state_hash_work, xfrm_hash_resize);
2675 	spin_lock_init(&net->xfrm.xfrm_state_lock);
2676 	seqcount_init(&net->xfrm.xfrm_state_hash_generation);
2677 	return 0;
2678 
2679 out_byspi:
2680 	xfrm_hash_free(net->xfrm.state_bysrc, sz);
2681 out_bysrc:
2682 	xfrm_hash_free(net->xfrm.state_bydst, sz);
2683 out_bydst:
2684 	return -ENOMEM;
2685 }
2686 
xfrm_state_fini(struct net * net)2687 void xfrm_state_fini(struct net *net)
2688 {
2689 	unsigned int sz;
2690 
2691 	flush_work(&net->xfrm.state_hash_work);
2692 	flush_work(&xfrm_state_gc_work);
2693 	xfrm_state_flush(net, 0, false, true);
2694 
2695 	WARN_ON(!list_empty(&net->xfrm.state_all));
2696 
2697 	sz = (net->xfrm.state_hmask + 1) * sizeof(struct hlist_head);
2698 	WARN_ON(!hlist_empty(net->xfrm.state_byspi));
2699 	xfrm_hash_free(net->xfrm.state_byspi, sz);
2700 	WARN_ON(!hlist_empty(net->xfrm.state_bysrc));
2701 	xfrm_hash_free(net->xfrm.state_bysrc, sz);
2702 	WARN_ON(!hlist_empty(net->xfrm.state_bydst));
2703 	xfrm_hash_free(net->xfrm.state_bydst, sz);
2704 }
2705 
2706 #ifdef CONFIG_AUDITSYSCALL
xfrm_audit_helper_sainfo(struct xfrm_state * x,struct audit_buffer * audit_buf)2707 static void xfrm_audit_helper_sainfo(struct xfrm_state *x,
2708 				     struct audit_buffer *audit_buf)
2709 {
2710 	struct xfrm_sec_ctx *ctx = x->security;
2711 	u32 spi = ntohl(x->id.spi);
2712 
2713 	if (ctx)
2714 		audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
2715 				 ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
2716 
2717 	switch (x->props.family) {
2718 	case AF_INET:
2719 		audit_log_format(audit_buf, " src=%pI4 dst=%pI4",
2720 				 &x->props.saddr.a4, &x->id.daddr.a4);
2721 		break;
2722 	case AF_INET6:
2723 		audit_log_format(audit_buf, " src=%pI6 dst=%pI6",
2724 				 x->props.saddr.a6, x->id.daddr.a6);
2725 		break;
2726 	}
2727 
2728 	audit_log_format(audit_buf, " spi=%u(0x%x)", spi, spi);
2729 }
2730 
xfrm_audit_helper_pktinfo(struct sk_buff * skb,u16 family,struct audit_buffer * audit_buf)2731 static void xfrm_audit_helper_pktinfo(struct sk_buff *skb, u16 family,
2732 				      struct audit_buffer *audit_buf)
2733 {
2734 	const struct iphdr *iph4;
2735 	const struct ipv6hdr *iph6;
2736 
2737 	switch (family) {
2738 	case AF_INET:
2739 		iph4 = ip_hdr(skb);
2740 		audit_log_format(audit_buf, " src=%pI4 dst=%pI4",
2741 				 &iph4->saddr, &iph4->daddr);
2742 		break;
2743 	case AF_INET6:
2744 		iph6 = ipv6_hdr(skb);
2745 		audit_log_format(audit_buf,
2746 				 " src=%pI6 dst=%pI6 flowlbl=0x%x%02x%02x",
2747 				 &iph6->saddr, &iph6->daddr,
2748 				 iph6->flow_lbl[0] & 0x0f,
2749 				 iph6->flow_lbl[1],
2750 				 iph6->flow_lbl[2]);
2751 		break;
2752 	}
2753 }
2754 
xfrm_audit_state_add(struct xfrm_state * x,int result,bool task_valid)2755 void xfrm_audit_state_add(struct xfrm_state *x, int result, bool task_valid)
2756 {
2757 	struct audit_buffer *audit_buf;
2758 
2759 	audit_buf = xfrm_audit_start("SAD-add");
2760 	if (audit_buf == NULL)
2761 		return;
2762 	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
2763 	xfrm_audit_helper_sainfo(x, audit_buf);
2764 	audit_log_format(audit_buf, " res=%u", result);
2765 	audit_log_end(audit_buf);
2766 }
2767 EXPORT_SYMBOL_GPL(xfrm_audit_state_add);
2768 
xfrm_audit_state_delete(struct xfrm_state * x,int result,bool task_valid)2769 void xfrm_audit_state_delete(struct xfrm_state *x, int result, bool task_valid)
2770 {
2771 	struct audit_buffer *audit_buf;
2772 
2773 	audit_buf = xfrm_audit_start("SAD-delete");
2774 	if (audit_buf == NULL)
2775 		return;
2776 	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
2777 	xfrm_audit_helper_sainfo(x, audit_buf);
2778 	audit_log_format(audit_buf, " res=%u", result);
2779 	audit_log_end(audit_buf);
2780 }
2781 EXPORT_SYMBOL_GPL(xfrm_audit_state_delete);
2782 
xfrm_audit_state_replay_overflow(struct xfrm_state * x,struct sk_buff * skb)2783 void xfrm_audit_state_replay_overflow(struct xfrm_state *x,
2784 				      struct sk_buff *skb)
2785 {
2786 	struct audit_buffer *audit_buf;
2787 	u32 spi;
2788 
2789 	audit_buf = xfrm_audit_start("SA-replay-overflow");
2790 	if (audit_buf == NULL)
2791 		return;
2792 	xfrm_audit_helper_pktinfo(skb, x->props.family, audit_buf);
2793 	/* don't record the sequence number because it's inherent in this kind
2794 	 * of audit message */
2795 	spi = ntohl(x->id.spi);
2796 	audit_log_format(audit_buf, " spi=%u(0x%x)", spi, spi);
2797 	audit_log_end(audit_buf);
2798 }
2799 EXPORT_SYMBOL_GPL(xfrm_audit_state_replay_overflow);
2800 
xfrm_audit_state_replay(struct xfrm_state * x,struct sk_buff * skb,__be32 net_seq)2801 void xfrm_audit_state_replay(struct xfrm_state *x,
2802 			     struct sk_buff *skb, __be32 net_seq)
2803 {
2804 	struct audit_buffer *audit_buf;
2805 	u32 spi;
2806 
2807 	audit_buf = xfrm_audit_start("SA-replayed-pkt");
2808 	if (audit_buf == NULL)
2809 		return;
2810 	xfrm_audit_helper_pktinfo(skb, x->props.family, audit_buf);
2811 	spi = ntohl(x->id.spi);
2812 	audit_log_format(audit_buf, " spi=%u(0x%x) seqno=%u",
2813 			 spi, spi, ntohl(net_seq));
2814 	audit_log_end(audit_buf);
2815 }
2816 EXPORT_SYMBOL_GPL(xfrm_audit_state_replay);
2817 
xfrm_audit_state_notfound_simple(struct sk_buff * skb,u16 family)2818 void xfrm_audit_state_notfound_simple(struct sk_buff *skb, u16 family)
2819 {
2820 	struct audit_buffer *audit_buf;
2821 
2822 	audit_buf = xfrm_audit_start("SA-notfound");
2823 	if (audit_buf == NULL)
2824 		return;
2825 	xfrm_audit_helper_pktinfo(skb, family, audit_buf);
2826 	audit_log_end(audit_buf);
2827 }
2828 EXPORT_SYMBOL_GPL(xfrm_audit_state_notfound_simple);
2829 
xfrm_audit_state_notfound(struct sk_buff * skb,u16 family,__be32 net_spi,__be32 net_seq)2830 void xfrm_audit_state_notfound(struct sk_buff *skb, u16 family,
2831 			       __be32 net_spi, __be32 net_seq)
2832 {
2833 	struct audit_buffer *audit_buf;
2834 	u32 spi;
2835 
2836 	audit_buf = xfrm_audit_start("SA-notfound");
2837 	if (audit_buf == NULL)
2838 		return;
2839 	xfrm_audit_helper_pktinfo(skb, family, audit_buf);
2840 	spi = ntohl(net_spi);
2841 	audit_log_format(audit_buf, " spi=%u(0x%x) seqno=%u",
2842 			 spi, spi, ntohl(net_seq));
2843 	audit_log_end(audit_buf);
2844 }
2845 EXPORT_SYMBOL_GPL(xfrm_audit_state_notfound);
2846 
xfrm_audit_state_icvfail(struct xfrm_state * x,struct sk_buff * skb,u8 proto)2847 void xfrm_audit_state_icvfail(struct xfrm_state *x,
2848 			      struct sk_buff *skb, u8 proto)
2849 {
2850 	struct audit_buffer *audit_buf;
2851 	__be32 net_spi;
2852 	__be32 net_seq;
2853 
2854 	audit_buf = xfrm_audit_start("SA-icv-failure");
2855 	if (audit_buf == NULL)
2856 		return;
2857 	xfrm_audit_helper_pktinfo(skb, x->props.family, audit_buf);
2858 	if (xfrm_parse_spi(skb, proto, &net_spi, &net_seq) == 0) {
2859 		u32 spi = ntohl(net_spi);
2860 		audit_log_format(audit_buf, " spi=%u(0x%x) seqno=%u",
2861 				 spi, spi, ntohl(net_seq));
2862 	}
2863 	audit_log_end(audit_buf);
2864 }
2865 EXPORT_SYMBOL_GPL(xfrm_audit_state_icvfail);
2866 #endif /* CONFIG_AUDITSYSCALL */
2867