xfrm_state.c 66.6 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
L
Linus Torvalds 已提交
2 3 4 5 6 7 8 9 10 11 12 13
/*
 * xfrm_state.c
 *
 * Changes:
 *	Mitsuru KANDA @USAGI
 * 	Kazunori MIYAZAWA @USAGI
 * 	Kunihiro Ishiguro <kunihiro@ipinfusion.com>
 * 		IPv6 support
 * 	YOSHIFUJI Hideaki @USAGI
 * 		Split up af-specific functions
 *	Derek Atkins <derek@ihtfp.com>
 *		Add UDP Encapsulation
14
 *
L
Linus Torvalds 已提交
15 16 17 18 19 20 21
 */

#include <linux/workqueue.h>
#include <net/xfrm.h>
#include <linux/pfkeyv2.h>
#include <linux/ipsec.h>
#include <linux/module.h>
22
#include <linux/cache.h>
P
Paul Moore 已提交
23
#include <linux/audit.h>
24
#include <linux/uaccess.h>
25
#include <linux/ktime.h>
26
#include <linux/slab.h>
27 28
#include <linux/interrupt.h>
#include <linux/kernel.h>
L
Linus Torvalds 已提交
29

30 31
#include <crypto/aead.h>

32 33
#include "xfrm_hash.h"

34 35 36
#define xfrm_state_deref_prot(table, net) \
	rcu_dereference_protected((table), lockdep_is_held(&(net)->xfrm.xfrm_state_lock))

37 38
static void xfrm_state_gc_task(struct work_struct *work);

L
Linus Torvalds 已提交
39 40 41
/* Each xfrm_state may be linked to two tables:

   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
L
Linus Torvalds 已提交
43 44 45
      destination/tunnel endpoint. (output)
 */

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 50 51
static DECLARE_WORK(xfrm_state_gc_work, xfrm_state_gc_task);
static HLIST_HEAD(xfrm_state_gc_list);

52 53
static inline bool xfrm_state_hold_rcu(struct xfrm_state __rcu *x)
{
54
	return refcount_inc_not_zero(&x->refcnt);
55 56
}

57
static inline unsigned int xfrm_dst_hash(struct net *net,
58 59
					 const xfrm_address_t *daddr,
					 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
}

66
static inline unsigned int xfrm_src_hash(struct net *net,
67 68
					 const xfrm_address_t *daddr,
					 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
75 76
xfrm_spi_hash(struct net *net, const xfrm_address_t *daddr,
	      __be32 spi, u8 proto, unsigned short family)
77
{
78
	return __xfrm_spi_hash(daddr, spi, proto, family, net->xfrm.state_hmask);
79 80 81 82 83 84 85 86
}

static void xfrm_hash_transfer(struct hlist_head *list,
			       struct hlist_head *ndsttable,
			       struct hlist_head *nsrctable,
			       struct hlist_head *nspitable,
			       unsigned int nhashmask)
{
87
	struct hlist_node *tmp;
88 89
	struct xfrm_state *x;

90
	hlist_for_each_entry_safe(x, tmp, list, bydst) {
91 92
		unsigned int h;

93 94 95
		h = __xfrm_dst_hash(&x->id.daddr, &x->props.saddr,
				    x->props.reqid, x->props.family,
				    nhashmask);
96
		hlist_add_head_rcu(&x->bydst, ndsttable + h);
97

98 99
		h = __xfrm_src_hash(&x->id.daddr, &x->props.saddr,
				    x->props.family,
100
				    nhashmask);
101
		hlist_add_head_rcu(&x->bysrc, nsrctable + h);
102

103 104 105 106
		if (x->id.spi) {
			h = __xfrm_spi_hash(&x->id.daddr, x->id.spi,
					    x->id.proto, x->props.family,
					    nhashmask);
107
			hlist_add_head_rcu(&x->byspi, nspitable + h);
108
		}
109 110 111
	}
}

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
}

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 121 122 123 124
	struct hlist_head *ndst, *nsrc, *nspi, *odst, *osrc, *ospi;
	unsigned long nsize, osize;
	unsigned int nhashmask, ohashmask;
	int i;

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 137
		xfrm_hash_free(ndst, nsize);
		xfrm_hash_free(nsrc, nsize);
138
		return;
139 140
	}

F
Fan Du 已提交
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 150
	osrc = xfrm_state_deref_prot(net->xfrm.state_bysrc, net);
	ospi = xfrm_state_deref_prot(net->xfrm.state_byspi, net);
151
	ohashmask = net->xfrm.state_hmask;
152

153 154 155
	rcu_assign_pointer(net->xfrm.state_bydst, ndst);
	rcu_assign_pointer(net->xfrm.state_bysrc, nsrc);
	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);
F
Fan Du 已提交
159
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
160 161

	osize = (ohashmask + 1) * sizeof(struct hlist_head);
162 163 164

	synchronize_rcu();

165 166 167
	xfrm_hash_free(odst, osize);
	xfrm_hash_free(osrc, osize);
	xfrm_hash_free(ospi, osize);
168 169
}

170 171
static DEFINE_SPINLOCK(xfrm_state_afinfo_lock);
static struct xfrm_state_afinfo __rcu *xfrm_state_afinfo[NPROTO];
L
Linus Torvalds 已提交
172 173 174

static DEFINE_SPINLOCK(xfrm_state_gc_lock);

175
int __xfrm_state_delete(struct xfrm_state *x);
L
Linus Torvalds 已提交
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);
L
Linus Torvalds 已提交
180

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 185
	int err = 0;

186
	if (!afinfo)
187
		return -EAFNOSUPPORT;
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221

#define X(afi, T, name) do {			\
		WARN_ON((afi)->type_ ## name);	\
		(afi)->type_ ## name = (T);	\
	} while (0)

	switch (type->proto) {
	case IPPROTO_COMP:
		X(afinfo, type, comp);
		break;
	case IPPROTO_AH:
		X(afinfo, type, ah);
		break;
	case IPPROTO_ESP:
		X(afinfo, type, esp);
		break;
	case IPPROTO_IPIP:
		X(afinfo, type, ipip);
		break;
	case IPPROTO_DSTOPTS:
		X(afinfo, type, dstopts);
		break;
	case IPPROTO_ROUTING:
		X(afinfo, type, routing);
		break;
	case IPPROTO_IPV6:
		X(afinfo, type, ipip6);
		break;
	default:
		WARN_ON(1);
		err = -EPROTONOSUPPORT;
		break;
	}
#undef X
222
	rcu_read_unlock();
223 224 225 226
	return err;
}
EXPORT_SYMBOL(xfrm_register_type);

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 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
		return;

#define X(afi, T, name) do {				\
		WARN_ON((afi)->type_ ## name != (T));	\
		(afi)->type_ ## name = NULL;		\
	} while (0)

	switch (type->proto) {
	case IPPROTO_COMP:
		X(afinfo, type, comp);
		break;
	case IPPROTO_AH:
		X(afinfo, type, ah);
		break;
	case IPPROTO_ESP:
		X(afinfo, type, esp);
		break;
	case IPPROTO_IPIP:
		X(afinfo, type, ipip);
		break;
	case IPPROTO_DSTOPTS:
		X(afinfo, type, dstopts);
		break;
	case IPPROTO_ROUTING:
		X(afinfo, type, routing);
		break;
	case IPPROTO_IPV6:
		X(afinfo, type, ipip6);
		break;
	default:
		WARN_ON(1);
		break;
	}
#undef X
266
	rcu_read_unlock();
267 268 269
}
EXPORT_SYMBOL(xfrm_unregister_type);

270
static const struct xfrm_type *xfrm_get_type(u8 proto, unsigned short family)
271
{
272
	const struct xfrm_type *type = NULL;
273 274 275 276 277 278 279 280
	struct xfrm_state_afinfo *afinfo;
	int modload_attempted = 0;

retry:
	afinfo = xfrm_state_get_afinfo(family);
	if (unlikely(afinfo == NULL))
		return NULL;

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
	switch (proto) {
	case IPPROTO_COMP:
		type = afinfo->type_comp;
		break;
	case IPPROTO_AH:
		type = afinfo->type_ah;
		break;
	case IPPROTO_ESP:
		type = afinfo->type_esp;
		break;
	case IPPROTO_IPIP:
		type = afinfo->type_ipip;
		break;
	case IPPROTO_DSTOPTS:
		type = afinfo->type_dstopts;
		break;
	case IPPROTO_ROUTING:
		type = afinfo->type_routing;
		break;
	case IPPROTO_IPV6:
		type = afinfo->type_ipip6;
		break;
	default:
		break;
	}

307 308
	if (unlikely(type && !try_module_get(type->owner)))
		type = NULL;
309 310 311

	rcu_read_unlock();

312 313 314 315 316 317 318 319 320
	if (!type && !modload_attempted) {
		request_module("xfrm-type-%d-%d", family, proto);
		modload_attempted = 1;
		goto retry;
	}

	return type;
}

321
static void xfrm_put_type(const struct xfrm_type *type)
322 323 324 325
{
	module_put(type->owner);
}

326 327 328 329 330 331 332 333
int xfrm_register_type_offload(const struct xfrm_type_offload *type,
			       unsigned short family)
{
	struct xfrm_state_afinfo *afinfo = xfrm_state_get_afinfo(family);
	int err = 0;

	if (unlikely(afinfo == NULL))
		return -EAFNOSUPPORT;
334 335 336 337 338 339 340 341 342 343 344 345

	switch (type->proto) {
	case IPPROTO_ESP:
		WARN_ON(afinfo->type_offload_esp);
		afinfo->type_offload_esp = type;
		break;
	default:
		WARN_ON(1);
		err = -EPROTONOSUPPORT;
		break;
	}

346 347 348 349 350
	rcu_read_unlock();
	return err;
}
EXPORT_SYMBOL(xfrm_register_type_offload);

351 352
void xfrm_unregister_type_offload(const struct xfrm_type_offload *type,
				  unsigned short family)
353 354 355 356
{
	struct xfrm_state_afinfo *afinfo = xfrm_state_get_afinfo(family);

	if (unlikely(afinfo == NULL))
357 358 359 360 361 362 363 364 365 366 367
		return;

	switch (type->proto) {
	case IPPROTO_ESP:
		WARN_ON(afinfo->type_offload_esp != type);
		afinfo->type_offload_esp = NULL;
		break;
	default:
		WARN_ON(1);
		break;
	}
368 369 370 371
	rcu_read_unlock();
}
EXPORT_SYMBOL(xfrm_unregister_type_offload);

372 373
static const struct xfrm_type_offload *
xfrm_get_type_offload(u8 proto, unsigned short family, bool try_load)
374
{
375
	const struct xfrm_type_offload *type = NULL;
376 377
	struct xfrm_state_afinfo *afinfo;

378
retry:
379 380 381 382
	afinfo = xfrm_state_get_afinfo(family);
	if (unlikely(afinfo == NULL))
		return NULL;

383 384 385 386 387 388 389 390
	switch (proto) {
	case IPPROTO_ESP:
		type = afinfo->type_offload_esp;
		break;
	default:
		break;
	}

391 392 393
	if ((type && !try_module_get(type->owner)))
		type = NULL;

394 395
	rcu_read_unlock();

396 397
	if (!type && try_load) {
		request_module("xfrm-offload-%d-%d", family, proto);
398
		try_load = false;
399 400 401
		goto retry;
	}

402 403 404 405 406 407 408 409
	return type;
}

static void xfrm_put_type_offload(const struct xfrm_type_offload *type)
{
	module_put(type->owner);
}

F
Florian Westphal 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
static const struct xfrm_mode xfrm4_mode_map[XFRM_MODE_MAX] = {
	[XFRM_MODE_BEET] = {
		.encap = XFRM_MODE_BEET,
		.flags = XFRM_MODE_FLAG_TUNNEL,
		.family = AF_INET,
	},
	[XFRM_MODE_TRANSPORT] = {
		.encap = XFRM_MODE_TRANSPORT,
		.family = AF_INET,
	},
	[XFRM_MODE_TUNNEL] = {
		.encap = XFRM_MODE_TUNNEL,
		.flags = XFRM_MODE_FLAG_TUNNEL,
		.family = AF_INET,
	},
};

static const struct xfrm_mode xfrm6_mode_map[XFRM_MODE_MAX] = {
	[XFRM_MODE_BEET] = {
		.encap = XFRM_MODE_BEET,
		.flags = XFRM_MODE_FLAG_TUNNEL,
		.family = AF_INET6,
	},
	[XFRM_MODE_ROUTEOPTIMIZATION] = {
		.encap = XFRM_MODE_ROUTEOPTIMIZATION,
		.family = AF_INET6,
	},
	[XFRM_MODE_TRANSPORT] = {
		.encap = XFRM_MODE_TRANSPORT,
		.family = AF_INET6,
	},
	[XFRM_MODE_TUNNEL] = {
		.encap = XFRM_MODE_TUNNEL,
		.flags = XFRM_MODE_FLAG_TUNNEL,
		.family = AF_INET6,
	},
};

static const struct xfrm_mode *xfrm_get_mode(unsigned int encap, int family)
{
	const struct xfrm_mode *mode;
451 452 453 454

	if (unlikely(encap >= XFRM_MODE_MAX))
		return NULL;

F
Florian Westphal 已提交
455 456 457 458 459 460 461 462 463 464 465 466 467
	switch (family) {
	case AF_INET:
		mode = &xfrm4_mode_map[encap];
		if (mode->family == family)
			return mode;
		break;
	case AF_INET6:
		mode = &xfrm6_mode_map[encap];
		if (mode->family == family)
			return mode;
		break;
	default:
		break;
468 469
	}

F
Florian Westphal 已提交
470
	return NULL;
471 472
}

473 474 475 476 477 478
void xfrm_state_free(struct xfrm_state *x)
{
	kmem_cache_free(xfrm_state_cache, x);
}
EXPORT_SYMBOL(xfrm_state_free);

