xref: /openbmc/linux/net/xfrm/xfrm_user.c (revision 7f877908)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* xfrm_user.c: User interface to configure xfrm engine.
3  *
4  * Copyright (C) 2002 David S. Miller (davem@redhat.com)
5  *
6  * Changes:
7  *	Mitsuru KANDA @USAGI
8  * 	Kazunori MIYAZAWA @USAGI
9  * 	Kunihiro Ishiguro <kunihiro@ipinfusion.com>
10  * 		IPv6 support
11  *
12  */
13 
14 #include <linux/crypto.h>
15 #include <linux/module.h>
16 #include <linux/kernel.h>
17 #include <linux/types.h>
18 #include <linux/slab.h>
19 #include <linux/socket.h>
20 #include <linux/string.h>
21 #include <linux/net.h>
22 #include <linux/skbuff.h>
23 #include <linux/pfkeyv2.h>
24 #include <linux/ipsec.h>
25 #include <linux/init.h>
26 #include <linux/security.h>
27 #include <net/sock.h>
28 #include <net/xfrm.h>
29 #include <net/netlink.h>
30 #include <net/ah.h>
31 #include <linux/uaccess.h>
32 #if IS_ENABLED(CONFIG_IPV6)
33 #include <linux/in6.h>
34 #endif
35 #include <asm/unaligned.h>
36 
37 static int verify_one_alg(struct nlattr **attrs, enum xfrm_attr_type_t type)
38 {
39 	struct nlattr *rt = attrs[type];
40 	struct xfrm_algo *algp;
41 
42 	if (!rt)
43 		return 0;
44 
45 	algp = nla_data(rt);
46 	if (nla_len(rt) < (int)xfrm_alg_len(algp))
47 		return -EINVAL;
48 
49 	switch (type) {
50 	case XFRMA_ALG_AUTH:
51 	case XFRMA_ALG_CRYPT:
52 	case XFRMA_ALG_COMP:
53 		break;
54 
55 	default:
56 		return -EINVAL;
57 	}
58 
59 	algp->alg_name[sizeof(algp->alg_name) - 1] = '\0';
60 	return 0;
61 }
62 
63 static int verify_auth_trunc(struct nlattr **attrs)
64 {
65 	struct nlattr *rt = attrs[XFRMA_ALG_AUTH_TRUNC];
66 	struct xfrm_algo_auth *algp;
67 
68 	if (!rt)
69 		return 0;
70 
71 	algp = nla_data(rt);
72 	if (nla_len(rt) < (int)xfrm_alg_auth_len(algp))
73 		return -EINVAL;
74 
75 	algp->alg_name[sizeof(algp->alg_name) - 1] = '\0';
76 	return 0;
77 }
78 
79 static int verify_aead(struct nlattr **attrs)
80 {
81 	struct nlattr *rt = attrs[XFRMA_ALG_AEAD];
82 	struct xfrm_algo_aead *algp;
83 
84 	if (!rt)
85 		return 0;
86 
87 	algp = nla_data(rt);
88 	if (nla_len(rt) < (int)aead_len(algp))
89 		return -EINVAL;
90 
91 	algp->alg_name[sizeof(algp->alg_name) - 1] = '\0';
92 	return 0;
93 }
94 
95 static void verify_one_addr(struct nlattr **attrs, enum xfrm_attr_type_t type,
96 			   xfrm_address_t **addrp)
97 {
98 	struct nlattr *rt = attrs[type];
99 
100 	if (rt && addrp)
101 		*addrp = nla_data(rt);
102 }
103 
104 static inline int verify_sec_ctx_len(struct nlattr **attrs)
105 {
106 	struct nlattr *rt = attrs[XFRMA_SEC_CTX];
107 	struct xfrm_user_sec_ctx *uctx;
108 
109 	if (!rt)
110 		return 0;
111 
112 	uctx = nla_data(rt);
113 	if (uctx->len != (sizeof(struct xfrm_user_sec_ctx) + uctx->ctx_len))
114 		return -EINVAL;
115 
116 	return 0;
117 }
118 
119 static inline int verify_replay(struct xfrm_usersa_info *p,
120 				struct nlattr **attrs)
121 {
122 	struct nlattr *rt = attrs[XFRMA_REPLAY_ESN_VAL];
123 	struct xfrm_replay_state_esn *rs;
124 
125 	if (!rt)
126 		return (p->flags & XFRM_STATE_ESN) ? -EINVAL : 0;
127 
128 	rs = nla_data(rt);
129 
130 	if (rs->bmp_len > XFRMA_REPLAY_ESN_MAX / sizeof(rs->bmp[0]) / 8)
131 		return -EINVAL;
132 
133 	if (nla_len(rt) < (int)xfrm_replay_state_esn_len(rs) &&
134 	    nla_len(rt) != sizeof(*rs))
135 		return -EINVAL;
136 
137 	/* As only ESP and AH support ESN feature. */
138 	if ((p->id.proto != IPPROTO_ESP) && (p->id.proto != IPPROTO_AH))
139 		return -EINVAL;
140 
141 	if (p->replay_window != 0)
142 		return -EINVAL;
143 
144 	return 0;
145 }
146 
147 static int verify_newsa_info(struct xfrm_usersa_info *p,
148 			     struct nlattr **attrs)
149 {
150 	int err;
151 
152 	err = -EINVAL;
153 	switch (p->family) {
154 	case AF_INET:
155 		break;
156 
157 	case AF_INET6:
158 #if IS_ENABLED(CONFIG_IPV6)
159 		break;
160 #else
161 		err = -EAFNOSUPPORT;
162 		goto out;
163 #endif
164 
165 	default:
166 		goto out;
167 	}
168 
169 	switch (p->sel.family) {
170 	case AF_UNSPEC:
171 		break;
172 
173 	case AF_INET:
174 		if (p->sel.prefixlen_d > 32 || p->sel.prefixlen_s > 32)
175 			goto out;
176 
177 		break;
178 
179 	case AF_INET6:
180 #if IS_ENABLED(CONFIG_IPV6)
181 		if (p->sel.prefixlen_d > 128 || p->sel.prefixlen_s > 128)
182 			goto out;
183 
184 		break;
185 #else
186 		err = -EAFNOSUPPORT;
187 		goto out;
188 #endif
189 
190 	default:
191 		goto out;
192 	}
193 
194 	err = -EINVAL;
195 	switch (p->id.proto) {
196 	case IPPROTO_AH:
197 		if ((!attrs[XFRMA_ALG_AUTH]	&&
198 		     !attrs[XFRMA_ALG_AUTH_TRUNC]) ||
199 		    attrs[XFRMA_ALG_AEAD]	||
200 		    attrs[XFRMA_ALG_CRYPT]	||
201 		    attrs[XFRMA_ALG_COMP]	||
202 		    attrs[XFRMA_TFCPAD])
203 			goto out;
204 		break;
205 
206 	case IPPROTO_ESP:
207 		if (attrs[XFRMA_ALG_COMP])
208 			goto out;
209 		if (!attrs[XFRMA_ALG_AUTH] &&
210 		    !attrs[XFRMA_ALG_AUTH_TRUNC] &&
211 		    !attrs[XFRMA_ALG_CRYPT] &&
212 		    !attrs[XFRMA_ALG_AEAD])
213 			goto out;
214 		if ((attrs[XFRMA_ALG_AUTH] ||
215 		     attrs[XFRMA_ALG_AUTH_TRUNC] ||
216 		     attrs[XFRMA_ALG_CRYPT]) &&
217 		    attrs[XFRMA_ALG_AEAD])
218 			goto out;
219 		if (attrs[XFRMA_TFCPAD] &&
220 		    p->mode != XFRM_MODE_TUNNEL)
221 			goto out;
222 		break;
223 
224 	case IPPROTO_COMP:
225 		if (!attrs[XFRMA_ALG_COMP]	||
226 		    attrs[XFRMA_ALG_AEAD]	||
227 		    attrs[XFRMA_ALG_AUTH]	||
228 		    attrs[XFRMA_ALG_AUTH_TRUNC]	||
229 		    attrs[XFRMA_ALG_CRYPT]	||
230 		    attrs[XFRMA_TFCPAD]		||
231 		    (ntohl(p->id.spi) >= 0x10000))
232 			goto out;
233 		break;
234 
235 #if IS_ENABLED(CONFIG_IPV6)
236 	case IPPROTO_DSTOPTS:
237 	case IPPROTO_ROUTING:
238 		if (attrs[XFRMA_ALG_COMP]	||
239 		    attrs[XFRMA_ALG_AUTH]	||
240 		    attrs[XFRMA_ALG_AUTH_TRUNC]	||
241 		    attrs[XFRMA_ALG_AEAD]	||
242 		    attrs[XFRMA_ALG_CRYPT]	||
243 		    attrs[XFRMA_ENCAP]		||
244 		    attrs[XFRMA_SEC_CTX]	||
245 		    attrs[XFRMA_TFCPAD]		||
246 		    !attrs[XFRMA_COADDR])
247 			goto out;
248 		break;
249 #endif
250 
251 	default:
252 		goto out;
253 	}
254 
255 	if ((err = verify_aead(attrs)))
256 		goto out;
257 	if ((err = verify_auth_trunc(attrs)))
258 		goto out;
259 	if ((err = verify_one_alg(attrs, XFRMA_ALG_AUTH)))
260 		goto out;
261 	if ((err = verify_one_alg(attrs, XFRMA_ALG_CRYPT)))
262 		goto out;
263 	if ((err = verify_one_alg(attrs, XFRMA_ALG_COMP)))
264 		goto out;
265 	if ((err = verify_sec_ctx_len(attrs)))
266 		goto out;
267 	if ((err = verify_replay(p, attrs)))
268 		goto out;
269 
270 	err = -EINVAL;
271 	switch (p->mode) {
272 	case XFRM_MODE_TRANSPORT:
273 	case XFRM_MODE_TUNNEL:
274 	case XFRM_MODE_ROUTEOPTIMIZATION:
275 	case XFRM_MODE_BEET:
276 		break;
277 
278 	default:
279 		goto out;
280 	}
281 
282 	err = 0;
283 
284 out:
285 	return err;
286 }
287 
288 static int attach_one_algo(struct xfrm_algo **algpp, u8 *props,
289 			   struct xfrm_algo_desc *(*get_byname)(const char *, int),
290 			   struct nlattr *rta)
291 {
292 	struct xfrm_algo *p, *ualg;
293 	struct xfrm_algo_desc *algo;
294 
295 	if (!rta)
296 		return 0;
297 
298 	ualg = nla_data(rta);
299 
300 	algo = get_byname(ualg->alg_name, 1);
301 	if (!algo)
302 		return -ENOSYS;
303 	*props = algo->desc.sadb_alg_id;
304 
305 	p = kmemdup(ualg, xfrm_alg_len(ualg), GFP_KERNEL);
306 	if (!p)
307 		return -ENOMEM;
308 
309 	strcpy(p->alg_name, algo->name);
310 	*algpp = p;
311 	return 0;
312 }
313 
314 static int attach_crypt(struct xfrm_state *x, struct nlattr *rta)
315 {
316 	struct xfrm_algo *p, *ualg;
317 	struct xfrm_algo_desc *algo;
318 
319 	if (!rta)
320 		return 0;
321 
322 	ualg = nla_data(rta);
323 
324 	algo = xfrm_ealg_get_byname(ualg->alg_name, 1);
325 	if (!algo)
326 		return -ENOSYS;
327 	x->props.ealgo = algo->desc.sadb_alg_id;
328 
329 	p = kmemdup(ualg, xfrm_alg_len(ualg), GFP_KERNEL);
330 	if (!p)
331 		return -ENOMEM;
332 
333 	strcpy(p->alg_name, algo->name);
334 	x->ealg = p;
335 	x->geniv = algo->uinfo.encr.geniv;
336 	return 0;
337 }
338 
339 static int attach_auth(struct xfrm_algo_auth **algpp, u8 *props,
340 		       struct nlattr *rta)
341 {
342 	struct xfrm_algo *ualg;
343 	struct xfrm_algo_auth *p;
344 	struct xfrm_algo_desc *algo;
345 
346 	if (!rta)
347 		return 0;
348 
349 	ualg = nla_data(rta);
350 
351 	algo = xfrm_aalg_get_byname(ualg->alg_name, 1);
352 	if (!algo)
353 		return -ENOSYS;
354 	*props = algo->desc.sadb_alg_id;
355 
356 	p = kmalloc(sizeof(*p) + (ualg->alg_key_len + 7) / 8, GFP_KERNEL);
357 	if (!p)
358 		return -ENOMEM;
359 
360 	strcpy(p->alg_name, algo->name);
361 	p->alg_key_len = ualg->alg_key_len;
362 	p->alg_trunc_len = algo->uinfo.auth.icv_truncbits;
363 	memcpy(p->alg_key, ualg->alg_key, (ualg->alg_key_len + 7) / 8);
364 
365 	*algpp = p;
366 	return 0;
367 }
368 
369 static int attach_auth_trunc(struct xfrm_algo_auth **algpp, u8 *props,
370 			     struct nlattr *rta)
371 {
372 	struct xfrm_algo_auth *p, *ualg;
373 	struct xfrm_algo_desc *algo;
374 
375 	if (!rta)
376 		return 0;
377 
378 	ualg = nla_data(rta);
379 
380 	algo = xfrm_aalg_get_byname(ualg->alg_name, 1);
381 	if (!algo)
382 		return -ENOSYS;
383 	if (ualg->alg_trunc_len > algo->uinfo.auth.icv_fullbits)
384 		return -EINVAL;
385 	*props = algo->desc.sadb_alg_id;
386 
387 	p = kmemdup(ualg, xfrm_alg_auth_len(ualg), GFP_KERNEL);
388 	if (!p)
389 		return -ENOMEM;
390 
391 	strcpy(p->alg_name, algo->name);
392 	if (!p->alg_trunc_len)
393 		p->alg_trunc_len = algo->uinfo.auth.icv_truncbits;
394 
395 	*algpp = p;
396 	return 0;
397 }
398 
399 static int attach_aead(struct xfrm_state *x, struct nlattr *rta)
400 {
401 	struct xfrm_algo_aead *p, *ualg;
402 	struct xfrm_algo_desc *algo;
403 
404 	if (!rta)
405 		return 0;
406 
407 	ualg = nla_data(rta);
408 
409 	algo = xfrm_aead_get_byname(ualg->alg_name, ualg->alg_icv_len, 1);
410 	if (!algo)
411 		return -ENOSYS;
412 	x->props.ealgo = algo->desc.sadb_alg_id;
413 
414 	p = kmemdup(ualg, aead_len(ualg), GFP_KERNEL);
415 	if (!p)
416 		return -ENOMEM;
417 
418 	strcpy(p->alg_name, algo->name);
419 	x->aead = p;
420 	x->geniv = algo->uinfo.aead.geniv;
421 	return 0;
422 }
423 
424 static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn,
425 					 struct nlattr *rp)
426 {
427 	struct xfrm_replay_state_esn *up;
428 	unsigned int ulen;
429 
430 	if (!replay_esn || !rp)
431 		return 0;
432 
433 	up = nla_data(rp);
434 	ulen = xfrm_replay_state_esn_len(up);
435 
436 	/* Check the overall length and the internal bitmap length to avoid
437 	 * potential overflow. */
438 	if (nla_len(rp) < (int)ulen ||
439 	    xfrm_replay_state_esn_len(replay_esn) != ulen ||
440 	    replay_esn->bmp_len != up->bmp_len)
441 		return -EINVAL;
442 
443 	if (up->replay_window > up->bmp_len * sizeof(__u32) * 8)
444 		return -EINVAL;
445 
446 	return 0;
447 }
448 
449 static int xfrm_alloc_replay_state_esn(struct xfrm_replay_state_esn **replay_esn,
450 				       struct xfrm_replay_state_esn **preplay_esn,
451 				       struct nlattr *rta)
452 {
453 	struct xfrm_replay_state_esn *p, *pp, *up;
454 	unsigned int klen, ulen;
455 
456 	if (!rta)
457 		return 0;
458 
459 	up = nla_data(rta);
460 	klen = xfrm_replay_state_esn_len(up);
461 	ulen = nla_len(rta) >= (int)klen ? klen : sizeof(*up);
462 
463 	p = kzalloc(klen, GFP_KERNEL);
464 	if (!p)
465 		return -ENOMEM;
466 
467 	pp = kzalloc(klen, GFP_KERNEL);
468 	if (!pp) {
469 		kfree(p);
470 		return -ENOMEM;
471 	}
472 
473 	memcpy(p, up, ulen);
474 	memcpy(pp, up, ulen);
475 
476 	*replay_esn = p;
477 	*preplay_esn = pp;
478 
479 	return 0;
480 }
481 
482 static inline unsigned int xfrm_user_sec_ctx_size(struct xfrm_sec_ctx *xfrm_ctx)
483 {
484 	unsigned int len = 0;
485 
486 	if (xfrm_ctx) {
487 		len += sizeof(struct xfrm_user_sec_ctx);
488 		len += xfrm_ctx->ctx_len;
489 	}
490 	return len;
491 }
492 
493 static void copy_from_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
494 {
495 	memcpy(&x->id, &p->id, sizeof(x->id));
496 	memcpy(&x->sel, &p->sel, sizeof(x->sel));
497 	memcpy(&x->lft, &p->lft, sizeof(x->lft));
498 	x->props.mode = p->mode;
499 	x->props.replay_window = min_t(unsigned int, p->replay_window,
500 					sizeof(x->replay.bitmap) * 8);
501 	x->props.reqid = p->reqid;
502 	x->props.family = p->family;
503 	memcpy(&x->props.saddr, &p->saddr, sizeof(x->props.saddr));
504 	x->props.flags = p->flags;
505 
506 	if (!x->sel.family && !(p->flags & XFRM_STATE_AF_UNSPEC))
507 		x->sel.family = p->family;
508 }
509 
510 /*
511  * someday when pfkey also has support, we could have the code
512  * somehow made shareable and move it to xfrm_state.c - JHS
513  *
514 */
515 static void xfrm_update_ae_params(struct xfrm_state *x, struct nlattr **attrs,
516 				  int update_esn)
517 {
518 	struct nlattr *rp = attrs[XFRMA_REPLAY_VAL];
519 	struct nlattr *re = update_esn ? attrs[XFRMA_REPLAY_ESN_VAL] : NULL;
520 	struct nlattr *lt = attrs[XFRMA_LTIME_VAL];
521 	struct nlattr *et = attrs[XFRMA_ETIMER_THRESH];
522 	struct nlattr *rt = attrs[XFRMA_REPLAY_THRESH];
523 
524 	if (re) {
525 		struct xfrm_replay_state_esn *replay_esn;
526 		replay_esn = nla_data(re);
527 		memcpy(x->replay_esn, replay_esn,
528 		       xfrm_replay_state_esn_len(replay_esn));
529 		memcpy(x->preplay_esn, replay_esn,
530 		       xfrm_replay_state_esn_len(replay_esn));
531 	}
532 
533 	if (rp) {
534 		struct xfrm_replay_state *replay;
535 		replay = nla_data(rp);
536 		memcpy(&x->replay, replay, sizeof(*replay));
537 		memcpy(&x->preplay, replay, sizeof(*replay));
538 	}
539 
540 	if (lt) {
541 		struct xfrm_lifetime_cur *ltime;
542 		ltime = nla_data(lt);
543 		x->curlft.bytes = ltime->bytes;
544 		x->curlft.packets = ltime->packets;
545 		x->curlft.add_time = ltime->add_time;
546 		x->curlft.use_time = ltime->use_time;
547 	}
548 
549 	if (et)
550 		x->replay_maxage = nla_get_u32(et);
551 
552 	if (rt)
553 		x->replay_maxdiff = nla_get_u32(rt);
554 }
555 
556 static void xfrm_smark_init(struct nlattr **attrs, struct xfrm_mark *m)
557 {
558 	if (attrs[XFRMA_SET_MARK]) {
559 		m->v = nla_get_u32(attrs[XFRMA_SET_MARK]);
560 		if (attrs[XFRMA_SET_MARK_MASK])
561 			m->m = nla_get_u32(attrs[XFRMA_SET_MARK_MASK]);
562 		else
563 			m->m = 0xffffffff;
564 	} else {
565 		m->v = m->m = 0;
566 	}
567 }
568 
569 static struct xfrm_state *xfrm_state_construct(struct net *net,
570 					       struct xfrm_usersa_info *p,
571 					       struct nlattr **attrs,
572 					       int *errp)
573 {
574 	struct xfrm_state *x = xfrm_state_alloc(net);
575 	int err = -ENOMEM;
576 
577 	if (!x)
578 		goto error_no_put;
579 
580 	copy_from_user_state(x, p);
581 
582 	if (attrs[XFRMA_SA_EXTRA_FLAGS])
583 		x->props.extra_flags = nla_get_u32(attrs[XFRMA_SA_EXTRA_FLAGS]);
584 
585 	if ((err = attach_aead(x, attrs[XFRMA_ALG_AEAD])))
586 		goto error;
587 	if ((err = attach_auth_trunc(&x->aalg, &x->props.aalgo,
588 				     attrs[XFRMA_ALG_AUTH_TRUNC])))
589 		goto error;
590 	if (!x->props.aalgo) {
591 		if ((err = attach_auth(&x->aalg, &x->props.aalgo,
592 				       attrs[XFRMA_ALG_AUTH])))
593 			goto error;
594 	}
595 	if ((err = attach_crypt(x, attrs[XFRMA_ALG_CRYPT])))
596 		goto error;
597 	if ((err = attach_one_algo(&x->calg, &x->props.calgo,
598 				   xfrm_calg_get_byname,
599 				   attrs[XFRMA_ALG_COMP])))
600 		goto error;
601 
602 	if (attrs[XFRMA_ENCAP]) {
603 		x->encap = kmemdup(nla_data(attrs[XFRMA_ENCAP]),
604 				   sizeof(*x->encap), GFP_KERNEL);
605 		if (x->encap == NULL)
606 			goto error;
607 	}
608 
609 	if (attrs[XFRMA_TFCPAD])
610 		x->tfcpad = nla_get_u32(attrs[XFRMA_TFCPAD]);
611 
612 	if (attrs[XFRMA_COADDR]) {
613 		x->coaddr = kmemdup(nla_data(attrs[XFRMA_COADDR]),
614 				    sizeof(*x->coaddr), GFP_KERNEL);
615 		if (x->coaddr == NULL)
616 			goto error;
617 	}
618 
619 	xfrm_mark_get(attrs, &x->mark);
620 
621 	xfrm_smark_init(attrs, &x->props.smark);
622 
623 	if (attrs[XFRMA_IF_ID])
624 		x->if_id = nla_get_u32(attrs[XFRMA_IF_ID]);
625 
626 	err = __xfrm_init_state(x, false, attrs[XFRMA_OFFLOAD_DEV]);
627 	if (err)
628 		goto error;
629 
630 	if (attrs[XFRMA_SEC_CTX]) {
631 		err = security_xfrm_state_alloc(x,
632 						nla_data(attrs[XFRMA_SEC_CTX]));
633 		if (err)
634 			goto error;
635 	}
636 
637 	if ((err = xfrm_alloc_replay_state_esn(&x->replay_esn, &x->preplay_esn,
638 					       attrs[XFRMA_REPLAY_ESN_VAL])))
639 		goto error;
640 
641 	x->km.seq = p->seq;
642 	x->replay_maxdiff = net->xfrm.sysctl_aevent_rseqth;
643 	/* sysctl_xfrm_aevent_etime is in 100ms units */
644 	x->replay_maxage = (net->xfrm.sysctl_aevent_etime*HZ)/XFRM_AE_ETH_M;
645 
646 	if ((err = xfrm_init_replay(x)))
647 		goto error;
648 
649 	/* override default values from above */
650 	xfrm_update_ae_params(x, attrs, 0);
651 
652 	/* configure the hardware if offload is requested */
653 	if (attrs[XFRMA_OFFLOAD_DEV]) {
654 		err = xfrm_dev_state_add(net, x,
655 					 nla_data(attrs[XFRMA_OFFLOAD_DEV]));
656 		if (err)
657 			goto error;
658 	}
659 
660 	return x;
661 
662 error:
663 	x->km.state = XFRM_STATE_DEAD;
664 	xfrm_state_put(x);
665 error_no_put:
666 	*errp = err;
667 	return NULL;
668 }
669 
670 static int xfrm_add_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
671 		struct nlattr **attrs)
672 {
673 	struct net *net = sock_net(skb->sk);
674 	struct xfrm_usersa_info *p = nlmsg_data(nlh);
675 	struct xfrm_state *x;
676 	int err;
677 	struct km_event c;
678 
679 	err = verify_newsa_info(p, attrs);
680 	if (err)
681 		return err;
682 
683 	x = xfrm_state_construct(net, p, attrs, &err);
684 	if (!x)
685 		return err;
686 
687 	xfrm_state_hold(x);
688 	if (nlh->nlmsg_type == XFRM_MSG_NEWSA)
689 		err = xfrm_state_add(x);
690 	else
691 		err = xfrm_state_update(x);
692 
693 	xfrm_audit_state_add(x, err ? 0 : 1, true);
694 
695 	if (err < 0) {
696 		x->km.state = XFRM_STATE_DEAD;
697 		xfrm_dev_state_delete(x);
698 		__xfrm_state_put(x);
699 		goto out;
700 	}
701 
702 	if (x->km.state == XFRM_STATE_VOID)
703 		x->km.state = XFRM_STATE_VALID;
704 
705 	c.seq = nlh->nlmsg_seq;
706 	c.portid = nlh->nlmsg_pid;
707 	c.event = nlh->nlmsg_type;
708 
709 	km_state_notify(x, &c);
710 out:
711 	xfrm_state_put(x);
712 	return err;
713 }
714 
715 static struct xfrm_state *xfrm_user_state_lookup(struct net *net,
716 						 struct xfrm_usersa_id *p,
717 						 struct nlattr **attrs,
718 						 int *errp)
719 {
720 	struct xfrm_state *x = NULL;
721 	struct xfrm_mark m;
722 	int err;
723 	u32 mark = xfrm_mark_get(attrs, &m);
724 
725 	if (xfrm_id_proto_match(p->proto, IPSEC_PROTO_ANY)) {
726 		err = -ESRCH;
727 		x = xfrm_state_lookup(net, mark, &p->daddr, p->spi, p->proto, p->family);
728 	} else {
729 		xfrm_address_t *saddr = NULL;
730 
731 		verify_one_addr(attrs, XFRMA_SRCADDR, &saddr);
732 		if (!saddr) {
733 			err = -EINVAL;
734 			goto out;
735 		}
736 
737 		err = -ESRCH;
738 		x = xfrm_state_lookup_byaddr(net, mark,
739 					     &p->daddr, saddr,
740 					     p->proto, p->family);
741 	}
742 
743  out:
744 	if (!x && errp)
745 		*errp = err;
746 	return x;
747 }
748 
749 static int xfrm_del_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
750 		struct nlattr **attrs)
751 {
752 	struct net *net = sock_net(skb->sk);
753 	struct xfrm_state *x;
754 	int err = -ESRCH;
755 	struct km_event c;
756 	struct xfrm_usersa_id *p = nlmsg_data(nlh);
757 
758 	x = xfrm_user_state_lookup(net, p, attrs, &err);
759 	if (x == NULL)
760 		return err;
761 
762 	if ((err = security_xfrm_state_delete(x)) != 0)
763 		goto out;
764 
765 	if (xfrm_state_kern(x)) {
766 		err = -EPERM;
767 		goto out;
768 	}
769 
770 	err = xfrm_state_delete(x);
771 
772 	if (err < 0)
773 		goto out;
774 
775 	c.seq = nlh->nlmsg_seq;
776 	c.portid = nlh->nlmsg_pid;
777 	c.event = nlh->nlmsg_type;
778 	km_state_notify(x, &c);
779 
780 out:
781 	xfrm_audit_state_delete(x, err ? 0 : 1, true);
782 	xfrm_state_put(x);
783 	return err;
784 }
785 
786 static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
787 {
788 	memset(p, 0, sizeof(*p));
789 	memcpy(&p->id, &x->id, sizeof(p->id));
790 	memcpy(&p->sel, &x->sel, sizeof(p->sel));
791 	memcpy(&p->lft, &x->lft, sizeof(p->lft));
792 	memcpy(&p->curlft, &x->curlft, sizeof(p->curlft));
793 	put_unaligned(x->stats.replay_window, &p->stats.replay_window);
794 	put_unaligned(x->stats.replay, &p->stats.replay);
795 	put_unaligned(x->stats.integrity_failed, &p->stats.integrity_failed);
796 	memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr));
797 	p->mode = x->props.mode;
798 	p->replay_window = x->props.replay_window;
799 	p->reqid = x->props.reqid;
800 	p->family = x->props.family;
801 	p->flags = x->props.flags;
802 	p->seq = x->km.seq;
803 }
804 
805 struct xfrm_dump_info {
806 	struct sk_buff *in_skb;
807 	struct sk_buff *out_skb;
808 	u32 nlmsg_seq;
809 	u16 nlmsg_flags;
810 };
811 
812 static int copy_sec_ctx(struct xfrm_sec_ctx *s, struct sk_buff *skb)
813 {
814 	struct xfrm_user_sec_ctx *uctx;
815 	struct nlattr *attr;
816 	int ctx_size = sizeof(*uctx) + s->ctx_len;
817 
818 	attr = nla_reserve(skb, XFRMA_SEC_CTX, ctx_size);
819 	if (attr == NULL)
820 		return -EMSGSIZE;
821 
822 	uctx = nla_data(attr);
823 	uctx->exttype = XFRMA_SEC_CTX;
824 	uctx->len = ctx_size;
825 	uctx->ctx_doi = s->ctx_doi;
826 	uctx->ctx_alg = s->ctx_alg;
827 	uctx->ctx_len = s->ctx_len;
828 	memcpy(uctx + 1, s->ctx_str, s->ctx_len);
829 
830 	return 0;
831 }
832 
833 static int copy_user_offload(struct xfrm_state_offload *xso, struct sk_buff *skb)
834 {
835 	struct xfrm_user_offload *xuo;
836 	struct nlattr *attr;
837 
838 	attr = nla_reserve(skb, XFRMA_OFFLOAD_DEV, sizeof(*xuo));
839 	if (attr == NULL)
840 		return -EMSGSIZE;
841 
842 	xuo = nla_data(attr);
843 	memset(xuo, 0, sizeof(*xuo));
844 	xuo->ifindex = xso->dev->ifindex;
845 	xuo->flags = xso->flags;
846 
847 	return 0;
848 }
849 
850 static int copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb)
851 {
852 	struct xfrm_algo *algo;
853 	struct nlattr *nla;
854 
855 	nla = nla_reserve(skb, XFRMA_ALG_AUTH,
856 			  sizeof(*algo) + (auth->alg_key_len + 7) / 8);
857 	if (!nla)
858 		return -EMSGSIZE;
859 
860 	algo = nla_data(nla);
861 	strncpy(algo->alg_name, auth->alg_name, sizeof(algo->alg_name));
862 	memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8);
863 	algo->alg_key_len = auth->alg_key_len;
864 
865 	return 0;
866 }
867 
868 static int xfrm_smark_put(struct sk_buff *skb, struct xfrm_mark *m)
869 {
870 	int ret = 0;
871 
872 	if (m->v | m->m) {
873 		ret = nla_put_u32(skb, XFRMA_SET_MARK, m->v);
874 		if (!ret)
875 			ret = nla_put_u32(skb, XFRMA_SET_MARK_MASK, m->m);
876 	}
877 	return ret;
878 }
879 
880 /* Don't change this without updating xfrm_sa_len! */
881 static int copy_to_user_state_extra(struct xfrm_state *x,
882 				    struct xfrm_usersa_info *p,
883 				    struct sk_buff *skb)
884 {
885 	int ret = 0;
886 
887 	copy_to_user_state(x, p);
888 
889 	if (x->props.extra_flags) {
890 		ret = nla_put_u32(skb, XFRMA_SA_EXTRA_FLAGS,
891 				  x->props.extra_flags);
892 		if (ret)
893 			goto out;
894 	}
895 
896 	if (x->coaddr) {
897 		ret = nla_put(skb, XFRMA_COADDR, sizeof(*x->coaddr), x->coaddr);
898 		if (ret)
899 			goto out;
900 	}
901 	if (x->lastused) {
902 		ret = nla_put_u64_64bit(skb, XFRMA_LASTUSED, x->lastused,
903 					XFRMA_PAD);
904 		if (ret)
905 			goto out;
906 	}
907 	if (x->aead) {
908 		ret = nla_put(skb, XFRMA_ALG_AEAD, aead_len(x->aead), x->aead);
909 		if (ret)
910 			goto out;
911 	}
912 	if (x->aalg) {
913 		ret = copy_to_user_auth(x->aalg, skb);
914 		if (!ret)
915 			ret = nla_put(skb, XFRMA_ALG_AUTH_TRUNC,
916 				      xfrm_alg_auth_len(x->aalg), x->aalg);
917 		if (ret)
918 			goto out;
919 	}
920 	if (x->ealg) {
921 		ret = nla_put(skb, XFRMA_ALG_CRYPT, xfrm_alg_len(x->ealg), x->ealg);
922 		if (ret)
923 			goto out;
924 	}
925 	if (x->calg) {
926 		ret = nla_put(skb, XFRMA_ALG_COMP, sizeof(*(x->calg)), x->calg);
927 		if (ret)
928 			goto out;
929 	}
930 	if (x->encap) {
931 		ret = nla_put(skb, XFRMA_ENCAP, sizeof(*x->encap), x->encap);
932 		if (ret)
933 			goto out;
934 	}
935 	if (x->tfcpad) {
936 		ret = nla_put_u32(skb, XFRMA_TFCPAD, x->tfcpad);
937 		if (ret)
938 			goto out;
939 	}
940 	ret = xfrm_mark_put(skb, &x->mark);
941 	if (ret)
942 		goto out;
943 
944 	ret = xfrm_smark_put(skb, &x->props.smark);
945 	if (ret)
946 		goto out;
947 
948 	if (x->replay_esn)
949 		ret = nla_put(skb, XFRMA_REPLAY_ESN_VAL,
950 			      xfrm_replay_state_esn_len(x->replay_esn),
951 			      x->replay_esn);
952 	else
953 		ret = nla_put(skb, XFRMA_REPLAY_VAL, sizeof(x->replay),
954 			      &x->replay);
955 	if (ret)
956 		goto out;
957 	if(x->xso.dev)
958 		ret = copy_user_offload(&x->xso, skb);
959 	if (ret)
960 		goto out;
961 	if (x->if_id) {
962 		ret = nla_put_u32(skb, XFRMA_IF_ID, x->if_id);
963 		if (ret)
964 			goto out;
965 	}
966 	if (x->security)
967 		ret = copy_sec_ctx(x->security, skb);
968 out:
969 	return ret;
970 }
971 
972 static int dump_one_state(struct xfrm_state *x, int count, void *ptr)
973 {
974 	struct xfrm_dump_info *sp = ptr;
975 	struct sk_buff *in_skb = sp->in_skb;
976 	struct sk_buff *skb = sp->out_skb;
977 	struct xfrm_usersa_info *p;
978 	struct nlmsghdr *nlh;
979 	int err;
980 
981 	nlh = nlmsg_put(skb, NETLINK_CB(in_skb).portid, sp->nlmsg_seq,
982 			XFRM_MSG_NEWSA, sizeof(*p), sp->nlmsg_flags);
983 	if (nlh == NULL)
984 		return -EMSGSIZE;
985 
986 	p = nlmsg_data(nlh);
987 
988 	err = copy_to_user_state_extra(x, p, skb);
989 	if (err) {
990 		nlmsg_cancel(skb, nlh);
991 		return err;
992 	}
993 	nlmsg_end(skb, nlh);
994 	return 0;
995 }
996 
997 static int xfrm_dump_sa_done(struct netlink_callback *cb)
998 {
999 	struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1];
1000 	struct sock *sk = cb->skb->sk;
1001 	struct net *net = sock_net(sk);
1002 
1003 	if (cb->args[0])
1004 		xfrm_state_walk_done(walk, net);
1005 	return 0;
1006 }
1007 
1008 static const struct nla_policy xfrma_policy[XFRMA_MAX+1];
1009 static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb)
1010 {
1011 	struct net *net = sock_net(skb->sk);
1012 	struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1];
1013 	struct xfrm_dump_info info;
1014 
1015 	BUILD_BUG_ON(sizeof(struct xfrm_state_walk) >
1016 		     sizeof(cb->args) - sizeof(cb->args[0]));
1017 
1018 	info.in_skb = cb->skb;
1019 	info.out_skb = skb;
1020 	info.nlmsg_seq = cb->nlh->nlmsg_seq;
1021 	info.nlmsg_flags = NLM_F_MULTI;
1022 
1023 	if (!cb->args[0]) {
1024 		struct nlattr *attrs[XFRMA_MAX+1];
1025 		struct xfrm_address_filter *filter = NULL;
1026 		u8 proto = 0;
1027 		int err;
1028 
1029 		err = nlmsg_parse_deprecated(cb->nlh, 0, attrs, XFRMA_MAX,
1030 					     xfrma_policy, cb->extack);
1031 		if (err < 0)
1032 			return err;
1033 
1034 		if (attrs[XFRMA_ADDRESS_FILTER]) {
1035 			filter = kmemdup(nla_data(attrs[XFRMA_ADDRESS_FILTER]),
1036 					 sizeof(*filter), GFP_KERNEL);
1037 			if (filter == NULL)
1038 				return -ENOMEM;
1039 		}
1040 
1041 		if (attrs[XFRMA_PROTO])
1042 			proto = nla_get_u8(attrs[XFRMA_PROTO]);
1043 
1044 		xfrm_state_walk_init(walk, proto, filter);
1045 		cb->args[0] = 1;
1046 	}
1047 
1048 	(void) xfrm_state_walk(net, walk, dump_one_state, &info);
1049 
1050 	return skb->len;
1051 }
1052 
1053 static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb,
1054 					  struct xfrm_state *x, u32 seq)
1055 {
1056 	struct xfrm_dump_info info;
1057 	struct sk_buff *skb;
1058 	int err;
1059 
1060 	skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
1061 	if (!skb)
1062 		return ERR_PTR(-ENOMEM);
1063 
1064 	info.in_skb = in_skb;
1065 	info.out_skb = skb;
1066 	info.nlmsg_seq = seq;
1067 	info.nlmsg_flags = 0;
1068 
1069 	err = dump_one_state(x, 0, &info);
1070 	if (err) {
1071 		kfree_skb(skb);
1072 		return ERR_PTR(err);
1073 	}
1074 
1075 	return skb;
1076 }
1077 
1078 /* A wrapper for nlmsg_multicast() checking that nlsk is still available.
1079  * Must be called with RCU read lock.
1080  */
1081 static inline int xfrm_nlmsg_multicast(struct net *net, struct sk_buff *skb,
1082 				       u32 pid, unsigned int group)
1083 {
1084 	struct sock *nlsk = rcu_dereference(net->xfrm.nlsk);
1085 
1086 	if (!nlsk) {
1087 		kfree_skb(skb);
1088 		return -EPIPE;
1089 	}
1090 
1091 	return nlmsg_multicast(nlsk, skb, pid, group, GFP_ATOMIC);
1092 }
1093 
1094 static inline unsigned int xfrm_spdinfo_msgsize(void)
1095 {
1096 	return NLMSG_ALIGN(4)
1097 	       + nla_total_size(sizeof(struct xfrmu_spdinfo))
1098 	       + nla_total_size(sizeof(struct xfrmu_spdhinfo))
1099 	       + nla_total_size(sizeof(struct xfrmu_spdhthresh))
1100 	       + nla_total_size(sizeof(struct xfrmu_spdhthresh));
1101 }
1102 
1103 static int build_spdinfo(struct sk_buff *skb, struct net *net,
1104 			 u32 portid, u32 seq, u32 flags)
1105 {
1106 	struct xfrmk_spdinfo si;
1107 	struct xfrmu_spdinfo spc;
1108 	struct xfrmu_spdhinfo sph;
1109 	struct xfrmu_spdhthresh spt4, spt6;
1110 	struct nlmsghdr *nlh;
1111 	int err;
1112 	u32 *f;
1113 	unsigned lseq;
1114 
1115 	nlh = nlmsg_put(skb, portid, seq, XFRM_MSG_NEWSPDINFO, sizeof(u32), 0);
1116 	if (nlh == NULL) /* shouldn't really happen ... */
1117 		return -EMSGSIZE;
1118 
1119 	f = nlmsg_data(nlh);
1120 	*f = flags;
1121 	xfrm_spd_getinfo(net, &si);
1122 	spc.incnt = si.incnt;
1123 	spc.outcnt = si.outcnt;
1124 	spc.fwdcnt = si.fwdcnt;
1125 	spc.inscnt = si.inscnt;
1126 	spc.outscnt = si.outscnt;
1127 	spc.fwdscnt = si.fwdscnt;
1128 	sph.spdhcnt = si.spdhcnt;
1129 	sph.spdhmcnt = si.spdhmcnt;
1130 
1131 	do {
1132 		lseq = read_seqbegin(&net->xfrm.policy_hthresh.lock);
1133 
1134 		spt4.lbits = net->xfrm.policy_hthresh.lbits4;
1135 		spt4.rbits = net->xfrm.policy_hthresh.rbits4;
1136 		spt6.lbits = net->xfrm.policy_hthresh.lbits6;
1137 		spt6.rbits = net->xfrm.policy_hthresh.rbits6;
1138 	} while (read_seqretry(&net->xfrm.policy_hthresh.lock, lseq));
1139 
1140 	err = nla_put(skb, XFRMA_SPD_INFO, sizeof(spc), &spc);
1141 	if (!err)
1142 		err = nla_put(skb, XFRMA_SPD_HINFO, sizeof(sph), &sph);
1143 	if (!err)
1144 		err = nla_put(skb, XFRMA_SPD_IPV4_HTHRESH, sizeof(spt4), &spt4);
1145 	if (!err)
1146 		err = nla_put(skb, XFRMA_SPD_IPV6_HTHRESH, sizeof(spt6), &spt6);
1147 	if (err) {
1148 		nlmsg_cancel(skb, nlh);
1149 		return err;
1150 	}
1151 
1152 	nlmsg_end(skb, nlh);
1153 	return 0;
1154 }
1155 
1156 static int xfrm_set_spdinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
1157 			    struct nlattr **attrs)
1158 {
1159 	struct net *net = sock_net(skb->sk);
1160 	struct xfrmu_spdhthresh *thresh4 = NULL;
1161 	struct xfrmu_spdhthresh *thresh6 = NULL;
1162 
1163 	/* selector prefixlen thresholds to hash policies */
1164 	if (attrs[XFRMA_SPD_IPV4_HTHRESH]) {
1165 		struct nlattr *rta = attrs[XFRMA_SPD_IPV4_HTHRESH];
1166 
1167 		if (nla_len(rta) < sizeof(*thresh4))
1168 			return -EINVAL;
1169 		thresh4 = nla_data(rta);
1170 		if (thresh4->lbits > 32 || thresh4->rbits > 32)
1171 			return -EINVAL;
1172 	}
1173 	if (attrs[XFRMA_SPD_IPV6_HTHRESH]) {
1174 		struct nlattr *rta = attrs[XFRMA_SPD_IPV6_HTHRESH];
1175 
1176 		if (nla_len(rta) < sizeof(*thresh6))
1177 			return -EINVAL;
1178 		thresh6 = nla_data(rta);
1179 		if (thresh6->lbits > 128 || thresh6->rbits > 128)
1180 			return -EINVAL;
1181 	}
1182 
1183 	if (thresh4 || thresh6) {
1184 		write_seqlock(&net->xfrm.policy_hthresh.lock);
1185 		if (thresh4) {
1186 			net->xfrm.policy_hthresh.lbits4 = thresh4->lbits;
1187 			net->xfrm.policy_hthresh.rbits4 = thresh4->rbits;
1188 		}
1189 		if (thresh6) {
1190 			net->xfrm.policy_hthresh.lbits6 = thresh6->lbits;
1191 			net->xfrm.policy_hthresh.rbits6 = thresh6->rbits;
1192 		}
1193 		write_sequnlock(&net->xfrm.policy_hthresh.lock);
1194 
1195 		xfrm_policy_hash_rebuild(net);
1196 	}
1197 
1198 	return 0;
1199 }
1200 
1201 static int xfrm_get_spdinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
1202 		struct nlattr **attrs)
1203 {
1204 	struct net *net = sock_net(skb->sk);
1205 	struct sk_buff *r_skb;
1206 	u32 *flags = nlmsg_data(nlh);
1207 	u32 sportid = NETLINK_CB(skb).portid;
1208 	u32 seq = nlh->nlmsg_seq;
1209 	int err;
1210 
1211 	r_skb = nlmsg_new(xfrm_spdinfo_msgsize(), GFP_ATOMIC);
1212 	if (r_skb == NULL)
1213 		return -ENOMEM;
1214 
1215 	err = build_spdinfo(r_skb, net, sportid, seq, *flags);
1216 	BUG_ON(err < 0);
1217 
1218 	return nlmsg_unicast(net->xfrm.nlsk, r_skb, sportid);
1219 }
1220 
1221 static inline unsigned int xfrm_sadinfo_msgsize(void)
1222 {
1223 	return NLMSG_ALIGN(4)
1224 	       + nla_total_size(sizeof(struct xfrmu_sadhinfo))
1225 	       + nla_total_size(4); /* XFRMA_SAD_CNT */
1226 }
1227 
1228 static int build_sadinfo(struct sk_buff *skb, struct net *net,
1229 			 u32 portid, u32 seq, u32 flags)
1230 {
1231 	struct xfrmk_sadinfo si;
1232 	struct xfrmu_sadhinfo sh;
1233 	struct nlmsghdr *nlh;
1234 	int err;
1235 	u32 *f;
1236 
1237 	nlh = nlmsg_put(skb, portid, seq, XFRM_MSG_NEWSADINFO, sizeof(u32), 0);
1238 	if (nlh == NULL) /* shouldn't really happen ... */
1239 		return -EMSGSIZE;
1240 
1241 	f = nlmsg_data(nlh);
1242 	*f = flags;
1243 	xfrm_sad_getinfo(net, &si);
1244 
1245 	sh.sadhmcnt = si.sadhmcnt;
1246 	sh.sadhcnt = si.sadhcnt;
1247 
1248 	err = nla_put_u32(skb, XFRMA_SAD_CNT, si.sadcnt);
1249 	if (!err)
1250 		err = nla_put(skb, XFRMA_SAD_HINFO, sizeof(sh), &sh);
1251 	if (err) {
1252 		nlmsg_cancel(skb, nlh);
1253 		return err;
1254 	}
1255 
1256 	nlmsg_end(skb, nlh);
1257 	return 0;
1258 }
1259 
1260 static int xfrm_get_sadinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
1261 		struct nlattr **attrs)
1262 {
1263 	struct net *net = sock_net(skb->sk);
1264 	struct sk_buff *r_skb;
1265 	u32 *flags = nlmsg_data(nlh);
1266 	u32 sportid = NETLINK_CB(skb).portid;
1267 	u32 seq = nlh->nlmsg_seq;
1268 	int err;
1269 
1270 	r_skb = nlmsg_new(xfrm_sadinfo_msgsize(), GFP_ATOMIC);
1271 	if (r_skb == NULL)
1272 		return -ENOMEM;
1273 
1274 	err = build_sadinfo(r_skb, net, sportid, seq, *flags);
1275 	BUG_ON(err < 0);
1276 
1277 	return nlmsg_unicast(net->xfrm.nlsk, r_skb, sportid);
1278 }
1279 
1280 static int xfrm_get_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
1281 		struct nlattr **attrs)
1282 {
1283 	struct net *net = sock_net(skb->sk);
1284 	struct xfrm_usersa_id *p = nlmsg_data(nlh);
1285 	struct xfrm_state *x;
1286 	struct sk_buff *resp_skb;
1287 	int err = -ESRCH;
1288 
1289 	x = xfrm_user_state_lookup(net, p, attrs, &err);
1290 	if (x == NULL)
1291 		goto out_noput;
1292 
1293 	resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq);
1294 	if (IS_ERR(resp_skb)) {
1295 		err = PTR_ERR(resp_skb);
1296 	} else {
1297 		err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).portid);
1298 	}
1299 	xfrm_state_put(x);
1300 out_noput:
1301 	return err;
1302 }
1303 
1304 static int xfrm_alloc_userspi(struct sk_buff *skb, struct nlmsghdr *nlh,
1305 		struct nlattr **attrs)
1306 {
1307 	struct net *net = sock_net(skb->sk);
1308 	struct xfrm_state *x;
1309 	struct xfrm_userspi_info *p;
1310 	struct sk_buff *resp_skb;
1311 	xfrm_address_t *daddr;
1312 	int family;
1313 	int err;
1314 	u32 mark;
1315 	struct xfrm_mark m;
1316 	u32 if_id = 0;
1317 
1318 	p = nlmsg_data(nlh);
1319 	err = verify_spi_info(p->info.id.proto, p->min, p->max);
1320 	if (err)
1321 		goto out_noput;
1322 
1323 	family = p->info.family;
1324 	daddr = &p->info.id.daddr;
1325 
1326 	x = NULL;
1327 
1328 	mark = xfrm_mark_get(attrs, &m);
1329 
1330 	if (attrs[XFRMA_IF_ID])
1331 		if_id = nla_get_u32(attrs[XFRMA_IF_ID]);
1332 
1333 	if (p->info.seq) {
1334 		x = xfrm_find_acq_byseq(net, mark, p->info.seq);
1335 		if (x && !xfrm_addr_equal(&x->id.daddr, daddr, family)) {
1336 			xfrm_state_put(x);
1337 			x = NULL;
1338 		}
1339 	}
1340 
1341 	if (!x)
1342 		x = xfrm_find_acq(net, &m, p->info.mode, p->info.reqid,
1343 				  if_id, p->info.id.proto, daddr,
1344 				  &p->info.saddr, 1,
1345 				  family);
1346 	err = -ENOENT;
1347 	if (x == NULL)
1348 		goto out_noput;
1349 
1350 	err = xfrm_alloc_spi(x, p->min, p->max);
1351 	if (err)
1352 		goto out;
1353 
1354 	resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq);
1355 	if (IS_ERR(resp_skb)) {
1356 		err = PTR_ERR(resp_skb);
1357 		goto out;
1358 	}
1359 
1360 	err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).portid);
1361 
1362 out:
1363 	xfrm_state_put(x);
1364 out_noput:
1365 	return err;
1366 }
1367 
1368 static int verify_policy_dir(u8 dir)
1369 {
1370 	switch (dir) {
1371 	case XFRM_POLICY_IN:
1372 	case XFRM_POLICY_OUT:
1373 	case XFRM_POLICY_FWD:
1374 		break;
1375 
1376 	default:
1377 		return -EINVAL;
1378 	}
1379 
1380 	return 0;
1381 }
1382 
1383 static int verify_policy_type(u8 type)
1384 {
1385 	switch (type) {
1386 	case XFRM_POLICY_TYPE_MAIN:
1387 #ifdef CONFIG_XFRM_SUB_POLICY
1388 	case XFRM_POLICY_TYPE_SUB:
1389 #endif
1390 		break;
1391 
1392 	default:
1393 		return -EINVAL;
1394 	}
1395 
1396 	return 0;
1397 }
1398 
1399 static int verify_newpolicy_info(struct xfrm_userpolicy_info *p)
1400 {
1401 	int ret;
1402 
1403 	switch (p->share) {
1404 	case XFRM_SHARE_ANY:
1405 	case XFRM_SHARE_SESSION:
1406 	case XFRM_SHARE_USER:
1407 	case XFRM_SHARE_UNIQUE:
1408 		break;
1409 
1410 	default:
1411 		return -EINVAL;
1412 	}
1413 
1414 	switch (p->action) {
1415 	case XFRM_POLICY_ALLOW:
1416 	case XFRM_POLICY_BLOCK:
1417 		break;
1418 
1419 	default:
1420 		return -EINVAL;
1421 	}
1422 
1423 	switch (p->sel.family) {
1424 	case AF_INET:
1425 		if (p->sel.prefixlen_d > 32 || p->sel.prefixlen_s > 32)
1426 			return -EINVAL;
1427 
1428 		break;
1429 
1430 	case AF_INET6:
1431 #if IS_ENABLED(CONFIG_IPV6)
1432 		if (p->sel.prefixlen_d > 128 || p->sel.prefixlen_s > 128)
1433 			return -EINVAL;
1434 
1435 		break;
1436 #else
1437 		return  -EAFNOSUPPORT;
1438 #endif
1439 
1440 	default:
1441 		return -EINVAL;
1442 	}
1443 
1444 	ret = verify_policy_dir(p->dir);
1445 	if (ret)
1446 		return ret;
1447 	if (p->index && (xfrm_policy_id2dir(p->index) != p->dir))
1448 		return -EINVAL;
1449 
1450 	return 0;
1451 }
1452 
1453 static int copy_from_user_sec_ctx(struct xfrm_policy *pol, struct nlattr **attrs)
1454 {
1455 	struct nlattr *rt = attrs[XFRMA_SEC_CTX];
1456 	struct xfrm_user_sec_ctx *uctx;
1457 
1458 	if (!rt)
1459 		return 0;
1460 
1461 	uctx = nla_data(rt);
1462 	return security_xfrm_policy_alloc(&pol->security, uctx, GFP_KERNEL);
1463 }
1464 
1465 static void copy_templates(struct xfrm_policy *xp, struct xfrm_user_tmpl *ut,
1466 			   int nr)
1467 {
1468 	int i;
1469 
1470 	xp->xfrm_nr = nr;
1471 	for (i = 0; i < nr; i++, ut++) {
1472 		struct xfrm_tmpl *t = &xp->xfrm_vec[i];
1473 
1474 		memcpy(&t->id, &ut->id, sizeof(struct xfrm_id));
1475 		memcpy(&t->saddr, &ut->saddr,
1476 		       sizeof(xfrm_address_t));
1477 		t->reqid = ut->reqid;
1478 		t->mode = ut->mode;
1479 		t->share = ut->share;
1480 		t->optional = ut->optional;
1481 		t->aalgos = ut->aalgos;
1482 		t->ealgos = ut->ealgos;
1483 		t->calgos = ut->calgos;
1484 		/* If all masks are ~0, then we allow all algorithms. */
1485 		t->allalgs = !~(t->aalgos & t->ealgos & t->calgos);
1486 		t->encap_family = ut->family;
1487 	}
1488 }
1489 
1490 static int validate_tmpl(int nr, struct xfrm_user_tmpl *ut, u16 family)
1491 {
1492 	u16 prev_family;
1493 	int i;
1494 
1495 	if (nr > XFRM_MAX_DEPTH)
1496 		return -EINVAL;
1497 
1498 	prev_family = family;
1499 
1500 	for (i = 0; i < nr; i++) {
1501 		/* We never validated the ut->family value, so many
1502 		 * applications simply leave it at zero.  The check was
1503 		 * never made and ut->family was ignored because all
1504 		 * templates could be assumed to have the same family as
1505 		 * the policy itself.  Now that we will have ipv4-in-ipv6
1506 		 * and ipv6-in-ipv4 tunnels, this is no longer true.
1507 		 */
1508 		if (!ut[i].family)
1509 			ut[i].family = family;
1510 
1511 		switch (ut[i].mode) {
1512 		case XFRM_MODE_TUNNEL:
1513 		case XFRM_MODE_BEET:
1514 			break;
1515 		default:
1516 			if (ut[i].family != prev_family)
1517 				return -EINVAL;
1518 			break;
1519 		}
1520 		if (ut[i].mode >= XFRM_MODE_MAX)
1521 			return -EINVAL;
1522 
1523 		prev_family = ut[i].family;
1524 
1525 		switch (ut[i].family) {
1526 		case AF_INET:
1527 			break;
1528 #if IS_ENABLED(CONFIG_IPV6)
1529 		case AF_INET6:
1530 			break;
1531 #endif
1532 		default:
1533 			return -EINVAL;
1534 		}
1535 
1536 		if (!xfrm_id_proto_valid(ut[i].id.proto))
1537 			return -EINVAL;
1538 	}
1539 
1540 	return 0;
1541 }
1542 
1543 static int copy_from_user_tmpl(struct xfrm_policy *pol, struct nlattr **attrs)
1544 {
1545 	struct nlattr *rt = attrs[XFRMA_TMPL];
1546 
1547 	if (!rt) {
1548 		pol->xfrm_nr = 0;
1549 	} else {
1550 		struct xfrm_user_tmpl *utmpl = nla_data(rt);
1551 		int nr = nla_len(rt) / sizeof(*utmpl);
1552 		int err;
1553 
1554 		err = validate_tmpl(nr, utmpl, pol->family);
1555 		if (err)
1556 			return err;
1557 
1558 		copy_templates(pol, utmpl, nr);
1559 	}
1560 	return 0;
1561 }
1562 
1563 static int copy_from_user_policy_type(u8 *tp, struct nlattr **attrs)
1564 {
1565 	struct nlattr *rt = attrs[XFRMA_POLICY_TYPE];
1566 	struct xfrm_userpolicy_type *upt;
1567 	u8 type = XFRM_POLICY_TYPE_MAIN;
1568 	int err;
1569 
1570 	if (rt) {
1571 		upt = nla_data(rt);
1572 		type = upt->type;
1573 	}
1574 
1575 	err = verify_policy_type(type);
1576 	if (err)
1577 		return err;
1578 
1579 	*tp = type;
1580 	return 0;
1581 }
1582 
1583 static void copy_from_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p)
1584 {
1585 	xp->priority = p->priority;
1586 	xp->index = p->index;
1587 	memcpy(&xp->selector, &p->sel, sizeof(xp->selector));
1588 	memcpy(&xp->lft, &p->lft, sizeof(xp->lft));
1589 	xp->action = p->action;
1590 	xp->flags = p->flags;
1591 	xp->family = p->sel.family;
1592 	/* XXX xp->share = p->share; */
1593 }
1594 
1595 static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir)
1596 {
1597 	memset(p, 0, sizeof(*p));
1598 	memcpy(&p->sel, &xp->selector, sizeof(p->sel));
1599 	memcpy(&p->lft, &xp->lft, sizeof(p->lft));
1600 	memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft));
1601 	p->priority = xp->priority;
1602 	p->index = xp->index;
1603 	p->sel.family = xp->family;
1604 	p->dir = dir;
1605 	p->action = xp->action;
1606 	p->flags = xp->flags;
1607 	p->share = XFRM_SHARE_ANY; /* XXX xp->share */
1608 }
1609 
1610 static struct xfrm_policy *xfrm_policy_construct(struct net *net, struct xfrm_userpolicy_info *p, struct nlattr **attrs, int *errp)
1611 {
1612 	struct xfrm_policy *xp = xfrm_policy_alloc(net, GFP_KERNEL);
1613 	int err;
1614 
1615 	if (!xp) {
1616 		*errp = -ENOMEM;
1617 		return NULL;
1618 	}
1619 
1620 	copy_from_user_policy(xp, p);
1621 
1622 	err = copy_from_user_policy_type(&xp->type, attrs);
1623 	if (err)
1624 		goto error;
1625 
1626 	if (!(err = copy_from_user_tmpl(xp, attrs)))
1627 		err = copy_from_user_sec_ctx(xp, attrs);
1628 	if (err)
1629 		goto error;
1630 
1631 	xfrm_mark_get(attrs, &xp->mark);
1632 
1633 	if (attrs[XFRMA_IF_ID])
1634 		xp->if_id = nla_get_u32(attrs[XFRMA_IF_ID]);
1635 
1636 	return xp;
1637  error:
1638 	*errp = err;
1639 	xp->walk.dead = 1;
1640 	xfrm_policy_destroy(xp);
1641 	return NULL;
1642 }
1643 
1644 static int xfrm_add_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
1645 		struct nlattr **attrs)
1646 {
1647 	struct net *net = sock_net(skb->sk);
1648 	struct xfrm_userpolicy_info *p = nlmsg_data(nlh);
1649 	struct xfrm_policy *xp;
1650 	struct km_event c;
1651 	int err;
1652 	int excl;
1653 
1654 	err = verify_newpolicy_info(p);
1655 	if (err)
1656 		return err;
1657 	err = verify_sec_ctx_len(attrs);
1658 	if (err)
1659 		return err;
1660 
1661 	xp = xfrm_policy_construct(net, p, attrs, &err);
1662 	if (!xp)
1663 		return err;
1664 
1665 	/* shouldn't excl be based on nlh flags??
1666 	 * Aha! this is anti-netlink really i.e  more pfkey derived
1667 	 * in netlink excl is a flag and you wouldnt need
1668 	 * a type XFRM_MSG_UPDPOLICY - JHS */
1669 	excl = nlh->nlmsg_type == XFRM_MSG_NEWPOLICY;
1670 	err = xfrm_policy_insert(p->dir, xp, excl);
1671 	xfrm_audit_policy_add(xp, err ? 0 : 1, true);
1672 
1673 	if (err) {
1674 		security_xfrm_policy_free(xp->security);
1675 		kfree(xp);
1676 		return err;
1677 	}
1678 
1679 	c.event = nlh->nlmsg_type;
1680 	c.seq = nlh->nlmsg_seq;
1681 	c.portid = nlh->nlmsg_pid;
1682 	km_policy_notify(xp, p->dir, &c);
1683 
1684 	xfrm_pol_put(xp);
1685 
1686 	return 0;
1687 }
1688 
1689 static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb)
1690 {
1691 	struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH];
1692 	int i;
1693 
1694 	if (xp->xfrm_nr == 0)
1695 		return 0;
1696 
1697 	for (i = 0; i < xp->xfrm_nr; i++) {
1698 		struct xfrm_user_tmpl *up = &vec[i];
1699 		struct xfrm_tmpl *kp = &xp->xfrm_vec[i];
1700 
1701 		memset(up, 0, sizeof(*up));
1702 		memcpy(&up->id, &kp->id, sizeof(up->id));
1703 		up->family = kp->encap_family;
1704 		memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr));
1705 		up->reqid = kp->reqid;
1706 		up->mode = kp->mode;
1707 		up->share = kp->share;
1708 		up->optional = kp->optional;
1709 		up->aalgos = kp->aalgos;
1710 		up->ealgos = kp->ealgos;
1711 		up->calgos = kp->calgos;
1712 	}
1713 
1714 	return nla_put(skb, XFRMA_TMPL,
1715 		       sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec);
1716 }
1717 
1718 static inline int copy_to_user_state_sec_ctx(struct xfrm_state *x, struct sk_buff *skb)
1719 {
1720 	if (x->security) {
1721 		return copy_sec_ctx(x->security, skb);
1722 	}
1723 	return 0;
1724 }
1725 
1726 static inline int copy_to_user_sec_ctx(struct xfrm_policy *xp, struct sk_buff *skb)
1727 {
1728 	if (xp->security)
1729 		return copy_sec_ctx(xp->security, skb);
1730 	return 0;
1731 }
1732 static inline unsigned int userpolicy_type_attrsize(void)
1733 {
1734 #ifdef CONFIG_XFRM_SUB_POLICY
1735 	return nla_total_size(sizeof(struct xfrm_userpolicy_type));
1736 #else
1737 	return 0;
1738 #endif
1739 }
1740 
1741 #ifdef CONFIG_XFRM_SUB_POLICY
1742 static int copy_to_user_policy_type(u8 type, struct sk_buff *skb)
1743 {
1744 	struct xfrm_userpolicy_type upt;
1745 
1746 	/* Sadly there are two holes in struct xfrm_userpolicy_type */
1747 	memset(&upt, 0, sizeof(upt));
1748 	upt.type = type;
1749 
1750 	return nla_put(skb, XFRMA_POLICY_TYPE, sizeof(upt), &upt);
1751 }
1752 
1753 #else
1754 static inline int copy_to_user_policy_type(u8 type, struct sk_buff *skb)
1755 {
1756 	return 0;
1757 }
1758 #endif
1759 
1760 static int dump_one_policy(struct xfrm_policy *xp, int dir, int count, void *ptr)
1761 {
1762 	struct xfrm_dump_info *sp = ptr;
1763 	struct xfrm_userpolicy_info *p;
1764 	struct sk_buff *in_skb = sp->in_skb;
1765 	struct sk_buff *skb = sp->out_skb;
1766 	struct nlmsghdr *nlh;
1767 	int err;
1768 
1769 	nlh = nlmsg_put(skb, NETLINK_CB(in_skb).portid, sp->nlmsg_seq,
1770 			XFRM_MSG_NEWPOLICY, sizeof(*p), sp->nlmsg_flags);
1771 	if (nlh == NULL)
1772 		return -EMSGSIZE;
1773 
1774 	p = nlmsg_data(nlh);
1775 	copy_to_user_policy(xp, p, dir);
1776 	err = copy_to_user_tmpl(xp, skb);
1777 	if (!err)
1778 		err = copy_to_user_sec_ctx(xp, skb);
1779 	if (!err)
1780 		err = copy_to_user_policy_type(xp->type, skb);
1781 	if (!err)
1782 		err = xfrm_mark_put(skb, &xp->mark);
1783 	if (!err)
1784 		err = xfrm_if_id_put(skb, xp->if_id);
1785 	if (err) {
1786 		nlmsg_cancel(skb, nlh);
1787 		return err;
1788 	}
1789 	nlmsg_end(skb, nlh);
1790 	return 0;
1791 }
1792 
1793 static int xfrm_dump_policy_done(struct netlink_callback *cb)
1794 {
1795 	struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *)cb->args;
1796 	struct net *net = sock_net(cb->skb->sk);
1797 
1798 	xfrm_policy_walk_done(walk, net);
1799 	return 0;
1800 }
1801 
1802 static int xfrm_dump_policy_start(struct netlink_callback *cb)
1803 {
1804 	struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *)cb->args;
1805 
1806 	BUILD_BUG_ON(sizeof(*walk) > sizeof(cb->args));
1807 
1808 	xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY);
1809 	return 0;
1810 }
1811 
1812 static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb)
1813 {
1814 	struct net *net = sock_net(skb->sk);
1815 	struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *)cb->args;
1816 	struct xfrm_dump_info info;
1817 
1818 	info.in_skb = cb->skb;
1819 	info.out_skb = skb;
1820 	info.nlmsg_seq = cb->nlh->nlmsg_seq;
1821 	info.nlmsg_flags = NLM_F_MULTI;
1822 
1823 	(void) xfrm_policy_walk(net, walk, dump_one_policy, &info);
1824 
1825 	return skb->len;
1826 }
1827 
1828 static struct sk_buff *xfrm_policy_netlink(struct sk_buff *in_skb,
1829 					  struct xfrm_policy *xp,
1830 					  int dir, u32 seq)
1831 {
1832 	struct xfrm_dump_info info;
1833 	struct sk_buff *skb;
1834 	int err;
1835 
1836 	skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1837 	if (!skb)
1838 		return ERR_PTR(-ENOMEM);
1839 
1840 	info.in_skb = in_skb;
1841 	info.out_skb = skb;
1842 	info.nlmsg_seq = seq;
1843 	info.nlmsg_flags = 0;
1844 
1845 	err = dump_one_policy(xp, dir, 0, &info);
1846 	if (err) {
1847 		kfree_skb(skb);
1848 		return ERR_PTR(err);
1849 	}
1850 
1851 	return skb;
1852 }
1853 
1854 static int xfrm_get_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
1855 		struct nlattr **attrs)
1856 {
1857 	struct net *net = sock_net(skb->sk);
1858 	struct xfrm_policy *xp;
1859 	struct xfrm_userpolicy_id *p;
1860 	u8 type = XFRM_POLICY_TYPE_MAIN;
1861 	int err;
1862 	struct km_event c;
1863 	int delete;
1864 	struct xfrm_mark m;
1865 	u32 mark = xfrm_mark_get(attrs, &m);
1866 	u32 if_id = 0;
1867 
1868 	p = nlmsg_data(nlh);
1869 	delete = nlh->nlmsg_type == XFRM_MSG_DELPOLICY;
1870 
1871 	err = copy_from_user_policy_type(&type, attrs);
1872 	if (err)
1873 		return err;
1874 
1875 	err = verify_policy_dir(p->dir);
1876 	if (err)
1877 		return err;
1878 
1879 	if (attrs[XFRMA_IF_ID])
1880 		if_id = nla_get_u32(attrs[XFRMA_IF_ID]);
1881 
1882 	if (p->index)
1883 		xp = xfrm_policy_byid(net, mark, if_id, type, p->dir, p->index, delete, &err);
1884 	else {
1885 		struct nlattr *rt = attrs[XFRMA_SEC_CTX];
1886 		struct xfrm_sec_ctx *ctx;
1887 
1888 		err = verify_sec_ctx_len(attrs);
1889 		if (err)
1890 			return err;
1891 
1892 		ctx = NULL;
1893 		if (rt) {
1894 			struct xfrm_user_sec_ctx *uctx = nla_data(rt);
1895 
1896 			err = security_xfrm_policy_alloc(&ctx, uctx, GFP_KERNEL);
1897 			if (err)
1898 				return err;
1899 		}
1900 		xp = xfrm_policy_bysel_ctx(net, mark, if_id, type, p->dir, &p->sel,
1901 					   ctx, delete, &err);
1902 		security_xfrm_policy_free(ctx);
1903 	}
1904 	if (xp == NULL)
1905 		return -ENOENT;
1906 
1907 	if (!delete) {
1908 		struct sk_buff *resp_skb;
1909 
1910 		resp_skb = xfrm_policy_netlink(skb, xp, p->dir, nlh->nlmsg_seq);
1911 		if (IS_ERR(resp_skb)) {
1912 			err = PTR_ERR(resp_skb);
1913 		} else {
1914 			err = nlmsg_unicast(net->xfrm.nlsk, resp_skb,
1915 					    NETLINK_CB(skb).portid);
1916 		}
1917 	} else {
1918 		xfrm_audit_policy_delete(xp, err ? 0 : 1, true);
1919 
1920 		if (err != 0)
1921 			goto out;
1922 
1923 		c.data.byid = p->index;
1924 		c.event = nlh->nlmsg_type;
1925 		c.seq = nlh->nlmsg_seq;
1926 		c.portid = nlh->nlmsg_pid;
1927 		km_policy_notify(xp, p->dir, &c);
1928 	}
1929 
1930 out:
1931 	xfrm_pol_put(xp);
1932 	return err;
1933 }
1934 
1935 static int xfrm_flush_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
1936 		struct nlattr **attrs)
1937 {
1938 	struct net *net = sock_net(skb->sk);
1939 	struct km_event c;
1940 	struct xfrm_usersa_flush *p = nlmsg_data(nlh);
1941 	int err;
1942 
1943 	err = xfrm_state_flush(net, p->proto, true, false);
1944 	if (err) {
1945 		if (err == -ESRCH) /* empty table */
1946 			return 0;
1947 		return err;
1948 	}
1949 	c.data.proto = p->proto;
1950 	c.event = nlh->nlmsg_type;
1951 	c.seq = nlh->nlmsg_seq;
1952 	c.portid = nlh->nlmsg_pid;
1953 	c.net = net;
1954 	km_state_notify(NULL, &c);
1955 
1956 	return 0;
1957 }
1958 
1959 static inline unsigned int xfrm_aevent_msgsize(struct xfrm_state *x)
1960 {
1961 	unsigned int replay_size = x->replay_esn ?
1962 			      xfrm_replay_state_esn_len(x->replay_esn) :
1963 			      sizeof(struct xfrm_replay_state);
1964 
1965 	return NLMSG_ALIGN(sizeof(struct xfrm_aevent_id))
1966 	       + nla_total_size(replay_size)
1967 	       + nla_total_size_64bit(sizeof(struct xfrm_lifetime_cur))
1968 	       + nla_total_size(sizeof(struct xfrm_mark))
1969 	       + nla_total_size(4) /* XFRM_AE_RTHR */
1970 	       + nla_total_size(4); /* XFRM_AE_ETHR */
1971 }
1972 
1973 static int build_aevent(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
1974 {
1975 	struct xfrm_aevent_id *id;
1976 	struct nlmsghdr *nlh;
1977 	int err;
1978 
1979 	nlh = nlmsg_put(skb, c->portid, c->seq, XFRM_MSG_NEWAE, sizeof(*id), 0);
1980 	if (nlh == NULL)
1981 		return -EMSGSIZE;
1982 
1983 	id = nlmsg_data(nlh);
1984 	memset(&id->sa_id, 0, sizeof(id->sa_id));
1985 	memcpy(&id->sa_id.daddr, &x->id.daddr, sizeof(x->id.daddr));
1986 	id->sa_id.spi = x->id.spi;
1987 	id->sa_id.family = x->props.family;
1988 	id->sa_id.proto = x->id.proto;
1989 	memcpy(&id->saddr, &x->props.saddr, sizeof(x->props.saddr));
1990 	id->reqid = x->props.reqid;
1991 	id->flags = c->data.aevent;
1992 
1993 	if (x->replay_esn) {
1994 		err = nla_put(skb, XFRMA_REPLAY_ESN_VAL,
1995 			      xfrm_replay_state_esn_len(x->replay_esn),
1996 			      x->replay_esn);
1997 	} else {
1998 		err = nla_put(skb, XFRMA_REPLAY_VAL, sizeof(x->replay),
1999 			      &x->replay);
2000 	}
2001 	if (err)
2002 		goto out_cancel;
2003 	err = nla_put_64bit(skb, XFRMA_LTIME_VAL, sizeof(x->curlft), &x->curlft,
2004 			    XFRMA_PAD);
2005 	if (err)
2006 		goto out_cancel;
2007 
2008 	if (id->flags & XFRM_AE_RTHR) {
2009 		err = nla_put_u32(skb, XFRMA_REPLAY_THRESH, x->replay_maxdiff);
2010 		if (err)
2011 			goto out_cancel;
2012 	}
2013 	if (id->flags & XFRM_AE_ETHR) {
2014 		err = nla_put_u32(skb, XFRMA_ETIMER_THRESH,
2015 				  x->replay_maxage * 10 / HZ);
2016 		if (err)
2017 			goto out_cancel;
2018 	}
2019 	err = xfrm_mark_put(skb, &x->mark);
2020 	if (err)
2021 		goto out_cancel;
2022 
2023 	err = xfrm_if_id_put(skb, x->if_id);
2024 	if (err)
2025 		goto out_cancel;
2026 
2027 	nlmsg_end(skb, nlh);
2028 	return 0;
2029 
2030 out_cancel:
2031 	nlmsg_cancel(skb, nlh);
2032 	return err;
2033 }
2034 
2035 static int xfrm_get_ae(struct sk_buff *skb, struct nlmsghdr *nlh,
2036 		struct nlattr **attrs)
2037 {
2038 	struct net *net = sock_net(skb->sk);
2039 	struct xfrm_state *x;
2040 	struct sk_buff *r_skb;
2041 	int err;
2042 	struct km_event c;
2043 	u32 mark;
2044 	struct xfrm_mark m;
2045 	struct xfrm_aevent_id *p = nlmsg_data(nlh);
2046 	struct xfrm_usersa_id *id = &p->sa_id;
2047 
2048 	mark = xfrm_mark_get(attrs, &m);
2049 
2050 	x = xfrm_state_lookup(net, mark, &id->daddr, id->spi, id->proto, id->family);
2051 	if (x == NULL)
2052 		return -ESRCH;
2053 
2054 	r_skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
2055 	if (r_skb == NULL) {
2056 		xfrm_state_put(x);
2057 		return -ENOMEM;
2058 	}
2059 
2060 	/*
2061 	 * XXX: is this lock really needed - none of the other
2062 	 * gets lock (the concern is things getting updated
2063 	 * while we are still reading) - jhs
2064 	*/
2065 	spin_lock_bh(&x->lock);
2066 	c.data.aevent = p->flags;
2067 	c.seq = nlh->nlmsg_seq;
2068 	c.portid = nlh->nlmsg_pid;
2069 
2070 	err = build_aevent(r_skb, x, &c);
2071 	BUG_ON(err < 0);
2072 
2073 	err = nlmsg_unicast(net->xfrm.nlsk, r_skb, NETLINK_CB(skb).portid);
2074 	spin_unlock_bh(&x->lock);
2075 	xfrm_state_put(x);
2076 	return err;
2077 }
2078 
2079 static int xfrm_new_ae(struct sk_buff *skb, struct nlmsghdr *nlh,
2080 		struct nlattr **attrs)
2081 {
2082 	struct net *net = sock_net(skb->sk);
2083 	struct xfrm_state *x;
2084 	struct km_event c;
2085 	int err = -EINVAL;
2086 	u32 mark = 0;
2087 	struct xfrm_mark m;
2088 	struct xfrm_aevent_id *p = nlmsg_data(nlh);
2089 	struct nlattr *rp = attrs[XFRMA_REPLAY_VAL];
2090 	struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL];
2091 	struct nlattr *lt = attrs[XFRMA_LTIME_VAL];
2092 	struct nlattr *et = attrs[XFRMA_ETIMER_THRESH];
2093 	struct nlattr *rt = attrs[XFRMA_REPLAY_THRESH];
2094 
2095 	if (!lt && !rp && !re && !et && !rt)
2096 		return err;
2097 
2098 	/* pedantic mode - thou shalt sayeth replaceth */
2099 	if (!(nlh->nlmsg_flags&NLM_F_REPLACE))
2100 		return err;
2101 
2102 	mark = xfrm_mark_get(attrs, &m);
2103 
2104 	x = xfrm_state_lookup(net, mark, &p->sa_id.daddr, p->sa_id.spi, p->sa_id.proto, p->sa_id.family);
2105 	if (x == NULL)
2106 		return -ESRCH;
2107 
2108 	if (x->km.state != XFRM_STATE_VALID)
2109 		goto out;
2110 
2111 	err = xfrm_replay_verify_len(x->replay_esn, re);
2112 	if (err)
2113 		goto out;
2114 
2115 	spin_lock_bh(&x->lock);
2116 	xfrm_update_ae_params(x, attrs, 1);
2117 	spin_unlock_bh(&x->lock);
2118 
2119 	c.event = nlh->nlmsg_type;
2120 	c.seq = nlh->nlmsg_seq;
2121 	c.portid = nlh->nlmsg_pid;
2122 	c.data.aevent = XFRM_AE_CU;
2123 	km_state_notify(x, &c);
2124 	err = 0;
2125 out:
2126 	xfrm_state_put(x);
2127 	return err;
2128 }
2129 
2130 static int xfrm_flush_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
2131 		struct nlattr **attrs)
2132 {
2133 	struct net *net = sock_net(skb->sk);
2134 	struct km_event c;
2135 	u8 type = XFRM_POLICY_TYPE_MAIN;
2136 	int err;
2137 
2138 	err = copy_from_user_policy_type(&type, attrs);
2139 	if (err)
2140 		return err;
2141 
2142 	err = xfrm_policy_flush(net, type, true);
2143 	if (err) {
2144 		if (err == -ESRCH) /* empty table */
2145 			return 0;
2146 		return err;
2147 	}
2148 
2149 	c.data.type = type;
2150 	c.event = nlh->nlmsg_type;
2151 	c.seq = nlh->nlmsg_seq;
2152 	c.portid = nlh->nlmsg_pid;
2153 	c.net = net;
2154 	km_policy_notify(NULL, 0, &c);
2155 	return 0;
2156 }
2157 
2158 static int xfrm_add_pol_expire(struct sk_buff *skb, struct nlmsghdr *nlh,
2159 		struct nlattr **attrs)
2160 {
2161 	struct net *net = sock_net(skb->sk);
2162 	struct xfrm_policy *xp;
2163 	struct xfrm_user_polexpire *up = nlmsg_data(nlh);
2164 	struct xfrm_userpolicy_info *p = &up->pol;
2165 	u8 type = XFRM_POLICY_TYPE_MAIN;
2166 	int err = -ENOENT;
2167 	struct xfrm_mark m;
2168 	u32 mark = xfrm_mark_get(attrs, &m);
2169 	u32 if_id = 0;
2170 
2171 	err = copy_from_user_policy_type(&type, attrs);
2172 	if (err)
2173 		return err;
2174 
2175 	err = verify_policy_dir(p->dir);
2176 	if (err)
2177 		return err;
2178 
2179 	if (attrs[XFRMA_IF_ID])
2180 		if_id = nla_get_u32(attrs[XFRMA_IF_ID]);
2181 
2182 	if (p->index)
2183 		xp = xfrm_policy_byid(net, mark, if_id, type, p->dir, p->index, 0, &err);
2184 	else {
2185 		struct nlattr *rt = attrs[XFRMA_SEC_CTX];
2186 		struct xfrm_sec_ctx *ctx;
2187 
2188 		err = verify_sec_ctx_len(attrs);
2189 		if (err)
2190 			return err;
2191 
2192 		ctx = NULL;
2193 		if (rt) {
2194 			struct xfrm_user_sec_ctx *uctx = nla_data(rt);
2195 
2196 			err = security_xfrm_policy_alloc(&ctx, uctx, GFP_KERNEL);
2197 			if (err)
2198 				return err;
2199 		}
2200 		xp = xfrm_policy_bysel_ctx(net, mark, if_id, type, p->dir,
2201 					   &p->sel, ctx, 0, &err);
2202 		security_xfrm_policy_free(ctx);
2203 	}
2204 	if (xp == NULL)
2205 		return -ENOENT;
2206 
2207 	if (unlikely(xp->walk.dead))
2208 		goto out;
2209 
2210 	err = 0;
2211 	if (up->hard) {
2212 		xfrm_policy_delete(xp, p->dir);
2213 		xfrm_audit_policy_delete(xp, 1, true);
2214 	}
2215 	km_policy_expired(xp, p->dir, up->hard, nlh->nlmsg_pid);
2216 
2217 out:
2218 	xfrm_pol_put(xp);
2219 	return err;
2220 }
2221 
2222 static int xfrm_add_sa_expire(struct sk_buff *skb, struct nlmsghdr *nlh,
2223 		struct nlattr **attrs)
2224 {
2225 	struct net *net = sock_net(skb->sk);
2226 	struct xfrm_state *x;
2227 	int err;
2228 	struct xfrm_user_expire *ue = nlmsg_data(nlh);
2229 	struct xfrm_usersa_info *p = &ue->state;
2230 	struct xfrm_mark m;
2231 	u32 mark = xfrm_mark_get(attrs, &m);
2232 
2233 	x = xfrm_state_lookup(net, mark, &p->id.daddr, p->id.spi, p->id.proto, p->family);
2234 
2235 	err = -ENOENT;
2236 	if (x == NULL)
2237 		return err;
2238 
2239 	spin_lock_bh(&x->lock);
2240 	err = -EINVAL;
2241 	if (x->km.state != XFRM_STATE_VALID)
2242 		goto out;
2243 	km_state_expired(x, ue->hard, nlh->nlmsg_pid);
2244 
2245 	if (ue->hard) {
2246 		__xfrm_state_delete(x);
2247 		xfrm_audit_state_delete(x, 1, true);
2248 	}
2249 	err = 0;
2250 out:
2251 	spin_unlock_bh(&x->lock);
2252 	xfrm_state_put(x);
2253 	return err;
2254 }
2255 
2256 static int xfrm_add_acquire(struct sk_buff *skb, struct nlmsghdr *nlh,
2257 		struct nlattr **attrs)
2258 {
2259 	struct net *net = sock_net(skb->sk);
2260 	struct xfrm_policy *xp;
2261 	struct xfrm_user_tmpl *ut;
2262 	int i;
2263 	struct nlattr *rt = attrs[XFRMA_TMPL];
2264 	struct xfrm_mark mark;
2265 
2266 	struct xfrm_user_acquire *ua = nlmsg_data(nlh);
2267 	struct xfrm_state *x = xfrm_state_alloc(net);
2268 	int err = -ENOMEM;
2269 
2270 	if (!x)
2271 		goto nomem;
2272 
2273 	xfrm_mark_get(attrs, &mark);
2274 
2275 	err = verify_newpolicy_info(&ua->policy);
2276 	if (err)
2277 		goto free_state;
2278 
2279 	/*   build an XP */
2280 	xp = xfrm_policy_construct(net, &ua->policy, attrs, &err);
2281 	if (!xp)
2282 		goto free_state;
2283 
2284 	memcpy(&x->id, &ua->id, sizeof(ua->id));
2285 	memcpy(&x->props.saddr, &ua->saddr, sizeof(ua->saddr));
2286 	memcpy(&x->sel, &ua->sel, sizeof(ua->sel));
2287 	xp->mark.m = x->mark.m = mark.m;
2288 	xp->mark.v = x->mark.v = mark.v;
2289 	ut = nla_data(rt);
2290 	/* extract the templates and for each call km_key */
2291 	for (i = 0; i < xp->xfrm_nr; i++, ut++) {
2292 		struct xfrm_tmpl *t = &xp->xfrm_vec[i];
2293 		memcpy(&x->id, &t->id, sizeof(x->id));
2294 		x->props.mode = t->mode;
2295 		x->props.reqid = t->reqid;
2296 		x->props.family = ut->family;
2297 		t->aalgos = ua->aalgos;
2298 		t->ealgos = ua->ealgos;
2299 		t->calgos = ua->calgos;
2300 		err = km_query(x, t, xp);
2301 
2302 	}
2303 
2304 	xfrm_state_free(x);
2305 	kfree(xp);
2306 
2307 	return 0;
2308 
2309 free_state:
2310 	xfrm_state_free(x);
2311 nomem:
2312 	return err;
2313 }
2314 
2315 #ifdef CONFIG_XFRM_MIGRATE
2316 static int copy_from_user_migrate(struct xfrm_migrate *ma,
2317 				  struct xfrm_kmaddress *k,
2318 				  struct nlattr **attrs, int *num)
2319 {
2320 	struct nlattr *rt = attrs[XFRMA_MIGRATE];
2321 	struct xfrm_user_migrate *um;
2322 	int i, num_migrate;
2323 
2324 	if (k != NULL) {
2325 		struct xfrm_user_kmaddress *uk;
2326 
2327 		uk = nla_data(attrs[XFRMA_KMADDRESS]);
2328 		memcpy(&k->local, &uk->local, sizeof(k->local));
2329 		memcpy(&k->remote, &uk->remote, sizeof(k->remote));
2330 		k->family = uk->family;
2331 		k->reserved = uk->reserved;
2332 	}
2333 
2334 	um = nla_data(rt);
2335 	num_migrate = nla_len(rt) / sizeof(*um);
2336 
2337 	if (num_migrate <= 0 || num_migrate > XFRM_MAX_DEPTH)
2338 		return -EINVAL;
2339 
2340 	for (i = 0; i < num_migrate; i++, um++, ma++) {
2341 		memcpy(&ma->old_daddr, &um->old_daddr, sizeof(ma->old_daddr));
2342 		memcpy(&ma->old_saddr, &um->old_saddr, sizeof(ma->old_saddr));
2343 		memcpy(&ma->new_daddr, &um->new_daddr, sizeof(ma->new_daddr));
2344 		memcpy(&ma->new_saddr, &um->new_saddr, sizeof(ma->new_saddr));
2345 
2346 		ma->proto = um->proto;
2347 		ma->mode = um->mode;
2348 		ma->reqid = um->reqid;
2349 
2350 		ma->old_family = um->old_family;
2351 		ma->new_family = um->new_family;
2352 	}
2353 
2354 	*num = i;
2355 	return 0;
2356 }
2357 
2358 static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh,
2359 			   struct nlattr **attrs)
2360 {
2361 	struct xfrm_userpolicy_id *pi = nlmsg_data(nlh);
2362 	struct xfrm_migrate m[XFRM_MAX_DEPTH];
2363 	struct xfrm_kmaddress km, *kmp;
2364 	u8 type;
2365 	int err;
2366 	int n = 0;
2367 	struct net *net = sock_net(skb->sk);
2368 	struct xfrm_encap_tmpl  *encap = NULL;
2369 
2370 	if (attrs[XFRMA_MIGRATE] == NULL)
2371 		return -EINVAL;
2372 
2373 	kmp = attrs[XFRMA_KMADDRESS] ? &km : NULL;
2374 
2375 	err = copy_from_user_policy_type(&type, attrs);
2376 	if (err)
2377 		return err;
2378 
2379 	err = copy_from_user_migrate((struct xfrm_migrate *)m, kmp, attrs, &n);
2380 	if (err)
2381 		return err;
2382 
2383 	if (!n)
2384 		return 0;
2385 
2386 	if (attrs[XFRMA_ENCAP]) {
2387 		encap = kmemdup(nla_data(attrs[XFRMA_ENCAP]),
2388 				sizeof(*encap), GFP_KERNEL);
2389 		if (!encap)
2390 			return 0;
2391 	}
2392 
2393 	err = xfrm_migrate(&pi->sel, pi->dir, type, m, n, kmp, net, encap);
2394 
2395 	kfree(encap);
2396 
2397 	return err;
2398 }
2399 #else
2400 static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh,
2401 			   struct nlattr **attrs)
2402 {
2403 	return -ENOPROTOOPT;
2404 }
2405 #endif
2406 
2407 #ifdef CONFIG_XFRM_MIGRATE
2408 static int copy_to_user_migrate(const struct xfrm_migrate *m, struct sk_buff *skb)
2409 {
2410 	struct xfrm_user_migrate um;
2411 
2412 	memset(&um, 0, sizeof(um));
2413 	um.proto = m->proto;
2414 	um.mode = m->mode;
2415 	um.reqid = m->reqid;
2416 	um.old_family = m->old_family;
2417 	memcpy(&um.old_daddr, &m->old_daddr, sizeof(um.old_daddr));
2418 	memcpy(&um.old_saddr, &m->old_saddr, sizeof(um.old_saddr));
2419 	um.new_family = m->new_family;
2420 	memcpy(&um.new_daddr, &m->new_daddr, sizeof(um.new_daddr));
2421 	memcpy(&um.new_saddr, &m->new_saddr, sizeof(um.new_saddr));
2422 
2423 	return nla_put(skb, XFRMA_MIGRATE, sizeof(um), &um);
2424 }
2425 
2426 static int copy_to_user_kmaddress(const struct xfrm_kmaddress *k, struct sk_buff *skb)
2427 {
2428 	struct xfrm_user_kmaddress uk;
2429 
2430 	memset(&uk, 0, sizeof(uk));
2431 	uk.family = k->family;
2432 	uk.reserved = k->reserved;
2433 	memcpy(&uk.local, &k->local, sizeof(uk.local));
2434 	memcpy(&uk.remote, &k->remote, sizeof(uk.remote));
2435 
2436 	return nla_put(skb, XFRMA_KMADDRESS, sizeof(uk), &uk);
2437 }
2438 
2439 static inline unsigned int xfrm_migrate_msgsize(int num_migrate, int with_kma,
2440 						int with_encp)
2441 {
2442 	return NLMSG_ALIGN(sizeof(struct xfrm_userpolicy_id))
2443 	      + (with_kma ? nla_total_size(sizeof(struct xfrm_kmaddress)) : 0)
2444 	      + (with_encp ? nla_total_size(sizeof(struct xfrm_encap_tmpl)) : 0)
2445 	      + nla_total_size(sizeof(struct xfrm_user_migrate) * num_migrate)
2446 	      + userpolicy_type_attrsize();
2447 }
2448 
2449 static int build_migrate(struct sk_buff *skb, const struct xfrm_migrate *m,
2450 			 int num_migrate, const struct xfrm_kmaddress *k,
2451 			 const struct xfrm_selector *sel,
2452 			 const struct xfrm_encap_tmpl *encap, u8 dir, u8 type)
2453 {
2454 	const struct xfrm_migrate *mp;
2455 	struct xfrm_userpolicy_id *pol_id;
2456 	struct nlmsghdr *nlh;
2457 	int i, err;
2458 
2459 	nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MIGRATE, sizeof(*pol_id), 0);
2460 	if (nlh == NULL)
2461 		return -EMSGSIZE;
2462 
2463 	pol_id = nlmsg_data(nlh);
2464 	/* copy data from selector, dir, and type to the pol_id */
2465 	memset(pol_id, 0, sizeof(*pol_id));
2466 	memcpy(&pol_id->sel, sel, sizeof(pol_id->sel));
2467 	pol_id->dir = dir;
2468 
2469 	if (k != NULL) {
2470 		err = copy_to_user_kmaddress(k, skb);
2471 		if (err)
2472 			goto out_cancel;
2473 	}
2474 	if (encap) {
2475 		err = nla_put(skb, XFRMA_ENCAP, sizeof(*encap), encap);
2476 		if (err)
2477 			goto out_cancel;
2478 	}
2479 	err = copy_to_user_policy_type(type, skb);
2480 	if (err)
2481 		goto out_cancel;
2482 	for (i = 0, mp = m ; i < num_migrate; i++, mp++) {
2483 		err = copy_to_user_migrate(mp, skb);
2484 		if (err)
2485 			goto out_cancel;
2486 	}
2487 
2488 	nlmsg_end(skb, nlh);
2489 	return 0;
2490 
2491 out_cancel:
2492 	nlmsg_cancel(skb, nlh);
2493 	return err;
2494 }
2495 
2496 static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
2497 			     const struct xfrm_migrate *m, int num_migrate,
2498 			     const struct xfrm_kmaddress *k,
2499 			     const struct xfrm_encap_tmpl *encap)
2500 {
2501 	struct net *net = &init_net;
2502 	struct sk_buff *skb;
2503 	int err;
2504 
2505 	skb = nlmsg_new(xfrm_migrate_msgsize(num_migrate, !!k, !!encap),
2506 			GFP_ATOMIC);
2507 	if (skb == NULL)
2508 		return -ENOMEM;
2509 
2510 	/* build migrate */
2511 	err = build_migrate(skb, m, num_migrate, k, sel, encap, dir, type);
2512 	BUG_ON(err < 0);
2513 
2514 	return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_MIGRATE);
2515 }
2516 #else
2517 static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
2518 			     const struct xfrm_migrate *m, int num_migrate,
2519 			     const struct xfrm_kmaddress *k,
2520 			     const struct xfrm_encap_tmpl *encap)
2521 {
2522 	return -ENOPROTOOPT;
2523 }
2524 #endif
2525 
2526 #define XMSGSIZE(type) sizeof(struct type)
2527 
2528 static const int xfrm_msg_min[XFRM_NR_MSGTYPES] = {
2529 	[XFRM_MSG_NEWSA       - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info),
2530 	[XFRM_MSG_DELSA       - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id),
2531 	[XFRM_MSG_GETSA       - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id),
2532 	[XFRM_MSG_NEWPOLICY   - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info),
2533 	[XFRM_MSG_DELPOLICY   - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
2534 	[XFRM_MSG_GETPOLICY   - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
2535 	[XFRM_MSG_ALLOCSPI    - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userspi_info),
2536 	[XFRM_MSG_ACQUIRE     - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_acquire),
2537 	[XFRM_MSG_EXPIRE      - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_expire),
2538 	[XFRM_MSG_UPDPOLICY   - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info),
2539 	[XFRM_MSG_UPDSA       - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info),
2540 	[XFRM_MSG_POLEXPIRE   - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_polexpire),
2541 	[XFRM_MSG_FLUSHSA     - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_flush),
2542 	[XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = 0,
2543 	[XFRM_MSG_NEWAE       - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id),
2544 	[XFRM_MSG_GETAE       - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id),
2545 	[XFRM_MSG_REPORT      - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_report),
2546 	[XFRM_MSG_MIGRATE     - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
2547 	[XFRM_MSG_GETSADINFO  - XFRM_MSG_BASE] = sizeof(u32),
2548 	[XFRM_MSG_NEWSPDINFO  - XFRM_MSG_BASE] = sizeof(u32),
2549 	[XFRM_MSG_GETSPDINFO  - XFRM_MSG_BASE] = sizeof(u32),
2550 };
2551 
2552 #undef XMSGSIZE
2553 
2554 static const struct nla_policy xfrma_policy[XFRMA_MAX+1] = {
2555 	[XFRMA_SA]		= { .len = sizeof(struct xfrm_usersa_info)},
2556 	[XFRMA_POLICY]		= { .len = sizeof(struct xfrm_userpolicy_info)},
2557 	[XFRMA_LASTUSED]	= { .type = NLA_U64},
2558 	[XFRMA_ALG_AUTH_TRUNC]	= { .len = sizeof(struct xfrm_algo_auth)},
2559 	[XFRMA_ALG_AEAD]	= { .len = sizeof(struct xfrm_algo_aead) },
2560 	[XFRMA_ALG_AUTH]	= { .len = sizeof(struct xfrm_algo) },
2561 	[XFRMA_ALG_CRYPT]	= { .len = sizeof(struct xfrm_algo) },
2562 	[XFRMA_ALG_COMP]	= { .len = sizeof(struct xfrm_algo) },
2563 	[XFRMA_ENCAP]		= { .len = sizeof(struct xfrm_encap_tmpl) },
2564 	[XFRMA_TMPL]		= { .len = sizeof(struct xfrm_user_tmpl) },
2565 	[XFRMA_SEC_CTX]		= { .len = sizeof(struct xfrm_sec_ctx) },
2566 	[XFRMA_LTIME_VAL]	= { .len = sizeof(struct xfrm_lifetime_cur) },
2567 	[XFRMA_REPLAY_VAL]	= { .len = sizeof(struct xfrm_replay_state) },
2568 	[XFRMA_REPLAY_THRESH]	= { .type = NLA_U32 },
2569 	[XFRMA_ETIMER_THRESH]	= { .type = NLA_U32 },
2570 	[XFRMA_SRCADDR]		= { .len = sizeof(xfrm_address_t) },
2571 	[XFRMA_COADDR]		= { .len = sizeof(xfrm_address_t) },
2572 	[XFRMA_POLICY_TYPE]	= { .len = sizeof(struct xfrm_userpolicy_type)},
2573 	[XFRMA_MIGRATE]		= { .len = sizeof(struct xfrm_user_migrate) },
2574 	[XFRMA_KMADDRESS]	= { .len = sizeof(struct xfrm_user_kmaddress) },
2575 	[XFRMA_MARK]		= { .len = sizeof(struct xfrm_mark) },
2576 	[XFRMA_TFCPAD]		= { .type = NLA_U32 },
2577 	[XFRMA_REPLAY_ESN_VAL]	= { .len = sizeof(struct xfrm_replay_state_esn) },
2578 	[XFRMA_SA_EXTRA_FLAGS]	= { .type = NLA_U32 },
2579 	[XFRMA_PROTO]		= { .type = NLA_U8 },
2580 	[XFRMA_ADDRESS_FILTER]	= { .len = sizeof(struct xfrm_address_filter) },
2581 	[XFRMA_OFFLOAD_DEV]	= { .len = sizeof(struct xfrm_user_offload) },
2582 	[XFRMA_SET_MARK]	= { .type = NLA_U32 },
2583 	[XFRMA_SET_MARK_MASK]	= { .type = NLA_U32 },
2584 	[XFRMA_IF_ID]		= { .type = NLA_U32 },
2585 };
2586 
2587 static const struct nla_policy xfrma_spd_policy[XFRMA_SPD_MAX+1] = {
2588 	[XFRMA_SPD_IPV4_HTHRESH] = { .len = sizeof(struct xfrmu_spdhthresh) },
2589 	[XFRMA_SPD_IPV6_HTHRESH] = { .len = sizeof(struct xfrmu_spdhthresh) },
2590 };
2591 
2592 static const struct xfrm_link {
2593 	int (*doit)(struct sk_buff *, struct nlmsghdr *, struct nlattr **);
2594 	int (*start)(struct netlink_callback *);
2595 	int (*dump)(struct sk_buff *, struct netlink_callback *);
2596 	int (*done)(struct netlink_callback *);
2597 	const struct nla_policy *nla_pol;
2598 	int nla_max;
2599 } xfrm_dispatch[XFRM_NR_MSGTYPES] = {
2600 	[XFRM_MSG_NEWSA       - XFRM_MSG_BASE] = { .doit = xfrm_add_sa        },
2601 	[XFRM_MSG_DELSA       - XFRM_MSG_BASE] = { .doit = xfrm_del_sa        },
2602 	[XFRM_MSG_GETSA       - XFRM_MSG_BASE] = { .doit = xfrm_get_sa,
2603 						   .dump = xfrm_dump_sa,
2604 						   .done = xfrm_dump_sa_done  },
2605 	[XFRM_MSG_NEWPOLICY   - XFRM_MSG_BASE] = { .doit = xfrm_add_policy    },
2606 	[XFRM_MSG_DELPOLICY   - XFRM_MSG_BASE] = { .doit = xfrm_get_policy    },
2607 	[XFRM_MSG_GETPOLICY   - XFRM_MSG_BASE] = { .doit = xfrm_get_policy,
2608 						   .start = xfrm_dump_policy_start,
2609 						   .dump = xfrm_dump_policy,
2610 						   .done = xfrm_dump_policy_done },
2611 	[XFRM_MSG_ALLOCSPI    - XFRM_MSG_BASE] = { .doit = xfrm_alloc_userspi },
2612 	[XFRM_MSG_ACQUIRE     - XFRM_MSG_BASE] = { .doit = xfrm_add_acquire   },
2613 	[XFRM_MSG_EXPIRE      - XFRM_MSG_BASE] = { .doit = xfrm_add_sa_expire },
2614 	[XFRM_MSG_UPDPOLICY   - XFRM_MSG_BASE] = { .doit = xfrm_add_policy    },
2615 	[XFRM_MSG_UPDSA       - XFRM_MSG_BASE] = { .doit = xfrm_add_sa        },
2616 	[XFRM_MSG_POLEXPIRE   - XFRM_MSG_BASE] = { .doit = xfrm_add_pol_expire},
2617 	[XFRM_MSG_FLUSHSA     - XFRM_MSG_BASE] = { .doit = xfrm_flush_sa      },
2618 	[XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_flush_policy  },
2619 	[XFRM_MSG_NEWAE       - XFRM_MSG_BASE] = { .doit = xfrm_new_ae  },
2620 	[XFRM_MSG_GETAE       - XFRM_MSG_BASE] = { .doit = xfrm_get_ae  },
2621 	[XFRM_MSG_MIGRATE     - XFRM_MSG_BASE] = { .doit = xfrm_do_migrate    },
2622 	[XFRM_MSG_GETSADINFO  - XFRM_MSG_BASE] = { .doit = xfrm_get_sadinfo   },
2623 	[XFRM_MSG_NEWSPDINFO  - XFRM_MSG_BASE] = { .doit = xfrm_set_spdinfo,
2624 						   .nla_pol = xfrma_spd_policy,
2625 						   .nla_max = XFRMA_SPD_MAX },
2626 	[XFRM_MSG_GETSPDINFO  - XFRM_MSG_BASE] = { .doit = xfrm_get_spdinfo   },
2627 };
2628 
2629 static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh,
2630 			     struct netlink_ext_ack *extack)
2631 {
2632 	struct net *net = sock_net(skb->sk);
2633 	struct nlattr *attrs[XFRMA_MAX+1];
2634 	const struct xfrm_link *link;
2635 	int type, err;
2636 
2637 	if (in_compat_syscall())
2638 		return -EOPNOTSUPP;
2639 
2640 	type = nlh->nlmsg_type;
2641 	if (type > XFRM_MSG_MAX)
2642 		return -EINVAL;
2643 
2644 	type -= XFRM_MSG_BASE;
2645 	link = &xfrm_dispatch[type];
2646 
2647 	/* All operations require privileges, even GET */
2648 	if (!netlink_net_capable(skb, CAP_NET_ADMIN))
2649 		return -EPERM;
2650 
2651 	if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) ||
2652 	     type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) &&
2653 	    (nlh->nlmsg_flags & NLM_F_DUMP)) {
2654 		if (link->dump == NULL)
2655 			return -EINVAL;
2656 
2657 		{
2658 			struct netlink_dump_control c = {
2659 				.start = link->start,
2660 				.dump = link->dump,
2661 				.done = link->done,
2662 			};
2663 			return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c);
2664 		}
2665 	}
2666 
2667 	err = nlmsg_parse_deprecated(nlh, xfrm_msg_min[type], attrs,
2668 				     link->nla_max ? : XFRMA_MAX,
2669 				     link->nla_pol ? : xfrma_policy, extack);
2670 	if (err < 0)
2671 		return err;
2672 
2673 	if (link->doit == NULL)
2674 		return -EINVAL;
2675 
2676 	return link->doit(skb, nlh, attrs);
2677 }
2678 
2679 static void xfrm_netlink_rcv(struct sk_buff *skb)
2680 {
2681 	struct net *net = sock_net(skb->sk);
2682 
2683 	mutex_lock(&net->xfrm.xfrm_cfg_mutex);
2684 	netlink_rcv_skb(skb, &xfrm_user_rcv_msg);
2685 	mutex_unlock(&net->xfrm.xfrm_cfg_mutex);
2686 }
2687 
2688 static inline unsigned int xfrm_expire_msgsize(void)
2689 {
2690 	return NLMSG_ALIGN(sizeof(struct xfrm_user_expire))
2691 	       + nla_total_size(sizeof(struct xfrm_mark));
2692 }
2693 
2694 static int build_expire(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
2695 {
2696 	struct xfrm_user_expire *ue;
2697 	struct nlmsghdr *nlh;
2698 	int err;
2699 
2700 	nlh = nlmsg_put(skb, c->portid, 0, XFRM_MSG_EXPIRE, sizeof(*ue), 0);
2701 	if (nlh == NULL)
2702 		return -EMSGSIZE;
2703 
2704 	ue = nlmsg_data(nlh);
2705 	copy_to_user_state(x, &ue->state);
2706 	ue->hard = (c->data.hard != 0) ? 1 : 0;
2707 	/* clear the padding bytes */
2708 	memset(&ue->hard + 1, 0, sizeof(*ue) - offsetofend(typeof(*ue), hard));
2709 
2710 	err = xfrm_mark_put(skb, &x->mark);
2711 	if (err)
2712 		return err;
2713 
2714 	err = xfrm_if_id_put(skb, x->if_id);
2715 	if (err)
2716 		return err;
2717 
2718 	nlmsg_end(skb, nlh);
2719 	return 0;
2720 }
2721 
2722 static int xfrm_exp_state_notify(struct xfrm_state *x, const struct km_event *c)
2723 {
2724 	struct net *net = xs_net(x);
2725 	struct sk_buff *skb;
2726 
2727 	skb = nlmsg_new(xfrm_expire_msgsize(), GFP_ATOMIC);
2728 	if (skb == NULL)
2729 		return -ENOMEM;
2730 
2731 	if (build_expire(skb, x, c) < 0) {
2732 		kfree_skb(skb);
2733 		return -EMSGSIZE;
2734 	}
2735 
2736 	return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_EXPIRE);
2737 }
2738 
2739 static int xfrm_aevent_state_notify(struct xfrm_state *x, const struct km_event *c)
2740 {
2741 	struct net *net = xs_net(x);
2742 	struct sk_buff *skb;
2743 	int err;
2744 
2745 	skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
2746 	if (skb == NULL)
2747 		return -ENOMEM;
2748 
2749 	err = build_aevent(skb, x, c);
2750 	BUG_ON(err < 0);
2751 
2752 	return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_AEVENTS);
2753 }
2754 
2755 static int xfrm_notify_sa_flush(const struct km_event *c)
2756 {
2757 	struct net *net = c->net;
2758 	struct xfrm_usersa_flush *p;
2759 	struct nlmsghdr *nlh;
2760 	struct sk_buff *skb;
2761 	int len = NLMSG_ALIGN(sizeof(struct xfrm_usersa_flush));
2762 
2763 	skb = nlmsg_new(len, GFP_ATOMIC);
2764 	if (skb == NULL)
2765 		return -ENOMEM;
2766 
2767 	nlh = nlmsg_put(skb, c->portid, c->seq, XFRM_MSG_FLUSHSA, sizeof(*p), 0);
2768 	if (nlh == NULL) {
2769 		kfree_skb(skb);
2770 		return -EMSGSIZE;
2771 	}
2772 
2773 	p = nlmsg_data(nlh);
2774 	p->proto = c->data.proto;
2775 
2776 	nlmsg_end(skb, nlh);
2777 
2778 	return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_SA);
2779 }
2780 
2781 static inline unsigned int xfrm_sa_len(struct xfrm_state *x)
2782 {
2783 	unsigned int l = 0;
2784 	if (x->aead)
2785 		l += nla_total_size(aead_len(x->aead));
2786 	if (x->aalg) {
2787 		l += nla_total_size(sizeof(struct xfrm_algo) +
2788 				    (x->aalg->alg_key_len + 7) / 8);
2789 		l += nla_total_size(xfrm_alg_auth_len(x->aalg));
2790 	}
2791 	if (x->ealg)
2792 		l += nla_total_size(xfrm_alg_len(x->ealg));
2793 	if (x->calg)
2794 		l += nla_total_size(sizeof(*x->calg));
2795 	if (x->encap)
2796 		l += nla_total_size(sizeof(*x->encap));
2797 	if (x->tfcpad)
2798 		l += nla_total_size(sizeof(x->tfcpad));
2799 	if (x->replay_esn)
2800 		l += nla_total_size(xfrm_replay_state_esn_len(x->replay_esn));
2801 	else
2802 		l += nla_total_size(sizeof(struct xfrm_replay_state));
2803 	if (x->security)
2804 		l += nla_total_size(sizeof(struct xfrm_user_sec_ctx) +
2805 				    x->security->ctx_len);
2806 	if (x->coaddr)
2807 		l += nla_total_size(sizeof(*x->coaddr));
2808 	if (x->props.extra_flags)
2809 		l += nla_total_size(sizeof(x->props.extra_flags));
2810 	if (x->xso.dev)
2811 		 l += nla_total_size(sizeof(x->xso));
2812 	if (x->props.smark.v | x->props.smark.m) {
2813 		l += nla_total_size(sizeof(x->props.smark.v));
2814 		l += nla_total_size(sizeof(x->props.smark.m));
2815 	}
2816 	if (x->if_id)
2817 		l += nla_total_size(sizeof(x->if_id));
2818 
2819 	/* Must count x->lastused as it may become non-zero behind our back. */
2820 	l += nla_total_size_64bit(sizeof(u64));
2821 
2822 	return l;
2823 }
2824 
2825 static int xfrm_notify_sa(struct xfrm_state *x, const struct km_event *c)
2826 {
2827 	struct net *net = xs_net(x);
2828 	struct xfrm_usersa_info *p;
2829 	struct xfrm_usersa_id *id;
2830 	struct nlmsghdr *nlh;
2831 	struct sk_buff *skb;
2832 	unsigned int len = xfrm_sa_len(x);
2833 	unsigned int headlen;
2834 	int err;
2835 
2836 	headlen = sizeof(*p);
2837 	if (c->event == XFRM_MSG_DELSA) {
2838 		len += nla_total_size(headlen);
2839 		headlen = sizeof(*id);
2840 		len += nla_total_size(sizeof(struct xfrm_mark));
2841 	}
2842 	len += NLMSG_ALIGN(headlen);
2843 
2844 	skb = nlmsg_new(len, GFP_ATOMIC);
2845 	if (skb == NULL)
2846 		return -ENOMEM;
2847 
2848 	nlh = nlmsg_put(skb, c->portid, c->seq, c->event, headlen, 0);
2849 	err = -EMSGSIZE;
2850 	if (nlh == NULL)
2851 		goto out_free_skb;
2852 
2853 	p = nlmsg_data(nlh);
2854 	if (c->event == XFRM_MSG_DELSA) {
2855 		struct nlattr *attr;
2856 
2857 		id = nlmsg_data(nlh);
2858 		memset(id, 0, sizeof(*id));
2859 		memcpy(&id->daddr, &x->id.daddr, sizeof(id->daddr));
2860 		id->spi = x->id.spi;
2861 		id->family = x->props.family;
2862 		id->proto = x->id.proto;
2863 
2864 		attr = nla_reserve(skb, XFRMA_SA, sizeof(*p));
2865 		err = -EMSGSIZE;
2866 		if (attr == NULL)
2867 			goto out_free_skb;
2868 
2869 		p = nla_data(attr);
2870 	}
2871 	err = copy_to_user_state_extra(x, p, skb);
2872 	if (err)
2873 		goto out_free_skb;
2874 
2875 	nlmsg_end(skb, nlh);
2876 
2877 	return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_SA);
2878 
2879 out_free_skb:
2880 	kfree_skb(skb);
2881 	return err;
2882 }
2883 
2884 static int xfrm_send_state_notify(struct xfrm_state *x, const struct km_event *c)
2885 {
2886 
2887 	switch (c->event) {
2888 	case XFRM_MSG_EXPIRE:
2889 		return xfrm_exp_state_notify(x, c);
2890 	case XFRM_MSG_NEWAE:
2891 		return xfrm_aevent_state_notify(x, c);
2892 	case XFRM_MSG_DELSA:
2893 	case XFRM_MSG_UPDSA:
2894 	case XFRM_MSG_NEWSA:
2895 		return xfrm_notify_sa(x, c);
2896 	case XFRM_MSG_FLUSHSA:
2897 		return xfrm_notify_sa_flush(c);
2898 	default:
2899 		printk(KERN_NOTICE "xfrm_user: Unknown SA event %d\n",
2900 		       c->event);
2901 		break;
2902 	}
2903 
2904 	return 0;
2905 
2906 }
2907 
2908 static inline unsigned int xfrm_acquire_msgsize(struct xfrm_state *x,
2909 						struct xfrm_policy *xp)
2910 {
2911 	return NLMSG_ALIGN(sizeof(struct xfrm_user_acquire))
2912 	       + nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr)
2913 	       + nla_total_size(sizeof(struct xfrm_mark))
2914 	       + nla_total_size(xfrm_user_sec_ctx_size(x->security))
2915 	       + userpolicy_type_attrsize();
2916 }
2917 
2918 static int build_acquire(struct sk_buff *skb, struct xfrm_state *x,
2919 			 struct xfrm_tmpl *xt, struct xfrm_policy *xp)
2920 {
2921 	__u32 seq = xfrm_get_acqseq();
2922 	struct xfrm_user_acquire *ua;
2923 	struct nlmsghdr *nlh;
2924 	int err;
2925 
2926 	nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_ACQUIRE, sizeof(*ua), 0);
2927 	if (nlh == NULL)
2928 		return -EMSGSIZE;
2929 
2930 	ua = nlmsg_data(nlh);
2931 	memcpy(&ua->id, &x->id, sizeof(ua->id));
2932 	memcpy(&ua->saddr, &x->props.saddr, sizeof(ua->saddr));
2933 	memcpy(&ua->sel, &x->sel, sizeof(ua->sel));
2934 	copy_to_user_policy(xp, &ua->policy, XFRM_POLICY_OUT);
2935 	ua->aalgos = xt->aalgos;
2936 	ua->ealgos = xt->ealgos;
2937 	ua->calgos = xt->calgos;
2938 	ua->seq = x->km.seq = seq;
2939 
2940 	err = copy_to_user_tmpl(xp, skb);
2941 	if (!err)
2942 		err = copy_to_user_state_sec_ctx(x, skb);
2943 	if (!err)
2944 		err = copy_to_user_policy_type(xp->type, skb);
2945 	if (!err)
2946 		err = xfrm_mark_put(skb, &xp->mark);
2947 	if (!err)
2948 		err = xfrm_if_id_put(skb, xp->if_id);
2949 	if (err) {
2950 		nlmsg_cancel(skb, nlh);
2951 		return err;
2952 	}
2953 
2954 	nlmsg_end(skb, nlh);
2955 	return 0;
2956 }
2957 
2958 static int xfrm_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *xt,
2959 			     struct xfrm_policy *xp)
2960 {
2961 	struct net *net = xs_net(x);
2962 	struct sk_buff *skb;
2963 	int err;
2964 
2965 	skb = nlmsg_new(xfrm_acquire_msgsize(x, xp), GFP_ATOMIC);
2966 	if (skb == NULL)
2967 		return -ENOMEM;
2968 
2969 	err = build_acquire(skb, x, xt, xp);
2970 	BUG_ON(err < 0);
2971 
2972 	return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_ACQUIRE);
2973 }
2974 
2975 /* User gives us xfrm_user_policy_info followed by an array of 0
2976  * or more templates.
2977  */
2978 static struct xfrm_policy *xfrm_compile_policy(struct sock *sk, int opt,
2979 					       u8 *data, int len, int *dir)
2980 {
2981 	struct net *net = sock_net(sk);
2982 	struct xfrm_userpolicy_info *p = (struct xfrm_userpolicy_info *)data;
2983 	struct xfrm_user_tmpl *ut = (struct xfrm_user_tmpl *) (p + 1);
2984 	struct xfrm_policy *xp;
2985 	int nr;
2986 
2987 	switch (sk->sk_family) {
2988 	case AF_INET:
2989 		if (opt != IP_XFRM_POLICY) {
2990 			*dir = -EOPNOTSUPP;
2991 			return NULL;
2992 		}
2993 		break;
2994 #if IS_ENABLED(CONFIG_IPV6)
2995 	case AF_INET6:
2996 		if (opt != IPV6_XFRM_POLICY) {
2997 			*dir = -EOPNOTSUPP;
2998 			return NULL;
2999 		}
3000 		break;
3001 #endif
3002 	default:
3003 		*dir = -EINVAL;
3004 		return NULL;
3005 	}
3006 
3007 	*dir = -EINVAL;
3008 
3009 	if (len < sizeof(*p) ||
3010 	    verify_newpolicy_info(p))
3011 		return NULL;
3012 
3013 	nr = ((len - sizeof(*p)) / sizeof(*ut));
3014 	if (validate_tmpl(nr, ut, p->sel.family))
3015 		return NULL;
3016 
3017 	if (p->dir > XFRM_POLICY_OUT)
3018 		return NULL;
3019 
3020 	xp = xfrm_policy_alloc(net, GFP_ATOMIC);
3021 	if (xp == NULL) {
3022 		*dir = -ENOBUFS;
3023 		return NULL;
3024 	}
3025 
3026 	copy_from_user_policy(xp, p);
3027 	xp->type = XFRM_POLICY_TYPE_MAIN;
3028 	copy_templates(xp, ut, nr);
3029 
3030 	*dir = p->dir;
3031 
3032 	return xp;
3033 }
3034 
3035 static inline unsigned int xfrm_polexpire_msgsize(struct xfrm_policy *xp)
3036 {
3037 	return NLMSG_ALIGN(sizeof(struct xfrm_user_polexpire))
3038 	       + nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr)
3039 	       + nla_total_size(xfrm_user_sec_ctx_size(xp->security))
3040 	       + nla_total_size(sizeof(struct xfrm_mark))
3041 	       + userpolicy_type_attrsize();
3042 }
3043 
3044 static int build_polexpire(struct sk_buff *skb, struct xfrm_policy *xp,
3045 			   int dir, const struct km_event *c)
3046 {
3047 	struct xfrm_user_polexpire *upe;
3048 	int hard = c->data.hard;
3049 	struct nlmsghdr *nlh;
3050 	int err;
3051 
3052 	nlh = nlmsg_put(skb, c->portid, 0, XFRM_MSG_POLEXPIRE, sizeof(*upe), 0);
3053 	if (nlh == NULL)
3054 		return -EMSGSIZE;
3055 
3056 	upe = nlmsg_data(nlh);
3057 	copy_to_user_policy(xp, &upe->pol, dir);
3058 	err = copy_to_user_tmpl(xp, skb);
3059 	if (!err)
3060 		err = copy_to_user_sec_ctx(xp, skb);
3061 	if (!err)
3062 		err = copy_to_user_policy_type(xp->type, skb);
3063 	if (!err)
3064 		err = xfrm_mark_put(skb, &xp->mark);
3065 	if (!err)
3066 		err = xfrm_if_id_put(skb, xp->if_id);
3067 	if (err) {
3068 		nlmsg_cancel(skb, nlh);
3069 		return err;
3070 	}
3071 	upe->hard = !!hard;
3072 
3073 	nlmsg_end(skb, nlh);
3074 	return 0;
3075 }
3076 
3077 static int xfrm_exp_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
3078 {
3079 	struct net *net = xp_net(xp);
3080 	struct sk_buff *skb;
3081 	int err;
3082 
3083 	skb = nlmsg_new(xfrm_polexpire_msgsize(xp), GFP_ATOMIC);
3084 	if (skb == NULL)
3085 		return -ENOMEM;
3086 
3087 	err = build_polexpire(skb, xp, dir, c);
3088 	BUG_ON(err < 0);
3089 
3090 	return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_EXPIRE);
3091 }
3092 
3093 static int xfrm_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c)
3094 {
3095 	unsigned int len = nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr);
3096 	struct net *net = xp_net(xp);
3097 	struct xfrm_userpolicy_info *p;
3098 	struct xfrm_userpolicy_id *id;
3099 	struct nlmsghdr *nlh;
3100 	struct sk_buff *skb;
3101 	unsigned int headlen;
3102 	int err;
3103 
3104 	headlen = sizeof(*p);
3105 	if (c->event == XFRM_MSG_DELPOLICY) {
3106 		len += nla_total_size(headlen);
3107 		headlen = sizeof(*id);
3108 	}
3109 	len += userpolicy_type_attrsize();
3110 	len += nla_total_size(sizeof(struct xfrm_mark));
3111 	len += NLMSG_ALIGN(headlen);
3112 
3113 	skb = nlmsg_new(len, GFP_ATOMIC);
3114 	if (skb == NULL)
3115 		return -ENOMEM;
3116 
3117 	nlh = nlmsg_put(skb, c->portid, c->seq, c->event, headlen, 0);
3118 	err = -EMSGSIZE;
3119 	if (nlh == NULL)
3120 		goto out_free_skb;
3121 
3122 	p = nlmsg_data(nlh);
3123 	if (c->event == XFRM_MSG_DELPOLICY) {
3124 		struct nlattr *attr;
3125 
3126 		id = nlmsg_data(nlh);
3127 		memset(id, 0, sizeof(*id));
3128 		id->dir = dir;
3129 		if (c->data.byid)
3130 			id->index = xp->index;
3131 		else
3132 			memcpy(&id->sel, &xp->selector, sizeof(id->sel));
3133 
3134 		attr = nla_reserve(skb, XFRMA_POLICY, sizeof(*p));
3135 		err = -EMSGSIZE;
3136 		if (attr == NULL)
3137 			goto out_free_skb;
3138 
3139 		p = nla_data(attr);
3140 	}
3141 
3142 	copy_to_user_policy(xp, p, dir);
3143 	err = copy_to_user_tmpl(xp, skb);
3144 	if (!err)
3145 		err = copy_to_user_policy_type(xp->type, skb);
3146 	if (!err)
3147 		err = xfrm_mark_put(skb, &xp->mark);
3148 	if (!err)
3149 		err = xfrm_if_id_put(skb, xp->if_id);
3150 	if (err)
3151 		goto out_free_skb;
3152 
3153 	nlmsg_end(skb, nlh);
3154 
3155 	return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_POLICY);
3156 
3157 out_free_skb:
3158 	kfree_skb(skb);
3159 	return err;
3160 }
3161 
3162 static int xfrm_notify_policy_flush(const struct km_event *c)
3163 {
3164 	struct net *net = c->net;
3165 	struct nlmsghdr *nlh;
3166 	struct sk_buff *skb;
3167 	int err;
3168 
3169 	skb = nlmsg_new(userpolicy_type_attrsize(), GFP_ATOMIC);
3170 	if (skb == NULL)
3171 		return -ENOMEM;
3172 
3173 	nlh = nlmsg_put(skb, c->portid, c->seq, XFRM_MSG_FLUSHPOLICY, 0, 0);
3174 	err = -EMSGSIZE;
3175 	if (nlh == NULL)
3176 		goto out_free_skb;
3177 	err = copy_to_user_policy_type(c->data.type, skb);
3178 	if (err)
3179 		goto out_free_skb;
3180 
3181 	nlmsg_end(skb, nlh);
3182 
3183 	return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_POLICY);
3184 
3185 out_free_skb:
3186 	kfree_skb(skb);
3187 	return err;
3188 }
3189 
3190 static int xfrm_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
3191 {
3192 
3193 	switch (c->event) {
3194 	case XFRM_MSG_NEWPOLICY:
3195 	case XFRM_MSG_UPDPOLICY:
3196 	case XFRM_MSG_DELPOLICY:
3197 		return xfrm_notify_policy(xp, dir, c);
3198 	case XFRM_MSG_FLUSHPOLICY:
3199 		return xfrm_notify_policy_flush(c);
3200 	case XFRM_MSG_POLEXPIRE:
3201 		return xfrm_exp_policy_notify(xp, dir, c);
3202 	default:
3203 		printk(KERN_NOTICE "xfrm_user: Unknown Policy event %d\n",
3204 		       c->event);
3205 	}
3206 
3207 	return 0;
3208 
3209 }
3210 
3211 static inline unsigned int xfrm_report_msgsize(void)
3212 {
3213 	return NLMSG_ALIGN(sizeof(struct xfrm_user_report));
3214 }
3215 
3216 static int build_report(struct sk_buff *skb, u8 proto,
3217 			struct xfrm_selector *sel, xfrm_address_t *addr)
3218 {
3219 	struct xfrm_user_report *ur;
3220 	struct nlmsghdr *nlh;
3221 
3222 	nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_REPORT, sizeof(*ur), 0);
3223 	if (nlh == NULL)
3224 		return -EMSGSIZE;
3225 
3226 	ur = nlmsg_data(nlh);
3227 	ur->proto = proto;
3228 	memcpy(&ur->sel, sel, sizeof(ur->sel));
3229 
3230 	if (addr) {
3231 		int err = nla_put(skb, XFRMA_COADDR, sizeof(*addr), addr);
3232 		if (err) {
3233 			nlmsg_cancel(skb, nlh);
3234 			return err;
3235 		}
3236 	}
3237 	nlmsg_end(skb, nlh);
3238 	return 0;
3239 }
3240 
3241 static int xfrm_send_report(struct net *net, u8 proto,
3242 			    struct xfrm_selector *sel, xfrm_address_t *addr)
3243 {
3244 	struct sk_buff *skb;
3245 	int err;
3246 
3247 	skb = nlmsg_new(xfrm_report_msgsize(), GFP_ATOMIC);
3248 	if (skb == NULL)
3249 		return -ENOMEM;
3250 
3251 	err = build_report(skb, proto, sel, addr);
3252 	BUG_ON(err < 0);
3253 
3254 	return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_REPORT);
3255 }
3256 
3257 static inline unsigned int xfrm_mapping_msgsize(void)
3258 {
3259 	return NLMSG_ALIGN(sizeof(struct xfrm_user_mapping));
3260 }
3261 
3262 static int build_mapping(struct sk_buff *skb, struct xfrm_state *x,
3263 			 xfrm_address_t *new_saddr, __be16 new_sport)
3264 {
3265 	struct xfrm_user_mapping *um;
3266 	struct nlmsghdr *nlh;
3267 
3268 	nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MAPPING, sizeof(*um), 0);
3269 	if (nlh == NULL)
3270 		return -EMSGSIZE;
3271 
3272 	um = nlmsg_data(nlh);
3273 
3274 	memcpy(&um->id.daddr, &x->id.daddr, sizeof(um->id.daddr));
3275 	um->id.spi = x->id.spi;
3276 	um->id.family = x->props.family;
3277 	um->id.proto = x->id.proto;
3278 	memcpy(&um->new_saddr, new_saddr, sizeof(um->new_saddr));
3279 	memcpy(&um->old_saddr, &x->props.saddr, sizeof(um->old_saddr));
3280 	um->new_sport = new_sport;
3281 	um->old_sport = x->encap->encap_sport;
3282 	um->reqid = x->props.reqid;
3283 
3284 	nlmsg_end(skb, nlh);
3285 	return 0;
3286 }
3287 
3288 static int xfrm_send_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr,
3289 			     __be16 sport)
3290 {
3291 	struct net *net = xs_net(x);
3292 	struct sk_buff *skb;
3293 	int err;
3294 
3295 	if (x->id.proto != IPPROTO_ESP)
3296 		return -EINVAL;
3297 
3298 	if (!x->encap)
3299 		return -EINVAL;
3300 
3301 	skb = nlmsg_new(xfrm_mapping_msgsize(), GFP_ATOMIC);
3302 	if (skb == NULL)
3303 		return -ENOMEM;
3304 
3305 	err = build_mapping(skb, x, ipaddr, sport);
3306 	BUG_ON(err < 0);
3307 
3308 	return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_MAPPING);
3309 }
3310 
3311 static bool xfrm_is_alive(const struct km_event *c)
3312 {
3313 	return (bool)xfrm_acquire_is_on(c->net);
3314 }
3315 
3316 static struct xfrm_mgr netlink_mgr = {
3317 	.notify		= xfrm_send_state_notify,
3318 	.acquire	= xfrm_send_acquire,
3319 	.compile_policy	= xfrm_compile_policy,
3320 	.notify_policy	= xfrm_send_policy_notify,
3321 	.report		= xfrm_send_report,
3322 	.migrate	= xfrm_send_migrate,
3323 	.new_mapping	= xfrm_send_mapping,
3324 	.is_alive	= xfrm_is_alive,
3325 };
3326 
3327 static int __net_init xfrm_user_net_init(struct net *net)
3328 {
3329 	struct sock *nlsk;
3330 	struct netlink_kernel_cfg cfg = {
3331 		.groups	= XFRMNLGRP_MAX,
3332 		.input	= xfrm_netlink_rcv,
3333 	};
3334 
3335 	nlsk = netlink_kernel_create(net, NETLINK_XFRM, &cfg);
3336 	if (nlsk == NULL)
3337 		return -ENOMEM;
3338 	net->xfrm.nlsk_stash = nlsk; /* Don't set to NULL */
3339 	rcu_assign_pointer(net->xfrm.nlsk, nlsk);
3340 	return 0;
3341 }
3342 
3343 static void __net_exit xfrm_user_net_exit(struct list_head *net_exit_list)
3344 {
3345 	struct net *net;
3346 	list_for_each_entry(net, net_exit_list, exit_list)
3347 		RCU_INIT_POINTER(net->xfrm.nlsk, NULL);
3348 	synchronize_net();
3349 	list_for_each_entry(net, net_exit_list, exit_list)
3350 		netlink_kernel_release(net->xfrm.nlsk_stash);
3351 }
3352 
3353 static struct pernet_operations xfrm_user_net_ops = {
3354 	.init	    = xfrm_user_net_init,
3355 	.exit_batch = xfrm_user_net_exit,
3356 };
3357 
3358 static int __init xfrm_user_init(void)
3359 {
3360 	int rv;
3361 
3362 	printk(KERN_INFO "Initializing XFRM netlink socket\n");
3363 
3364 	rv = register_pernet_subsys(&xfrm_user_net_ops);
3365 	if (rv < 0)
3366 		return rv;
3367 	rv = xfrm_register_km(&netlink_mgr);
3368 	if (rv < 0)
3369 		unregister_pernet_subsys(&xfrm_user_net_ops);
3370 	return rv;
3371 }
3372 
3373 static void __exit xfrm_user_exit(void)
3374 {
3375 	xfrm_unregister_km(&netlink_mgr);
3376 	unregister_pernet_subsys(&xfrm_user_net_ops);
3377 }
3378 
3379 module_init(xfrm_user_init);
3380 module_exit(xfrm_user_exit);
3381 MODULE_LICENSE("GPL");
3382 MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_XFRM);
3383