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