479
static void ___xfrm_state_destroy(struct xfrm_state *x)
L
Linus Torvalds 已提交
480
{
481
	hrtimer_cancel(&x->mtimer);
482
	del_timer_sync(&x->rtimer);
483
	kfree(x->aead);
J
Jesper Juhl 已提交
484 485 486 487
	kfree(x->aalg);
	kfree(x->ealg);
	kfree(x->calg);
	kfree(x->encap);
488
	kfree(x->coaddr);
489 490
	kfree(x->replay_esn);
	kfree(x->preplay_esn);
491 492
	if (x->type_offload)
		xfrm_put_type_offload(x->type_offload);
L
Linus Torvalds 已提交
493 494 495 496
	if (x->type) {
		x->type->destructor(x);
		xfrm_put_type(x->type);
	}
497 498
	if (x->xfrag.page)
		put_page(x->xfrag.page);
499
	xfrm_dev_state_free(x);
500
	security_xfrm_state_free(x);
501
	xfrm_state_free(x);
L
Linus Torvalds 已提交
502 503
}

504
static void xfrm_state_gc_task(struct work_struct *work)
L
Linus Torvalds 已提交
505
{
H
Herbert Xu 已提交
506
	struct xfrm_state *x;
507
	struct hlist_node *tmp;
H
Herbert Xu 已提交
508
	struct hlist_head gc_list;
L
Linus Torvalds 已提交
509 510

	spin_lock_bh(&xfrm_state_gc_lock);
511
	hlist_move_list(&xfrm_state_gc_list, &gc_list);
L
Linus Torvalds 已提交
512 513
	spin_unlock_bh(&xfrm_state_gc_lock);

514 515
	synchronize_rcu();

516
	hlist_for_each_entry_safe(x, tmp, &gc_list, gclist)
517
		___xfrm_state_destroy(x);
L
Linus Torvalds 已提交
518 519
}

520
static enum hrtimer_restart xfrm_timer_handler(struct hrtimer *me)
L
Linus Torvalds 已提交
521
{
522 523
	struct xfrm_state *x = container_of(me, struct xfrm_state, mtimer);
	enum hrtimer_restart ret = HRTIMER_NORESTART;
524 525
	time64_t now = ktime_get_real_seconds();
	time64_t next = TIME64_MAX;
L
Linus Torvalds 已提交
526
	int warn = 0;
J
Joy Latten 已提交
527
	int err = 0;
L
Linus Torvalds 已提交
528 529 530 531 532 533 534 535 536

	spin_lock(&x->lock);
	if (x->km.state == XFRM_STATE_DEAD)
		goto out;
	if (x->km.state == XFRM_STATE_EXPIRED)
		goto expired;
	if (x->lft.hard_add_expires_seconds) {
		long tmo = x->lft.hard_add_expires_seconds +
			x->curlft.add_time - now;
537 538 539 540
		if (tmo <= 0) {
			if (x->xflags & XFRM_SOFT_EXPIRE) {
				/* enter hard expire without soft expire first?!
				 * setting a new date could trigger this.
A
Alexander Alemayhu 已提交
541
				 * workaround: fix x->curflt.add_time by below:
542 543 544 545 546 547
				 */
				x->curlft.add_time = now - x->saved_tmo - 1;
				tmo = x->lft.hard_add_expires_seconds - x->saved_tmo;
			} else
				goto expired;
		}
L
Linus Torvalds 已提交
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
		if (tmo < next)
			next = tmo;
	}
	if (x->lft.hard_use_expires_seconds) {
		long tmo = x->lft.hard_use_expires_seconds +
			(x->curlft.use_time ? : now) - now;
		if (tmo <= 0)
			goto expired;
		if (tmo < next)
			next = tmo;
	}
	if (x->km.dying)
		goto resched;
	if (x->lft.soft_add_expires_seconds) {
		long tmo = x->lft.soft_add_expires_seconds +
			x->curlft.add_time - now;
564
		if (tmo <= 0) {
L
Linus Torvalds 已提交
565
			warn = 1;
566 567
			x->xflags &= ~XFRM_SOFT_EXPIRE;
		} else if (tmo < next) {
L
Linus Torvalds 已提交
568
			next = tmo;
569 570 571
			x->xflags |= XFRM_SOFT_EXPIRE;
			x->saved_tmo = tmo;
		}
L
Linus Torvalds 已提交
572 573 574 575 576 577 578 579 580 581
	}
	if (x->lft.soft_use_expires_seconds) {
		long tmo = x->lft.soft_use_expires_seconds +
			(x->curlft.use_time ? : now) - now;
		if (tmo <= 0)
			warn = 1;
		else if (tmo < next)
			next = tmo;
	}

582
	x->km.dying = warn;
L
Linus Torvalds 已提交
583
	if (warn)
584
		km_state_expired(x, 0, 0);
L
Linus Torvalds 已提交
585
resched:
586
	if (next != TIME64_MAX) {
587 588
		hrtimer_forward_now(&x->mtimer, ktime_set(next, 0));
		ret = HRTIMER_RESTART;
589
	}
590

L
Linus Torvalds 已提交
591 592 593
	goto out;

expired:
594
	if (x->km.state == XFRM_STATE_ACQ && x->id.spi == 0)
L
Linus Torvalds 已提交
595
		x->km.state = XFRM_STATE_EXPIRED;
J
Joy Latten 已提交
596 597

	err = __xfrm_state_delete(x);
598
	if (!err)
599
		km_state_expired(x, 1, 0);
L
Linus Torvalds 已提交
600

601
	xfrm_audit_state_delete(x, err ? 0 : 1, true);
J
Joy Latten 已提交
602

L
Linus Torvalds 已提交
603 604
out:
	spin_unlock(&x->lock);
605
	return ret;
L
Linus Torvalds 已提交
606 607
}

608
static void xfrm_replay_timer_handler(struct timer_list *t);
609

610
struct xfrm_state *xfrm_state_alloc(struct net *net)
L
Linus Torvalds 已提交
611 612 613
{
	struct xfrm_state *x;

614
	x = kmem_cache_zalloc(xfrm_state_cache, GFP_ATOMIC);
L
Linus Torvalds 已提交
615 616

	if (x) {
617
		write_pnet(&x->xs_net, net);
618
		refcount_set(&x->refcnt, 1);
L
Linus Torvalds 已提交
619
		atomic_set(&x->tunnel_users, 0);
H
Herbert Xu 已提交
620
		INIT_LIST_HEAD(&x->km.all);
621 622 623
		INIT_HLIST_NODE(&x->bydst);
		INIT_HLIST_NODE(&x->bysrc);
		INIT_HLIST_NODE(&x->byspi);
624 625
		hrtimer_init(&x->mtimer, CLOCK_BOOTTIME, HRTIMER_MODE_ABS_SOFT);
		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();
L
Linus Torvalds 已提交
628 629 630 631
		x->lft.soft_byte_limit = XFRM_INF;
		x->lft.soft_packet_limit = XFRM_INF;
		x->lft.hard_byte_limit = XFRM_INF;
		x->lft.hard_packet_limit = XFRM_INF;
632 633
		x->replay_maxage = 0;
		x->replay_maxdiff = 0;
L
Linus Torvalds 已提交
634 635 636 637 638 639
		spin_lock_init(&x->lock);
	}
	return x;
}
EXPORT_SYMBOL(xfrm_state_alloc);

640
void __xfrm_state_destroy(struct xfrm_state *x, bool sync)
L
Linus Torvalds 已提交
641
{
642
	WARN_ON(x->km.state != XFRM_STATE_DEAD);
L
Linus Torvalds 已提交
643

644 645 646 647 648 649 650 651 652
	if (sync) {
		synchronize_rcu();
		___xfrm_state_destroy(x);
	} else {
		spin_lock_bh(&xfrm_state_gc_lock);
		hlist_add_head(&x->gclist, &xfrm_state_gc_list);
		spin_unlock_bh(&xfrm_state_gc_lock);
		schedule_work(&xfrm_state_gc_work);
	}
L
Linus Torvalds 已提交
653 654 655
}
EXPORT_SYMBOL(__xfrm_state_destroy);

656
int __xfrm_state_delete(struct xfrm_state *x)
L
Linus Torvalds 已提交
657
{
658
	struct net *net = xs_net(x);
659 660
	int err = -ESRCH;

L
Linus Torvalds 已提交
661 662
	if (x->km.state != XFRM_STATE_DEAD) {
		x->km.state = XFRM_STATE_DEAD;
F
Fan Du 已提交
663
		spin_lock(&net->xfrm.xfrm_state_lock);
H
Herbert Xu 已提交
664
		list_del(&x->km.all);
665 666
		hlist_del_rcu(&x->bydst);
		hlist_del_rcu(&x->bysrc);
667
		if (x->id.spi)
668
			hlist_del_rcu(&x->byspi);
669
		net->xfrm.state_num--;
F
Fan Du 已提交
670
		spin_unlock(&net->xfrm.xfrm_state_lock);
L
Linus Torvalds 已提交
671

S
Sabrina Dubroca 已提交
672 673 674
		if (x->encap_sk)
			sock_put(rcu_dereference_raw(x->encap_sk));

675 676
		xfrm_dev_state_delete(x);

L
Linus Torvalds 已提交
677 678 679 680
		/* All xfrm_state objects are created by xfrm_state_alloc.
		 * The xfrm_state_alloc call gives a reference, and that
		 * is what we are dropping here.
		 */
681
		xfrm_state_put(x);
682
		err = 0;
L
Linus Torvalds 已提交
683
	}
684 685

	return err;
L
Linus Torvalds 已提交
686
}
687
EXPORT_SYMBOL(__xfrm_state_delete);
L
Linus Torvalds 已提交
688

689
int xfrm_state_delete(struct xfrm_state *x)
L
Linus Torvalds 已提交
690
{
691 692
	int err;

L
Linus Torvalds 已提交
693
	spin_lock_bh(&x->lock);
694
	err = __xfrm_state_delete(x);
L
Linus Torvalds 已提交
695
	spin_unlock_bh(&x->lock);
696 697

	return err;
L
Linus Torvalds 已提交
698 699 700
}
EXPORT_SYMBOL(xfrm_state_delete);

701 702
#ifdef CONFIG_SECURITY_NETWORK_XFRM
static inline int
703
xfrm_state_flush_secctx_check(struct net *net, u8 proto, bool task_valid)
L
Linus Torvalds 已提交
704
{
705 706
	int i, err = 0;

A
Alexey Dobriyan 已提交
707
	for (i = 0; i <= net->xfrm.state_hmask; i++) {
708 709
		struct xfrm_state *x;

710
		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
711 712
			if (xfrm_id_proto_match(x->id.proto, proto) &&
			   (err = security_xfrm_state_delete(x)) != 0) {
713
				xfrm_audit_state_delete(x, 0, task_valid);
714 715 716 717 718 719 720
				return err;
			}
		}
	}

	return err;
}
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743

static inline int
xfrm_dev_state_flush_secctx_check(struct net *net, struct net_device *dev, bool task_valid)
{
	int i, err = 0;

	for (i = 0; i <= net->xfrm.state_hmask; i++) {
		struct xfrm_state *x;
		struct xfrm_state_offload *xso;

		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
			xso = &x->xso;

			if (xso->dev == dev &&
			   (err = security_xfrm_state_delete(x)) != 0) {
				xfrm_audit_state_delete(x, 0, task_valid);
				return err;
			}
		}
	}

	return err;
}
744 745
#else
static inline int
746
xfrm_state_flush_secctx_check(struct net *net, u8 proto, bool task_valid)
747 748 749
{
	return 0;
}
750 751 752 753 754 755

static inline int
xfrm_dev_state_flush_secctx_check(struct net *net, struct net_device *dev, bool task_valid)
{
	return 0;
}
756 757
#endif

758
int xfrm_state_flush(struct net *net, u8 proto, bool task_valid, bool sync)
759
{
760
	int i, err = 0, cnt = 0;
L
Linus Torvalds 已提交
761

F
Fan Du 已提交
762
	spin_lock_bh(&net->xfrm.xfrm_state_lock);
763
	err = xfrm_state_flush_secctx_check(net, proto, task_valid);
764 765 766
	if (err)
		goto out;

767
	err = -ESRCH;
A
Alexey Dobriyan 已提交
768
	for (i = 0; i <= net->xfrm.state_hmask; i++) {
769
		struct xfrm_state *x;
L
Linus Torvalds 已提交
770
restart:
771
		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
L
Linus Torvalds 已提交
772
			if (!xfrm_state_kern(x) &&
773
			    xfrm_id_proto_match(x->id.proto, proto)) {
L
Linus Torvalds 已提交
774
				xfrm_state_hold(x);
F
Fan Du 已提交
775
				spin_unlock_bh(&net->xfrm.xfrm_state_lock);
L
Linus Torvalds 已提交
776

J
Joy Latten 已提交
777
				err = xfrm_state_delete(x);
J
Joy Latten 已提交
778
				xfrm_audit_state_delete(x, err ? 0 : 1,
779
							task_valid);
780 781 782 783
				if (sync)
					xfrm_state_put_sync(x);
				else
					xfrm_state_put(x);
784 785
				if (!err)
					cnt++;
L
Linus Torvalds 已提交
786

F
Fan Du 已提交
787
				spin_lock_bh(&net->xfrm.xfrm_state_lock);
L
Linus Torvalds 已提交
788 789 790 791
				goto restart;
			}
		}
	}
792 793
out:
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
794
	if (cnt)
795
		err = 0;
796

797
	return err;
L
Linus Torvalds 已提交
798 799 800
}
EXPORT_SYMBOL(xfrm_state_flush);

801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_valid)
{
	int i, err = 0, cnt = 0;

	spin_lock_bh(&net->xfrm.xfrm_state_lock);
	err = xfrm_dev_state_flush_secctx_check(net, dev, task_valid);
	if (err)
		goto out;

	err = -ESRCH;
	for (i = 0; i <= net->xfrm.state_hmask; i++) {
		struct xfrm_state *x;
		struct xfrm_state_offload *xso;
restart:
		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
			xso = &x->xso;

			if (!xfrm_state_kern(x) && xso->dev == dev) {
				xfrm_state_hold(x);
				spin_unlock_bh(&net->xfrm.xfrm_state_lock);

				err = xfrm_state_delete(x);
				xfrm_audit_state_delete(x, err ? 0 : 1,
							task_valid);
				xfrm_state_put(x);
				if (!err)
					cnt++;

				spin_lock_bh(&net->xfrm.xfrm_state_lock);
				goto restart;
			}
		}
	}
	if (cnt)
		err = 0;

