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