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