out:
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
	return err;
}
EXPORT_SYMBOL(xfrm_dev_state_flush);

843
void xfrm_sad_getinfo(struct net *net, struct xfrmk_sadinfo *si)
J
Jamal Hadi Salim 已提交
844
{
F
Fan Du 已提交
845
	spin_lock_bh(&net->xfrm.xfrm_state_lock);
846
	si->sadcnt = net->xfrm.state_num;
847
	si->sadhcnt = net->xfrm.state_hmask + 1;
J
Jamal Hadi Salim 已提交
848
	si->sadhmcnt = xfrm_state_hashmax;
F
Fan Du 已提交
849
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
J
Jamal Hadi Salim 已提交
850 851 852
}
EXPORT_SYMBOL(xfrm_sad_getinfo);

853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
static void
__xfrm4_init_tempsel(struct xfrm_selector *sel, const struct flowi *fl)
{
	const struct flowi4 *fl4 = &fl->u.ip4;

	sel->daddr.a4 = fl4->daddr;
	sel->saddr.a4 = fl4->saddr;
	sel->dport = xfrm_flowi_dport(fl, &fl4->uli);
	sel->dport_mask = htons(0xffff);
	sel->sport = xfrm_flowi_sport(fl, &fl4->uli);
	sel->sport_mask = htons(0xffff);
	sel->family = AF_INET;
	sel->prefixlen_d = 32;
	sel->prefixlen_s = 32;
	sel->proto = fl4->flowi4_proto;
	sel->ifindex = fl4->flowi4_oif;
}

static void
__xfrm6_init_tempsel(struct xfrm_selector *sel, const struct flowi *fl)
{
	const struct flowi6 *fl6 = &fl->u.ip6;

	/* Initialize temporary selector matching only to current session. */
	*(struct in6_addr *)&sel->daddr = fl6->daddr;
	*(struct in6_addr *)&sel->saddr = fl6->saddr;
	sel->dport = xfrm_flowi_dport(fl, &fl6->uli);
	sel->dport_mask = htons(0xffff);
	sel->sport = xfrm_flowi_sport(fl, &fl6->uli);
	sel->sport_mask = htons(0xffff);
	sel->family = AF_INET6;
	sel->prefixlen_d = 128;
	sel->prefixlen_s = 128;
	sel->proto = fl6->flowi6_proto;
	sel->ifindex = fl6->flowi6_oif;
}

890
static void
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)
L
Linus Torvalds 已提交
895
{
896 897 898 899 900 901 902 903 904
	switch (family) {
	case AF_INET:
		__xfrm4_init_tempsel(&x->sel, fl);
		break;
	case AF_INET6:
		__xfrm6_init_tempsel(&x->sel, fl);
		break;
	}

905
	x->id = tmpl->id;
906

907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
	switch (tmpl->encap_family) {
	case AF_INET:
		if (x->id.daddr.a4 == 0)
			x->id.daddr.a4 = daddr->a4;
		x->props.saddr = tmpl->saddr;
		if (x->props.saddr.a4 == 0)
			x->props.saddr.a4 = saddr->a4;
		break;
	case AF_INET6:
		if (ipv6_addr_any((struct in6_addr *)&x->id.daddr))
			memcpy(&x->id.daddr, daddr, sizeof(x->sel.daddr));
		memcpy(&x->props.saddr, &tmpl->saddr, sizeof(x->props.saddr));
		if (ipv6_addr_any((struct in6_addr *)&x->props.saddr))
			memcpy(&x->props.saddr, saddr, sizeof(x->props.saddr));
		break;
	}
923

924 925 926
	x->props.mode = tmpl->mode;
	x->props.reqid = tmpl->reqid;
	x->props.family = tmpl->encap_family;
L
Linus Torvalds 已提交
927 928
}

929 930 931 932
static struct xfrm_state *__xfrm_state_lookup(struct net *net, u32 mark,
					      const xfrm_address_t *daddr,
					      __be32 spi, u8 proto,
					      unsigned short family)
933
{
934
	unsigned int h = xfrm_spi_hash(net, daddr, spi, proto, family);
935 936
	struct xfrm_state *x;

937
	hlist_for_each_entry_rcu(x, net->xfrm.state_byspi + h, byspi) {
938 939
		if (x->props.family != family ||
		    x->id.spi       != spi ||
940
		    x->id.proto     != proto ||
941
		    !xfrm_addr_equal(&x->id.daddr, daddr, family))
942 943
			continue;

J
Jamal Hadi Salim 已提交
944 945
		if ((mark & x->mark.m) != x->mark.v)
			continue;
946 947
		if (!xfrm_state_hold_rcu(x))
			continue;
948 949 950 951 952 953
		return x;
	}

	return NULL;
}

954 955 956 957
static 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)
958
{
959
	unsigned int h = xfrm_src_hash(net, daddr, saddr, family);
960 961
	struct xfrm_state *x;

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 966
		    !xfrm_addr_equal(&x->id.daddr, daddr, family) ||
		    !xfrm_addr_equal(&x->props.saddr, saddr, family))
967 968
			continue;

J
Jamal Hadi Salim 已提交
969 970
		if ((mark & x->mark.m) != x->mark.v)
			continue;
971 972
		if (!xfrm_state_hold_rcu(x))
			continue;
973 974 975 976 977 978 979 980 981
		return x;
	}

	return NULL;
}

static inline struct xfrm_state *
__xfrm_state_locate(struct xfrm_state *x, int use_spi, int family)
{
982
	struct net *net = xs_net(x);
983
	u32 mark = x->mark.v & x->mark.m;
984

985
	if (use_spi)
986 987
		return __xfrm_state_lookup(net, mark, &x->id.daddr,
					   x->id.spi, x->id.proto, family);
988
	else
989 990
		return __xfrm_state_lookup_byaddr(net, mark,
						  &x->id.daddr,
991 992 993 994
						  &x->props.saddr,
						  x->id.proto, family);
}

995
static void xfrm_hash_grow_check(struct net *net, int have_hash_collision)
996 997
{
	if (have_hash_collision &&
998 999 1000
	    (net->xfrm.state_hmask + 1) < xfrm_state_hashmax &&
	    net->xfrm.state_num > net->xfrm.state_hmask)
		schedule_work(&net->xfrm.state_hash_work);
1001 1002
}

1003
static void xfrm_state_look_at(struct xfrm_policy *pol, struct xfrm_state *x,
1004
			       const struct flowi *fl, unsigned short family,
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
			       struct xfrm_state **best, int *acq_in_progress,
			       int *error)
{
	/* Resolution logic:
	 * 1. There is a valid state with matching selector. Done.
	 * 2. Valid state with inappropriate selector. Skip.
	 *
	 * Entering area of "sysdeps".
	 *
	 * 3. If state is not valid, selector is temporary, it selects
	 *    only session which triggered previous resolution. Key
	 *    manager will do something to install a state with proper
	 *    selector.
	 */
	if (x->km.state == XFRM_STATE_VALID) {
		if ((x->sel.family &&
1021 1022
		     (x->sel.family != family ||
		      !xfrm_selector_match(&x->sel, fl, family))) ||
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
		    !security_xfrm_state_pol_flow_match(x, pol, fl))
			return;

		if (!*best ||
		    (*best)->km.dying > x->km.dying ||
		    ((*best)->km.dying == x->km.dying &&
		     (*best)->curlft.add_time < x->curlft.add_time))
			*best = x;
	} else if (x->km.state == XFRM_STATE_ACQ) {
		*acq_in_progress = 1;
	} else if (x->km.state == XFRM_STATE_ERROR ||
		   x->km.state == XFRM_STATE_EXPIRED) {
1035 1036 1037
		if ((!x->sel.family ||
		     (x->sel.family == family &&
		      xfrm_selector_match(&x->sel, fl, family))) &&
1038 1039 1040 1041 1042
		    security_xfrm_state_pol_flow_match(x, pol, fl))
			*error = -ESRCH;
	}
}

L
Linus Torvalds 已提交
1043
struct xfrm_state *
1044
xfrm_state_find(const xfrm_address_t *daddr, const xfrm_address_t *saddr,
1045
		const struct flowi *fl, struct xfrm_tmpl *tmpl,
L
Linus Torvalds 已提交
1046
		struct xfrm_policy *pol, int *err,
1047
		unsigned short family, u32 if_id)
L
Linus Torvalds 已提交
1048
{
1049
	static xfrm_address_t saddr_wildcard = { };
1050
	struct net *net = xp_net(pol);
1051
	unsigned int h, h_wildcard;
1052
	struct xfrm_state *x, *x0, *to_put;
L
Linus Torvalds 已提交
1053 1054 1055
	int acquire_in_progress = 0;
	int error = 0;
	struct xfrm_state *best = NULL;
1056
	u32 mark = pol->mark.v & pol->mark.m;
1057
	unsigned short encap_family = tmpl->encap_family;
1058
	unsigned int sequence;
1059
	struct km_event c;
1060

1061 1062
	to_put = NULL;

1063
	sequence = read_seqcount_begin(&net->xfrm.xfrm_state_hash_generation);
1064

1065
	rcu_read_lock();
1066
	h = xfrm_dst_hash(net, daddr, saddr, tmpl->reqid, encap_family);
1067
	hlist_for_each_entry_rcu(x, net->xfrm.state_bydst + h, bydst) {
1068
		if (x->props.family == encap_family &&
L
Linus Torvalds 已提交
1069
		    x->props.reqid == tmpl->reqid &&
J
Jamal Hadi Salim 已提交
1070
		    (mark & x->mark.m) == x->mark.v &&
1071
		    x->if_id == if_id &&
1072
		    !(x->props.flags & XFRM_STATE_WILDRECV) &&
1073
		    xfrm_state_addr_check(x, daddr, saddr, encap_family) &&
L
Linus Torvalds 已提交
1074 1075
		    tmpl->mode == x->props.mode &&
		    tmpl->id.proto == x->id.proto &&
1076
		    (tmpl->id.spi == x->id.spi || !tmpl->id.spi))
1077
			xfrm_state_look_at(pol, x, fl, family,
1078 1079
					   &best, &acquire_in_progress, &error);
	}
1080
	if (best || acquire_in_progress)
1081 1082
		goto found;

1083
	h_wildcard = xfrm_dst_hash(net, daddr, &saddr_wildcard, tmpl->reqid, encap_family);
1084
	hlist_for_each_entry_rcu(x, net->xfrm.state_bydst + h_wildcard, bydst) {
1085
		if (x->props.family == encap_family &&
1086
		    x->props.reqid == tmpl->reqid &&
J
Jamal Hadi Salim 已提交
1087
		    (mark & x->mark.m) == x->mark.v &&
1088
		    x->if_id == if_id &&
1089
		    !(x->props.flags & XFRM_STATE_WILDRECV) &&
1090
		    xfrm_addr_equal(&x->id.daddr, daddr, encap_family) &&
1091 1092 1093
		    tmpl->mode == x->props.mode &&
		    tmpl->id.proto == x->id.proto &&
		    (tmpl->id.spi == x->id.spi || !tmpl->id.spi))
1094
			xfrm_state_look_at(pol, x, fl, family,
1095
					   &best, &acquire_in_progress, &error);
L
Linus Torvalds 已提交
1096 1097
	}

1098
found:
L
Linus Torvalds 已提交
1099 1100
	x = best;
	if (!x && !error && !acquire_in_progress) {
1101
		if (tmpl->id.spi &&
1102
		    (x0 = __xfrm_state_lookup(net, mark, daddr, tmpl->id.spi,
1103
					      tmpl->id.proto, encap_family)) != NULL) {
1104
			to_put = x0;
L
Linus Torvalds 已提交
1105 1106 1107
			error = -EEXIST;
			goto out;
		}
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118

		c.net = net;
		/* If the KMs have no listeners (yet...), avoid allocating an SA
		 * for each and every packet - garbage collection might not
		 * handle the flood.
		 */
		if (!km_is_alive(&c)) {
			error = -ESRCH;
			goto out;
		}

1119
		x = xfrm_state_alloc(net);
L
Linus Torvalds 已提交
1120 1121 1122 1123
		if (x == NULL) {
			error = -ENOMEM;
			goto out;
		}
1124
		/* Initialize temporary state matching only
L
Linus Torvalds 已提交
1125
		 * to current session. */
1126
		xfrm_init_tempstate(x, fl, tmpl, daddr, saddr, family);
1127
		memcpy(&x->mark, &pol->mark, sizeof(x->mark));
1128
		x->if_id = if_id;
L
Linus Torvalds 已提交
1129

1130
		error = security_xfrm_state_alloc_acquire(x, pol->security, fl->flowi_secid);
1131 1132
		if (error) {
			x->km.state = XFRM_STATE_DEAD;
1133
			to_put = x;
1134 1135 1136 1137
			x = NULL;
			goto out;
		}

L
Linus Torvalds 已提交
1138
		if (km_query(x, tmpl, pol) == 0) {
1139
			spin_lock_bh(&net->xfrm.xfrm_state_lock);
L
Linus Torvalds 已提交
1140
			x->km.state = XFRM_STATE_ACQ;
1141
			list_add(&x->km.all, &net->xfrm.state_all);
1142
			hlist_add_head_rcu(&x->bydst, net->xfrm.state_bydst + h);
1143
			h = xfrm_src_hash(net, daddr, saddr, encap_family);
1144
			hlist_add_head_rcu(&x->bysrc, net->xfrm.state_bysrc + h);
L
Linus Torvalds 已提交
1145
			if (x->id.spi) {
1146
				h = xfrm_spi_hash(net, &x->id.daddr, x->id.spi, x->id.proto, encap_family);
1147
				hlist_add_head_rcu(&x->byspi, net->xfrm.state_byspi + h);
L
Linus Torvalds 已提交
1148
			}
A
Alexey Dobriyan 已提交
1149
			x->lft.hard_add_expires_seconds = net->xfrm.sysctl_acq_expires;
1150 1151 1152
			hrtimer_start(&x->mtimer,
				      ktime_set(net->xfrm.sysctl_acq_expires, 0),
				      HRTIMER_MODE_REL_SOFT);
1153 1154
			net->xfrm.state_num++;
			xfrm_hash_grow_check(net, x->bydst.next != NULL);
1155
			spin_unlock_bh(&net->xfrm.xfrm_state_lock);
L
Linus Torvalds 已提交
1156 1157
		} else {
			x->km.state = XFRM_STATE_DEAD;
1158
			to_put = x;
L
Linus Torvalds 已提交
1159 1160 1161 1162 1163
			x = NULL;
			error = -ESRCH;
		}
	}
out:
1164 1165 1166 1167 1168 1169
	if (x) {
		if (!xfrm_state_hold_rcu(x)) {
			*err = -EAGAIN;
			x = NULL;
		}
	} else {
L
Linus Torvalds 已提交
1170
		*err = acquire_in_progress ? -EAGAIN : error;
1171
	}
1172
	rcu_read_unlock();
1173 1174
	if (to_put)
		xfrm_state_put(to_put);
1175

1176
	if (read_seqcount_retry(&net->xfrm.xfrm_state_hash_generation, sequence)) {
1177 1178 1179 1180 1181 1182 1183
		*err = -EAGAIN;
		if (x) {
			xfrm_state_put(x);
			x = NULL;
		}
	}

L
Linus Torvalds 已提交
1184 1185 1186
	return x;
}

