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