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