1187
struct xfrm_state *
1188
xfrm_stateonly_find(struct net *net, u32 mark, u32 if_id,
1189
		    xfrm_address_t *daddr, xfrm_address_t *saddr,
1190 1191
		    unsigned short family, u8 mode, u8 proto, u32 reqid)
{
1192
	unsigned int h;
1193 1194
	struct xfrm_state *rx = NULL, *x = NULL;

1195
	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1196
	h = xfrm_dst_hash(net, daddr, saddr, reqid, family);
1197
	hlist_for_each_entry(x, net->xfrm.state_bydst+h, bydst) {
1198 1199
		if (x->props.family == family &&
		    x->props.reqid == reqid &&
J
Jamal Hadi Salim 已提交
1200
		    (mark & x->mark.m) == x->mark.v &&
1201
		    x->if_id == if_id &&
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
		    !(x->props.flags & XFRM_STATE_WILDRECV) &&
		    xfrm_state_addr_check(x, daddr, saddr, family) &&
		    mode == x->props.mode &&
		    proto == x->id.proto &&
		    x->km.state == XFRM_STATE_VALID) {
			rx = x;
			break;
		}
	}

	if (rx)
		xfrm_state_hold(rx);
1214
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1215 1216 1217 1218 1219 1220


	return rx;
}
EXPORT_SYMBOL(xfrm_stateonly_find);

1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
struct xfrm_state *xfrm_state_lookup_byspi(struct net *net, __be32 spi,
					      unsigned short family)
{
	struct xfrm_state *x;
	struct xfrm_state_walk *w;

	spin_lock_bh(&net->xfrm.xfrm_state_lock);
	list_for_each_entry(w, &net->xfrm.state_all, all) {
		x = container_of(w, struct xfrm_state, km);
		if (x->props.family != family ||
			x->id.spi != spi)
			continue;

		xfrm_state_hold(x);
1235
		spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1236 1237 1238 1239 1240 1241 1242
		return x;
	}
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
	return NULL;
}
EXPORT_SYMBOL(xfrm_state_lookup_byspi);

L
Linus Torvalds 已提交
1243 1244
static void __xfrm_state_insert(struct xfrm_state *x)
{
1245
	struct net *net = xs_net(x);
1246
	unsigned int h;
L
Linus Torvalds 已提交
1247

1248
	list_add(&x->km.all, &net->xfrm.state_all);
1249

1250
	h = xfrm_dst_hash(net, &x->id.daddr, &x->props.saddr,
1251
			  x->props.reqid, x->props.family);
1252
	hlist_add_head_rcu(&x->bydst, net->xfrm.state_bydst + h);
L
Linus Torvalds 已提交
1253

1254
	h = xfrm_src_hash(net, &x->id.daddr, &x->props.saddr, x->props.family);
1255
	hlist_add_head_rcu(&x->bysrc, net->xfrm.state_bysrc + h);
L
Linus Torvalds 已提交
1256

1257
	if (x->id.spi) {
1258
		h = xfrm_spi_hash(net, &x->id.daddr, x->id.spi, x->id.proto,
1259 1260
				  x->props.family);

1261
		hlist_add_head_rcu(&x->byspi, net->xfrm.state_byspi + h);
1262 1263
	}

1264
	hrtimer_start(&x->mtimer, ktime_set(1, 0), HRTIMER_MODE_REL_SOFT);
1265 1266
	if (x->replay_maxage)
		mod_timer(&x->rtimer, jiffies + x->replay_maxage);
1267

1268
	net->xfrm.state_num++;
1269

1270
	xfrm_hash_grow_check(net, x->bydst.next != NULL);
L
Linus Torvalds 已提交
1271 1272
}

F
Fan Du 已提交
1273
/* net->xfrm.xfrm_state_lock is held */
1274 1275
static void __xfrm_state_bump_genids(struct xfrm_state *xnew)
{
1276
	struct net *net = xs_net(xnew);
1277 1278 1279 1280
	unsigned short family = xnew->props.family;
	u32 reqid = xnew->props.reqid;
	struct xfrm_state *x;
	unsigned int h;
J
Jamal Hadi Salim 已提交
1281
	u32 mark = xnew->mark.v & xnew->mark.m;
1282
	u32 if_id = xnew->if_id;
1283

1284
	h = xfrm_dst_hash(net, &xnew->id.daddr, &xnew->props.saddr, reqid, family);
1285
	hlist_for_each_entry(x, net->xfrm.state_bydst+h, bydst) {
1286 1287
		if (x->props.family	== family &&
		    x->props.reqid	== reqid &&
1288
		    x->if_id		== if_id &&
J
Jamal Hadi Salim 已提交
1289
		    (mark & x->mark.m) == x->mark.v &&
1290 1291
		    xfrm_addr_equal(&x->id.daddr, &xnew->id.daddr, family) &&
		    xfrm_addr_equal(&x->props.saddr, &xnew->props.saddr, family))
H
Herbert Xu 已提交
1292
			x->genid++;
1293 1294 1295
	}
}

L
Linus Torvalds 已提交
1296 1297
void xfrm_state_insert(struct xfrm_state *x)
{
F
Fan Du 已提交
1298 1299 1300
	struct net *net = xs_net(x);

	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1301
	__xfrm_state_bump_genids(x);
L
Linus Torvalds 已提交
1302
	__xfrm_state_insert(x);
F
Fan Du 已提交
1303
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
L
Linus Torvalds 已提交
1304 1305 1306
}
EXPORT_SYMBOL(xfrm_state_insert);

F
Fan Du 已提交
1307
/* net->xfrm.xfrm_state_lock is held */
1308 1309
static struct xfrm_state *__find_acq_core(struct net *net,
					  const struct xfrm_mark *m,
1310
					  unsigned short family, u8 mode,
1311
					  u32 reqid, u32 if_id, u8 proto,
1312
					  const xfrm_address_t *daddr,
1313 1314
					  const xfrm_address_t *saddr,
					  int create)
1315
{
1316
	unsigned int h = xfrm_dst_hash(net, daddr, saddr, reqid, family);
1317
	struct xfrm_state *x;
J
Jamal Hadi Salim 已提交
1318
	u32 mark = m->v & m->m;
1319

1320
	hlist_for_each_entry(x, net->xfrm.state_bydst+h, bydst) {
1321 1322 1323 1324
		if (x->props.reqid  != reqid ||
		    x->props.mode   != mode ||
		    x->props.family != family ||
		    x->km.state     != XFRM_STATE_ACQ ||
1325
		    x->id.spi       != 0 ||
1326
		    x->id.proto	    != proto ||
J
Jamal Hadi Salim 已提交
1327
		    (mark & x->mark.m) != x->mark.v ||
1328 1329
		    !xfrm_addr_equal(&x->id.daddr, daddr, family) ||
		    !xfrm_addr_equal(&x->props.saddr, saddr, family))
1330 1331 1332 1333 1334 1335 1336 1337 1338
			continue;

		xfrm_state_hold(x);
		return x;
	}

	if (!create)
		return NULL;

1339
	x = xfrm_state_alloc(net);
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
	if (likely(x)) {
		switch (family) {
		case AF_INET:
			x->sel.daddr.a4 = daddr->a4;
			x->sel.saddr.a4 = saddr->a4;
			x->sel.prefixlen_d = 32;
			x->sel.prefixlen_s = 32;
			x->props.saddr.a4 = saddr->a4;
			x->id.daddr.a4 = daddr->a4;
			break;

		case AF_INET6:
J
Jiri Benc 已提交
1352 1353
			x->sel.daddr.in6 = daddr->in6;
			x->sel.saddr.in6 = saddr->in6;
1354 1355
			x->sel.prefixlen_d = 128;
			x->sel.prefixlen_s = 128;
J
Jiri Benc 已提交
1356 1357
			x->props.saddr.in6 = saddr->in6;
			x->id.daddr.in6 = daddr->in6;
1358
			break;
1359
		}
1360 1361 1362 1363 1364 1365

		x->km.state = XFRM_STATE_ACQ;
		x->id.proto = proto;
		x->props.family = family;
		x->props.mode = mode;
		x->props.reqid = reqid;
1366
		x->if_id = if_id;
1367 1368
		x->mark.v = m->v;
		x->mark.m = m->m;
A
Alexey Dobriyan 已提交
1369
		x->lft.hard_add_expires_seconds = net->xfrm.sysctl_acq_expires;
1370
		xfrm_state_hold(x);
1371 1372 1373
		hrtimer_start(&x->mtimer,
			      ktime_set(net->xfrm.sysctl_acq_expires, 0),
			      HRTIMER_MODE_REL_SOFT);
1374
		list_add(&x->km.all, &net->xfrm.state_all);
1375
		hlist_add_head_rcu(&x->bydst, net->xfrm.state_bydst + h);
1376
		h = xfrm_src_hash(net, daddr, saddr, family);
1377
		hlist_add_head_rcu(&x->bysrc, net->xfrm.state_bysrc + h);
1378

1379
		net->xfrm.state_num++;
1380

1381
		xfrm_hash_grow_check(net, x->bydst.next != NULL);
1382 1383 1384 1385 1386
	}

	return x;
}

1387
static struct xfrm_state *__xfrm_find_acq_byseq(struct net *net, u32 mark, u32 seq);
L
Linus Torvalds 已提交
1388 1389 1390

int xfrm_state_add(struct xfrm_state *x)
{
1391
	struct net *net = xs_net(x);
1392
	struct xfrm_state *x1, *to_put;
L
Linus Torvalds 已提交
1393 1394
	int family;
	int err;
1395
	u32 mark = x->mark.v & x->mark.m;
1396
	int use_spi = xfrm_id_proto_match(x->id.proto, IPSEC_PROTO_ANY);
L
Linus Torvalds 已提交
1397 1398 1399

	family = x->props.family;

1400 1401
	to_put = NULL;

F
Fan Du 已提交
1402
	spin_lock_bh(&net->xfrm.xfrm_state_lock);
L
Linus Torvalds 已提交
1403

1404
	x1 = __xfrm_state_locate(x, use_spi, family);
L
Linus Torvalds 已提交
1405
	if (x1) {
1406
		to_put = x1;
L
Linus Torvalds 已提交
1407 1408 1409 1410 1411
		x1 = NULL;
		err = -EEXIST;
		goto out;
	}

1412
	if (use_spi && x->km.seq) {
1413
		x1 = __xfrm_find_acq_byseq(net, mark, x->km.seq);
1414
		if (x1 && ((x1->id.proto != x->id.proto) ||
1415
		    !xfrm_addr_equal(&x1->id.daddr, &x->id.daddr, family))) {
1416
			to_put = x1;
L
Linus Torvalds 已提交
1417 1418 1419 1420
			x1 = NULL;
		}
	}

1421
	if (use_spi && !x1)
1422
		x1 = __find_acq_core(net, &x->mark, family, x->props.mode,
1423
				     x->props.reqid, x->if_id, x->id.proto,
1424
				     &x->id.daddr, &x->props.saddr, 0);
L
Linus Torvalds 已提交
1425

1426
	__xfrm_state_bump_genids(x);
L
Linus Torvalds 已提交
1427 1428 1429 1430
	__xfrm_state_insert(x);
	err = 0;

out:
F
Fan Du 已提交
1431
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
L
Linus Torvalds 已提交
1432 1433 1434 1435 1436 1437

	if (x1) {
		xfrm_state_delete(x1);
		xfrm_state_put(x1);
	}

1438 1439 1440
	if (to_put)
		xfrm_state_put(to_put);

L
Linus Torvalds 已提交
1441 1442 1443 1444
	return err;
}
EXPORT_SYMBOL(xfrm_state_add);

1445
#ifdef CONFIG_XFRM_MIGRATE
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
static inline int clone_security(struct xfrm_state *x, struct xfrm_sec_ctx *security)
{
	struct xfrm_user_sec_ctx *uctx;
	int size = sizeof(*uctx) + security->ctx_len;
	int err;

	uctx = kmalloc(size, GFP_KERNEL);
	if (!uctx)
		return -ENOMEM;

	uctx->exttype = XFRMA_SEC_CTX;
	uctx->len = size;
	uctx->ctx_doi = security->ctx_doi;
	uctx->ctx_alg = security->ctx_alg;
	uctx->ctx_len = security->ctx_len;
	memcpy(uctx + 1, security->ctx_str, security->ctx_len);
	err = security_xfrm_state_alloc(x, uctx);
	kfree(uctx);
	if (err)
		return err;

	return 0;
}

1470 1471
static struct xfrm_state *xfrm_state_clone(struct xfrm_state *orig,
					   struct xfrm_encap_tmpl *encap)
