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