File Index
Files and directories
Sign in
FILE

xfrm_user.c

File preview with syntax highlighting.

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