1472
{
1473 1474
	struct net *net = xs_net(orig);
	struct xfrm_state *x = xfrm_state_alloc(net);
1475
	if (!x)
H
Herbert Xu 已提交
1476
		goto out;
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487

	memcpy(&x->id, &orig->id, sizeof(x->id));
	memcpy(&x->sel, &orig->sel, sizeof(x->sel));
	memcpy(&x->lft, &orig->lft, sizeof(x->lft));
	x->props.mode = orig->props.mode;
	x->props.replay_window = orig->props.replay_window;
	x->props.reqid = orig->props.reqid;
	x->props.family = orig->props.family;
	x->props.saddr = orig->props.saddr;

	if (orig->aalg) {
1488
		x->aalg = xfrm_algo_auth_clone(orig->aalg);
1489 1490 1491 1492 1493
		if (!x->aalg)
			goto error;
	}
	x->props.aalgo = orig->props.aalgo;

1494 1495
	if (orig->aead) {
		x->aead = xfrm_algo_aead_clone(orig->aead);
1496
		x->geniv = orig->geniv;
1497 1498 1499
		if (!x->aead)
			goto error;
	}
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
	if (orig->ealg) {
		x->ealg = xfrm_algo_clone(orig->ealg);
		if (!x->ealg)
			goto error;
	}
	x->props.ealgo = orig->props.ealgo;

	if (orig->calg) {
		x->calg = xfrm_algo_clone(orig->calg);
		if (!x->calg)
			goto error;
	}
	x->props.calgo = orig->props.calgo;

1514 1515 1516 1517 1518 1519 1520 1521
	if (encap || orig->encap) {
		if (encap)
			x->encap = kmemdup(encap, sizeof(*x->encap),
					GFP_KERNEL);
		else
			x->encap = kmemdup(orig->encap, sizeof(*x->encap),
					GFP_KERNEL);

1522 1523 1524 1525
		if (!x->encap)
			goto error;
	}

1526 1527 1528 1529
	if (orig->security)
		if (clone_security(x, orig->security))
			goto error;

1530 1531 1532 1533 1534 1535 1536
	if (orig->coaddr) {
		x->coaddr = kmemdup(orig->coaddr, sizeof(*x->coaddr),
				    GFP_KERNEL);
		if (!x->coaddr)
			goto error;
	}

1537
	if (orig->replay_esn) {
1538
		if (xfrm_replay_clone(x, orig))
1539 1540 1541
			goto error;
	}

1542
	memcpy(&x->mark, &orig->mark, sizeof(x->mark));
1543
	memcpy(&x->props.smark, &orig->props.smark, sizeof(x->props.smark));
1544

1545
	if (xfrm_init_state(x) < 0)
1546 1547 1548
		goto error;

	x->props.flags = orig->props.flags;
1549
	x->props.extra_flags = orig->props.extra_flags;
1550

1551
	x->if_id = orig->if_id;
1552 1553 1554
	x->tfcpad = orig->tfcpad;
	x->replay_maxdiff = orig->replay_maxdiff;
	x->replay_maxage = orig->replay_maxage;
1555
	memcpy(&x->curlft, &orig->curlft, sizeof(x->curlft));
1556 1557
	x->km.state = orig->km.state;
	x->km.seq = orig->km.seq;
1558 1559
	x->replay = orig->replay;
	x->preplay = orig->preplay;
1560 1561 1562 1563

	return x;

 error:
H
Herbert Xu 已提交
1564 1565
	xfrm_state_put(x);
out:
1566 1567 1568
	return NULL;
}

Y
Yan Yan 已提交
1569 1570
struct xfrm_state *xfrm_migrate_state_find(struct xfrm_migrate *m, struct net *net,
						u32 if_id)
1571 1572
{
	unsigned int h;
1573 1574 1575
	struct xfrm_state *x = NULL;

	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1576 1577

	if (m->reqid) {
F
Fan Du 已提交
1578
		h = xfrm_dst_hash(net, &m->old_daddr, &m->old_saddr,
1579
				  m->reqid, m->old_family);
F
Fan Du 已提交
1580
		hlist_for_each_entry(x, net->xfrm.state_bydst+h, bydst) {
1581 1582 1583 1584 1585
			if (x->props.mode != m->mode ||
			    x->id.proto != m->proto)
				continue;
			if (m->reqid && x->props.reqid != m->reqid)
				continue;
Y
Yan Yan 已提交
1586 1587
			if (if_id != 0 && x->if_id != if_id)
				continue;
1588 1589 1590 1591
			if (!xfrm_addr_equal(&x->id.daddr, &m->old_daddr,
					     m->old_family) ||
			    !xfrm_addr_equal(&x->props.saddr, &m->old_saddr,
					     m->old_family))
1592 1593
				continue;
			xfrm_state_hold(x);
1594
			break;
1595 1596
		}
	} else {
F
Fan Du 已提交
1597
		h = xfrm_src_hash(net, &m->old_daddr, &m->old_saddr,
1598
				  m->old_family);
F
Fan Du 已提交
1599
		hlist_for_each_entry(x, net->xfrm.state_bysrc+h, bysrc) {
1600 1601 1602
			if (x->props.mode != m->mode ||
			    x->id.proto != m->proto)
				continue;
Y
Yan Yan 已提交
1603 1604
			if (if_id != 0 && x->if_id != if_id)
				continue;
1605 1606 1607 1608
			if (!xfrm_addr_equal(&x->id.daddr, &m->old_daddr,
					     m->old_family) ||
			    !xfrm_addr_equal(&x->props.saddr, &m->old_saddr,
					     m->old_family))
1609 1610
				continue;
			xfrm_state_hold(x);
1611
			break;
1612 1613 1614
		}
	}

1615 1616 1617
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);

	return x;
1618 1619 1620
}
EXPORT_SYMBOL(xfrm_migrate_state_find);

1621
struct xfrm_state *xfrm_state_migrate(struct xfrm_state *x,
1622 1623
				      struct xfrm_migrate *m,
				      struct xfrm_encap_tmpl *encap)
1624 1625 1626
{
	struct xfrm_state *xc;

1627
	xc = xfrm_state_clone(x, encap);
1628 1629 1630 1631 1632 1633 1634
	if (!xc)
		return NULL;

	memcpy(&xc->id.daddr, &m->new_daddr, sizeof(xc->id.daddr));
	memcpy(&xc->props.saddr, &m->new_saddr, sizeof(xc->props.saddr));

	/* add state */
1635
	if (xfrm_addr_equal(&x->id.daddr, &m->new_daddr, m->new_family)) {
1636 1637 1638 1639
		/* a care is needed when the destination address of the
		   state is to be updated as it is a part of triplet */
		xfrm_state_insert(xc);
	} else {
1640
		if (xfrm_state_add(xc) < 0)
1641 1642 1643 1644 1645
			goto error;
	}

	return xc;
error:
T
Thomas Egerer 已提交
1646
	xfrm_state_put(xc);
1647 1648 1649 1650 1651
	return NULL;
}
EXPORT_SYMBOL(xfrm_state_migrate);
#endif

L
Linus Torvalds 已提交
1652 1653
int xfrm_state_update(struct xfrm_state *x)
{
1654
	struct xfrm_state *x1, *to_put;
L
Linus Torvalds 已提交
1655
	int err;
1656
	int use_spi = xfrm_id_proto_match(x->id.proto, IPSEC_PROTO_ANY);
F
Fan Du 已提交
1657
	struct net *net = xs_net(x);
L
Linus Torvalds 已提交
1658

1659 1660
	to_put = NULL;

F
Fan Du 已提交
1661
	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1662
	x1 = __xfrm_state_locate(x, use_spi, x->props.family);
L
Linus Torvalds 已提交
1663 1664 1665 1666 1667 1668

	err = -ESRCH;
	if (!x1)
		goto out;

	if (xfrm_state_kern(x1)) {
1669
		to_put = x1;
L
Linus Torvalds 已提交
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
		err = -EEXIST;
		goto out;
	}

	if (x1->km.state == XFRM_STATE_ACQ) {
		__xfrm_state_insert(x);
		x = NULL;
	}
	err = 0;

out:
F
Fan Du 已提交
1681
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
L
Linus Torvalds 已提交
1682

1683 1684 1685
	if (to_put)
		xfrm_state_put(to_put);

L
Linus Torvalds 已提交
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
	if (err)
		return err;

	if (!x) {
		xfrm_state_delete(x1);
		xfrm_state_put(x1);
		return 0;
	}

	err = -EINVAL;
	spin_lock_bh(&x1->lock);
	if (likely(x1->km.state == XFRM_STATE_VALID)) {
1698 1699
		if (x->encap && x1->encap &&
		    x->encap->encap_type == x1->encap->encap_type)
L
Linus Torvalds 已提交
1700
			memcpy(x1->encap, x->encap, sizeof(*x1->encap));
1701 1702 1703
		else if (x->encap || x1->encap)
			goto fail;

1704 1705 1706 1707 1708
		if (x->coaddr && x1->coaddr) {
			memcpy(x1->coaddr, x->coaddr, sizeof(*x1->coaddr));
		}
		if (!use_spi && memcmp(&x1->sel, &x->sel, sizeof(x1->sel)))
			memcpy(&x1->sel, &x->sel, sizeof(x1->sel));
L
Linus Torvalds 已提交
1709 1710 1711
		memcpy(&x1->lft, &x->lft, sizeof(x1->lft));
		x1->km.dying = 0;

1712 1713
		hrtimer_start(&x1->mtimer, ktime_set(1, 0),
			      HRTIMER_MODE_REL_SOFT);
L
Linus Torvalds 已提交
1714 1715 1716
		if (x1->curlft.use_time)
			xfrm_state_check_expire(x1);

1717
		if (x->props.smark.m || x->props.smark.v || x->if_id) {
1718 1719
			spin_lock_bh(&net->xfrm.xfrm_state_lock);

1720 1721 1722 1723 1724
			if (x->props.smark.m || x->props.smark.v)
				x1->props.smark = x->props.smark;

			if (x->if_id)
				x1->if_id = x->if_id;
1725 1726 1727 1728 1729

			__xfrm_state_bump_genids(x1);
			spin_unlock_bh(&net->xfrm.xfrm_state_lock);
		}

L
Linus Torvalds 已提交
1730
		err = 0;
1731 1732
		x->km.state = XFRM_STATE_DEAD;
		__xfrm_state_put(x);
L
Linus Torvalds 已提交
1733
	}
1734 1735

fail:
L
Linus Torvalds 已提交
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
	spin_unlock_bh(&x1->lock);

	xfrm_state_put(x1);

	return err;
}
EXPORT_SYMBOL(xfrm_state_update);

int xfrm_state_check_expire(struct xfrm_state *x)
{
	if (!x->curlft.use_time)
1747
		x->curlft.use_time = ktime_get_real_seconds();
L
Linus Torvalds 已提交
1748 1749 1750

	if (x->curlft.bytes >= x->lft.hard_byte_limit ||
	    x->curlft.packets >= x->lft.hard_packet_limit) {
1751
		x->km.state = XFRM_STATE_EXPIRED;
1752
		hrtimer_start(&x->mtimer, 0, HRTIMER_MODE_REL_SOFT);
L
Linus Torvalds 已提交
1753 1754 1755 1756 1757
		return -EINVAL;
	}

	if (!x->km.dying &&
	    (x->curlft.bytes >= x->lft.soft_byte_limit ||
1758 1759
	     x->curlft.packets >= x->lft.soft_packet_limit)) {
		x->km.dying = 1;
1760
		km_state_expired(x, 0, 0);
1761
	}
L
Linus Torvalds 已提交
1762 1763 1764 1765 1766
	return 0;
}
EXPORT_SYMBOL(xfrm_state_check_expire);

struct xfrm_state *
1767
xfrm_state_lookup(struct net *net, u32 mark, const xfrm_address_t *daddr, __be32 spi,
1768
		  u8 proto, unsigned short family)
L
Linus Torvalds 已提交
1769 1770 1771
{
	struct xfrm_state *x;

1772
	rcu_read_lock();
1773
	x = __xfrm_state_lookup(net, mark, daddr, spi, proto, family);
1774
	rcu_read_unlock();
L
Linus Torvalds 已提交
1775 1776 1777 1778 1779
	return x;
}
EXPORT_SYMBOL(xfrm_state_lookup);

struct xfrm_state *
1780
xfrm_state_lookup_byaddr(struct net *net, u32 mark,
1781
			 const xfrm_address_t *daddr, const xfrm_address_t *saddr,
1782 1783 1784 1785
			 u8 proto, unsigned short family)
{
	struct xfrm_state *x;

F
Fan Du 已提交
1786
	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1787
	x = __xfrm_state_lookup_byaddr(net, mark, daddr, saddr, proto, family);
F
Fan Du 已提交
1788
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1789 1790 1791 1792 1793
	return x;
}
EXPORT_SYMBOL(xfrm_state_lookup_byaddr);

struct xfrm_state *
1794
xfrm_find_acq(struct net *net, const struct xfrm_mark *mark, u8 mode, u32 reqid,
1795
	      u32 if_id, u8 proto, const xfrm_address_t *daddr,
1796
	      const xfrm_address_t *saddr, int create, unsigned short family)
L
Linus Torvalds 已提交
1797 1798 1799
{
	struct xfrm_state *x;

F
Fan Du 已提交
1800
	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1801
	x = __find_acq_core(net, mark, family, mode, reqid, if_id, proto, daddr, saddr, create);
F
Fan Du 已提交
1802
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1803

L
Linus Torvalds 已提交
1804 1805 1806 1807
	return x;
}
EXPORT_SYMBOL(xfrm_find_acq);

1808
#ifdef CONFIG_XFRM_SUB_POLICY
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
#if IS_ENABLED(CONFIG_IPV6)
/* distribution counting sort function for xfrm_state and xfrm_tmpl */
static void
__xfrm6_sort(void **dst, void **src, int n,
	     int (*cmp)(const void *p), int maxclass)
{
	int count[XFRM_MAX_DEPTH] = { };
	int class[XFRM_MAX_DEPTH];
	int i;

	for (i = 0; i < n; i++) {
		int c = cmp(src[i]);

		class[i] = c;
		count[c]++;
	}

	for (i = 2; i < maxclass; i++)
		count[i] += count[i - 1];

	for (i = 0; i < n; i++) {
		dst[count[class[i] - 1]++] = src[i];
		src[i] = NULL;
	}
}

/* Rule for xfrm_state:
 *
 * rule 1: select IPsec transport except AH
 * rule 2: select MIPv6 RO or inbound trigger
 * rule 3: select IPsec transport AH
 * rule 4: select IPsec tunnel
 * rule 5: others
 */
static int __xfrm6_state_sort_cmp(const void *p)
{
	const struct xfrm_state *v = p;

	switch (v->props.mode) {
	case XFRM_MODE_TRANSPORT:
		if (v->id.proto != IPPROTO_AH)
			return 1;
		else
			return 3;
#if IS_ENABLED(CONFIG_IPV6_MIP6)
	case XFRM_MODE_ROUTEOPTIMIZATION:
	case XFRM_MODE_IN_TRIGGER:
		return 2;
#endif
	case XFRM_MODE_TUNNEL:
	case XFRM_MODE_BEET:
		return 4;
	}
	return 5;
}

/* Rule for xfrm_tmpl:
 *
 * rule 1: select IPsec transport
 * rule 2: select MIPv6 RO or inbound trigger
 * rule 3: select IPsec tunnel
 * rule 4: others
 */
static int __xfrm6_tmpl_sort_cmp(const void *p)
{
	const struct xfrm_tmpl *v = p;

	switch (v->mode) {
	case XFRM_MODE_TRANSPORT:
		return 1;
#if IS_ENABLED(CONFIG_IPV6_MIP6)
	case XFRM_MODE_ROUTEOPTIMIZATION:
	case XFRM_MODE_IN_TRIGGER:
		return 2;
#endif
	case XFRM_MODE_TUNNEL:
	case XFRM_MODE_BEET:
		return 3;
	}
	return 4;
}
#else
static inline int __xfrm6_state_sort_cmp(const void *p) { return 5; }
static inline int __xfrm6_tmpl_sort_cmp(const void *p) { return 4; }

static inline void
__xfrm6_sort(void **dst, void **src, int n,
	     int (*cmp)(const void *p), int maxclass)
{
	int i;

	for (i = 0; i < n; i++)
		dst[i] = src[i];
}
#endif /* CONFIG_IPV6 */

void
1906
xfrm_tmpl_sort(struct xfrm_tmpl **dst, struct xfrm_tmpl **src, int n,
1907
	       unsigned short family)
1908
{
1909
	int i;
1910

1911 1912 1913
	if (family == AF_INET6)
		__xfrm6_sort((void **)dst, (void **)src, n,
			     __xfrm6_tmpl_sort_cmp, 5);
1914 1915 1916
	else
		for (i = 0; i < n; i++)
			dst[i] = src[i];
1917 1918
}

1919
void
1920 1921 1922
xfrm_state_sort(struct xfrm_state **dst, struct xfrm_state **src, int n,
		unsigned short family)
{
1923
	int i;
F
Fan Du 已提交
1924

1925 1926 1927
	if (family == AF_INET6)
		__xfrm6_sort((void **)dst, (void **)src, n,
			     __xfrm6_state_sort_cmp, 6);
1928 1929 1930
	else
		for (i = 0; i < n; i++)
			dst[i] = src[i];
1931 1932 1933
}
#endif

L
Linus Torvalds 已提交
1934 1935
/* Silly enough, but I'm lazy to build resolution list */

1936
static struct xfrm_state *__xfrm_find_acq_byseq(struct net *net, u32 mark, u32 seq)
L
Linus Torvalds 已提交
1937 1938 1939
{
	int i;

1940
	for (i = 0; i <= net->xfrm.state_hmask; i++) {
1941 1942
		struct xfrm_state *x;

1943
		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
1944
			if (x->km.seq == seq &&
J
Jamal Hadi Salim 已提交
1945
			    (mark & x->mark.m) == x->mark.v &&
1946
			    x->km.state == XFRM_STATE_ACQ) {
L
Linus Torvalds 已提交
1947 1948 1949 1950 1951 1952 1953 1954
				xfrm_state_hold(x);
				return x;
			}
		}
	}
	return NULL;
}

1955
struct xfrm_state *xfrm_find_acq_byseq(struct net *net, u32 mark, u32 seq)
L
Linus Torvalds 已提交
1956 1957 1958
{
	struct xfrm_state *x;

F
Fan Du 已提交
1959
	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1960
	x = __xfrm_find_acq_byseq(net, mark, seq);
F
Fan Du 已提交
1961
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
L
Linus Torvalds 已提交
1962 1963 1964 1965 1966 1967 1968
	return x;
}
EXPORT_SYMBOL(xfrm_find_acq_byseq);

u32 xfrm_get_acqseq(void)
{
	u32 res;
1969 1970 1971 1972 1973
	static atomic_t acqseq;

	do {
		res = atomic_inc_return(&acqseq);
	} while (!res);
L
Linus Torvalds 已提交
1974 1975 1976 1977 1978

	return res;
}
EXPORT_SYMBOL(xfrm_get_acqseq);

1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
int verify_spi_info(u8 proto, u32 min, u32 max)
{
	switch (proto) {
	case IPPROTO_AH:
	case IPPROTO_ESP:
		break;

	case IPPROTO_COMP:
		/* IPCOMP spi is 16-bits. */
		if (max >= 0x10000)
			return -EINVAL;
		break;

	default:
		return -EINVAL;
	}

	if (min > max)
		return -EINVAL;

	return 0;
}
EXPORT_SYMBOL(verify_spi_info);

2003
int xfrm_alloc_spi(struct xfrm_state *x, u32 low, u32 high)
L
Linus Torvalds 已提交
2004
{
2005
	struct net *net = xs_net(x);
2006
	unsigned int h;
L
Linus Torvalds 已提交
2007
	struct xfrm_state *x0;
2008 2009 2010
	int err = -ENOENT;
	__be32 minspi = htonl(low);
	__be32 maxspi = htonl(high);
2011
	__be32 newspi = 0;
2012
	u32 mark = x->mark.v & x->mark.m;
L
Linus Torvalds 已提交
2013

2014 2015 2016 2017 2018
	spin_lock_bh(&x->lock);
	if (x->km.state == XFRM_STATE_DEAD)
		goto unlock;

	err = 0;
L
Linus Torvalds 已提交
2019
	if (x->id.spi)
2020 2021 2022
		goto unlock;

	err = -ENOENT;
L
Linus Torvalds 已提交
2023 2024

	if (minspi == maxspi) {
2025
		x0 = xfrm_state_lookup(net, mark, &x->id.daddr, minspi, x->id.proto, x->props.family);
L
Linus Torvalds 已提交
2026 2027
		if (x0) {
			xfrm_state_put(x0);
2028
			goto unlock;
L
Linus Torvalds 已提交
2029
		}
2030
		newspi = minspi;
L
Linus Torvalds 已提交
2031 2032
	} else {
		u32 spi = 0;
2033
		for (h = 0; h < high-low+1; h++) {
2034
			spi = low + prandom_u32()%(high-low+1);
2035
			x0 = xfrm_state_lookup(net, mark, &x->id.daddr, htonl(spi), x->id.proto, x->props.family);
L
Linus Torvalds 已提交
2036
			if (x0 == NULL) {
2037
				newspi = htonl(spi);
L
Linus Torvalds 已提交
2038 2039 2040 2041 2042
				break;
			}
			xfrm_state_put(x0);
		}
	}
2043
	if (newspi) {
F
Fan Du 已提交
2044
		spin_lock_bh(&net->xfrm.xfrm_state_lock);
2045
		x->id.spi = newspi;
2046
		h = xfrm_spi_hash(net, &x->id.daddr, x->id.spi, x->id.proto, x->props.family);
2047
		hlist_add_head_rcu(&x->byspi, net->xfrm.state_byspi + h);
F
Fan Du 已提交
2048
		spin_unlock_bh(&net->xfrm.xfrm_state_lock);
2049 2050

		err = 0;
L
Linus Torvalds 已提交
2051
	}
2052 2053 2054 2055 2056

unlock:
	spin_unlock_bh(&x->lock);

	return err;
L
Linus Torvalds 已提交
2057 2058 2059
}
EXPORT_SYMBOL(xfrm_alloc_spi);

2060
static bool __xfrm_state_filter_match(struct xfrm_state *x,
2061
				      struct xfrm_address_filter *filter)
2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
{
	if (filter) {
		if ((filter->family == AF_INET ||
		     filter->family == AF_INET6) &&
		    x->props.family != filter->family)
			return false;

		return addr_match(&x->props.saddr, &filter->saddr,
				  filter->splen) &&
		       addr_match(&x->id.daddr, &filter->daddr,
				  filter->dplen);
	}
	return true;
}

2077
int xfrm_state_walk(struct net *net, struct xfrm_state_walk *walk,
2078
		    int (*func)(struct xfrm_state *, int, void*),
L
Linus Torvalds 已提交
2079 2080
		    void *data)
{
H
Herbert Xu 已提交
2081 2082
	struct xfrm_state *state;
	struct xfrm_state_walk *x;
L
Linus Torvalds 已提交
2083 2084
	int err = 0;

H
Herbert Xu 已提交
2085
	if (walk->seq != 0 && list_empty(&walk->all))
2086 2087
		return 0;

F
Fan Du 已提交
2088
	spin_lock_bh(&net->xfrm.xfrm_state_lock);
H
Herbert Xu 已提交
2089
	if (list_empty(&walk->all))
2090
		x = list_first_entry(&net->xfrm.state_all, struct xfrm_state_walk, all);
H
Herbert Xu 已提交
2091
	else
2092
		x = list_first_entry(&walk->all, struct xfrm_state_walk, all);
2093
	list_for_each_entry_from(x, &net->xfrm.state_all, all) {
H
Herbert Xu 已提交
2094
		if (x->state == XFRM_STATE_DEAD)
2095
			continue;
H
Herbert Xu 已提交
2096 2097
		state = container_of(x, struct xfrm_state, km);
		if (!xfrm_id_proto_match(state->id.proto, walk->proto))
2098
			continue;
2099 2100
		if (!__xfrm_state_filter_match(state, walk->filter))
			continue;
H
Herbert Xu 已提交
2101 2102 2103 2104
		err = func(state, walk->seq, data);
		if (err) {
			list_move_tail(&walk->all, &x->all);
			goto out;
L
Linus Torvalds 已提交
2105
		}
H
Herbert Xu 已提交
2106
		walk->seq++;
L
Linus Torvalds 已提交
2107
	}
H
Herbert Xu 已提交
2108
	if (walk->seq == 0) {
L
Linus Torvalds 已提交
2109 2110 2111
		err = -ENOENT;
		goto out;
	}
H
Herbert Xu 已提交
2112
	list_del_init(&walk->all);
L
Linus Torvalds 已提交
2113
out:
F
Fan Du 已提交
2114
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
L
Linus Torvalds 已提交
2115 2116 2117 2118
	return err;
}
EXPORT_SYMBOL(xfrm_state_walk);

2119
void xfrm_state_walk_init(struct xfrm_state_walk *walk, u8 proto,
2120
			  struct xfrm_address_filter *filter)
H
Herbert Xu 已提交
2121
{
H
Herbert Xu 已提交
2122
	INIT_LIST_HEAD(&walk->all);
H
Herbert Xu 已提交
2123
	walk->proto = proto;
H
Herbert Xu 已提交
2124 2125
	walk->state = XFRM_STATE_DEAD;
	walk->seq = 0;
2126
	walk->filter = filter;
H
Herbert Xu 已提交
2127 2128 2129
}
EXPORT_SYMBOL(xfrm_state_walk_init);

F
Fan Du 已提交
2130
void xfrm_state_walk_done(struct xfrm_state_walk *walk, struct net *net)
2131
{
2132 2133
	kfree(walk->filter);

H
Herbert Xu 已提交
2134
	if (list_empty(&walk->all))
H
Herbert Xu 已提交
2135 2136
		return;

F
Fan Du 已提交
2137
	spin_lock_bh(&net->xfrm.xfrm_state_lock);
H
Herbert Xu 已提交
2138
	list_del(&walk->all);
F
Fan Du 已提交
2139
	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
2140 2141 2142
}
EXPORT_SYMBOL(xfrm_state_walk_done);

2143
static void xfrm_replay_timer_handler(struct timer_list *t)
2144
{
2145
	struct xfrm_state *x = from_timer(x, t, rtimer);
2146 2147 2148

	spin_lock(&x->lock);

J
Jamal Hadi Salim 已提交
2149
	if (x->km.state == XFRM_STATE_VALID) {
2150
		if (xfrm_aevent_is_on(xs_net(x)))
2151
			x->repl->notify(x, XFRM_REPLAY_TIMEOUT);
J
Jamal Hadi Salim 已提交
2152 2153 2154
		else
			x->xflags |= XFRM_TIME_DEFER;
	}
2155 2156 2157 2158

	spin_unlock(&x->lock);
}

2159
static LIST_HEAD(xfrm_km_list);
L
Linus Torvalds 已提交
2160

2161
void km_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
L
Linus Torvalds 已提交
2162 2163 2164
{
	struct xfrm_mgr *km;

2165 2166
	rcu_read_lock();
	list_for_each_entry_rcu(km, &xfrm_km_list, list)
2167 2168
		if (km->notify_policy)
			km->notify_policy(xp, dir, c);
2169
	rcu_read_unlock();
2170
}
L
Linus Torvalds 已提交
2171

2172
void km_state_notify(struct xfrm_state *x, const struct km_event *c)
2173 2174
{
	struct xfrm_mgr *km;
2175 2176
	rcu_read_lock();
	list_for_each_entry_rcu(km, &xfrm_km_list, list)
2177 2178
		if (km->notify)
			km->notify(x, c);
2179
	rcu_read_unlock();
2180 2181 2182 2183 2184
}

EXPORT_SYMBOL(km_policy_notify);
EXPORT_SYMBOL(km_state_notify);

2185
void km_state_expired(struct xfrm_state *x, int hard, u32 portid)
2186 2187 2188
{
	struct km_event c;

2189
	c.data.hard = hard;
2190
	c.portid = portid;
2191
	c.event = XFRM_MSG_EXPIRE;
2192
	km_state_notify(x, &c);
L
Linus Torvalds 已提交
2193 2194
}

2195
EXPORT_SYMBOL(km_state_expired);
2196 2197 2198 2199
/*
 * We send to all registered managers regardless of failure
 * We are happy with one success
*/
2200
int km_query(struct xfrm_state *x, struct xfrm_tmpl *t, struct xfrm_policy *pol)
L
Linus Torvalds 已提交
2201
{
2202
	int err = -EINVAL, acqret;
L
Linus Torvalds 已提交
2203 2204
	struct xfrm_mgr *km;

2205 2206
	rcu_read_lock();
	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2207
		acqret = km->acquire(x, t, pol);
2208 2209
		if (!acqret)
			err = acqret;
L
Linus Torvalds 已提交
2210
	}
2211
	rcu_read_unlock();
L
Linus Torvalds 已提交
2212 2213
	return err;
}
2214
EXPORT_SYMBOL(km_query);
L
Linus Torvalds 已提交
2215

2216
int km_new_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr, __be16 sport)
L
Linus Torvalds 已提交
2217 2218 2219 2220
{
	int err = -EINVAL;
	struct xfrm_mgr *km;

2221 2222
	rcu_read_lock();
	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
L
Linus Torvalds 已提交
2223 2224 2225 2226 2227
		if (km->new_mapping)
			err = km->new_mapping(x, ipaddr, sport);
		if (!err)
			break;
	}
2228
	rcu_read_unlock();
L
Linus Torvalds 已提交
2229 2230 2231 2232
	return err;
}
EXPORT_SYMBOL(km_new_mapping);

2233
void km_policy_expired(struct xfrm_policy *pol, int dir, int hard, u32 portid)
L
Linus Torvalds 已提交
2234
{
2235
	struct km_event c;
L
Linus Torvalds 已提交
2236

2237
	c.data.hard = hard;
2238
	c.portid = portid;
2239
	c.event = XFRM_MSG_POLEXPIRE;
2240
	km_policy_notify(pol, dir, &c);
L
Linus Torvalds 已提交
2241
}
2242
EXPORT_SYMBOL(km_policy_expired);
L
Linus Torvalds 已提交
2243

2244
#ifdef CONFIG_XFRM_MIGRATE
2245 2246
int km_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
	       const struct xfrm_migrate *m, int num_migrate,
2247 2248
	       const struct xfrm_kmaddress *k,
	       const struct xfrm_encap_tmpl *encap)
2249 2250 2251 2252 2253
{
	int err = -EINVAL;
	int ret;
	struct xfrm_mgr *km;

2254 2255
	rcu_read_lock();
	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2256
		if (km->migrate) {
2257 2258
			ret = km->migrate(sel, dir, type, m, num_migrate, k,
					  encap);
2259 2260 2261 2262
			if (!ret)
				err = ret;
		}
	}
2263
	rcu_read_unlock();
2264 2265 2266
	return err;
}
EXPORT_SYMBOL(km_migrate);
2267
#endif
2268

2269
int km_report(struct net *net, u8 proto, struct xfrm_selector *sel, xfrm_address_t *addr)
2270 2271 2272 2273 2274
{
	int err = -EINVAL;
	int ret;
	struct xfrm_mgr *km;

2275 2276
	rcu_read_lock();
	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2277
		if (km->report) {
2278
			ret = km->report(net, proto, sel, addr);
2279 2280 2281 2282
			if (!ret)
				err = ret;
		}
	}
2283
	rcu_read_unlock();
2284 2285 2286 2287
	return err;
}
EXPORT_SYMBOL(km_report);

2288
static bool km_is_alive(const struct km_event *c)
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
{
	struct xfrm_mgr *km;
	bool is_alive = false;

	rcu_read_lock();
	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
		if (km->is_alive && km->is_alive(c)) {
			is_alive = true;
			break;
		}
	}
	rcu_read_unlock();

	return is_alive;
}

2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
#if IS_ENABLED(CONFIG_XFRM_USER_COMPAT)
static DEFINE_SPINLOCK(xfrm_translator_lock);
static struct xfrm_translator __rcu *xfrm_translator;

struct xfrm_translator *xfrm_get_translator(void)
{
	struct xfrm_translator *xtr;

	rcu_read_lock();
	xtr = rcu_dereference(xfrm_translator);
	if (unlikely(!xtr))
		goto out;
	if (!try_module_get(xtr->owner))
		xtr = NULL;
out:
	rcu_read_unlock();
	return xtr;
}
EXPORT_SYMBOL_GPL(xfrm_get_translator);

void xfrm_put_translator(struct xfrm_translator *xtr)
{
	module_put(xtr->owner);
}
EXPORT_SYMBOL_GPL(xfrm_put_translator);

int xfrm_register_translator(struct xfrm_translator *xtr)
{
	int err = 0;

	spin_lock_bh(&xfrm_translator_lock);
	if (unlikely(xfrm_translator != NULL))
		err = -EEXIST;
	else
		rcu_assign_pointer(xfrm_translator, xtr);
	spin_unlock_bh(&xfrm_translator_lock);

	return err;
}
EXPORT_SYMBOL_GPL(xfrm_register_translator);

int xfrm_unregister_translator(struct xfrm_translator *xtr)
{
	int err = 0;

	spin_lock_bh(&xfrm_translator_lock);
	if (likely(xfrm_translator != NULL)) {
		if (rcu_access_pointer(xfrm_translator) != xtr)
			err = -EINVAL;
		else
			RCU_INIT_POINTER(xfrm_translator, NULL);
	}
	spin_unlock_bh(&xfrm_translator_lock);
	synchronize_rcu();

	return err;
}
EXPORT_SYMBOL_GPL(xfrm_unregister_translator);
#endif

2365
int xfrm_user_policy(struct sock *sk, int optname, sockptr_t optval, int optlen)
L
Linus Torvalds 已提交
2366 2367 2368 2369 2370 2371
{
	int err;
	u8 *data;
	struct xfrm_mgr *km;
	struct xfrm_policy *pol = NULL;

2372
	if (sockptr_is_null(optval) && !optlen) {
2373 2374 2375 2376 2377 2378
		xfrm_sk_policy_insert(sk, XFRM_POLICY_IN, NULL);
		xfrm_sk_policy_insert(sk, XFRM_POLICY_OUT, NULL);
		__sk_dst_reset(sk);
		return 0;
	}

L
Linus Torvalds 已提交
2379 2380 2381
	if (optlen <= 0 || optlen > PAGE_SIZE)
		return -EMSGSIZE;

2382
	data = memdup_sockptr(optval, optlen);
G
Geliang Tang 已提交
2383 2384
	if (IS_ERR(data))
		return PTR_ERR(data);
L
Linus Torvalds 已提交
2385

2386 2387 2388
	if (in_compat_syscall()) {
		struct xfrm_translator *xtr = xfrm_get_translator();

2389 2390
		if (!xtr) {
			kfree(data);
2391
			return -EOPNOTSUPP;
2392
		}
2393 2394 2395 2396 2397 2398 2399 2400 2401

		err = xtr->xlate_user_policy_sockptr(&data, optlen);
		xfrm_put_translator(xtr);
		if (err) {
			kfree(data);
			return err;
		}
	}

L
Linus Torvalds 已提交
2402
	err = -EINVAL;
2403 2404
	rcu_read_lock();
	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2405
		pol = km->compile_policy(sk, optname, data,
L
Linus Torvalds 已提交
2406 2407 2408 2409
					 optlen, &err);
		if (err >= 0)
			break;
	}
2410
	rcu_read_unlock();
L
Linus Torvalds 已提交
2411 2412 2413 2414

	if (err >= 0) {
		xfrm_sk_policy_insert(sk, err, pol);
		xfrm_pol_put(pol);
2415
		__sk_dst_reset(sk);
L
Linus Torvalds 已提交
2416 2417 2418 2419 2420 2421 2422 2423
		err = 0;
	}

	kfree(data);
	return err;
}
EXPORT_SYMBOL(xfrm_user_policy);

2424 2425
static DEFINE_SPINLOCK(xfrm_km_lock);

L
Linus Torvalds 已提交
2426 2427
int xfrm_register_km(struct xfrm_mgr *km)
{
2428 2429 2430
	spin_lock_bh(&xfrm_km_lock);
	list_add_tail_rcu(&km->list, &xfrm_km_list);
	spin_unlock_bh(&xfrm_km_lock);
L
Linus Torvalds 已提交
2431 2432 2433 2434 2435 2436
	return 0;
}
EXPORT_SYMBOL(xfrm_register_km);

int xfrm_unregister_km(struct xfrm_mgr *km)
{
2437 2438 2439 2440
	spin_lock_bh(&xfrm_km_lock);
	list_del_rcu(&km->list);
	spin_unlock_bh(&xfrm_km_lock);
	synchronize_rcu();
L
Linus Torvalds 已提交
2441 2442 2443 2444 2445 2446 2447
	return 0;
}
EXPORT_SYMBOL(xfrm_unregister_km);

int xfrm_state_register_afinfo(struct xfrm_state_afinfo *afinfo)
{
	int err = 0;
2448 2449

	if (WARN_ON(afinfo->family >= NPROTO))
L
Linus Torvalds 已提交
2450
		return -EAFNOSUPPORT;
2451

2452
	spin_lock_bh(&xfrm_state_afinfo_lock);
L
Linus Torvalds 已提交
2453
	if (unlikely(xfrm_state_afinfo[afinfo->family] != NULL))
2454
		err = -EEXIST;
2455
	else
2456 2457
		rcu_assign_pointer(xfrm_state_afinfo[afinfo->family], afinfo);
	spin_unlock_bh(&xfrm_state_afinfo_lock);
L
Linus Torvalds 已提交
2458 2459 2460 2461 2462 2463
	return err;
}
EXPORT_SYMBOL(xfrm_state_register_afinfo);

int xfrm_state_unregister_afinfo(struct xfrm_state_afinfo *afinfo)
{
2464 2465 2466
	int err = 0, family = afinfo->family;

	if (WARN_ON(family >= NPROTO))
L
Linus Torvalds 已提交
2467
		return -EAFNOSUPPORT;
2468

2469
	spin_lock_bh(&xfrm_state_afinfo_lock);
L
Linus Torvalds 已提交
2470
	if (likely(xfrm_state_afinfo[afinfo->family] != NULL)) {
2471
		if (rcu_access_pointer(xfrm_state_afinfo[family]) != afinfo)
L
Linus Torvalds 已提交
2472
			err = -EINVAL;
2473
		else
2474
			RCU_INIT_POINTER(xfrm_state_afinfo[afinfo->family], NULL);
L
Linus Torvalds 已提交
2475
	}
2476 2477
	spin_unlock_bh(&xfrm_state_afinfo_lock);
	synchronize_rcu();
L
Linus Torvalds 已提交
2478 2479 2480 2481
	return err;
}
EXPORT_SYMBOL(xfrm_state_unregister_afinfo);

2482 2483 2484 2485 2486 2487 2488
struct xfrm_state_afinfo *xfrm_state_afinfo_get_rcu(unsigned int family)
{
	if (unlikely(family >= NPROTO))
		return NULL;

	return rcu_dereference(xfrm_state_afinfo[family]);
}
2489
EXPORT_SYMBOL_GPL(xfrm_state_afinfo_get_rcu);
2490

2491
struct xfrm_state_afinfo *xfrm_state_get_afinfo(unsigned int family)
L
Linus Torvalds 已提交
2492 2493 2494 2495
{
	struct xfrm_state_afinfo *afinfo;
	if (unlikely(family >= NPROTO))
		return NULL;
2496 2497
	rcu_read_lock();
	afinfo = rcu_dereference(xfrm_state_afinfo[family]);
2498
	if (unlikely(!afinfo))
2499
		rcu_read_unlock();
L
Linus Torvalds 已提交
2500 2501 2502
	return afinfo;
}

2503 2504 2505 2506 2507 2508
void xfrm_flush_gc(void)
{
	flush_work(&xfrm_state_gc_work);
}
EXPORT_SYMBOL(xfrm_flush_gc);

L
Linus Torvalds 已提交
2509 2510 2511 2512 2513 2514 2515 2516 2517
/* Temporarily located here until net/xfrm/xfrm_tunnel.c is created */
void xfrm_state_delete_tunnel(struct xfrm_state *x)
{
	if (x->tunnel) {
		struct xfrm_state *t = x->tunnel;

		if (atomic_read(&t->tunnel_users) == 2)
			xfrm_state_delete(t);
		atomic_dec(&t->tunnel_users);
2518
		xfrm_state_put_sync(t);
L
Linus Torvalds 已提交
2519 2520 2521 2522 2523
		x->tunnel = NULL;
	}
}
EXPORT_SYMBOL(xfrm_state_delete_tunnel);

2524
u32 xfrm_state_mtu(struct xfrm_state *x, int mtu)
L
Linus Torvalds 已提交
2525
{
2526
	const struct xfrm_type *type = READ_ONCE(x->type);
2527 2528 2529 2530 2531 2532 2533 2534 2535
	struct crypto_aead *aead;
	u32 blksize, net_adj = 0;

	if (x->km.state != XFRM_STATE_VALID ||
	    !type || type->proto != IPPROTO_ESP)
		return mtu - x->props.header_len;

	aead = x->data;
	blksize = ALIGN(crypto_aead_blocksize(aead), 4);
L
Linus Torvalds 已提交
2536

2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550
	switch (x->props.mode) {
	case XFRM_MODE_TRANSPORT:
	case XFRM_MODE_BEET:
		if (x->props.family == AF_INET)
			net_adj = sizeof(struct iphdr);
		else if (x->props.family == AF_INET6)
			net_adj = sizeof(struct ipv6hdr);
		break;
	case XFRM_MODE_TUNNEL:
		break;
	default:
		WARN_ON_ONCE(1);
		break;
	}
2551

2552 2553
	return ((mtu - x->props.header_len - crypto_aead_authsize(aead) -
		 net_adj) & ~(blksize - 1)) + net_adj - 2;
L
Linus Torvalds 已提交
2554
}
2555
EXPORT_SYMBOL_GPL(xfrm_state_mtu);
L
Linus Torvalds 已提交
2556

2557
int __xfrm_init_state(struct xfrm_state *x, bool init_replay, bool offload)
H
Herbert Xu 已提交
2558
{
2559 2560
	const struct xfrm_mode *inner_mode;
	const struct xfrm_mode *outer_mode;
2561
	int family = x->props.family;
H
Herbert Xu 已提交
2562 2563
	int err;

2564 2565 2566
	if (family == AF_INET &&
	    xs_net(x)->ipv4.sysctl_ip_no_pmtu_disc)
		x->props.flags |= XFRM_STATE_NOPMTUDISC;
2567 2568

	err = -EPROTONOSUPPORT;
2569

2570 2571 2572 2573 2574 2575
	if (x->sel.family != AF_UNSPEC) {
		inner_mode = xfrm_get_mode(x->props.mode, x->sel.family);
		if (inner_mode == NULL)
			goto error;

		if (!(inner_mode->flags & XFRM_MODE_FLAG_TUNNEL) &&
F
Florian Westphal 已提交
2576
		    family != x->sel.family)
2577 2578
			goto error;

2579
		x->inner_mode = *inner_mode;
2580
	} else {
F
Florian Westphal 已提交
2581
		const struct xfrm_mode *inner_mode_iaf;
2582
		int iafamily = AF_INET;
2583

2584
		inner_mode = xfrm_get_mode(x->props.mode, x->props.family);
2585 2586 2587
		if (inner_mode == NULL)
			goto error;

F
Florian Westphal 已提交
2588
		if (!(inner_mode->flags & XFRM_MODE_FLAG_TUNNEL))
2589
			goto error;
F
Florian Westphal 已提交
2590

2591
		x->inner_mode = *inner_mode;
2592

2593 2594
		if (x->props.family == AF_INET)
			iafamily = AF_INET6;
2595

2596 2597 2598
		inner_mode_iaf = xfrm_get_mode(x->props.mode, iafamily);
		if (inner_mode_iaf) {
			if (inner_mode_iaf->flags & XFRM_MODE_FLAG_TUNNEL)
2599
				x->inner_mode_iaf = *inner_mode_iaf;
2600 2601
		}
	}
2602

2603
	x->type = xfrm_get_type(x->id.proto, family);
H
Herbert Xu 已提交
2604 2605 2606
	if (x->type == NULL)
		goto error;

2607
	x->type_offload = xfrm_get_type_offload(x->id.proto, family, offload);
2608

H
Herbert Xu 已提交
2609 2610 2611 2612
	err = x->type->init_state(x);
	if (err)
		goto error;

2613 2614
	outer_mode = xfrm_get_mode(x->props.mode, family);
	if (!outer_mode) {
2615
		err = -EPROTONOSUPPORT;
2616
		goto error;
2617
	}
2618

2619
	x->outer_mode = *outer_mode;
2620 2621 2622 2623 2624 2625
	if (init_replay) {
		err = xfrm_init_replay(x);
		if (err)
			goto error;
	}

H
Herbert Xu 已提交
2626 2627 2628 2629
error:
	return err;
}

2630 2631 2632 2633
EXPORT_SYMBOL(__xfrm_init_state);

int xfrm_init_state(struct xfrm_state *x)
{
2634 2635 2636 2637 2638 2639 2640
	int err;

	err = __xfrm_init_state(x, true, false);
	if (!err)
		x->km.state = XFRM_STATE_VALID;

	return err;
2641 2642
}

H
Herbert Xu 已提交
2643
EXPORT_SYMBOL(xfrm_init_state);
2644

2645
int __net_init xfrm_state_init(struct net *net)
L
Linus Torvalds 已提交
2646
{
2647 2648
	unsigned int sz;

2649 2650 2651 2652
	if (net_eq(net, &init_net))
		xfrm_state_cache = KMEM_CACHE(xfrm_state,
					      SLAB_HWCACHE_ALIGN | SLAB_PANIC);

2653 2654
	INIT_LIST_HEAD(&net->xfrm.state_all);

2655 2656
	sz = sizeof(struct hlist_head) * 8;

2657 2658 2659
	net->xfrm.state_bydst = xfrm_hash_alloc(sz);
	if (!net->xfrm.state_bydst)
		goto out_bydst;
2660 2661 2662
	net->xfrm.state_bysrc = xfrm_hash_alloc(sz);
	if (!net->xfrm.state_bysrc)
		goto out_bysrc;
2663 2664 2665
	net->xfrm.state_byspi = xfrm_hash_alloc(sz);
	if (!net->xfrm.state_byspi)
		goto out_byspi;
2666
	net->xfrm.state_hmask = ((sz / sizeof(struct hlist_head)) - 1);
L
Linus Torvalds 已提交
2667

2668
	net->xfrm.state_num = 0;
2669
	INIT_WORK(&net->xfrm.state_hash_work, xfrm_hash_resize);
F
Fan Du 已提交
2670
	spin_lock_init(&net->xfrm.xfrm_state_lock);
2671
	seqcount_init(&net->xfrm.xfrm_state_hash_generation);
2672
	return 0;
2673

2674 2675
out_byspi:
	xfrm_hash_free(net->xfrm.state_bysrc, sz);
2676 2677
out_bysrc:
	xfrm_hash_free(net->xfrm.state_bydst, sz);
2678 2679
out_bydst:
	return -ENOMEM;
2680 2681 2682 2683
}

void xfrm_state_fini(struct net *net)
{
2684 2685
	unsigned int sz;

2686
	flush_work(&net->xfrm.state_hash_work);
2687
	flush_work(&xfrm_state_gc_work);
C
Cong Wang 已提交
2688
	xfrm_state_flush(net, 0, false, true);
2689

2690
	WARN_ON(!list_empty(&net->xfrm.state_all));
2691

2692
	sz = (net->xfrm.state_hmask + 1) * sizeof(struct hlist_head);
2693 2694
	WARN_ON(!hlist_empty(net->xfrm.state_byspi));
	xfrm_hash_free(net->xfrm.state_byspi, sz);
2695 2696
	WARN_ON(!hlist_empty(net->xfrm.state_bysrc));
	xfrm_hash_free(net->xfrm.state_bysrc, sz);
2697 2698
	WARN_ON(!hlist_empty(net->xfrm.state_bydst));
	xfrm_hash_free(net->xfrm.state_bydst, sz);
L
Linus Torvalds 已提交
2699 2700
}

J
Joy Latten 已提交
2701
#ifdef CONFIG_AUDITSYSCALL
I
Ilpo Järvinen 已提交
2702 2703
static void xfrm_audit_helper_sainfo(struct xfrm_state *x,
				     struct audit_buffer *audit_buf)
J
Joy Latten 已提交
2704
{
P
Paul Moore 已提交
2705 2706 2707 2708
	struct xfrm_sec_ctx *ctx = x->security;
	u32 spi = ntohl(x->id.spi);

	if (ctx)
J
Joy Latten 已提交
2709
		audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
P
Paul Moore 已提交
2710
				 ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
J
Joy Latten 已提交
2711

2712
	switch (x->props.family) {
J
Joy Latten 已提交
2713
	case AF_INET:
H
Harvey Harrison 已提交
2714 2715
		audit_log_format(audit_buf, " src=%pI4 dst=%pI4",
				 &x->props.saddr.a4, &x->id.daddr.a4);
J
Joy Latten 已提交
2716 2717
		break;
	case AF_INET6:
H
Harvey Harrison 已提交
2718
		audit_log_format(audit_buf, " src=%pI6 dst=%pI6",
2719
				 x->props.saddr.a6, x->id.daddr.a6);
J
Joy Latten 已提交
2720 2721
		break;
	}
P
Paul Moore 已提交
2722 2723

	audit_log_format(audit_buf, " spi=%u(0x%x)", spi, spi);
J
Joy Latten 已提交
2724 2725
}

I
Ilpo Järvinen 已提交
2726 2727
static void xfrm_audit_helper_pktinfo(struct sk_buff *skb, u16 family,
				      struct audit_buffer *audit_buf)
P
Paul Moore 已提交
2728
{
2729 2730
	const struct iphdr *iph4;
	const struct ipv6hdr *iph6;
P
Paul Moore 已提交
2731 2732 2733 2734

	switch (family) {
	case AF_INET:
		iph4 = ip_hdr(skb);
H
Harvey Harrison 已提交
2735 2736
		audit_log_format(audit_buf, " src=%pI4 dst=%pI4",
				 &iph4->saddr, &iph4->daddr);
P
Paul Moore 已提交
2737 2738 2739 2740
		break;
	case AF_INET6:
		iph6 = ipv6_hdr(skb);
		audit_log_format(audit_buf,
H
Harvey Harrison 已提交
2741
				 " src=%pI6 dst=%pI6 flowlbl=0x%x%02x%02x",
2742
				 &iph6->saddr, &iph6->daddr,
P
Paul Moore 已提交
2743 2744 2745 2746 2747 2748 2749
				 iph6->flow_lbl[0] & 0x0f,
				 iph6->flow_lbl[1],
				 iph6->flow_lbl[2]);
		break;
	}
}

2750
void xfrm_audit_state_add(struct xfrm_state *x, int result, bool task_valid)
J
Joy Latten 已提交
2751 2752 2753
{
	struct audit_buffer *audit_buf;

P
Paul Moore 已提交
2754
	audit_buf = xfrm_audit_start("SAD-add");
J
Joy Latten 已提交
2755 2756
	if (audit_buf == NULL)
		return;
2757
	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
P
Paul Moore 已提交
2758 2759
	xfrm_audit_helper_sainfo(x, audit_buf);
	audit_log_format(audit_buf, " res=%u", result);
J
Joy Latten 已提交
2760 2761 2762 2763
	audit_log_end(audit_buf);
}
EXPORT_SYMBOL_GPL(xfrm_audit_state_add);

2764
void xfrm_audit_state_delete(struct xfrm_state *x, int result, bool task_valid)
J
Joy Latten 已提交
2765 2766 2767
{
	struct audit_buffer *audit_buf;

P
Paul Moore 已提交
2768
	audit_buf = xfrm_audit_start("SAD-delete");
J
Joy Latten 已提交
2769 2770
	if (audit_buf == NULL)
		return;
2771
	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
P
Paul Moore 已提交
2772 2773
	xfrm_audit_helper_sainfo(x, audit_buf);
	audit_log_format(audit_buf, " res=%u", result);
J
Joy Latten 已提交
2774 2775 2776
	audit_log_end(audit_buf);
}
EXPORT_SYMBOL_GPL(xfrm_audit_state_delete);
P
Paul Moore 已提交
2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795

void xfrm_audit_state_replay_overflow(struct xfrm_state *x,
				      struct sk_buff *skb)
{
	struct audit_buffer *audit_buf;
	u32 spi;

	audit_buf = xfrm_audit_start("SA-replay-overflow");
	if (audit_buf == NULL)
		return;
	xfrm_audit_helper_pktinfo(skb, x->props.family, audit_buf);
	/* don't record the sequence number because it's inherent in this kind
	 * of audit message */
	spi = ntohl(x->id.spi);
	audit_log_format(audit_buf, " spi=%u(0x%x)", spi, spi);
	audit_log_end(audit_buf);
}
EXPORT_SYMBOL_GPL(xfrm_audit_state_replay_overflow);

2796
void xfrm_audit_state_replay(struct xfrm_state *x,
P
Paul Moore 已提交
2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810
			     struct sk_buff *skb, __be32 net_seq)
{
	struct audit_buffer *audit_buf;
	u32 spi;

	audit_buf = xfrm_audit_start("SA-replayed-pkt");
	if (audit_buf == NULL)
		return;
	xfrm_audit_helper_pktinfo(skb, x->props.family, audit_buf);
	spi = ntohl(x->id.spi);
	audit_log_format(audit_buf, " spi=%u(0x%x) seqno=%u",
			 spi, spi, ntohl(net_seq));
	audit_log_end(audit_buf);
}
2811
EXPORT_SYMBOL_GPL(xfrm_audit_state_replay);
P
Paul Moore 已提交
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860

void xfrm_audit_state_notfound_simple(struct sk_buff *skb, u16 family)
{
	struct audit_buffer *audit_buf;

	audit_buf = xfrm_audit_start("SA-notfound");
	if (audit_buf == NULL)
		return;
	xfrm_audit_helper_pktinfo(skb, family, audit_buf);
	audit_log_end(audit_buf);
}
EXPORT_SYMBOL_GPL(xfrm_audit_state_notfound_simple);

void xfrm_audit_state_notfound(struct sk_buff *skb, u16 family,
			       __be32 net_spi, __be32 net_seq)
{
	struct audit_buffer *audit_buf;
	u32 spi;

	audit_buf = xfrm_audit_start("SA-notfound");
	if (audit_buf == NULL)
		return;
	xfrm_audit_helper_pktinfo(skb, family, audit_buf);
	spi = ntohl(net_spi);
	audit_log_format(audit_buf, " spi=%u(0x%x) seqno=%u",
			 spi, spi, ntohl(net_seq));
	audit_log_end(audit_buf);
}
EXPORT_SYMBOL_GPL(xfrm_audit_state_notfound);

void xfrm_audit_state_icvfail(struct xfrm_state *x,
			      struct sk_buff *skb, u8 proto)
{
	struct audit_buffer *audit_buf;
	__be32 net_spi;
	__be32 net_seq;

	audit_buf = xfrm_audit_start("SA-icv-failure");
	if (audit_buf == NULL)
		return;
	xfrm_audit_helper_pktinfo(skb, x->props.family, audit_buf);
	if (xfrm_parse_spi(skb, proto, &net_spi, &net_seq) == 0) {
		u32 spi = ntohl(net_spi);
		audit_log_format(audit_buf, " spi=%u(0x%x) seqno=%u",
				 spi, spi, ntohl(net_seq));
	}
	audit_log_end(audit_buf);
}
EXPORT_SYMBOL_GPL(xfrm_audit_state_icvfail);
J
Joy Latten 已提交
2861
#endif /* CONFIG_AUDITSYSCALL */