Home | History | Annotate | Line # | Download | only in netipsec
key.c revision 1.100
      1 /*	$NetBSD: key.c,v 1.100 2016/07/07 06:59:30 ozaki-r Exp $	*/
      2 /*	$FreeBSD: src/sys/netipsec/key.c,v 1.3.2.3 2004/02/14 22:23:23 bms Exp $	*/
      3 /*	$KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $	*/
      4 
      5 /*
      6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      7  * All rights reserved.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. Neither the name of the project nor the names of its contributors
     18  *    may be used to endorse or promote products derived from this software
     19  *    without specific prior written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     31  * SUCH DAMAGE.
     32  */
     33 
     34 #include <sys/cdefs.h>
     35 __KERNEL_RCSID(0, "$NetBSD: key.c,v 1.100 2016/07/07 06:59:30 ozaki-r Exp $");
     36 
     37 /*
     38  * This code is referd to RFC 2367
     39  */
     40 
     41 #include "opt_inet.h"
     42 #ifdef __FreeBSD__
     43 #include "opt_inet6.h"
     44 #endif
     45 #include "opt_ipsec.h"
     46 #ifdef __NetBSD__
     47 #include "opt_gateway.h"
     48 #endif
     49 
     50 #include <sys/types.h>
     51 #include <sys/param.h>
     52 #include <sys/systm.h>
     53 #include <sys/callout.h>
     54 #include <sys/kernel.h>
     55 #include <sys/mbuf.h>
     56 #include <sys/domain.h>
     57 #include <sys/protosw.h>
     58 #include <sys/malloc.h>
     59 #include <sys/socket.h>
     60 #include <sys/socketvar.h>
     61 #include <sys/sysctl.h>
     62 #include <sys/errno.h>
     63 #include <sys/proc.h>
     64 #include <sys/queue.h>
     65 #include <sys/syslog.h>
     66 #include <sys/once.h>
     67 #include <sys/cprng.h>
     68 
     69 #include <net/if.h>
     70 #include <net/route.h>
     71 #include <net/raw_cb.h>
     72 
     73 #include <netinet/in.h>
     74 #include <netinet/in_systm.h>
     75 #include <netinet/ip.h>
     76 #include <netinet/in_var.h>
     77 #ifdef INET
     78 #include <netinet/ip_var.h>
     79 #endif
     80 
     81 #ifdef INET6
     82 #include <netinet/ip6.h>
     83 #include <netinet6/in6_var.h>
     84 #include <netinet6/ip6_var.h>
     85 #endif /* INET6 */
     86 
     87 #ifdef INET
     88 #include <netinet/in_pcb.h>
     89 #endif
     90 #ifdef INET6
     91 #include <netinet6/in6_pcb.h>
     92 #endif /* INET6 */
     93 
     94 #include <net/pfkeyv2.h>
     95 #include <netipsec/keydb.h>
     96 #include <netipsec/key.h>
     97 #include <netipsec/keysock.h>
     98 #include <netipsec/key_debug.h>
     99 
    100 #include <netipsec/ipsec.h>
    101 #ifdef INET6
    102 #include <netipsec/ipsec6.h>
    103 #endif
    104 #include <netipsec/ipsec_private.h>
    105 
    106 #include <netipsec/xform.h>
    107 #include <netipsec/ipsec_osdep.h>
    108 #include <netipsec/ipcomp.h>
    109 
    110 
    111 #include <net/net_osdep.h>
    112 
    113 #define FULLMASK	0xff
    114 #define	_BITS(bytes)	((bytes) << 3)
    115 
    116 #define PORT_NONE	0
    117 #define PORT_LOOSE	1
    118 #define PORT_STRICT	2
    119 
    120 percpu_t *pfkeystat_percpu;
    121 
    122 /*
    123  * Note on SA reference counting:
    124  * - SAs that are not in DEAD state will have (total external reference + 1)
    125  *   following value in reference count field.  they cannot be freed and are
    126  *   referenced from SA header.
    127  * - SAs that are in DEAD state will have (total external reference)
    128  *   in reference count field.  they are ready to be freed.  reference from
    129  *   SA header will be removed in key_delsav(), when the reference count
    130  *   field hits 0 (= no external reference other than from SA header.
    131  */
    132 
    133 u_int32_t key_debug_level = 0;
    134 static u_int key_spi_trycnt = 1000;
    135 static u_int32_t key_spi_minval = 0x100;
    136 static u_int32_t key_spi_maxval = 0x0fffffff;	/* XXX */
    137 static u_int32_t policy_id = 0;
    138 static u_int key_int_random = 60;	/*interval to initialize randseed,1(m)*/
    139 static u_int key_larval_lifetime = 30;	/* interval to expire acquiring, 30(s)*/
    140 static int key_blockacq_count = 10;	/* counter for blocking SADB_ACQUIRE.*/
    141 static int key_blockacq_lifetime = 20;	/* lifetime for blocking SADB_ACQUIRE.*/
    142 static int key_prefered_oldsa = 0;	/* prefered old sa rather than new sa.*/
    143 
    144 static u_int32_t acq_seq = 0;
    145 
    146 static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];	/* SPD */
    147 static LIST_HEAD(_sahtree, secashead) sahtree;			/* SAD */
    148 static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
    149 							/* registed list */
    150 #ifndef IPSEC_NONBLOCK_ACQUIRE
    151 static LIST_HEAD(_acqtree, secacq) acqtree;		/* acquiring list */
    152 #endif
    153 static LIST_HEAD(_spacqtree, secspacq) spacqtree;	/* SP acquiring list */
    154 
    155 /* search order for SAs */
    156 	/*
    157 	 * This order is important because we must select the oldest SA
    158 	 * for outbound processing.  For inbound, This is not important.
    159 	 */
    160 static const u_int saorder_state_valid_prefer_old[] = {
    161 	SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
    162 };
    163 static const u_int saorder_state_valid_prefer_new[] = {
    164 	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
    165 };
    166 
    167 static const u_int saorder_state_alive[] = {
    168 	/* except DEAD */
    169 	SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
    170 };
    171 static const u_int saorder_state_any[] = {
    172 	SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
    173 	SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
    174 };
    175 
    176 static const int minsize[] = {
    177 	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
    178 	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
    179 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
    180 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
    181 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
    182 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_SRC */
    183 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_DST */
    184 	sizeof(struct sadb_address),	/* SADB_EXT_ADDRESS_PROXY */
    185 	sizeof(struct sadb_key),	/* SADB_EXT_KEY_AUTH */
    186 	sizeof(struct sadb_key),	/* SADB_EXT_KEY_ENCRYPT */
    187 	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_SRC */
    188 	sizeof(struct sadb_ident),	/* SADB_EXT_IDENTITY_DST */
    189 	sizeof(struct sadb_sens),	/* SADB_EXT_SENSITIVITY */
    190 	sizeof(struct sadb_prop),	/* SADB_EXT_PROPOSAL */
    191 	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_AUTH */
    192 	sizeof(struct sadb_supported),	/* SADB_EXT_SUPPORTED_ENCRYPT */
    193 	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
    194 	0,				/* SADB_X_EXT_KMPRIVATE */
    195 	sizeof(struct sadb_x_policy),	/* SADB_X_EXT_POLICY */
    196 	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
    197 	sizeof(struct sadb_x_nat_t_type),	/* SADB_X_EXT_NAT_T_TYPE */
    198 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_SPORT */
    199 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_DPORT */
    200 	sizeof(struct sadb_address),		/* SADB_X_EXT_NAT_T_OAI */
    201 	sizeof(struct sadb_address),		/* SADB_X_EXT_NAT_T_OAR */
    202 	sizeof(struct sadb_x_nat_t_frag),	/* SADB_X_EXT_NAT_T_FRAG */
    203 };
    204 static const int maxsize[] = {
    205 	sizeof(struct sadb_msg),	/* SADB_EXT_RESERVED */
    206 	sizeof(struct sadb_sa),		/* SADB_EXT_SA */
    207 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_CURRENT */
    208 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_HARD */
    209 	sizeof(struct sadb_lifetime),	/* SADB_EXT_LIFETIME_SOFT */
    210 	0,				/* SADB_EXT_ADDRESS_SRC */
    211 	0,				/* SADB_EXT_ADDRESS_DST */
    212 	0,				/* SADB_EXT_ADDRESS_PROXY */
    213 	0,				/* SADB_EXT_KEY_AUTH */
    214 	0,				/* SADB_EXT_KEY_ENCRYPT */
    215 	0,				/* SADB_EXT_IDENTITY_SRC */
    216 	0,				/* SADB_EXT_IDENTITY_DST */
    217 	0,				/* SADB_EXT_SENSITIVITY */
    218 	0,				/* SADB_EXT_PROPOSAL */
    219 	0,				/* SADB_EXT_SUPPORTED_AUTH */
    220 	0,				/* SADB_EXT_SUPPORTED_ENCRYPT */
    221 	sizeof(struct sadb_spirange),	/* SADB_EXT_SPIRANGE */
    222 	0,				/* SADB_X_EXT_KMPRIVATE */
    223 	0,				/* SADB_X_EXT_POLICY */
    224 	sizeof(struct sadb_x_sa2),	/* SADB_X_SA2 */
    225 	sizeof(struct sadb_x_nat_t_type),	/* SADB_X_EXT_NAT_T_TYPE */
    226 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_SPORT */
    227 	sizeof(struct sadb_x_nat_t_port),	/* SADB_X_EXT_NAT_T_DPORT */
    228 	0,					/* SADB_X_EXT_NAT_T_OAI */
    229 	0,					/* SADB_X_EXT_NAT_T_OAR */
    230 	sizeof(struct sadb_x_nat_t_frag),	/* SADB_X_EXT_NAT_T_FRAG */
    231 };
    232 
    233 static int ipsec_esp_keymin = 256;
    234 static int ipsec_esp_auth = 0;
    235 static int ipsec_ah_keymin = 128;
    236 
    237 #ifdef SYSCTL_DECL
    238 SYSCTL_DECL(_net_key);
    239 #endif
    240 
    241 #ifdef SYSCTL_INT
    242 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL,	debug,	CTLFLAG_RW, \
    243 	&key_debug_level,	0,	"");
    244 
    245 /* max count of trial for the decision of spi value */
    246 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY,		spi_trycnt,	CTLFLAG_RW, \
    247 	&key_spi_trycnt,	0,	"");
    248 
    249 /* minimum spi value to allocate automatically. */
    250 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE,	spi_minval,	CTLFLAG_RW, \
    251 	&key_spi_minval,	0,	"");
    252 
    253 /* maximun spi value to allocate automatically. */
    254 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE,	spi_maxval,	CTLFLAG_RW, \
    255 	&key_spi_maxval,	0,	"");
    256 
    257 /* interval to initialize randseed */
    258 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT,	int_random,	CTLFLAG_RW, \
    259 	&key_int_random,	0,	"");
    260 
    261 /* lifetime for larval SA */
    262 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME,	larval_lifetime, CTLFLAG_RW, \
    263 	&key_larval_lifetime,	0,	"");
    264 
    265 /* counter for blocking to send SADB_ACQUIRE to IKEd */
    266 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,	blockacq_count,	CTLFLAG_RW, \
    267 	&key_blockacq_count,	0,	"");
    268 
    269 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
    270 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,	blockacq_lifetime, CTLFLAG_RW, \
    271 	&key_blockacq_lifetime,	0,	"");
    272 
    273 /* ESP auth */
    274 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH,	esp_auth, CTLFLAG_RW, \
    275 	&ipsec_esp_auth,	0,	"");
    276 
    277 /* minimum ESP key length */
    278 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN,	esp_keymin, CTLFLAG_RW, \
    279 	&ipsec_esp_keymin,	0,	"");
    280 
    281 /* minimum AH key length */
    282 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN,	ah_keymin, CTLFLAG_RW, \
    283 	&ipsec_ah_keymin,	0,	"");
    284 
    285 /* perfered old SA rather than new SA */
    286 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA,	prefered_oldsa, CTLFLAG_RW,\
    287 	&key_prefered_oldsa,	0,	"");
    288 #endif /* SYSCTL_INT */
    289 
    290 #ifndef LIST_FOREACH
    291 #define LIST_FOREACH(elm, head, field)                                     \
    292 	for (elm = LIST_FIRST(head); elm; elm = LIST_NEXT(elm, field))
    293 #endif
    294 #define __LIST_CHAINED(elm) \
    295 	(!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
    296 #define LIST_INSERT_TAIL(head, elm, type, field) \
    297 do {\
    298 	struct type *curelm = LIST_FIRST(head); \
    299 	if (curelm == NULL) {\
    300 		LIST_INSERT_HEAD(head, elm, field); \
    301 	} else { \
    302 		while (LIST_NEXT(curelm, field)) \
    303 			curelm = LIST_NEXT(curelm, field);\
    304 		LIST_INSERT_AFTER(curelm, elm, field);\
    305 	}\
    306 } while (0)
    307 
    308 #define KEY_CHKSASTATE(head, sav, name) \
    309 /* do */ { \
    310 	if ((head) != (sav)) {						\
    311 		ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
    312 			(name), (head), (sav)));			\
    313 		continue;						\
    314 	}								\
    315 } /* while (0) */
    316 
    317 #define KEY_CHKSPDIR(head, sp, name) \
    318 do { \
    319 	if ((head) != (sp)) {						\
    320 		ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
    321 			"anyway continue.\n",				\
    322 			(name), (head), (sp)));				\
    323 	}								\
    324 } while (0)
    325 
    326 MALLOC_DEFINE(M_SECA, "key mgmt", "security associations, key management");
    327 
    328 #if 1
    329 #define KMALLOC(p, t, n)                                                     \
    330 	((p) = (t) malloc((unsigned long)(n), M_SECA, M_NOWAIT))
    331 #define KFREE(p)                                                             \
    332 	free((p), M_SECA)
    333 #else
    334 #define KMALLOC(p, t, n) \
    335 do { \
    336 	((p) = malloc((unsigned long)(n), M_SECA, M_NOWAIT));             \
    337 	printf("%s %d: %p <- KMALLOC(%s, %d)\n",                             \
    338 	    __FILE__, __LINE__, (p), #t, n);                             	\
    339 } while (0)
    340 
    341 #define KFREE(p)                                                             \
    342 	do {                                                                 \
    343 		printf("%s %d: %p -> KFREE()\n", __FILE__, __LINE__, (p));   \
    344 		free((p), M_SECA);                                  \
    345 	} while (0)
    346 #endif
    347 
    348 /*
    349  * set parameters into secpolicyindex buffer.
    350  * Must allocate secpolicyindex buffer passed to this function.
    351  */
    352 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
    353 do { \
    354 	memset((idx), 0, sizeof(struct secpolicyindex));                     \
    355 	(idx)->dir = (_dir);                                                 \
    356 	(idx)->prefs = (ps);                                                 \
    357 	(idx)->prefd = (pd);                                                 \
    358 	(idx)->ul_proto = (ulp);                                             \
    359 	memcpy(&(idx)->src, (s), ((const struct sockaddr *)(s))->sa_len);    \
    360 	memcpy(&(idx)->dst, (d), ((const struct sockaddr *)(d))->sa_len);    \
    361 } while (0)
    362 
    363 /*
    364  * set parameters into secasindex buffer.
    365  * Must allocate secasindex buffer before calling this function.
    366  */
    367 static int
    368 key_setsecasidx (int, int, int, const struct sadb_address *,
    369 		     const struct sadb_address *, struct secasindex *);
    370 
    371 /* key statistics */
    372 struct _keystat {
    373 	u_long getspi_count; /* the avarage of count to try to get new SPI */
    374 } keystat;
    375 
    376 struct sadb_msghdr {
    377 	struct sadb_msg *msg;
    378 	struct sadb_ext *ext[SADB_EXT_MAX + 1];
    379 	int extoff[SADB_EXT_MAX + 1];
    380 	int extlen[SADB_EXT_MAX + 1];
    381 };
    382 
    383 static struct secasvar *key_allocsa_policy (const struct secasindex *);
    384 static void key_freesp_so (struct secpolicy **);
    385 static struct secasvar *key_do_allocsa_policy (struct secashead *, u_int);
    386 static void key_delsp (struct secpolicy *);
    387 static struct secpolicy *key_getsp (const struct secpolicyindex *);
    388 static struct secpolicy *key_getspbyid (u_int32_t);
    389 static u_int16_t key_newreqid (void);
    390 static struct mbuf *key_gather_mbuf (struct mbuf *,
    391 	const struct sadb_msghdr *, int, int, ...);
    392 static int key_spdadd (struct socket *, struct mbuf *,
    393 	const struct sadb_msghdr *);
    394 static u_int32_t key_getnewspid (void);
    395 static int key_spddelete (struct socket *, struct mbuf *,
    396 	const struct sadb_msghdr *);
    397 static int key_spddelete2 (struct socket *, struct mbuf *,
    398 	const struct sadb_msghdr *);
    399 static int key_spdget (struct socket *, struct mbuf *,
    400 	const struct sadb_msghdr *);
    401 static int key_spdflush (struct socket *, struct mbuf *,
    402 	const struct sadb_msghdr *);
    403 static int key_spddump (struct socket *, struct mbuf *,
    404 	const struct sadb_msghdr *);
    405 static struct mbuf * key_setspddump (int *errorp, pid_t);
    406 static struct mbuf * key_setspddump_chain (int *errorp, int *lenp, pid_t pid);
    407 static int key_nat_map (struct socket *, struct mbuf *,
    408 	const struct sadb_msghdr *);
    409 static struct mbuf *key_setdumpsp (struct secpolicy *,
    410 	u_int8_t, u_int32_t, pid_t);
    411 static u_int key_getspreqmsglen (const struct secpolicy *);
    412 static int key_spdexpire (struct secpolicy *);
    413 static struct secashead *key_newsah (const struct secasindex *);
    414 static void key_delsah (struct secashead *);
    415 static struct secasvar *key_newsav (struct mbuf *,
    416 	const struct sadb_msghdr *, struct secashead *, int *,
    417 	const char*, int);
    418 #define	KEY_NEWSAV(m, sadb, sah, e)				\
    419 	key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
    420 static void key_delsav (struct secasvar *);
    421 static struct secashead *key_getsah (const struct secasindex *);
    422 static struct secasvar *key_checkspidup (const struct secasindex *, u_int32_t);
    423 static struct secasvar *key_getsavbyspi (struct secashead *, u_int32_t);
    424 static int key_setsaval (struct secasvar *, struct mbuf *,
    425 	const struct sadb_msghdr *);
    426 static int key_mature (struct secasvar *);
    427 static struct mbuf *key_setdumpsa (struct secasvar *, u_int8_t,
    428 	u_int8_t, u_int32_t, u_int32_t);
    429 static struct mbuf *key_setsadbxport (u_int16_t, u_int16_t);
    430 static struct mbuf *key_setsadbxtype (u_int16_t);
    431 static struct mbuf *key_setsadbxfrag (u_int16_t);
    432 static void key_porttosaddr (union sockaddr_union *, u_int16_t);
    433 static int key_checksalen (const union sockaddr_union *);
    434 static struct mbuf *key_setsadbmsg (u_int8_t, u_int16_t, u_int8_t,
    435 	u_int32_t, pid_t, u_int16_t);
    436 static struct mbuf *key_setsadbsa (struct secasvar *);
    437 static struct mbuf *key_setsadbaddr (u_int16_t,
    438 	const struct sockaddr *, u_int8_t, u_int16_t);
    439 #if 0
    440 static struct mbuf *key_setsadbident (u_int16_t, u_int16_t, void *,
    441 	int, u_int64_t);
    442 #endif
    443 static struct mbuf *key_setsadbxsa2 (u_int8_t, u_int32_t, u_int16_t);
    444 static struct mbuf *key_setsadbxpolicy (u_int16_t, u_int8_t,
    445 	u_int32_t);
    446 static void *key_newbuf (const void *, u_int);
    447 #ifdef INET6
    448 static int key_ismyaddr6 (const struct sockaddr_in6 *);
    449 #endif
    450 
    451 /* flags for key_cmpsaidx() */
    452 #define CMP_HEAD	1	/* protocol, addresses. */
    453 #define CMP_MODE_REQID	2	/* additionally HEAD, reqid, mode. */
    454 #define CMP_REQID	3	/* additionally HEAD, reaid. */
    455 #define CMP_EXACTLY	4	/* all elements. */
    456 static int key_cmpsaidx
    457 	(const struct secasindex *, const struct secasindex *, int);
    458 
    459 static int key_sockaddrcmp (const struct sockaddr *, const struct sockaddr *, int);
    460 static int key_bbcmp (const void *, const void *, u_int);
    461 static u_int16_t key_satype2proto (u_int8_t);
    462 static u_int8_t key_proto2satype (u_int16_t);
    463 
    464 static int key_getspi (struct socket *, struct mbuf *,
    465 	const struct sadb_msghdr *);
    466 static u_int32_t key_do_getnewspi (const struct sadb_spirange *,
    467 					const struct secasindex *);
    468 static int key_handle_natt_info (struct secasvar *,
    469 				     const struct sadb_msghdr *);
    470 static int key_set_natt_ports (union sockaddr_union *,
    471 			 	union sockaddr_union *,
    472 				const struct sadb_msghdr *);
    473 static int key_update (struct socket *, struct mbuf *,
    474 	const struct sadb_msghdr *);
    475 #ifdef IPSEC_DOSEQCHECK
    476 static struct secasvar *key_getsavbyseq (struct secashead *, u_int32_t);
    477 #endif
    478 static int key_add (struct socket *, struct mbuf *,
    479 	const struct sadb_msghdr *);
    480 static int key_setident (struct secashead *, struct mbuf *,
    481 	const struct sadb_msghdr *);
    482 static struct mbuf *key_getmsgbuf_x1 (struct mbuf *,
    483 	const struct sadb_msghdr *);
    484 static int key_delete (struct socket *, struct mbuf *,
    485 	const struct sadb_msghdr *);
    486 static int key_get (struct socket *, struct mbuf *,
    487 	const struct sadb_msghdr *);
    488 
    489 static void key_getcomb_setlifetime (struct sadb_comb *);
    490 static struct mbuf *key_getcomb_esp (void);
    491 static struct mbuf *key_getcomb_ah (void);
    492 static struct mbuf *key_getcomb_ipcomp (void);
    493 static struct mbuf *key_getprop (const struct secasindex *);
    494 
    495 static int key_acquire (const struct secasindex *, struct secpolicy *);
    496 #ifndef IPSEC_NONBLOCK_ACQUIRE
    497 static struct secacq *key_newacq (const struct secasindex *);
    498 static struct secacq *key_getacq (const struct secasindex *);
    499 static struct secacq *key_getacqbyseq (u_int32_t);
    500 #endif
    501 static struct secspacq *key_newspacq (const struct secpolicyindex *);
    502 static struct secspacq *key_getspacq (const struct secpolicyindex *);
    503 static int key_acquire2 (struct socket *, struct mbuf *,
    504 	const struct sadb_msghdr *);
    505 static int key_register (struct socket *, struct mbuf *,
    506 	const struct sadb_msghdr *);
    507 static int key_expire (struct secasvar *);
    508 static int key_flush (struct socket *, struct mbuf *,
    509 	const struct sadb_msghdr *);
    510 static struct mbuf *key_setdump_chain (u_int8_t req_satype, int *errorp,
    511 	int *lenp, pid_t pid);
    512 static int key_dump (struct socket *, struct mbuf *,
    513 	const struct sadb_msghdr *);
    514 static int key_promisc (struct socket *, struct mbuf *,
    515 	const struct sadb_msghdr *);
    516 static int key_senderror (struct socket *, struct mbuf *, int);
    517 static int key_validate_ext (const struct sadb_ext *, int);
    518 static int key_align (struct mbuf *, struct sadb_msghdr *);
    519 #if 0
    520 static const char *key_getfqdn (void);
    521 static const char *key_getuserfqdn (void);
    522 #endif
    523 static void key_sa_chgstate (struct secasvar *, u_int8_t);
    524 static inline void key_sp_dead (struct secpolicy *);
    525 static void key_sp_unlink (struct secpolicy *sp);
    526 
    527 static struct mbuf *key_alloc_mbuf (int);
    528 struct callout key_timehandler_ch;
    529 
    530 #define	SA_ADDREF(p) do {						\
    531 	(p)->refcnt++;							\
    532 	IPSEC_ASSERT((p)->refcnt != 0,					\
    533 		("SA refcnt overflow at %s:%u", __FILE__, __LINE__));	\
    534 } while (0)
    535 #define	SA_DELREF(p) do {						\
    536 	IPSEC_ASSERT((p)->refcnt > 0,					\
    537 		("SA refcnt underflow at %s:%u", __FILE__, __LINE__));	\
    538 	(p)->refcnt--;							\
    539 } while (0)
    540 
    541 #define	SP_ADDREF(p) do {						\
    542 	(p)->refcnt++;							\
    543 	IPSEC_ASSERT((p)->refcnt != 0,					\
    544 		("SP refcnt overflow at %s:%u", __FILE__, __LINE__));	\
    545 } while (0)
    546 #define	SP_DELREF(p) do {						\
    547 	IPSEC_ASSERT((p)->refcnt > 0,					\
    548 		("SP refcnt underflow at %s:%u", __FILE__, __LINE__));	\
    549 	(p)->refcnt--;							\
    550 } while (0)
    551 
    552 
    553 static inline void
    554 key_sp_dead(struct secpolicy *sp)
    555 {
    556 
    557 	/* mark the SP dead */
    558 	sp->state = IPSEC_SPSTATE_DEAD;
    559 }
    560 
    561 static void
    562 key_sp_unlink(struct secpolicy *sp)
    563 {
    564 
    565 	/* remove from SP index */
    566 	if (__LIST_CHAINED(sp)) {
    567 		LIST_REMOVE(sp, chain);
    568 		/* Release refcount held just for being on chain */
    569 		KEY_FREESP(&sp);
    570 	}
    571 }
    572 
    573 
    574 /*
    575  * Return 0 when there are known to be no SP's for the specified
    576  * direction.  Otherwise return 1.  This is used by IPsec code
    577  * to optimize performance.
    578  */
    579 int
    580 key_havesp(u_int dir)
    581 {
    582 	return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
    583 		LIST_FIRST(&sptree[dir]) != NULL : 1);
    584 }
    585 
    586 /* %%% IPsec policy management */
    587 /*
    588  * allocating a SP for OUTBOUND or INBOUND packet.
    589  * Must call key_freesp() later.
    590  * OUT:	NULL:	not found
    591  *	others:	found and return the pointer.
    592  */
    593 struct secpolicy *
    594 key_allocsp(const struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
    595 {
    596 	struct secpolicy *sp;
    597 	int s;
    598 
    599 	IPSEC_ASSERT(spidx != NULL, ("key_allocsp: null spidx"));
    600 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
    601 		("key_allocsp: invalid direction %u", dir));
    602 
    603 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
    604 		printf("DP %s from %s:%u\n", __func__, where, tag));
    605 
    606 	/* get a SP entry */
    607 	s = splsoftnet();	/*called from softclock()*/
    608 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
    609 		printf("*** objects\n");
    610 		kdebug_secpolicyindex(spidx));
    611 
    612 	LIST_FOREACH(sp, &sptree[dir], chain) {
    613 		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
    614 			printf("*** in SPD\n");
    615 			kdebug_secpolicyindex(&sp->spidx));
    616 
    617 		if (sp->state == IPSEC_SPSTATE_DEAD)
    618 			continue;
    619 		if (key_cmpspidx_withmask(&sp->spidx, spidx))
    620 			goto found;
    621 	}
    622 	sp = NULL;
    623 found:
    624 	if (sp) {
    625 		/* sanity check */
    626 		KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp");
    627 
    628 		/* found a SPD entry */
    629 		sp->lastused = time_uptime;
    630 		SP_ADDREF(sp);
    631 	}
    632 	splx(s);
    633 
    634 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
    635 		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
    636 		    sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
    637 	return sp;
    638 }
    639 
    640 /*
    641  * allocating a SP for OUTBOUND or INBOUND packet.
    642  * Must call key_freesp() later.
    643  * OUT:	NULL:	not found
    644  *	others:	found and return the pointer.
    645  */
    646 struct secpolicy *
    647 key_allocsp2(u_int32_t spi,
    648 	     const union sockaddr_union *dst,
    649 	     u_int8_t proto,
    650 	     u_int dir,
    651 	     const char* where, int tag)
    652 {
    653 	struct secpolicy *sp;
    654 	int s;
    655 
    656 	IPSEC_ASSERT(dst != NULL, ("key_allocsp2: null dst"));
    657 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
    658 		("key_allocsp2: invalid direction %u", dir));
    659 
    660 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
    661 		printf("DP %s from %s:%u\n", __func__, where, tag));
    662 
    663 	/* get a SP entry */
    664 	s = splsoftnet();	/*called from softclock()*/
    665 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
    666 		printf("*** objects\n");
    667 		printf("spi %u proto %u dir %u\n", spi, proto, dir);
    668 		kdebug_sockaddr(&dst->sa));
    669 
    670 	LIST_FOREACH(sp, &sptree[dir], chain) {
    671 		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
    672 			printf("*** in SPD\n");
    673 			kdebug_secpolicyindex(&sp->spidx));
    674 
    675 		if (sp->state == IPSEC_SPSTATE_DEAD)
    676 			continue;
    677 		/* compare simple values, then dst address */
    678 		if (sp->spidx.ul_proto != proto)
    679 			continue;
    680 		/* NB: spi's must exist and match */
    681 		if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
    682 			continue;
    683 		if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, PORT_STRICT) == 0)
    684 			goto found;
    685 	}
    686 	sp = NULL;
    687 found:
    688 	if (sp) {
    689 		/* sanity check */
    690 		KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp2");
    691 
    692 		/* found a SPD entry */
    693 		sp->lastused = time_uptime;
    694 		SP_ADDREF(sp);
    695 	}
    696 	splx(s);
    697 
    698 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
    699 		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
    700 		    sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
    701 	return sp;
    702 }
    703 
    704 /*
    705  * return a policy that matches this particular inbound packet.
    706  * XXX slow
    707  */
    708 struct secpolicy *
    709 key_gettunnel(const struct sockaddr *osrc,
    710 	      const struct sockaddr *odst,
    711 	      const struct sockaddr *isrc,
    712 	      const struct sockaddr *idst,
    713 	      const char* where, int tag)
    714 {
    715 	struct secpolicy *sp;
    716 	const int dir = IPSEC_DIR_INBOUND;
    717 	int s;
    718 	struct ipsecrequest *r1, *r2, *p;
    719 	struct secpolicyindex spidx;
    720 
    721 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
    722 		printf("DP %s from %s:%u\n", __func__, where, tag));
    723 
    724 	if (isrc->sa_family != idst->sa_family) {
    725 		ipseclog((LOG_ERR, "protocol family mismatched %d != %d\n.",
    726 			isrc->sa_family, idst->sa_family));
    727 		sp = NULL;
    728 		goto done;
    729 	}
    730 
    731 	s = splsoftnet();	/*called from softclock()*/
    732 	LIST_FOREACH(sp, &sptree[dir], chain) {
    733 		if (sp->state == IPSEC_SPSTATE_DEAD)
    734 			continue;
    735 
    736 		r1 = r2 = NULL;
    737 		for (p = sp->req; p; p = p->next) {
    738 			if (p->saidx.mode != IPSEC_MODE_TUNNEL)
    739 				continue;
    740 
    741 			r1 = r2;
    742 			r2 = p;
    743 
    744 			if (!r1) {
    745 				/* here we look at address matches only */
    746 				spidx = sp->spidx;
    747 				if (isrc->sa_len > sizeof(spidx.src) ||
    748 				    idst->sa_len > sizeof(spidx.dst))
    749 					continue;
    750 				memcpy(&spidx.src, isrc, isrc->sa_len);
    751 				memcpy(&spidx.dst, idst, idst->sa_len);
    752 				if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
    753 					continue;
    754 			} else {
    755 				if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, PORT_NONE) ||
    756 				    key_sockaddrcmp(&r1->saidx.dst.sa, idst, PORT_NONE))
    757 					continue;
    758 			}
    759 
    760 			if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, PORT_NONE) ||
    761 			    key_sockaddrcmp(&r2->saidx.dst.sa, odst, PORT_NONE))
    762 				continue;
    763 
    764 			goto found;
    765 		}
    766 	}
    767 	sp = NULL;
    768 found:
    769 	if (sp) {
    770 		sp->lastused = time_uptime;
    771 		SP_ADDREF(sp);
    772 	}
    773 	splx(s);
    774 done:
    775 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
    776 		printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
    777 		    sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
    778 	return sp;
    779 }
    780 
    781 /*
    782  * allocating an SA entry for an *OUTBOUND* packet.
    783  * checking each request entries in SP, and acquire an SA if need.
    784  * OUT:	0: there are valid requests.
    785  *	ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
    786  */
    787 int
    788 key_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
    789 {
    790 	u_int level;
    791 	int error;
    792 
    793 	IPSEC_ASSERT(isr != NULL, ("key_checkrequest: null isr"));
    794 	IPSEC_ASSERT(saidx != NULL, ("key_checkrequest: null saidx"));
    795 	IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
    796 		saidx->mode == IPSEC_MODE_TUNNEL,
    797 		("key_checkrequest: unexpected policy %u", saidx->mode));
    798 
    799 	/* get current level */
    800 	level = ipsec_get_reqlevel(isr);
    801 
    802 	/*
    803 	 * XXX guard against protocol callbacks from the crypto
    804 	 * thread as they reference ipsecrequest.sav which we
    805 	 * temporarily null out below.  Need to rethink how we
    806 	 * handle bundled SA's in the callback thread.
    807 	 */
    808 	IPSEC_SPLASSERT_SOFTNET("key_checkrequest");
    809 #if 0
    810 	/*
    811 	 * We do allocate new SA only if the state of SA in the holder is
    812 	 * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
    813 	 */
    814 	if (isr->sav != NULL) {
    815 		if (isr->sav->sah == NULL)
    816 			panic("key_checkrequest: sah is null");
    817 		if (isr->sav == (struct secasvar *)LIST_FIRST(
    818 			    &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
    819 			KEY_FREESAV(&isr->sav);
    820 			isr->sav = NULL;
    821 		}
    822 	}
    823 #else
    824 	/*
    825 	 * we free any SA stashed in the IPsec request because a different
    826 	 * SA may be involved each time this request is checked, either
    827 	 * because new SAs are being configured, or this request is
    828 	 * associated with an unconnected datagram socket, or this request
    829 	 * is associated with a system default policy.
    830 	 *
    831 	 * The operation may have negative impact to performance.  We may
    832 	 * want to check cached SA carefully, rather than picking new SA
    833 	 * every time.
    834 	 */
    835 	if (isr->sav != NULL) {
    836 		KEY_FREESAV(&isr->sav);
    837 		isr->sav = NULL;
    838 	}
    839 #endif
    840 
    841 	/*
    842 	 * new SA allocation if no SA found.
    843 	 * key_allocsa_policy should allocate the oldest SA available.
    844 	 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
    845 	 */
    846 	if (isr->sav == NULL)
    847 		isr->sav = key_allocsa_policy(saidx);
    848 
    849 	/* When there is SA. */
    850 	if (isr->sav != NULL) {
    851 		if (isr->sav->state != SADB_SASTATE_MATURE &&
    852 		    isr->sav->state != SADB_SASTATE_DYING)
    853 			return EINVAL;
    854 		return 0;
    855 	}
    856 
    857 	/* there is no SA */
    858 	error = key_acquire(saidx, isr->sp);
    859 	if (error != 0) {
    860 		/* XXX What should I do ? */
    861 		ipseclog((LOG_DEBUG, "key_checkrequest: error %d returned "
    862 			"from key_acquire.\n", error));
    863 		return error;
    864 	}
    865 
    866 	if (level != IPSEC_LEVEL_REQUIRE) {
    867 		/* XXX sigh, the interface to this routine is botched */
    868 		IPSEC_ASSERT(isr->sav == NULL, ("key_checkrequest: unexpected SA"));
    869 		return 0;
    870 	} else {
    871 		return ENOENT;
    872 	}
    873 }
    874 
    875 /*
    876  * allocating a SA for policy entry from SAD.
    877  * NOTE: searching SAD of aliving state.
    878  * OUT:	NULL:	not found.
    879  *	others:	found and return the pointer.
    880  */
    881 static struct secasvar *
    882 key_allocsa_policy(const struct secasindex *saidx)
    883 {
    884 	struct secashead *sah;
    885 	struct secasvar *sav;
    886 	u_int stateidx, state;
    887 	const u_int *saorder_state_valid;
    888 	int arraysize;
    889 
    890 	LIST_FOREACH(sah, &sahtree, chain) {
    891 		if (sah->state == SADB_SASTATE_DEAD)
    892 			continue;
    893 		if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID))
    894 			goto found;
    895 	}
    896 
    897 	return NULL;
    898 
    899     found:
    900 
    901 	/*
    902 	 * search a valid state list for outbound packet.
    903 	 * This search order is important.
    904 	 */
    905 	if (key_prefered_oldsa) {
    906 		saorder_state_valid = saorder_state_valid_prefer_old;
    907 		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
    908 	} else {
    909 		saorder_state_valid = saorder_state_valid_prefer_new;
    910 		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
    911 	}
    912 
    913 	/* search valid state */
    914 	for (stateidx = 0;
    915 	     stateidx < arraysize;
    916 	     stateidx++) {
    917 
    918 		state = saorder_state_valid[stateidx];
    919 
    920 		sav = key_do_allocsa_policy(sah, state);
    921 		if (sav != NULL)
    922 			return sav;
    923 	}
    924 
    925 	return NULL;
    926 }
    927 
    928 /*
    929  * searching SAD with direction, protocol, mode and state.
    930  * called by key_allocsa_policy().
    931  * OUT:
    932  *	NULL	: not found
    933  *	others	: found, pointer to a SA.
    934  */
    935 static struct secasvar *
    936 key_do_allocsa_policy(struct secashead *sah, u_int state)
    937 {
    938 	struct secasvar *sav, *nextsav, *candidate, *d;
    939 
    940 	/* initilize */
    941 	candidate = NULL;
    942 
    943 	for (sav = LIST_FIRST(&sah->savtree[state]);
    944 	     sav != NULL;
    945 	     sav = nextsav) {
    946 
    947 		nextsav = LIST_NEXT(sav, chain);
    948 
    949 		/* sanity check */
    950 		KEY_CHKSASTATE(sav->state, state, "key_do_allocsa_policy");
    951 
    952 		/* initialize */
    953 		if (candidate == NULL) {
    954 			candidate = sav;
    955 			continue;
    956 		}
    957 
    958 		/* Which SA is the better ? */
    959 
    960 		/* sanity check 2 */
    961 		if (candidate->lft_c == NULL || sav->lft_c == NULL)
    962 			panic("key_do_allocsa_policy: "
    963 			    "lifetime_current is NULL");
    964 
    965 		/* What the best method is to compare ? */
    966 		if (key_prefered_oldsa) {
    967 			if (candidate->lft_c->sadb_lifetime_addtime >
    968 					sav->lft_c->sadb_lifetime_addtime) {
    969 				candidate = sav;
    970 			}
    971 			continue;
    972 			/*NOTREACHED*/
    973 		}
    974 
    975 		/* prefered new sa rather than old sa */
    976 		if (candidate->lft_c->sadb_lifetime_addtime <
    977 				sav->lft_c->sadb_lifetime_addtime) {
    978 			d = candidate;
    979 			candidate = sav;
    980 		} else
    981 			d = sav;
    982 
    983 		/*
    984 		 * prepared to delete the SA when there is more
    985 		 * suitable candidate and the lifetime of the SA is not
    986 		 * permanent.
    987 		 */
    988 		if (d->lft_c->sadb_lifetime_addtime != 0) {
    989 			struct mbuf *m, *result = 0;
    990 			uint8_t satype;
    991 
    992 			key_sa_chgstate(d, SADB_SASTATE_DEAD);
    993 
    994 			IPSEC_ASSERT(d->refcnt > 0,
    995 				("key_do_allocsa_policy: bogus ref count"));
    996 
    997 			satype = key_proto2satype(d->sah->saidx.proto);
    998 			if (satype == 0)
    999 				goto msgfail;
   1000 
   1001 			m = key_setsadbmsg(SADB_DELETE, 0,
   1002 			    satype, 0, 0, d->refcnt - 1);
   1003 			if (!m)
   1004 				goto msgfail;
   1005 			result = m;
   1006 
   1007 			/* set sadb_address for saidx's. */
   1008 			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   1009 				&d->sah->saidx.src.sa,
   1010 				d->sah->saidx.src.sa.sa_len << 3,
   1011 				IPSEC_ULPROTO_ANY);
   1012 			if (!m)
   1013 				goto msgfail;
   1014 			m_cat(result, m);
   1015 
   1016 			/* set sadb_address for saidx's. */
   1017 			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   1018 				&d->sah->saidx.src.sa,
   1019 				d->sah->saidx.src.sa.sa_len << 3,
   1020 				IPSEC_ULPROTO_ANY);
   1021 			if (!m)
   1022 				goto msgfail;
   1023 			m_cat(result, m);
   1024 
   1025 			/* create SA extension */
   1026 			m = key_setsadbsa(d);
   1027 			if (!m)
   1028 				goto msgfail;
   1029 			m_cat(result, m);
   1030 
   1031 			if (result->m_len < sizeof(struct sadb_msg)) {
   1032 				result = m_pullup(result,
   1033 						sizeof(struct sadb_msg));
   1034 				if (result == NULL)
   1035 					goto msgfail;
   1036 			}
   1037 
   1038 			result->m_pkthdr.len = 0;
   1039 			for (m = result; m; m = m->m_next)
   1040 				result->m_pkthdr.len += m->m_len;
   1041 			mtod(result, struct sadb_msg *)->sadb_msg_len =
   1042 				PFKEY_UNIT64(result->m_pkthdr.len);
   1043 
   1044 			key_sendup_mbuf(NULL, result,
   1045 					KEY_SENDUP_REGISTERED);
   1046 			result = 0;
   1047 		 msgfail:
   1048 			if (result)
   1049 				m_freem(result);
   1050 			KEY_FREESAV(&d);
   1051 		}
   1052 	}
   1053 
   1054 	if (candidate) {
   1055 		SA_ADDREF(candidate);
   1056 		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
   1057 			printf("DP %s cause refcnt++:%d SA:%p\n", __func__,
   1058 			    candidate->refcnt, candidate));
   1059 	}
   1060 	return candidate;
   1061 }
   1062 
   1063 /*
   1064  * allocating a usable SA entry for a *INBOUND* packet.
   1065  * Must call key_freesav() later.
   1066  * OUT: positive:	pointer to a usable sav (i.e. MATURE or DYING state).
   1067  *	NULL:		not found, or error occurred.
   1068  *
   1069  * In the comparison, no source address is used--for RFC2401 conformance.
   1070  * To quote, from section 4.1:
   1071  *	A security association is uniquely identified by a triple consisting
   1072  *	of a Security Parameter Index (SPI), an IP Destination Address, and a
   1073  *	security protocol (AH or ESP) identifier.
   1074  * Note that, however, we do need to keep source address in IPsec SA.
   1075  * IKE specification and PF_KEY specification do assume that we
   1076  * keep source address in IPsec SA.  We see a tricky situation here.
   1077  *
   1078  * sport and dport are used for NAT-T. network order is always used.
   1079  */
   1080 struct secasvar *
   1081 key_allocsa(
   1082 	const union sockaddr_union *dst,
   1083 	u_int proto,
   1084 	u_int32_t spi,
   1085 	u_int16_t sport,
   1086 	u_int16_t dport,
   1087 	const char* where, int tag)
   1088 {
   1089 	struct secashead *sah;
   1090 	struct secasvar *sav;
   1091 	u_int stateidx, state;
   1092 	const u_int *saorder_state_valid;
   1093 	int arraysize, chkport;
   1094 	int s;
   1095 
   1096 	int must_check_spi = 1;
   1097 	int must_check_alg = 0;
   1098 	u_int16_t cpi = 0;
   1099 	u_int8_t algo = 0;
   1100 
   1101 	if ((sport != 0) && (dport != 0))
   1102 		chkport = PORT_STRICT;
   1103 	else
   1104 		chkport = PORT_NONE;
   1105 
   1106 	IPSEC_ASSERT(dst != NULL, ("key_allocsa: null dst address"));
   1107 
   1108 	/*
   1109 	 * XXX IPCOMP case
   1110 	 * We use cpi to define spi here. In the case where cpi <=
   1111 	 * IPCOMP_CPI_NEGOTIATE_MIN, cpi just define the algorithm used, not
   1112 	 * the real spi. In this case, don't check the spi but check the
   1113 	 * algorithm
   1114 	 */
   1115 
   1116 	if (proto == IPPROTO_IPCOMP) {
   1117 		u_int32_t tmp;
   1118 		tmp = ntohl(spi);
   1119 		cpi = (u_int16_t) tmp;
   1120 		if (cpi < IPCOMP_CPI_NEGOTIATE_MIN) {
   1121 			algo = (u_int8_t) cpi;
   1122 			must_check_spi = 0;
   1123 			must_check_alg = 1;
   1124 		}
   1125 	}
   1126 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
   1127 		printf("DP %s from %s:%u check_spi=%d, check_alg=%d\n",
   1128 		    __func__, where, tag, must_check_spi, must_check_alg));
   1129 
   1130 
   1131 	/*
   1132 	 * searching SAD.
   1133 	 * XXX: to be checked internal IP header somewhere.  Also when
   1134 	 * IPsec tunnel packet is received.  But ESP tunnel mode is
   1135 	 * encrypted so we can't check internal IP header.
   1136 	 */
   1137 	s = splsoftnet();	/*called from softclock()*/
   1138 	if (key_prefered_oldsa) {
   1139 		saorder_state_valid = saorder_state_valid_prefer_old;
   1140 		arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
   1141 	} else {
   1142 		saorder_state_valid = saorder_state_valid_prefer_new;
   1143 		arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
   1144 	}
   1145 	LIST_FOREACH(sah, &sahtree, chain) {
   1146 		/* search valid state */
   1147 		for (stateidx = 0; stateidx < arraysize; stateidx++) {
   1148 			state = saorder_state_valid[stateidx];
   1149 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   1150 				KEYDEBUG(KEYDEBUG_MATCH,
   1151 				    printf("try match spi %#x, %#x\n",
   1152 						ntohl(spi), ntohl(sav->spi)));
   1153 				/* sanity check */
   1154 				KEY_CHKSASTATE(sav->state, state, "key_allocsav");
   1155 				/* do not return entries w/ unusable state */
   1156 				if (sav->state != SADB_SASTATE_MATURE &&
   1157 				    sav->state != SADB_SASTATE_DYING) {
   1158 					KEYDEBUG(KEYDEBUG_MATCH,
   1159 					    printf("bad state %d\n",
   1160 						sav->state));
   1161 					continue;
   1162 				}
   1163 				if (proto != sav->sah->saidx.proto) {
   1164 					KEYDEBUG(KEYDEBUG_MATCH,
   1165 					    printf("proto fail %d != %d\n",
   1166 						proto, sav->sah->saidx.proto));
   1167 					continue;
   1168 				}
   1169 				if (must_check_spi && spi != sav->spi) {
   1170 					KEYDEBUG(KEYDEBUG_MATCH,
   1171 					    printf("spi fail %#x != %#x\n",
   1172 						ntohl(spi), ntohl(sav->spi)));
   1173 					continue;
   1174 				}
   1175 				/* XXX only on the ipcomp case */
   1176 				if (must_check_alg && algo != sav->alg_comp) {
   1177 					KEYDEBUG(KEYDEBUG_MATCH,
   1178 					    printf("algo fail %d != %d\n",
   1179 						algo, sav->alg_comp));
   1180 					continue;
   1181 				}
   1182 
   1183 #if 0	/* don't check src */
   1184 	/* Fix port in src->sa */
   1185 
   1186 				/* check src address */
   1187 				if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, PORT_NONE) != 0)
   1188 					continue;
   1189 #endif
   1190 				/* fix port of dst address XXX*/
   1191 				key_porttosaddr(__UNCONST(dst), dport);
   1192 				/* check dst address */
   1193 				if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, chkport) != 0)
   1194 					continue;
   1195 				SA_ADDREF(sav);
   1196 				goto done;
   1197 			}
   1198 		}
   1199 	}
   1200 	sav = NULL;
   1201 done:
   1202 	splx(s);
   1203 
   1204 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
   1205 		printf("DP %s return SA:%p; refcnt %u\n", __func__,
   1206 		    sav, sav ? sav->refcnt : 0));
   1207 	return sav;
   1208 }
   1209 
   1210 /*
   1211  * Must be called after calling key_allocsp().
   1212  * For both the packet without socket and key_freeso().
   1213  */
   1214 void
   1215 _key_freesp(struct secpolicy **spp, const char* where, int tag)
   1216 {
   1217 	struct secpolicy *sp = *spp;
   1218 
   1219 	IPSEC_ASSERT(sp != NULL, ("key_freesp: null sp"));
   1220 
   1221 	SP_DELREF(sp);
   1222 
   1223 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
   1224 		printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
   1225 		    __func__, sp, sp->id, where, tag, sp->refcnt));
   1226 
   1227 	if (sp->refcnt == 0) {
   1228 		*spp = NULL;
   1229 		key_delsp(sp);
   1230 	}
   1231 }
   1232 
   1233 /*
   1234  * Must be called after calling key_allocsp().
   1235  * For the packet with socket.
   1236  */
   1237 void
   1238 key_freeso(struct socket *so)
   1239 {
   1240 	/* sanity check */
   1241 	IPSEC_ASSERT(so != NULL, ("key_freeso: null so"));
   1242 
   1243 	switch (so->so_proto->pr_domain->dom_family) {
   1244 #ifdef INET
   1245 	case PF_INET:
   1246 	    {
   1247 		struct inpcb *pcb = sotoinpcb(so);
   1248 
   1249 		/* Does it have a PCB ? */
   1250 		if (pcb == NULL)
   1251 			return;
   1252 
   1253 		struct inpcbpolicy *sp = pcb->inp_sp;
   1254 		key_freesp_so(&sp->sp_in);
   1255 		key_freesp_so(&sp->sp_out);
   1256 	    }
   1257 		break;
   1258 #endif
   1259 #ifdef INET6
   1260 	case PF_INET6:
   1261 	    {
   1262 #ifdef HAVE_NRL_INPCB
   1263 		struct inpcb *pcb  = sotoinpcb(so);
   1264 		struct inpcbpolicy *sp = pcb->inp_sp;
   1265 
   1266 		/* Does it have a PCB ? */
   1267 		if (pcb == NULL)
   1268 			return;
   1269 		key_freesp_so(&sp->sp_in);
   1270 		key_freesp_so(&sp->sp_out);
   1271 #else
   1272 		struct in6pcb *pcb  = sotoin6pcb(so);
   1273 
   1274 		/* Does it have a PCB ? */
   1275 		if (pcb == NULL)
   1276 			return;
   1277 		key_freesp_so(&pcb->in6p_sp->sp_in);
   1278 		key_freesp_so(&pcb->in6p_sp->sp_out);
   1279 #endif
   1280 	    }
   1281 		break;
   1282 #endif /* INET6 */
   1283 	default:
   1284 		ipseclog((LOG_DEBUG, "key_freeso: unknown address family=%d.\n",
   1285 		    so->so_proto->pr_domain->dom_family));
   1286 		return;
   1287 	}
   1288 }
   1289 
   1290 static void
   1291 key_freesp_so(struct secpolicy **sp)
   1292 {
   1293 	IPSEC_ASSERT(sp != NULL && *sp != NULL, ("key_freesp_so: null sp"));
   1294 
   1295 	if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
   1296 	    (*sp)->policy == IPSEC_POLICY_BYPASS)
   1297 		return;
   1298 
   1299 	IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
   1300 		("key_freesp_so: invalid policy %u", (*sp)->policy));
   1301 	KEY_FREESP(sp);
   1302 }
   1303 
   1304 /*
   1305  * Must be called after calling key_allocsa().
   1306  * This function is called by key_freesp() to free some SA allocated
   1307  * for a policy.
   1308  */
   1309 void
   1310 key_freesav(struct secasvar **psav, const char* where, int tag)
   1311 {
   1312 	struct secasvar *sav = *psav;
   1313 
   1314 	IPSEC_ASSERT(sav != NULL, ("key_freesav: null sav"));
   1315 
   1316 	SA_DELREF(sav);
   1317 
   1318 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
   1319 		printf("DP %s SA:%p (SPI %lu) from %s:%u; refcnt now %u\n",
   1320 		    __func__, sav, (u_long)ntohl(sav->spi), where, tag,
   1321 		    sav->refcnt));
   1322 
   1323 	if (sav->refcnt == 0) {
   1324 		*psav = NULL;
   1325 		key_delsav(sav);
   1326 	}
   1327 }
   1328 
   1329 /* %%% SPD management */
   1330 /*
   1331  * free security policy entry.
   1332  */
   1333 static void
   1334 key_delsp(struct secpolicy *sp)
   1335 {
   1336 	int s;
   1337 
   1338 	IPSEC_ASSERT(sp != NULL, ("key_delsp: null sp"));
   1339 
   1340 	key_sp_dead(sp);
   1341 
   1342 	IPSEC_ASSERT(sp->refcnt == 0,
   1343 		("key_delsp: SP with references deleted (refcnt %u)",
   1344 		sp->refcnt));
   1345 
   1346 	s = splsoftnet();	/*called from softclock()*/
   1347 
   1348     {
   1349 	struct ipsecrequest *isr = sp->req, *nextisr;
   1350 
   1351 	while (isr != NULL) {
   1352 		if (isr->sav != NULL) {
   1353 			KEY_FREESAV(&isr->sav);
   1354 			isr->sav = NULL;
   1355 		}
   1356 
   1357 		nextisr = isr->next;
   1358 		KFREE(isr);
   1359 		isr = nextisr;
   1360 	}
   1361     }
   1362 
   1363 	KFREE(sp);
   1364 
   1365 	splx(s);
   1366 }
   1367 
   1368 /*
   1369  * search SPD
   1370  * OUT:	NULL	: not found
   1371  *	others	: found, pointer to a SP.
   1372  */
   1373 static struct secpolicy *
   1374 key_getsp(const struct secpolicyindex *spidx)
   1375 {
   1376 	struct secpolicy *sp;
   1377 
   1378 	IPSEC_ASSERT(spidx != NULL, ("key_getsp: null spidx"));
   1379 
   1380 	LIST_FOREACH(sp, &sptree[spidx->dir], chain) {
   1381 		if (sp->state == IPSEC_SPSTATE_DEAD)
   1382 			continue;
   1383 		if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
   1384 			SP_ADDREF(sp);
   1385 			return sp;
   1386 		}
   1387 	}
   1388 
   1389 	return NULL;
   1390 }
   1391 
   1392 /*
   1393  * get SP by index.
   1394  * OUT:	NULL	: not found
   1395  *	others	: found, pointer to a SP.
   1396  */
   1397 static struct secpolicy *
   1398 key_getspbyid(u_int32_t id)
   1399 {
   1400 	struct secpolicy *sp;
   1401 
   1402 	LIST_FOREACH(sp, &sptree[IPSEC_DIR_INBOUND], chain) {
   1403 		if (sp->state == IPSEC_SPSTATE_DEAD)
   1404 			continue;
   1405 		if (sp->id == id) {
   1406 			SP_ADDREF(sp);
   1407 			return sp;
   1408 		}
   1409 	}
   1410 
   1411 	LIST_FOREACH(sp, &sptree[IPSEC_DIR_OUTBOUND], chain) {
   1412 		if (sp->state == IPSEC_SPSTATE_DEAD)
   1413 			continue;
   1414 		if (sp->id == id) {
   1415 			SP_ADDREF(sp);
   1416 			return sp;
   1417 		}
   1418 	}
   1419 
   1420 	return NULL;
   1421 }
   1422 
   1423 struct secpolicy *
   1424 key_newsp(const char* where, int tag)
   1425 {
   1426 	struct secpolicy *newsp = NULL;
   1427 
   1428 	newsp = (struct secpolicy *)
   1429 		malloc(sizeof(struct secpolicy), M_SECA, M_NOWAIT|M_ZERO);
   1430 	if (newsp) {
   1431 		newsp->refcnt = 1;
   1432 		newsp->req = NULL;
   1433 	}
   1434 
   1435 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
   1436 		printf("DP %s from %s:%u return SP:%p\n", __func__,
   1437 		    where, tag, newsp));
   1438 	return newsp;
   1439 }
   1440 
   1441 /*
   1442  * create secpolicy structure from sadb_x_policy structure.
   1443  * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
   1444  * so must be set properly later.
   1445  */
   1446 struct secpolicy *
   1447 key_msg2sp(const struct sadb_x_policy *xpl0, size_t len, int *error)
   1448 {
   1449 	struct secpolicy *newsp;
   1450 
   1451 	/* sanity check */
   1452 	if (xpl0 == NULL)
   1453 		panic("key_msg2sp: NULL pointer was passed");
   1454 	if (len < sizeof(*xpl0))
   1455 		panic("key_msg2sp: invalid length");
   1456 	if (len != PFKEY_EXTLEN(xpl0)) {
   1457 		ipseclog((LOG_DEBUG, "key_msg2sp: Invalid msg length.\n"));
   1458 		*error = EINVAL;
   1459 		return NULL;
   1460 	}
   1461 
   1462 	if ((newsp = KEY_NEWSP()) == NULL) {
   1463 		*error = ENOBUFS;
   1464 		return NULL;
   1465 	}
   1466 
   1467 	newsp->spidx.dir = xpl0->sadb_x_policy_dir;
   1468 	newsp->policy = xpl0->sadb_x_policy_type;
   1469 
   1470 	/* check policy */
   1471 	switch (xpl0->sadb_x_policy_type) {
   1472 	case IPSEC_POLICY_DISCARD:
   1473 	case IPSEC_POLICY_NONE:
   1474 	case IPSEC_POLICY_ENTRUST:
   1475 	case IPSEC_POLICY_BYPASS:
   1476 		newsp->req = NULL;
   1477 		break;
   1478 
   1479 	case IPSEC_POLICY_IPSEC:
   1480 	    {
   1481 		int tlen;
   1482 		const struct sadb_x_ipsecrequest *xisr;
   1483 		uint16_t xisr_reqid;
   1484 		struct ipsecrequest **p_isr = &newsp->req;
   1485 
   1486 		/* validity check */
   1487 		if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
   1488 			ipseclog((LOG_DEBUG,
   1489 			    "key_msg2sp: Invalid msg length.\n"));
   1490 			KEY_FREESP(&newsp);
   1491 			*error = EINVAL;
   1492 			return NULL;
   1493 		}
   1494 
   1495 		tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
   1496 		xisr = (const struct sadb_x_ipsecrequest *)(xpl0 + 1);
   1497 
   1498 		while (tlen > 0) {
   1499 			/* length check */
   1500 			if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
   1501 				ipseclog((LOG_DEBUG, "key_msg2sp: "
   1502 					"invalid ipsecrequest length.\n"));
   1503 				KEY_FREESP(&newsp);
   1504 				*error = EINVAL;
   1505 				return NULL;
   1506 			}
   1507 
   1508 			/* allocate request buffer */
   1509 			KMALLOC(*p_isr, struct ipsecrequest *, sizeof(**p_isr));
   1510 			if ((*p_isr) == NULL) {
   1511 				ipseclog((LOG_DEBUG,
   1512 				    "key_msg2sp: No more memory.\n"));
   1513 				KEY_FREESP(&newsp);
   1514 				*error = ENOBUFS;
   1515 				return NULL;
   1516 			}
   1517 			memset(*p_isr, 0, sizeof(**p_isr));
   1518 
   1519 			/* set values */
   1520 			(*p_isr)->next = NULL;
   1521 
   1522 			switch (xisr->sadb_x_ipsecrequest_proto) {
   1523 			case IPPROTO_ESP:
   1524 			case IPPROTO_AH:
   1525 			case IPPROTO_IPCOMP:
   1526 				break;
   1527 			default:
   1528 				ipseclog((LOG_DEBUG,
   1529 				    "key_msg2sp: invalid proto type=%u\n",
   1530 				    xisr->sadb_x_ipsecrequest_proto));
   1531 				KEY_FREESP(&newsp);
   1532 				*error = EPROTONOSUPPORT;
   1533 				return NULL;
   1534 			}
   1535 			(*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
   1536 
   1537 			switch (xisr->sadb_x_ipsecrequest_mode) {
   1538 			case IPSEC_MODE_TRANSPORT:
   1539 			case IPSEC_MODE_TUNNEL:
   1540 				break;
   1541 			case IPSEC_MODE_ANY:
   1542 			default:
   1543 				ipseclog((LOG_DEBUG,
   1544 				    "key_msg2sp: invalid mode=%u\n",
   1545 				    xisr->sadb_x_ipsecrequest_mode));
   1546 				KEY_FREESP(&newsp);
   1547 				*error = EINVAL;
   1548 				return NULL;
   1549 			}
   1550 			(*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
   1551 
   1552 			switch (xisr->sadb_x_ipsecrequest_level) {
   1553 			case IPSEC_LEVEL_DEFAULT:
   1554 			case IPSEC_LEVEL_USE:
   1555 			case IPSEC_LEVEL_REQUIRE:
   1556 				break;
   1557 			case IPSEC_LEVEL_UNIQUE:
   1558 				xisr_reqid = xisr->sadb_x_ipsecrequest_reqid;
   1559 				/* validity check */
   1560 				/*
   1561 				 * If range violation of reqid, kernel will
   1562 				 * update it, don't refuse it.
   1563 				 */
   1564 				if (xisr_reqid > IPSEC_MANUAL_REQID_MAX) {
   1565 					ipseclog((LOG_DEBUG,
   1566 					    "key_msg2sp: reqid=%d range "
   1567 					    "violation, updated by kernel.\n",
   1568 					    xisr_reqid));
   1569 					xisr_reqid = 0;
   1570 				}
   1571 
   1572 				/* allocate new reqid id if reqid is zero. */
   1573 				if (xisr_reqid == 0) {
   1574 					u_int16_t reqid;
   1575 					if ((reqid = key_newreqid()) == 0) {
   1576 						KEY_FREESP(&newsp);
   1577 						*error = ENOBUFS;
   1578 						return NULL;
   1579 					}
   1580 					(*p_isr)->saidx.reqid = reqid;
   1581 				} else {
   1582 				/* set it for manual keying. */
   1583 					(*p_isr)->saidx.reqid = xisr_reqid;
   1584 				}
   1585 				break;
   1586 
   1587 			default:
   1588 				ipseclog((LOG_DEBUG, "key_msg2sp: invalid level=%u\n",
   1589 					xisr->sadb_x_ipsecrequest_level));
   1590 				KEY_FREESP(&newsp);
   1591 				*error = EINVAL;
   1592 				return NULL;
   1593 			}
   1594 			(*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
   1595 
   1596 			/* set IP addresses if there */
   1597 			if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
   1598 				const struct sockaddr *paddr;
   1599 
   1600 				paddr = (const struct sockaddr *)(xisr + 1);
   1601 
   1602 				/* validity check */
   1603 				if (paddr->sa_len
   1604 				    > sizeof((*p_isr)->saidx.src)) {
   1605 					ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
   1606 						"address length.\n"));
   1607 					KEY_FREESP(&newsp);
   1608 					*error = EINVAL;
   1609 					return NULL;
   1610 				}
   1611 				memcpy(&(*p_isr)->saidx.src, paddr, paddr->sa_len);
   1612 
   1613 				paddr = (const struct sockaddr *)((const char *)paddr
   1614 							+ paddr->sa_len);
   1615 
   1616 				/* validity check */
   1617 				if (paddr->sa_len
   1618 				    > sizeof((*p_isr)->saidx.dst)) {
   1619 					ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
   1620 						"address length.\n"));
   1621 					KEY_FREESP(&newsp);
   1622 					*error = EINVAL;
   1623 					return NULL;
   1624 				}
   1625 				memcpy(&(*p_isr)->saidx.dst, paddr, paddr->sa_len);
   1626 			}
   1627 
   1628 			(*p_isr)->sav = NULL;
   1629 			(*p_isr)->sp = newsp;
   1630 
   1631 			/* initialization for the next. */
   1632 			p_isr = &(*p_isr)->next;
   1633 			tlen -= xisr->sadb_x_ipsecrequest_len;
   1634 
   1635 			/* validity check */
   1636 			if (tlen < 0) {
   1637 				ipseclog((LOG_DEBUG, "key_msg2sp: becoming tlen < 0.\n"));
   1638 				KEY_FREESP(&newsp);
   1639 				*error = EINVAL;
   1640 				return NULL;
   1641 			}
   1642 
   1643 			xisr = (const struct sadb_x_ipsecrequest *)((const char *)xisr
   1644 			                 + xisr->sadb_x_ipsecrequest_len);
   1645 		}
   1646 	    }
   1647 		break;
   1648 	default:
   1649 		ipseclog((LOG_DEBUG, "key_msg2sp: invalid policy type.\n"));
   1650 		KEY_FREESP(&newsp);
   1651 		*error = EINVAL;
   1652 		return NULL;
   1653 	}
   1654 
   1655 	*error = 0;
   1656 	return newsp;
   1657 }
   1658 
   1659 static u_int16_t
   1660 key_newreqid(void)
   1661 {
   1662 	static u_int16_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
   1663 
   1664 	auto_reqid = (auto_reqid == 0xffff
   1665 			? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
   1666 
   1667 	/* XXX should be unique check */
   1668 
   1669 	return auto_reqid;
   1670 }
   1671 
   1672 /*
   1673  * copy secpolicy struct to sadb_x_policy structure indicated.
   1674  */
   1675 struct mbuf *
   1676 key_sp2msg(const struct secpolicy *sp)
   1677 {
   1678 	struct sadb_x_policy *xpl;
   1679 	int tlen;
   1680 	char *p;
   1681 	struct mbuf *m;
   1682 
   1683 	/* sanity check. */
   1684 	if (sp == NULL)
   1685 		panic("key_sp2msg: NULL pointer was passed");
   1686 
   1687 	tlen = key_getspreqmsglen(sp);
   1688 
   1689 	m = key_alloc_mbuf(tlen);
   1690 	if (!m || m->m_next) {	/*XXX*/
   1691 		if (m)
   1692 			m_freem(m);
   1693 		return NULL;
   1694 	}
   1695 
   1696 	m->m_len = tlen;
   1697 	m->m_next = NULL;
   1698 	xpl = mtod(m, struct sadb_x_policy *);
   1699 	memset(xpl, 0, tlen);
   1700 
   1701 	xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
   1702 	xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
   1703 	xpl->sadb_x_policy_type = sp->policy;
   1704 	xpl->sadb_x_policy_dir = sp->spidx.dir;
   1705 	xpl->sadb_x_policy_id = sp->id;
   1706 	p = (char *)xpl + sizeof(*xpl);
   1707 
   1708 	/* if is the policy for ipsec ? */
   1709 	if (sp->policy == IPSEC_POLICY_IPSEC) {
   1710 		struct sadb_x_ipsecrequest *xisr;
   1711 		struct ipsecrequest *isr;
   1712 
   1713 		for (isr = sp->req; isr != NULL; isr = isr->next) {
   1714 
   1715 			xisr = (struct sadb_x_ipsecrequest *)p;
   1716 
   1717 			xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
   1718 			xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
   1719 			xisr->sadb_x_ipsecrequest_level = isr->level;
   1720 			xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
   1721 
   1722 			p += sizeof(*xisr);
   1723 			memcpy(p, &isr->saidx.src, isr->saidx.src.sa.sa_len);
   1724 			p += isr->saidx.src.sa.sa_len;
   1725 			memcpy(p, &isr->saidx.dst, isr->saidx.dst.sa.sa_len);
   1726 			p += isr->saidx.src.sa.sa_len;
   1727 
   1728 			xisr->sadb_x_ipsecrequest_len =
   1729 				PFKEY_ALIGN8(sizeof(*xisr)
   1730 					+ isr->saidx.src.sa.sa_len
   1731 					+ isr->saidx.dst.sa.sa_len);
   1732 		}
   1733 	}
   1734 
   1735 	return m;
   1736 }
   1737 
   1738 /* m will not be freed nor modified */
   1739 static struct mbuf *
   1740 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
   1741 		int ndeep, int nitem, ...)
   1742 {
   1743 	va_list ap;
   1744 	int idx;
   1745 	int i;
   1746 	struct mbuf *result = NULL, *n;
   1747 	int len;
   1748 
   1749 	if (m == NULL || mhp == NULL)
   1750 		panic("null pointer passed to key_gather");
   1751 
   1752 	va_start(ap, nitem);
   1753 	for (i = 0; i < nitem; i++) {
   1754 		idx = va_arg(ap, int);
   1755 		if (idx < 0 || idx > SADB_EXT_MAX)
   1756 			goto fail;
   1757 		/* don't attempt to pull empty extension */
   1758 		if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
   1759 			continue;
   1760 		if (idx != SADB_EXT_RESERVED  &&
   1761 		    (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
   1762 			continue;
   1763 
   1764 		if (idx == SADB_EXT_RESERVED) {
   1765 			len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
   1766 #ifdef DIAGNOSTIC
   1767 			if (len > MHLEN)
   1768 				panic("assumption failed");
   1769 #endif
   1770 			MGETHDR(n, M_DONTWAIT, MT_DATA);
   1771 			if (!n)
   1772 				goto fail;
   1773 			n->m_len = len;
   1774 			n->m_next = NULL;
   1775 			m_copydata(m, 0, sizeof(struct sadb_msg),
   1776 			    mtod(n, void *));
   1777 		} else if (i < ndeep) {
   1778 			len = mhp->extlen[idx];
   1779 			n = key_alloc_mbuf(len);
   1780 			if (!n || n->m_next) {	/*XXX*/
   1781 				if (n)
   1782 					m_freem(n);
   1783 				goto fail;
   1784 			}
   1785 			m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
   1786 			    mtod(n, void *));
   1787 		} else {
   1788 			n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
   1789 			    M_DONTWAIT);
   1790 		}
   1791 		if (n == NULL)
   1792 			goto fail;
   1793 
   1794 		if (result)
   1795 			m_cat(result, n);
   1796 		else
   1797 			result = n;
   1798 	}
   1799 	va_end(ap);
   1800 
   1801 	if (result && (result->m_flags & M_PKTHDR) != 0) {
   1802 		result->m_pkthdr.len = 0;
   1803 		for (n = result; n; n = n->m_next)
   1804 			result->m_pkthdr.len += n->m_len;
   1805 	}
   1806 
   1807 	return result;
   1808 
   1809 fail:
   1810 	va_end(ap);
   1811 	m_freem(result);
   1812 	return NULL;
   1813 }
   1814 
   1815 /*
   1816  * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
   1817  * add an entry to SP database, when received
   1818  *   <base, address(SD), (lifetime(H),) policy>
   1819  * from the user(?).
   1820  * Adding to SP database,
   1821  * and send
   1822  *   <base, address(SD), (lifetime(H),) policy>
   1823  * to the socket which was send.
   1824  *
   1825  * SPDADD set a unique policy entry.
   1826  * SPDSETIDX like SPDADD without a part of policy requests.
   1827  * SPDUPDATE replace a unique policy entry.
   1828  *
   1829  * m will always be freed.
   1830  */
   1831 static int
   1832 key_spdadd(struct socket *so, struct mbuf *m,
   1833 	   const struct sadb_msghdr *mhp)
   1834 {
   1835 	const struct sadb_address *src0, *dst0;
   1836 	const struct sadb_x_policy *xpl0;
   1837 	struct sadb_x_policy *xpl;
   1838 	const struct sadb_lifetime *lft = NULL;
   1839 	struct secpolicyindex spidx;
   1840 	struct secpolicy *newsp;
   1841 	int error;
   1842 
   1843 	/* sanity check */
   1844 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   1845 		panic("key_spdadd: NULL pointer is passed");
   1846 
   1847 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   1848 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   1849 	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
   1850 		ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
   1851 		return key_senderror(so, m, EINVAL);
   1852 	}
   1853 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   1854 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
   1855 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
   1856 		ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
   1857 		return key_senderror(so, m, EINVAL);
   1858 	}
   1859 	if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
   1860 		if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
   1861 			< sizeof(struct sadb_lifetime)) {
   1862 			ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
   1863 			return key_senderror(so, m, EINVAL);
   1864 		}
   1865 		lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
   1866 	}
   1867 
   1868 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
   1869 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
   1870 	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
   1871 
   1872 	/* make secindex */
   1873 	/* XXX boundary check against sa_len */
   1874 	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
   1875 	                src0 + 1,
   1876 	                dst0 + 1,
   1877 	                src0->sadb_address_prefixlen,
   1878 	                dst0->sadb_address_prefixlen,
   1879 	                src0->sadb_address_proto,
   1880 	                &spidx);
   1881 
   1882 	/* checking the direciton. */
   1883 	switch (xpl0->sadb_x_policy_dir) {
   1884 	case IPSEC_DIR_INBOUND:
   1885 	case IPSEC_DIR_OUTBOUND:
   1886 		break;
   1887 	default:
   1888 		ipseclog((LOG_DEBUG, "key_spdadd: Invalid SP direction.\n"));
   1889 		mhp->msg->sadb_msg_errno = EINVAL;
   1890 		return 0;
   1891 	}
   1892 
   1893 	/* check policy */
   1894 	/* key_spdadd() accepts DISCARD, NONE and IPSEC. */
   1895 	if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
   1896 	 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
   1897 		ipseclog((LOG_DEBUG, "key_spdadd: Invalid policy type.\n"));
   1898 		return key_senderror(so, m, EINVAL);
   1899 	}
   1900 
   1901 	/* policy requests are mandatory when action is ipsec. */
   1902         if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
   1903 	 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
   1904 	 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
   1905 		ipseclog((LOG_DEBUG, "key_spdadd: some policy requests part required.\n"));
   1906 		return key_senderror(so, m, EINVAL);
   1907 	}
   1908 
   1909 	/*
   1910 	 * checking there is SP already or not.
   1911 	 * SPDUPDATE doesn't depend on whether there is a SP or not.
   1912 	 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
   1913 	 * then error.
   1914 	 */
   1915 	newsp = key_getsp(&spidx);
   1916 	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
   1917 		if (newsp) {
   1918 			key_sp_dead(newsp);
   1919 			key_sp_unlink(newsp);	/* XXX jrs ordering */
   1920 			KEY_FREESP(&newsp);
   1921 			newsp = NULL;
   1922 		}
   1923 	} else {
   1924 		if (newsp != NULL) {
   1925 			KEY_FREESP(&newsp);
   1926 			ipseclog((LOG_DEBUG, "key_spdadd: a SP entry exists already.\n"));
   1927 			return key_senderror(so, m, EEXIST);
   1928 		}
   1929 	}
   1930 
   1931 	/* allocation new SP entry */
   1932 	if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
   1933 		return key_senderror(so, m, error);
   1934 	}
   1935 
   1936 	if ((newsp->id = key_getnewspid()) == 0) {
   1937 		KFREE(newsp);
   1938 		return key_senderror(so, m, ENOBUFS);
   1939 	}
   1940 
   1941 	/* XXX boundary check against sa_len */
   1942 	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
   1943 	                src0 + 1,
   1944 	                dst0 + 1,
   1945 	                src0->sadb_address_prefixlen,
   1946 	                dst0->sadb_address_prefixlen,
   1947 	                src0->sadb_address_proto,
   1948 	                &newsp->spidx);
   1949 
   1950 	/* sanity check on addr pair */
   1951 	if (((const struct sockaddr *)(src0 + 1))->sa_family !=
   1952 			((const struct sockaddr *)(dst0+ 1))->sa_family) {
   1953 		KFREE(newsp);
   1954 		return key_senderror(so, m, EINVAL);
   1955 	}
   1956 	if (((const struct sockaddr *)(src0 + 1))->sa_len !=
   1957 			((const struct sockaddr *)(dst0+ 1))->sa_len) {
   1958 		KFREE(newsp);
   1959 		return key_senderror(so, m, EINVAL);
   1960 	}
   1961 
   1962 	newsp->created = time_uptime;
   1963 	newsp->lastused = newsp->created;
   1964 	newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
   1965 	newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
   1966 
   1967 	newsp->refcnt = 1;	/* do not reclaim until I say I do */
   1968 	newsp->state = IPSEC_SPSTATE_ALIVE;
   1969 	LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain);
   1970 
   1971 	/* delete the entry in spacqtree */
   1972 	if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
   1973 		struct secspacq *spacq;
   1974 		if ((spacq = key_getspacq(&spidx)) != NULL) {
   1975 			/* reset counter in order to deletion by timehandler. */
   1976 			spacq->created = time_uptime;
   1977 			spacq->count = 0;
   1978 		}
   1979     	}
   1980 
   1981 #if defined(__NetBSD__)
   1982 	/* Invalidate all cached SPD pointers in the PCBs. */
   1983 	ipsec_invalpcbcacheall();
   1984 
   1985 #if defined(GATEWAY)
   1986 	/* Invalidate the ipflow cache, as well. */
   1987 	ipflow_invalidate_all(0);
   1988 #ifdef INET6
   1989 	ip6flow_invalidate_all(0);
   1990 #endif /* INET6 */
   1991 #endif /* GATEWAY */
   1992 #endif /* __NetBSD__ */
   1993 
   1994     {
   1995 	struct mbuf *n, *mpolicy;
   1996 	struct sadb_msg *newmsg;
   1997 	int off;
   1998 
   1999 	/* create new sadb_msg to reply. */
   2000 	if (lft) {
   2001 		n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
   2002 		    SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
   2003 		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   2004 	} else {
   2005 		n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
   2006 		    SADB_X_EXT_POLICY,
   2007 		    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   2008 	}
   2009 	if (!n)
   2010 		return key_senderror(so, m, ENOBUFS);
   2011 
   2012 	if (n->m_len < sizeof(*newmsg)) {
   2013 		n = m_pullup(n, sizeof(*newmsg));
   2014 		if (!n)
   2015 			return key_senderror(so, m, ENOBUFS);
   2016 	}
   2017 	newmsg = mtod(n, struct sadb_msg *);
   2018 	newmsg->sadb_msg_errno = 0;
   2019 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
   2020 
   2021 	off = 0;
   2022 	mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
   2023 	    sizeof(*xpl), &off);
   2024 	if (mpolicy == NULL) {
   2025 		/* n is already freed */
   2026 		return key_senderror(so, m, ENOBUFS);
   2027 	}
   2028 	xpl = (struct sadb_x_policy *)(mtod(mpolicy, char *) + off);
   2029 	if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
   2030 		m_freem(n);
   2031 		return key_senderror(so, m, EINVAL);
   2032 	}
   2033 	xpl->sadb_x_policy_id = newsp->id;
   2034 
   2035 	m_freem(m);
   2036 	key_update_used();
   2037 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   2038     }
   2039 }
   2040 
   2041 /*
   2042  * get new policy id.
   2043  * OUT:
   2044  *	0:	failure.
   2045  *	others: success.
   2046  */
   2047 static u_int32_t
   2048 key_getnewspid(void)
   2049 {
   2050 	u_int32_t newid = 0;
   2051 	int count = key_spi_trycnt;	/* XXX */
   2052 	struct secpolicy *sp;
   2053 
   2054 	/* when requesting to allocate spi ranged */
   2055 	while (count--) {
   2056 		newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
   2057 
   2058 		if ((sp = key_getspbyid(newid)) == NULL)
   2059 			break;
   2060 
   2061 		KEY_FREESP(&sp);
   2062 	}
   2063 
   2064 	if (count == 0 || newid == 0) {
   2065 		ipseclog((LOG_DEBUG, "key_getnewspid: to allocate policy id is failed.\n"));
   2066 		return 0;
   2067 	}
   2068 
   2069 	return newid;
   2070 }
   2071 
   2072 /*
   2073  * SADB_SPDDELETE processing
   2074  * receive
   2075  *   <base, address(SD), policy(*)>
   2076  * from the user(?), and set SADB_SASTATE_DEAD,
   2077  * and send,
   2078  *   <base, address(SD), policy(*)>
   2079  * to the ikmpd.
   2080  * policy(*) including direction of policy.
   2081  *
   2082  * m will always be freed.
   2083  */
   2084 static int
   2085 key_spddelete(struct socket *so, struct mbuf *m,
   2086               const struct sadb_msghdr *mhp)
   2087 {
   2088 	struct sadb_address *src0, *dst0;
   2089 	struct sadb_x_policy *xpl0;
   2090 	struct secpolicyindex spidx;
   2091 	struct secpolicy *sp;
   2092 
   2093 	/* sanity check */
   2094 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   2095 		panic("key_spddelete: NULL pointer is passed");
   2096 
   2097 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   2098 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   2099 	    mhp->ext[SADB_X_EXT_POLICY] == NULL) {
   2100 		ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
   2101 		return key_senderror(so, m, EINVAL);
   2102 	}
   2103 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   2104 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
   2105 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
   2106 		ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
   2107 		return key_senderror(so, m, EINVAL);
   2108 	}
   2109 
   2110 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
   2111 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
   2112 	xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
   2113 
   2114 	/* make secindex */
   2115 	/* XXX boundary check against sa_len */
   2116 	KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
   2117 	                src0 + 1,
   2118 	                dst0 + 1,
   2119 	                src0->sadb_address_prefixlen,
   2120 	                dst0->sadb_address_prefixlen,
   2121 	                src0->sadb_address_proto,
   2122 	                &spidx);
   2123 
   2124 	/* checking the direciton. */
   2125 	switch (xpl0->sadb_x_policy_dir) {
   2126 	case IPSEC_DIR_INBOUND:
   2127 	case IPSEC_DIR_OUTBOUND:
   2128 		break;
   2129 	default:
   2130 		ipseclog((LOG_DEBUG, "key_spddelete: Invalid SP direction.\n"));
   2131 		return key_senderror(so, m, EINVAL);
   2132 	}
   2133 
   2134 	/* Is there SP in SPD ? */
   2135 	if ((sp = key_getsp(&spidx)) == NULL) {
   2136 		ipseclog((LOG_DEBUG, "key_spddelete: no SP found.\n"));
   2137 		return key_senderror(so, m, EINVAL);
   2138 	}
   2139 
   2140 	/* save policy id to buffer to be returned. */
   2141 	xpl0->sadb_x_policy_id = sp->id;
   2142 
   2143 	key_sp_dead(sp);
   2144 	key_sp_unlink(sp);	/* XXX jrs ordering */
   2145 	KEY_FREESP(&sp);	/* ref gained by key_getspbyid */
   2146 
   2147 #if defined(__NetBSD__)
   2148 	/* Invalidate all cached SPD pointers in the PCBs. */
   2149 	ipsec_invalpcbcacheall();
   2150 
   2151 	/* We're deleting policy; no need to invalidate the ipflow cache. */
   2152 #endif /* __NetBSD__ */
   2153 
   2154     {
   2155 	struct mbuf *n;
   2156 	struct sadb_msg *newmsg;
   2157 
   2158 	/* create new sadb_msg to reply. */
   2159 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
   2160 	    SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   2161 	if (!n)
   2162 		return key_senderror(so, m, ENOBUFS);
   2163 
   2164 	newmsg = mtod(n, struct sadb_msg *);
   2165 	newmsg->sadb_msg_errno = 0;
   2166 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
   2167 
   2168 	m_freem(m);
   2169 	key_update_used();
   2170 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   2171     }
   2172 }
   2173 
   2174 /*
   2175  * SADB_SPDDELETE2 processing
   2176  * receive
   2177  *   <base, policy(*)>
   2178  * from the user(?), and set SADB_SASTATE_DEAD,
   2179  * and send,
   2180  *   <base, policy(*)>
   2181  * to the ikmpd.
   2182  * policy(*) including direction of policy.
   2183  *
   2184  * m will always be freed.
   2185  */
   2186 static int
   2187 key_spddelete2(struct socket *so, struct mbuf *m,
   2188 	       const struct sadb_msghdr *mhp)
   2189 {
   2190 	u_int32_t id;
   2191 	struct secpolicy *sp;
   2192 
   2193 	/* sanity check */
   2194 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   2195 		panic("key_spddelete2: NULL pointer is passed");
   2196 
   2197 	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
   2198 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
   2199 		ipseclog((LOG_DEBUG, "key_spddelete2: invalid message is passed.\n"));
   2200 		key_senderror(so, m, EINVAL);
   2201 		return 0;
   2202 	}
   2203 
   2204 	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
   2205 
   2206 	/* Is there SP in SPD ? */
   2207 	if ((sp = key_getspbyid(id)) == NULL) {
   2208 		ipseclog((LOG_DEBUG, "key_spddelete2: no SP found id:%u.\n", id));
   2209 		return key_senderror(so, m, EINVAL);
   2210 	}
   2211 
   2212 	key_sp_dead(sp);
   2213 	key_sp_unlink(sp);	/* XXX jrs ordering */
   2214 	KEY_FREESP(&sp);	/* ref gained by key_getsp */
   2215 	sp = NULL;
   2216 
   2217 #if defined(__NetBSD__)
   2218 	/* Invalidate all cached SPD pointers in the PCBs. */
   2219 	ipsec_invalpcbcacheall();
   2220 
   2221 	/* We're deleting policy; no need to invalidate the ipflow cache. */
   2222 #endif /* __NetBSD__ */
   2223 
   2224     {
   2225 	struct mbuf *n, *nn;
   2226 	struct sadb_msg *newmsg;
   2227 	int off, len;
   2228 
   2229 	/* create new sadb_msg to reply. */
   2230 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
   2231 
   2232 	if (len > MCLBYTES)
   2233 		return key_senderror(so, m, ENOBUFS);
   2234 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   2235 	if (n && len > MHLEN) {
   2236 		MCLGET(n, M_DONTWAIT);
   2237 		if ((n->m_flags & M_EXT) == 0) {
   2238 			m_freem(n);
   2239 			n = NULL;
   2240 		}
   2241 	}
   2242 	if (!n)
   2243 		return key_senderror(so, m, ENOBUFS);
   2244 
   2245 	n->m_len = len;
   2246 	n->m_next = NULL;
   2247 	off = 0;
   2248 
   2249 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   2250 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   2251 
   2252 #ifdef DIAGNOSTIC
   2253 	if (off != len)
   2254 		panic("length inconsistency in key_spddelete2");
   2255 #endif
   2256 
   2257 	n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
   2258 	    mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
   2259 	if (!n->m_next) {
   2260 		m_freem(n);
   2261 		return key_senderror(so, m, ENOBUFS);
   2262 	}
   2263 
   2264 	n->m_pkthdr.len = 0;
   2265 	for (nn = n; nn; nn = nn->m_next)
   2266 		n->m_pkthdr.len += nn->m_len;
   2267 
   2268 	newmsg = mtod(n, struct sadb_msg *);
   2269 	newmsg->sadb_msg_errno = 0;
   2270 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
   2271 
   2272 	m_freem(m);
   2273 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   2274     }
   2275 }
   2276 
   2277 /*
   2278  * SADB_X_GET processing
   2279  * receive
   2280  *   <base, policy(*)>
   2281  * from the user(?),
   2282  * and send,
   2283  *   <base, address(SD), policy>
   2284  * to the ikmpd.
   2285  * policy(*) including direction of policy.
   2286  *
   2287  * m will always be freed.
   2288  */
   2289 static int
   2290 key_spdget(struct socket *so, struct mbuf *m,
   2291 	   const struct sadb_msghdr *mhp)
   2292 {
   2293 	u_int32_t id;
   2294 	struct secpolicy *sp;
   2295 	struct mbuf *n;
   2296 
   2297 	/* sanity check */
   2298 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   2299 		panic("key_spdget: NULL pointer is passed");
   2300 
   2301 	if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
   2302 	    mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
   2303 		ipseclog((LOG_DEBUG, "key_spdget: invalid message is passed.\n"));
   2304 		return key_senderror(so, m, EINVAL);
   2305 	}
   2306 
   2307 	id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
   2308 
   2309 	/* Is there SP in SPD ? */
   2310 	if ((sp = key_getspbyid(id)) == NULL) {
   2311 		ipseclog((LOG_DEBUG, "key_spdget: no SP found id:%u.\n", id));
   2312 		return key_senderror(so, m, ENOENT);
   2313 	}
   2314 
   2315 	n = key_setdumpsp(sp, SADB_X_SPDGET, mhp->msg->sadb_msg_seq,
   2316                                          mhp->msg->sadb_msg_pid);
   2317     KEY_FREESP(&sp); /* ref gained by key_getspbyid */
   2318 	if (n != NULL) {
   2319 		m_freem(m);
   2320 		return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   2321 	} else
   2322 		return key_senderror(so, m, ENOBUFS);
   2323 }
   2324 
   2325 /*
   2326  * SADB_X_SPDACQUIRE processing.
   2327  * Acquire policy and SA(s) for a *OUTBOUND* packet.
   2328  * send
   2329  *   <base, policy(*)>
   2330  * to KMD, and expect to receive
   2331  *   <base> with SADB_X_SPDACQUIRE if error occurred,
   2332  * or
   2333  *   <base, policy>
   2334  * with SADB_X_SPDUPDATE from KMD by PF_KEY.
   2335  * policy(*) is without policy requests.
   2336  *
   2337  *    0     : succeed
   2338  *    others: error number
   2339  */
   2340 int
   2341 key_spdacquire(const struct secpolicy *sp)
   2342 {
   2343 	struct mbuf *result = NULL, *m;
   2344 	struct secspacq *newspacq;
   2345 	int error;
   2346 
   2347 	/* sanity check */
   2348 	if (sp == NULL)
   2349 		panic("key_spdacquire: NULL pointer is passed");
   2350 	if (sp->req != NULL)
   2351 		panic("key_spdacquire: called but there is request");
   2352 	if (sp->policy != IPSEC_POLICY_IPSEC)
   2353 		panic("key_spdacquire: policy mismathed. IPsec is expected");
   2354 
   2355 	/* Get an entry to check whether sent message or not. */
   2356 	if ((newspacq = key_getspacq(&sp->spidx)) != NULL) {
   2357 		if (key_blockacq_count < newspacq->count) {
   2358 			/* reset counter and do send message. */
   2359 			newspacq->count = 0;
   2360 		} else {
   2361 			/* increment counter and do nothing. */
   2362 			newspacq->count++;
   2363 			return 0;
   2364 		}
   2365 	} else {
   2366 		/* make new entry for blocking to send SADB_ACQUIRE. */
   2367 		if ((newspacq = key_newspacq(&sp->spidx)) == NULL)
   2368 			return ENOBUFS;
   2369 
   2370 		/* add to acqtree */
   2371 		LIST_INSERT_HEAD(&spacqtree, newspacq, chain);
   2372 	}
   2373 
   2374 	/* create new sadb_msg to reply. */
   2375 	m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
   2376 	if (!m) {
   2377 		error = ENOBUFS;
   2378 		goto fail;
   2379 	}
   2380 	result = m;
   2381 
   2382 	result->m_pkthdr.len = 0;
   2383 	for (m = result; m; m = m->m_next)
   2384 		result->m_pkthdr.len += m->m_len;
   2385 
   2386 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   2387 	    PFKEY_UNIT64(result->m_pkthdr.len);
   2388 
   2389 	return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
   2390 
   2391 fail:
   2392 	if (result)
   2393 		m_freem(result);
   2394 	return error;
   2395 }
   2396 
   2397 /*
   2398  * SADB_SPDFLUSH processing
   2399  * receive
   2400  *   <base>
   2401  * from the user, and free all entries in secpctree.
   2402  * and send,
   2403  *   <base>
   2404  * to the user.
   2405  * NOTE: what to do is only marking SADB_SASTATE_DEAD.
   2406  *
   2407  * m will always be freed.
   2408  */
   2409 static int
   2410 key_spdflush(struct socket *so, struct mbuf *m,
   2411 	     const struct sadb_msghdr *mhp)
   2412 {
   2413 	struct sadb_msg *newmsg;
   2414 	struct secpolicy *sp;
   2415 	u_int dir;
   2416 
   2417 	/* sanity check */
   2418 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   2419 		panic("key_spdflush: NULL pointer is passed");
   2420 
   2421 	if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
   2422 		return key_senderror(so, m, EINVAL);
   2423 
   2424 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   2425 		struct secpolicy * nextsp;
   2426 		for (sp = LIST_FIRST(&sptree[dir]);
   2427 		     sp != NULL;
   2428 		     sp = nextsp) {
   2429 
   2430  			nextsp = LIST_NEXT(sp, chain);
   2431 			if (sp->state == IPSEC_SPSTATE_DEAD)
   2432 				continue;
   2433 			key_sp_dead(sp);
   2434 			key_sp_unlink(sp);
   2435 			/* 'sp' dead; continue transfers to 'sp = nextsp' */
   2436 			continue;
   2437 		}
   2438 	}
   2439 
   2440 #if defined(__NetBSD__)
   2441 	/* Invalidate all cached SPD pointers in the PCBs. */
   2442 	ipsec_invalpcbcacheall();
   2443 
   2444 	/* We're deleting policy; no need to invalidate the ipflow cache. */
   2445 #endif /* __NetBSD__ */
   2446 
   2447 	if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
   2448 		ipseclog((LOG_DEBUG, "key_spdflush: No more memory.\n"));
   2449 		return key_senderror(so, m, ENOBUFS);
   2450 	}
   2451 
   2452 	if (m->m_next)
   2453 		m_freem(m->m_next);
   2454 	m->m_next = NULL;
   2455 	m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
   2456 	newmsg = mtod(m, struct sadb_msg *);
   2457 	newmsg->sadb_msg_errno = 0;
   2458 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
   2459 
   2460 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   2461 }
   2462 
   2463 static struct sockaddr key_src = {
   2464 	.sa_len = 2,
   2465 	.sa_family = PF_KEY,
   2466 };
   2467 
   2468 static struct mbuf *
   2469 key_setspddump_chain(int *errorp, int *lenp, pid_t pid)
   2470 {
   2471 	struct secpolicy *sp;
   2472 	int cnt;
   2473 	u_int dir;
   2474 	struct mbuf *m, *n, *prev;
   2475 	int totlen;
   2476 
   2477 	*lenp = 0;
   2478 
   2479 	/* search SPD entry and get buffer size. */
   2480 	cnt = 0;
   2481 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   2482 		LIST_FOREACH(sp, &sptree[dir], chain) {
   2483 			cnt++;
   2484 		}
   2485 	}
   2486 
   2487 	if (cnt == 0) {
   2488 		*errorp = ENOENT;
   2489 		return (NULL);
   2490 	}
   2491 
   2492 	m = NULL;
   2493 	prev = m;
   2494 	totlen = 0;
   2495 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   2496 		LIST_FOREACH(sp, &sptree[dir], chain) {
   2497 			--cnt;
   2498 			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
   2499 
   2500 			if (!n) {
   2501 				*errorp = ENOBUFS;
   2502 				if (m) m_freem(m);
   2503 				return (NULL);
   2504 			}
   2505 
   2506 			totlen += n->m_pkthdr.len;
   2507 			if (!m) {
   2508 				m = n;
   2509 			} else {
   2510 				prev->m_nextpkt = n;
   2511 			}
   2512 			prev = n;
   2513 		}
   2514 	}
   2515 
   2516 	*lenp = totlen;
   2517 	*errorp = 0;
   2518 	return (m);
   2519 }
   2520 
   2521 /*
   2522  * SADB_SPDDUMP processing
   2523  * receive
   2524  *   <base>
   2525  * from the user, and dump all SP leaves
   2526  * and send,
   2527  *   <base> .....
   2528  * to the ikmpd.
   2529  *
   2530  * m will always be freed.
   2531  */
   2532 static int
   2533 key_spddump(struct socket *so, struct mbuf *m0,
   2534  	    const struct sadb_msghdr *mhp)
   2535 {
   2536 	struct mbuf *n;
   2537 	int error, len;
   2538 	int ok, s;
   2539 	pid_t pid;
   2540 
   2541 	/* sanity check */
   2542 	if (so == NULL || m0 == NULL || mhp == NULL || mhp->msg == NULL)
   2543 		panic("key_spddump: NULL pointer is passed");
   2544 
   2545 
   2546 	pid = mhp->msg->sadb_msg_pid;
   2547 	/*
   2548 	 * If the requestor has insufficient socket-buffer space
   2549 	 * for the entire chain, nobody gets any response to the DUMP.
   2550 	 * XXX For now, only the requestor ever gets anything.
   2551 	 * Moreover, if the requestor has any space at all, they receive
   2552 	 * the entire chain, otherwise the request is refused with  ENOBUFS.
   2553 	 */
   2554 	if (sbspace(&so->so_rcv) <= 0) {
   2555 		return key_senderror(so, m0, ENOBUFS);
   2556 	}
   2557 
   2558 	s = splsoftnet();
   2559 	n = key_setspddump_chain(&error, &len, pid);
   2560 	splx(s);
   2561 
   2562 	if (n == NULL) {
   2563 		return key_senderror(so, m0, ENOENT);
   2564 	}
   2565 	{
   2566 		uint64_t *ps = PFKEY_STAT_GETREF();
   2567 		ps[PFKEY_STAT_IN_TOTAL]++;
   2568 		ps[PFKEY_STAT_IN_BYTES] += len;
   2569 		PFKEY_STAT_PUTREF();
   2570 	}
   2571 
   2572 	/*
   2573 	 * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
   2574 	 * The requestor receives either the entire chain, or an
   2575 	 * error message with ENOBUFS.
   2576 	 */
   2577 
   2578 	/*
   2579 	 * sbappendchainwith record takes the chain of entries, one
   2580 	 * packet-record per SPD entry, prepends the key_src sockaddr
   2581 	 * to each packet-record, links the sockaddr mbufs into a new
   2582 	 * list of records, then   appends the entire resulting
   2583 	 * list to the requesting socket.
   2584 	 */
   2585 	ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src,
   2586 	        n, SB_PRIO_ONESHOT_OVERFLOW);
   2587 
   2588 	if (!ok) {
   2589 		PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
   2590 		m_freem(n);
   2591 		return key_senderror(so, m0, ENOBUFS);
   2592 	}
   2593 
   2594 	m_freem(m0);
   2595 	return error;
   2596 }
   2597 
   2598 /*
   2599  * SADB_X_NAT_T_NEW_MAPPING. Unused by racoon as of 2005/04/23
   2600  */
   2601 static int
   2602 key_nat_map(struct socket *so, struct mbuf *m,
   2603 	    const struct sadb_msghdr *mhp)
   2604 {
   2605 	struct sadb_x_nat_t_type *type;
   2606 	struct sadb_x_nat_t_port *sport;
   2607 	struct sadb_x_nat_t_port *dport;
   2608 	struct sadb_address *iaddr, *raddr;
   2609 	struct sadb_x_nat_t_frag *frag;
   2610 
   2611 	/* sanity check */
   2612 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   2613 		panic("key_nat_map: NULL pointer is passed.");
   2614 
   2615 	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] == NULL ||
   2616 		mhp->ext[SADB_X_EXT_NAT_T_SPORT] == NULL ||
   2617 		mhp->ext[SADB_X_EXT_NAT_T_DPORT] == NULL) {
   2618 		ipseclog((LOG_DEBUG, "key_nat_map: invalid message.\n"));
   2619 		return key_senderror(so, m, EINVAL);
   2620 	}
   2621 	if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
   2622 		(mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
   2623 		(mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
   2624 		ipseclog((LOG_DEBUG, "key_nat_map: invalid message.\n"));
   2625 		return key_senderror(so, m, EINVAL);
   2626 	}
   2627 
   2628 	if ((mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL) &&
   2629 		(mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr))) {
   2630 		ipseclog((LOG_DEBUG, "key_nat_map: invalid message\n"));
   2631 		return key_senderror(so, m, EINVAL);
   2632 	}
   2633 
   2634 	if ((mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) &&
   2635 		(mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr))) {
   2636 		ipseclog((LOG_DEBUG, "key_nat_map: invalid message\n"));
   2637 		return key_senderror(so, m, EINVAL);
   2638 	}
   2639 
   2640 	if ((mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) &&
   2641 		(mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag))) {
   2642 		ipseclog((LOG_DEBUG, "key_nat_map: invalid message\n"));
   2643 		return key_senderror(so, m, EINVAL);
   2644 	}
   2645 
   2646 	type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
   2647 	sport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   2648 	dport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   2649 	iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
   2650 	raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
   2651 	frag = (struct sadb_x_nat_t_frag *) mhp->ext[SADB_X_EXT_NAT_T_FRAG];
   2652 
   2653 	/*
   2654 	 * XXX handle that, it should also contain a SA, or anything
   2655 	 * that enable to update the SA information.
   2656 	 */
   2657 
   2658 	return 0;
   2659 }
   2660 
   2661 static struct mbuf *
   2662 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, pid_t pid)
   2663 {
   2664 	struct mbuf *result = NULL, *m;
   2665 
   2666 	m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
   2667 	if (!m)
   2668 		goto fail;
   2669 	result = m;
   2670 
   2671 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   2672 	    &sp->spidx.src.sa, sp->spidx.prefs,
   2673 	    sp->spidx.ul_proto);
   2674 	if (!m)
   2675 		goto fail;
   2676 	m_cat(result, m);
   2677 
   2678 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   2679 	    &sp->spidx.dst.sa, sp->spidx.prefd,
   2680 	    sp->spidx.ul_proto);
   2681 	if (!m)
   2682 		goto fail;
   2683 	m_cat(result, m);
   2684 
   2685 	m = key_sp2msg(sp);
   2686 	if (!m)
   2687 		goto fail;
   2688 	m_cat(result, m);
   2689 
   2690 	if ((result->m_flags & M_PKTHDR) == 0)
   2691 		goto fail;
   2692 
   2693 	if (result->m_len < sizeof(struct sadb_msg)) {
   2694 		result = m_pullup(result, sizeof(struct sadb_msg));
   2695 		if (result == NULL)
   2696 			goto fail;
   2697 	}
   2698 
   2699 	result->m_pkthdr.len = 0;
   2700 	for (m = result; m; m = m->m_next)
   2701 		result->m_pkthdr.len += m->m_len;
   2702 
   2703 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   2704 	    PFKEY_UNIT64(result->m_pkthdr.len);
   2705 
   2706 	return result;
   2707 
   2708 fail:
   2709 	m_freem(result);
   2710 	return NULL;
   2711 }
   2712 
   2713 /*
   2714  * get PFKEY message length for security policy and request.
   2715  */
   2716 static u_int
   2717 key_getspreqmsglen(const struct secpolicy *sp)
   2718 {
   2719 	u_int tlen;
   2720 
   2721 	tlen = sizeof(struct sadb_x_policy);
   2722 
   2723 	/* if is the policy for ipsec ? */
   2724 	if (sp->policy != IPSEC_POLICY_IPSEC)
   2725 		return tlen;
   2726 
   2727 	/* get length of ipsec requests */
   2728     {
   2729 	const struct ipsecrequest *isr;
   2730 	int len;
   2731 
   2732 	for (isr = sp->req; isr != NULL; isr = isr->next) {
   2733 		len = sizeof(struct sadb_x_ipsecrequest)
   2734 			+ isr->saidx.src.sa.sa_len
   2735 			+ isr->saidx.dst.sa.sa_len;
   2736 
   2737 		tlen += PFKEY_ALIGN8(len);
   2738 	}
   2739     }
   2740 
   2741 	return tlen;
   2742 }
   2743 
   2744 /*
   2745  * SADB_SPDEXPIRE processing
   2746  * send
   2747  *   <base, address(SD), lifetime(CH), policy>
   2748  * to KMD by PF_KEY.
   2749  *
   2750  * OUT:	0	: succeed
   2751  *	others	: error number
   2752  */
   2753 static int
   2754 key_spdexpire(struct secpolicy *sp)
   2755 {
   2756 	int s;
   2757 	struct mbuf *result = NULL, *m;
   2758 	int len;
   2759 	int error = -1;
   2760 	struct sadb_lifetime *lt;
   2761 
   2762 	/* XXX: Why do we lock ? */
   2763 	s = splsoftnet();	/*called from softclock()*/
   2764 
   2765 	/* sanity check */
   2766 	if (sp == NULL)
   2767 		panic("key_spdexpire: NULL pointer is passed");
   2768 
   2769 	/* set msg header */
   2770 	m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
   2771 	if (!m) {
   2772 		error = ENOBUFS;
   2773 		goto fail;
   2774 	}
   2775 	result = m;
   2776 
   2777 	/* create lifetime extension (current and hard) */
   2778 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
   2779 	m = key_alloc_mbuf(len);
   2780 	if (!m || m->m_next) {	/*XXX*/
   2781 		if (m)
   2782 			m_freem(m);
   2783 		error = ENOBUFS;
   2784 		goto fail;
   2785 	}
   2786 	memset(mtod(m, void *), 0, len);
   2787 	lt = mtod(m, struct sadb_lifetime *);
   2788 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   2789 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
   2790 	lt->sadb_lifetime_allocations = 0;
   2791 	lt->sadb_lifetime_bytes = 0;
   2792 	lt->sadb_lifetime_addtime = sp->created + time_second - time_uptime;
   2793 	lt->sadb_lifetime_usetime = sp->lastused + time_second - time_uptime;
   2794 	lt = (struct sadb_lifetime *)(mtod(m, char *) + len / 2);
   2795 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   2796 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
   2797 	lt->sadb_lifetime_allocations = 0;
   2798 	lt->sadb_lifetime_bytes = 0;
   2799 	lt->sadb_lifetime_addtime = sp->lifetime;
   2800 	lt->sadb_lifetime_usetime = sp->validtime;
   2801 	m_cat(result, m);
   2802 
   2803 	/* set sadb_address for source */
   2804 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   2805 	    &sp->spidx.src.sa,
   2806 	    sp->spidx.prefs, sp->spidx.ul_proto);
   2807 	if (!m) {
   2808 		error = ENOBUFS;
   2809 		goto fail;
   2810 	}
   2811 	m_cat(result, m);
   2812 
   2813 	/* set sadb_address for destination */
   2814 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   2815 	    &sp->spidx.dst.sa,
   2816 	    sp->spidx.prefd, sp->spidx.ul_proto);
   2817 	if (!m) {
   2818 		error = ENOBUFS;
   2819 		goto fail;
   2820 	}
   2821 	m_cat(result, m);
   2822 
   2823 	/* set secpolicy */
   2824 	m = key_sp2msg(sp);
   2825 	if (!m) {
   2826 		error = ENOBUFS;
   2827 		goto fail;
   2828 	}
   2829 	m_cat(result, m);
   2830 
   2831 	if ((result->m_flags & M_PKTHDR) == 0) {
   2832 		error = EINVAL;
   2833 		goto fail;
   2834 	}
   2835 
   2836 	if (result->m_len < sizeof(struct sadb_msg)) {
   2837 		result = m_pullup(result, sizeof(struct sadb_msg));
   2838 		if (result == NULL) {
   2839 			error = ENOBUFS;
   2840 			goto fail;
   2841 		}
   2842 	}
   2843 
   2844 	result->m_pkthdr.len = 0;
   2845 	for (m = result; m; m = m->m_next)
   2846 		result->m_pkthdr.len += m->m_len;
   2847 
   2848 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   2849 	    PFKEY_UNIT64(result->m_pkthdr.len);
   2850 
   2851 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   2852 
   2853  fail:
   2854 	if (result)
   2855 		m_freem(result);
   2856 	splx(s);
   2857 	return error;
   2858 }
   2859 
   2860 /* %%% SAD management */
   2861 /*
   2862  * allocating a memory for new SA head, and copy from the values of mhp.
   2863  * OUT:	NULL	: failure due to the lack of memory.
   2864  *	others	: pointer to new SA head.
   2865  */
   2866 static struct secashead *
   2867 key_newsah(const struct secasindex *saidx)
   2868 {
   2869 	struct secashead *newsah;
   2870 
   2871 	IPSEC_ASSERT(saidx != NULL, ("key_newsaidx: null saidx"));
   2872 
   2873 	newsah = (struct secashead *)
   2874 		malloc(sizeof(struct secashead), M_SECA, M_NOWAIT|M_ZERO);
   2875 	if (newsah != NULL) {
   2876 		int i;
   2877 		for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
   2878 			LIST_INIT(&newsah->savtree[i]);
   2879 		newsah->saidx = *saidx;
   2880 
   2881 		/* add to saidxtree */
   2882 		newsah->state = SADB_SASTATE_MATURE;
   2883 		LIST_INSERT_HEAD(&sahtree, newsah, chain);
   2884 	}
   2885 	return(newsah);
   2886 }
   2887 
   2888 /*
   2889  * delete SA index and all SA registerd.
   2890  */
   2891 static void
   2892 key_delsah(struct secashead *sah)
   2893 {
   2894 	struct secasvar *sav, *nextsav;
   2895 	u_int stateidx, state;
   2896 	int s;
   2897 	int zombie = 0;
   2898 
   2899 	/* sanity check */
   2900 	if (sah == NULL)
   2901 		panic("key_delsah: NULL pointer is passed");
   2902 
   2903 	s = splsoftnet();	/*called from softclock()*/
   2904 
   2905 	/* searching all SA registerd in the secindex. */
   2906 	for (stateidx = 0;
   2907 	     stateidx < _ARRAYLEN(saorder_state_any);
   2908 	     stateidx++) {
   2909 
   2910 		state = saorder_state_any[stateidx];
   2911 		for (sav = (struct secasvar *)LIST_FIRST(&sah->savtree[state]);
   2912 		     sav != NULL;
   2913 		     sav = nextsav) {
   2914 
   2915 			nextsav = LIST_NEXT(sav, chain);
   2916 
   2917 			if (sav->refcnt == 0) {
   2918 				/* sanity check */
   2919 				KEY_CHKSASTATE(state, sav->state, "key_delsah");
   2920 				KEY_FREESAV(&sav);
   2921 			} else {
   2922 				/* give up to delete this sa */
   2923 				zombie++;
   2924 			}
   2925 		}
   2926 	}
   2927 
   2928 	/* don't delete sah only if there are savs. */
   2929 	if (zombie) {
   2930 		splx(s);
   2931 		return;
   2932 	}
   2933 
   2934 	rtcache_free(&sah->sa_route);
   2935 
   2936 	/* remove from tree of SA index */
   2937 	if (__LIST_CHAINED(sah))
   2938 		LIST_REMOVE(sah, chain);
   2939 
   2940 	KFREE(sah);
   2941 
   2942 	splx(s);
   2943 	return;
   2944 }
   2945 
   2946 /*
   2947  * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
   2948  * and copy the values of mhp into new buffer.
   2949  * When SAD message type is GETSPI:
   2950  *	to set sequence number from acq_seq++,
   2951  *	to set zero to SPI.
   2952  *	not to call key_setsava().
   2953  * OUT:	NULL	: fail
   2954  *	others	: pointer to new secasvar.
   2955  *
   2956  * does not modify mbuf.  does not free mbuf on error.
   2957  */
   2958 static struct secasvar *
   2959 key_newsav(struct mbuf *m, const struct sadb_msghdr *mhp,
   2960 	   struct secashead *sah, int *errp,
   2961 	   const char* where, int tag)
   2962 {
   2963 	struct secasvar *newsav;
   2964 	const struct sadb_sa *xsa;
   2965 
   2966 	/* sanity check */
   2967 	if (m == NULL || mhp == NULL || mhp->msg == NULL || sah == NULL)
   2968 		panic("key_newsa: NULL pointer is passed");
   2969 
   2970 	KMALLOC(newsav, struct secasvar *, sizeof(struct secasvar));
   2971 	if (newsav == NULL) {
   2972 		ipseclog((LOG_DEBUG, "key_newsa: No more memory.\n"));
   2973 		*errp = ENOBUFS;
   2974 		goto done;
   2975 	}
   2976 	memset(newsav, 0, sizeof(struct secasvar));
   2977 
   2978 	switch (mhp->msg->sadb_msg_type) {
   2979 	case SADB_GETSPI:
   2980 		newsav->spi = 0;
   2981 
   2982 #ifdef IPSEC_DOSEQCHECK
   2983 		/* sync sequence number */
   2984 		if (mhp->msg->sadb_msg_seq == 0)
   2985 			newsav->seq =
   2986 				(acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
   2987 		else
   2988 #endif
   2989 			newsav->seq = mhp->msg->sadb_msg_seq;
   2990 		break;
   2991 
   2992 	case SADB_ADD:
   2993 		/* sanity check */
   2994 		if (mhp->ext[SADB_EXT_SA] == NULL) {
   2995 			KFREE(newsav), newsav = NULL;
   2996 			ipseclog((LOG_DEBUG, "key_newsa: invalid message is passed.\n"));
   2997 			*errp = EINVAL;
   2998 			goto done;
   2999 		}
   3000 		xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   3001 		newsav->spi = xsa->sadb_sa_spi;
   3002 		newsav->seq = mhp->msg->sadb_msg_seq;
   3003 		break;
   3004 	default:
   3005 		KFREE(newsav), newsav = NULL;
   3006 		*errp = EINVAL;
   3007 		goto done;
   3008 	}
   3009 
   3010 	/* copy sav values */
   3011 	if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
   3012 		*errp = key_setsaval(newsav, m, mhp);
   3013 		if (*errp) {
   3014 			KFREE(newsav), newsav = NULL;
   3015 			goto done;
   3016 		}
   3017 	}
   3018 
   3019 	/* reset created */
   3020 	newsav->created = time_uptime;
   3021 	newsav->pid = mhp->msg->sadb_msg_pid;
   3022 
   3023 	/* add to satree */
   3024 	newsav->sah = sah;
   3025 	newsav->refcnt = 1;
   3026 	newsav->state = SADB_SASTATE_LARVAL;
   3027 	LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
   3028 			secasvar, chain);
   3029 done:
   3030 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
   3031 		printf("DP %s from %s:%u return SP:%p\n", __func__,
   3032 		    where, tag, newsav));
   3033 
   3034 	return newsav;
   3035 }
   3036 
   3037 /*
   3038  * free() SA variable entry.
   3039  */
   3040 static void
   3041 key_delsav(struct secasvar *sav)
   3042 {
   3043 	IPSEC_ASSERT(sav != NULL, ("key_delsav: null sav"));
   3044 	IPSEC_ASSERT(sav->refcnt == 0,
   3045 		("key_delsav: reference count %u > 0", sav->refcnt));
   3046 
   3047 	/* remove from SA header */
   3048 	if (__LIST_CHAINED(sav))
   3049 		LIST_REMOVE(sav, chain);
   3050 
   3051 	/*
   3052 	 * Cleanup xform state.  Note that zeroize'ing causes the
   3053 	 * keys to be cleared; otherwise we must do it ourself.
   3054 	 */
   3055 	if (sav->tdb_xform != NULL) {
   3056 		sav->tdb_xform->xf_zeroize(sav);
   3057 		sav->tdb_xform = NULL;
   3058 	} else {
   3059 		if (sav->key_auth != NULL)
   3060 			explicit_memset(_KEYBUF(sav->key_auth), 0,
   3061 			    _KEYLEN(sav->key_auth));
   3062 		if (sav->key_enc != NULL)
   3063 			explicit_memset(_KEYBUF(sav->key_enc), 0,
   3064 			    _KEYLEN(sav->key_enc));
   3065 	}
   3066 	if (sav->key_auth != NULL) {
   3067 		KFREE(sav->key_auth);
   3068 		sav->key_auth = NULL;
   3069 	}
   3070 	if (sav->key_enc != NULL) {
   3071 		KFREE(sav->key_enc);
   3072 		sav->key_enc = NULL;
   3073 	}
   3074 	if (sav->replay != NULL) {
   3075 		KFREE(sav->replay);
   3076 		sav->replay = NULL;
   3077 	}
   3078 	if (sav->lft_c != NULL) {
   3079 		KFREE(sav->lft_c);
   3080 		sav->lft_c = NULL;
   3081 	}
   3082 	if (sav->lft_h != NULL) {
   3083 		KFREE(sav->lft_h);
   3084 		sav->lft_h = NULL;
   3085 	}
   3086 	if (sav->lft_s != NULL) {
   3087 		KFREE(sav->lft_s);
   3088 		sav->lft_s = NULL;
   3089 	}
   3090 
   3091 	KFREE(sav);
   3092 
   3093 	return;
   3094 }
   3095 
   3096 /*
   3097  * search SAD.
   3098  * OUT:
   3099  *	NULL	: not found
   3100  *	others	: found, pointer to a SA.
   3101  */
   3102 static struct secashead *
   3103 key_getsah(const struct secasindex *saidx)
   3104 {
   3105 	struct secashead *sah;
   3106 
   3107 	LIST_FOREACH(sah, &sahtree, chain) {
   3108 		if (sah->state == SADB_SASTATE_DEAD)
   3109 			continue;
   3110 		if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
   3111 			return sah;
   3112 	}
   3113 
   3114 	return NULL;
   3115 }
   3116 
   3117 /*
   3118  * check not to be duplicated SPI.
   3119  * NOTE: this function is too slow due to searching all SAD.
   3120  * OUT:
   3121  *	NULL	: not found
   3122  *	others	: found, pointer to a SA.
   3123  */
   3124 static struct secasvar *
   3125 key_checkspidup(const struct secasindex *saidx, u_int32_t spi)
   3126 {
   3127 	struct secashead *sah;
   3128 	struct secasvar *sav;
   3129 
   3130 	/* check address family */
   3131 	if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
   3132 		ipseclog((LOG_DEBUG, "key_checkspidup: address family mismatched.\n"));
   3133 		return NULL;
   3134 	}
   3135 
   3136 	/* check all SAD */
   3137 	LIST_FOREACH(sah, &sahtree, chain) {
   3138 		if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
   3139 			continue;
   3140 		sav = key_getsavbyspi(sah, spi);
   3141 		if (sav != NULL)
   3142 			return sav;
   3143 	}
   3144 
   3145 	return NULL;
   3146 }
   3147 
   3148 /*
   3149  * search SAD litmited alive SA, protocol, SPI.
   3150  * OUT:
   3151  *	NULL	: not found
   3152  *	others	: found, pointer to a SA.
   3153  */
   3154 static struct secasvar *
   3155 key_getsavbyspi(struct secashead *sah, u_int32_t spi)
   3156 {
   3157 	struct secasvar *sav;
   3158 	u_int stateidx, state;
   3159 
   3160 	/* search all status */
   3161 	for (stateidx = 0;
   3162 	     stateidx < _ARRAYLEN(saorder_state_alive);
   3163 	     stateidx++) {
   3164 
   3165 		state = saorder_state_alive[stateidx];
   3166 		LIST_FOREACH(sav, &sah->savtree[state], chain) {
   3167 
   3168 			/* sanity check */
   3169 			if (sav->state != state) {
   3170 				ipseclog((LOG_DEBUG, "key_getsavbyspi: "
   3171 				    "invalid sav->state (queue: %d SA: %d)\n",
   3172 				    state, sav->state));
   3173 				continue;
   3174 			}
   3175 
   3176 			if (sav->spi == spi)
   3177 				return sav;
   3178 		}
   3179 	}
   3180 
   3181 	return NULL;
   3182 }
   3183 
   3184 /*
   3185  * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
   3186  * You must update these if need.
   3187  * OUT:	0:	success.
   3188  *	!0:	failure.
   3189  *
   3190  * does not modify mbuf.  does not free mbuf on error.
   3191  */
   3192 static int
   3193 key_setsaval(struct secasvar *sav, struct mbuf *m,
   3194 	     const struct sadb_msghdr *mhp)
   3195 {
   3196 	int error = 0;
   3197 
   3198 	/* sanity check */
   3199 	if (m == NULL || mhp == NULL || mhp->msg == NULL)
   3200 		panic("key_setsaval: NULL pointer is passed");
   3201 
   3202 	/* initialization */
   3203 	sav->replay = NULL;
   3204 	sav->key_auth = NULL;
   3205 	sav->key_enc = NULL;
   3206 	sav->lft_c = NULL;
   3207 	sav->lft_h = NULL;
   3208 	sav->lft_s = NULL;
   3209 	sav->tdb_xform = NULL;		/* transform */
   3210 	sav->tdb_encalgxform = NULL;	/* encoding algorithm */
   3211 	sav->tdb_authalgxform = NULL;	/* authentication algorithm */
   3212 	sav->tdb_compalgxform = NULL;	/* compression algorithm */
   3213 	sav->natt_type = 0;
   3214 	sav->esp_frag = 0;
   3215 
   3216 	/* SA */
   3217 	if (mhp->ext[SADB_EXT_SA] != NULL) {
   3218 		const struct sadb_sa *sa0;
   3219 
   3220 		sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   3221 		if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
   3222 			error = EINVAL;
   3223 			goto fail;
   3224 		}
   3225 
   3226 		sav->alg_auth = sa0->sadb_sa_auth;
   3227 		sav->alg_enc = sa0->sadb_sa_encrypt;
   3228 		sav->flags = sa0->sadb_sa_flags;
   3229 
   3230 		/* replay window */
   3231 		if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
   3232 			sav->replay = (struct secreplay *)
   3233 				malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_SECA, M_NOWAIT|M_ZERO);
   3234 			if (sav->replay == NULL) {
   3235 				ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
   3236 				error = ENOBUFS;
   3237 				goto fail;
   3238 			}
   3239 			if (sa0->sadb_sa_replay != 0)
   3240 				sav->replay->bitmap = (char*)(sav->replay+1);
   3241 			sav->replay->wsize = sa0->sadb_sa_replay;
   3242 		}
   3243 	}
   3244 
   3245 	/* Authentication keys */
   3246 	if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
   3247 		const struct sadb_key *key0;
   3248 		int len;
   3249 
   3250 		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
   3251 		len = mhp->extlen[SADB_EXT_KEY_AUTH];
   3252 
   3253 		error = 0;
   3254 		if (len < sizeof(*key0)) {
   3255 			error = EINVAL;
   3256 			goto fail;
   3257 		}
   3258 		switch (mhp->msg->sadb_msg_satype) {
   3259 		case SADB_SATYPE_AH:
   3260 		case SADB_SATYPE_ESP:
   3261 		case SADB_X_SATYPE_TCPSIGNATURE:
   3262 			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
   3263 			    sav->alg_auth != SADB_X_AALG_NULL)
   3264 				error = EINVAL;
   3265 			break;
   3266 		case SADB_X_SATYPE_IPCOMP:
   3267 		default:
   3268 			error = EINVAL;
   3269 			break;
   3270 		}
   3271 		if (error) {
   3272 			ipseclog((LOG_DEBUG, "key_setsaval: invalid key_auth values.\n"));
   3273 			goto fail;
   3274 		}
   3275 
   3276 		sav->key_auth = (struct sadb_key *)key_newbuf(key0, len);
   3277 		if (sav->key_auth == NULL) {
   3278 			ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
   3279 			error = ENOBUFS;
   3280 			goto fail;
   3281 		}
   3282 	}
   3283 
   3284 	/* Encryption key */
   3285 	if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
   3286 		const struct sadb_key *key0;
   3287 		int len;
   3288 
   3289 		key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
   3290 		len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
   3291 
   3292 		error = 0;
   3293 		if (len < sizeof(*key0)) {
   3294 			error = EINVAL;
   3295 			goto fail;
   3296 		}
   3297 		switch (mhp->msg->sadb_msg_satype) {
   3298 		case SADB_SATYPE_ESP:
   3299 			if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
   3300 			    sav->alg_enc != SADB_EALG_NULL) {
   3301 				error = EINVAL;
   3302 				break;
   3303 			}
   3304 			sav->key_enc = (struct sadb_key *)key_newbuf(key0, len);
   3305 			if (sav->key_enc == NULL) {
   3306 				ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
   3307 				error = ENOBUFS;
   3308 				goto fail;
   3309 			}
   3310 			break;
   3311 		case SADB_X_SATYPE_IPCOMP:
   3312 			if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
   3313 				error = EINVAL;
   3314 			sav->key_enc = NULL;	/*just in case*/
   3315 			break;
   3316 		case SADB_SATYPE_AH:
   3317 		case SADB_X_SATYPE_TCPSIGNATURE:
   3318 		default:
   3319 			error = EINVAL;
   3320 			break;
   3321 		}
   3322 		if (error) {
   3323 			ipseclog((LOG_DEBUG, "key_setsatval: invalid key_enc value.\n"));
   3324 			goto fail;
   3325 		}
   3326 	}
   3327 
   3328 	/* set iv */
   3329 	sav->ivlen = 0;
   3330 
   3331 	switch (mhp->msg->sadb_msg_satype) {
   3332 	case SADB_SATYPE_AH:
   3333 		error = xform_init(sav, XF_AH);
   3334 		break;
   3335 	case SADB_SATYPE_ESP:
   3336 		error = xform_init(sav, XF_ESP);
   3337 		break;
   3338 	case SADB_X_SATYPE_IPCOMP:
   3339 		error = xform_init(sav, XF_IPCOMP);
   3340 		break;
   3341 	case SADB_X_SATYPE_TCPSIGNATURE:
   3342 		error = xform_init(sav, XF_TCPSIGNATURE);
   3343 		break;
   3344 	}
   3345 	if (error) {
   3346 		ipseclog((LOG_DEBUG,
   3347 			"key_setsaval: unable to initialize SA type %u.\n",
   3348 		        mhp->msg->sadb_msg_satype));
   3349 		goto fail;
   3350 	}
   3351 
   3352 	/* reset created */
   3353 	sav->created = time_uptime;
   3354 
   3355 	/* make lifetime for CURRENT */
   3356 	KMALLOC(sav->lft_c, struct sadb_lifetime *,
   3357 	    sizeof(struct sadb_lifetime));
   3358 	if (sav->lft_c == NULL) {
   3359 		ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
   3360 		error = ENOBUFS;
   3361 		goto fail;
   3362 	}
   3363 
   3364 	sav->lft_c->sadb_lifetime_len =
   3365 	    PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   3366 	sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
   3367 	sav->lft_c->sadb_lifetime_allocations = 0;
   3368 	sav->lft_c->sadb_lifetime_bytes = 0;
   3369 	sav->lft_c->sadb_lifetime_addtime = time_uptime;
   3370 	sav->lft_c->sadb_lifetime_usetime = 0;
   3371 
   3372 	/* lifetimes for HARD and SOFT */
   3373     {
   3374 	const struct sadb_lifetime *lft0;
   3375 
   3376 	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
   3377 	if (lft0 != NULL) {
   3378 		if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
   3379 			error = EINVAL;
   3380 			goto fail;
   3381 		}
   3382 		sav->lft_h = (struct sadb_lifetime *)key_newbuf(lft0,
   3383 		    sizeof(*lft0));
   3384 		if (sav->lft_h == NULL) {
   3385 			ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
   3386 			error = ENOBUFS;
   3387 			goto fail;
   3388 		}
   3389 		/* to be initialize ? */
   3390 	}
   3391 
   3392 	lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
   3393 	if (lft0 != NULL) {
   3394 		if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
   3395 			error = EINVAL;
   3396 			goto fail;
   3397 		}
   3398 		sav->lft_s = (struct sadb_lifetime *)key_newbuf(lft0,
   3399 		    sizeof(*lft0));
   3400 		if (sav->lft_s == NULL) {
   3401 			ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
   3402 			error = ENOBUFS;
   3403 			goto fail;
   3404 		}
   3405 		/* to be initialize ? */
   3406 	}
   3407     }
   3408 
   3409 	return 0;
   3410 
   3411  fail:
   3412 	/* initialization */
   3413 	if (sav->replay != NULL) {
   3414 		KFREE(sav->replay);
   3415 		sav->replay = NULL;
   3416 	}
   3417 	if (sav->key_auth != NULL) {
   3418 		KFREE(sav->key_auth);
   3419 		sav->key_auth = NULL;
   3420 	}
   3421 	if (sav->key_enc != NULL) {
   3422 		KFREE(sav->key_enc);
   3423 		sav->key_enc = NULL;
   3424 	}
   3425 	if (sav->lft_c != NULL) {
   3426 		KFREE(sav->lft_c);
   3427 		sav->lft_c = NULL;
   3428 	}
   3429 	if (sav->lft_h != NULL) {
   3430 		KFREE(sav->lft_h);
   3431 		sav->lft_h = NULL;
   3432 	}
   3433 	if (sav->lft_s != NULL) {
   3434 		KFREE(sav->lft_s);
   3435 		sav->lft_s = NULL;
   3436 	}
   3437 
   3438 	return error;
   3439 }
   3440 
   3441 /*
   3442  * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
   3443  * OUT:	0:	valid
   3444  *	other:	errno
   3445  */
   3446 static int
   3447 key_mature(struct secasvar *sav)
   3448 {
   3449 	int error;
   3450 
   3451 	/* check SPI value */
   3452 	switch (sav->sah->saidx.proto) {
   3453 	case IPPROTO_ESP:
   3454 	case IPPROTO_AH:
   3455 		if (ntohl(sav->spi) <= 255) {
   3456 			ipseclog((LOG_DEBUG,
   3457 			    "key_mature: illegal range of SPI %u.\n",
   3458 			    (u_int32_t)ntohl(sav->spi)));
   3459 			return EINVAL;
   3460 		}
   3461 		break;
   3462 	}
   3463 
   3464 	/* check satype */
   3465 	switch (sav->sah->saidx.proto) {
   3466 	case IPPROTO_ESP:
   3467 		/* check flags */
   3468 		if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
   3469 		    (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
   3470 			ipseclog((LOG_DEBUG, "key_mature: "
   3471 			    "invalid flag (derived) given to old-esp.\n"));
   3472 			return EINVAL;
   3473 		}
   3474 		error = xform_init(sav, XF_ESP);
   3475 		break;
   3476 	case IPPROTO_AH:
   3477 		/* check flags */
   3478 		if (sav->flags & SADB_X_EXT_DERIV) {
   3479 			ipseclog((LOG_DEBUG, "key_mature: "
   3480 			    "invalid flag (derived) given to AH SA.\n"));
   3481 			return EINVAL;
   3482 		}
   3483 		if (sav->alg_enc != SADB_EALG_NONE) {
   3484 			ipseclog((LOG_DEBUG, "key_mature: "
   3485 			    "protocol and algorithm mismated.\n"));
   3486 			return(EINVAL);
   3487 		}
   3488 		error = xform_init(sav, XF_AH);
   3489 		break;
   3490 	case IPPROTO_IPCOMP:
   3491 		if (sav->alg_auth != SADB_AALG_NONE) {
   3492 			ipseclog((LOG_DEBUG, "key_mature: "
   3493 				"protocol and algorithm mismated.\n"));
   3494 			return(EINVAL);
   3495 		}
   3496 		if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
   3497 		 && ntohl(sav->spi) >= 0x10000) {
   3498 			ipseclog((LOG_DEBUG, "key_mature: invalid cpi for IPComp.\n"));
   3499 			return(EINVAL);
   3500 		}
   3501 		error = xform_init(sav, XF_IPCOMP);
   3502 		break;
   3503 	case IPPROTO_TCP:
   3504 		if (sav->alg_enc != SADB_EALG_NONE) {
   3505 			ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
   3506 				"mismated.\n", __func__));
   3507 			return(EINVAL);
   3508 		}
   3509 		error = xform_init(sav, XF_TCPSIGNATURE);
   3510 		break;
   3511 	default:
   3512 		ipseclog((LOG_DEBUG, "key_mature: Invalid satype.\n"));
   3513 		error = EPROTONOSUPPORT;
   3514 		break;
   3515 	}
   3516 	if (error == 0)
   3517 		key_sa_chgstate(sav, SADB_SASTATE_MATURE);
   3518 	return (error);
   3519 }
   3520 
   3521 /*
   3522  * subroutine for SADB_GET and SADB_DUMP.
   3523  */
   3524 static struct mbuf *
   3525 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
   3526 	      u_int32_t seq, u_int32_t pid)
   3527 {
   3528 	struct mbuf *result = NULL, *tres = NULL, *m;
   3529 	int l = 0;
   3530 	int i;
   3531 	void *p;
   3532 	struct sadb_lifetime lt;
   3533 	int dumporder[] = {
   3534 		SADB_EXT_SA, SADB_X_EXT_SA2,
   3535 		SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
   3536 		SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
   3537 		SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
   3538 		SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
   3539 		SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
   3540 		SADB_X_EXT_NAT_T_TYPE,
   3541 		SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
   3542 		SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
   3543 		SADB_X_EXT_NAT_T_FRAG,
   3544 
   3545 	};
   3546 
   3547 	m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
   3548 	if (m == NULL)
   3549 		goto fail;
   3550 	result = m;
   3551 
   3552 	for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
   3553 		m = NULL;
   3554 		p = NULL;
   3555 		switch (dumporder[i]) {
   3556 		case SADB_EXT_SA:
   3557 			m = key_setsadbsa(sav);
   3558 			break;
   3559 
   3560 		case SADB_X_EXT_SA2:
   3561 			m = key_setsadbxsa2(sav->sah->saidx.mode,
   3562 					sav->replay ? sav->replay->count : 0,
   3563 					sav->sah->saidx.reqid);
   3564 			break;
   3565 
   3566 		case SADB_EXT_ADDRESS_SRC:
   3567 			m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   3568 			    &sav->sah->saidx.src.sa,
   3569 			    FULLMASK, IPSEC_ULPROTO_ANY);
   3570 			break;
   3571 
   3572 		case SADB_EXT_ADDRESS_DST:
   3573 			m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   3574 			    &sav->sah->saidx.dst.sa,
   3575 			    FULLMASK, IPSEC_ULPROTO_ANY);
   3576 			break;
   3577 
   3578 		case SADB_EXT_KEY_AUTH:
   3579 			if (!sav->key_auth)
   3580 				continue;
   3581 			l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
   3582 			p = sav->key_auth;
   3583 			break;
   3584 
   3585 		case SADB_EXT_KEY_ENCRYPT:
   3586 			if (!sav->key_enc)
   3587 				continue;
   3588 			l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
   3589 			p = sav->key_enc;
   3590 			break;
   3591 
   3592 		case SADB_EXT_LIFETIME_CURRENT:
   3593 			if (!sav->lft_c)
   3594 				continue;
   3595 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
   3596 			memcpy(&lt, sav->lft_c, sizeof(struct sadb_lifetime));
   3597 			lt.sadb_lifetime_addtime += time_second - time_uptime;
   3598 			lt.sadb_lifetime_usetime += time_second - time_uptime;
   3599 			p = &lt;
   3600 			break;
   3601 
   3602 		case SADB_EXT_LIFETIME_HARD:
   3603 			if (!sav->lft_h)
   3604 				continue;
   3605 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
   3606 			p = sav->lft_h;
   3607 			break;
   3608 
   3609 		case SADB_EXT_LIFETIME_SOFT:
   3610 			if (!sav->lft_s)
   3611 				continue;
   3612 			l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
   3613 			p = sav->lft_s;
   3614 			break;
   3615 
   3616 		case SADB_X_EXT_NAT_T_TYPE:
   3617 			m = key_setsadbxtype(sav->natt_type);
   3618 			break;
   3619 
   3620 		case SADB_X_EXT_NAT_T_DPORT:
   3621 			if (sav->natt_type == 0)
   3622 				continue;
   3623 			m = key_setsadbxport(
   3624 				key_portfromsaddr(&sav->sah->saidx.dst),
   3625 				SADB_X_EXT_NAT_T_DPORT);
   3626 			break;
   3627 
   3628 		case SADB_X_EXT_NAT_T_SPORT:
   3629 			if (sav->natt_type == 0)
   3630 				continue;
   3631 			m = key_setsadbxport(
   3632 				key_portfromsaddr(&sav->sah->saidx.src),
   3633 				SADB_X_EXT_NAT_T_SPORT);
   3634 			break;
   3635 
   3636 		case SADB_X_EXT_NAT_T_FRAG:
   3637 			/* don't send frag info if not set */
   3638 			if (sav->natt_type == 0 || sav->esp_frag == IP_MAXPACKET)
   3639 				continue;
   3640 			m = key_setsadbxfrag(sav->esp_frag);
   3641 			break;
   3642 
   3643 		case SADB_X_EXT_NAT_T_OAI:
   3644 		case SADB_X_EXT_NAT_T_OAR:
   3645 			continue;
   3646 
   3647 		case SADB_EXT_ADDRESS_PROXY:
   3648 		case SADB_EXT_IDENTITY_SRC:
   3649 		case SADB_EXT_IDENTITY_DST:
   3650 			/* XXX: should we brought from SPD ? */
   3651 		case SADB_EXT_SENSITIVITY:
   3652 		default:
   3653 			continue;
   3654 		}
   3655 
   3656 		KASSERT(!(m && p));
   3657 		if (!m && !p)
   3658 			goto fail;
   3659 		if (p && tres) {
   3660 			M_PREPEND(tres, l, M_DONTWAIT);
   3661 			if (!tres)
   3662 				goto fail;
   3663 			memcpy(mtod(tres, void *), p, l);
   3664 			continue;
   3665 		}
   3666 		if (p) {
   3667 			m = key_alloc_mbuf(l);
   3668 			if (!m)
   3669 				goto fail;
   3670 			m_copyback(m, 0, l, p);
   3671 		}
   3672 
   3673 		if (tres)
   3674 			m_cat(m, tres);
   3675 		tres = m;
   3676 	}
   3677 
   3678 	m_cat(result, tres);
   3679 	tres = NULL; /* avoid free on error below */
   3680 
   3681 	if (result->m_len < sizeof(struct sadb_msg)) {
   3682 		result = m_pullup(result, sizeof(struct sadb_msg));
   3683 		if (result == NULL)
   3684 			goto fail;
   3685 	}
   3686 
   3687 	result->m_pkthdr.len = 0;
   3688 	for (m = result; m; m = m->m_next)
   3689 		result->m_pkthdr.len += m->m_len;
   3690 
   3691 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   3692 	    PFKEY_UNIT64(result->m_pkthdr.len);
   3693 
   3694 	return result;
   3695 
   3696 fail:
   3697 	m_freem(result);
   3698 	m_freem(tres);
   3699 	return NULL;
   3700 }
   3701 
   3702 
   3703 /*
   3704  * set a type in sadb_x_nat_t_type
   3705  */
   3706 static struct mbuf *
   3707 key_setsadbxtype(u_int16_t type)
   3708 {
   3709 	struct mbuf *m;
   3710 	size_t len;
   3711 	struct sadb_x_nat_t_type *p;
   3712 
   3713 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
   3714 
   3715 	m = key_alloc_mbuf(len);
   3716 	if (!m || m->m_next) {	/*XXX*/
   3717 		if (m)
   3718 			m_freem(m);
   3719 		return NULL;
   3720 	}
   3721 
   3722 	p = mtod(m, struct sadb_x_nat_t_type *);
   3723 
   3724 	memset(p, 0, len);
   3725 	p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
   3726 	p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
   3727 	p->sadb_x_nat_t_type_type = type;
   3728 
   3729 	return m;
   3730 }
   3731 /*
   3732  * set a port in sadb_x_nat_t_port. port is in network order
   3733  */
   3734 static struct mbuf *
   3735 key_setsadbxport(u_int16_t port, u_int16_t type)
   3736 {
   3737 	struct mbuf *m;
   3738 	size_t len;
   3739 	struct sadb_x_nat_t_port *p;
   3740 
   3741 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
   3742 
   3743 	m = key_alloc_mbuf(len);
   3744 	if (!m || m->m_next) {	/*XXX*/
   3745 		if (m)
   3746 			m_freem(m);
   3747 		return NULL;
   3748 	}
   3749 
   3750 	p = mtod(m, struct sadb_x_nat_t_port *);
   3751 
   3752 	memset(p, 0, len);
   3753 	p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
   3754 	p->sadb_x_nat_t_port_exttype = type;
   3755 	p->sadb_x_nat_t_port_port = port;
   3756 
   3757 	return m;
   3758 }
   3759 
   3760 /*
   3761  * set fragmentation info in sadb_x_nat_t_frag
   3762  */
   3763 static struct mbuf *
   3764 key_setsadbxfrag(u_int16_t flen)
   3765 {
   3766 	struct mbuf *m;
   3767 	size_t len;
   3768 	struct sadb_x_nat_t_frag *p;
   3769 
   3770 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_frag));
   3771 
   3772 	m = key_alloc_mbuf(len);
   3773 	if (!m || m->m_next) {  /*XXX*/
   3774 		if (m)
   3775 			m_freem(m);
   3776 		return NULL;
   3777 	}
   3778 
   3779 	p = mtod(m, struct sadb_x_nat_t_frag *);
   3780 
   3781 	memset(p, 0, len);
   3782 	p->sadb_x_nat_t_frag_len = PFKEY_UNIT64(len);
   3783 	p->sadb_x_nat_t_frag_exttype = SADB_X_EXT_NAT_T_FRAG;
   3784 	p->sadb_x_nat_t_frag_fraglen = flen;
   3785 
   3786 	return m;
   3787 }
   3788 
   3789 /*
   3790  * Get port from sockaddr, port is in network order
   3791  */
   3792 u_int16_t
   3793 key_portfromsaddr(const union sockaddr_union *saddr)
   3794 {
   3795 	u_int16_t port;
   3796 
   3797 	switch (saddr->sa.sa_family) {
   3798 	case AF_INET: {
   3799 		port = saddr->sin.sin_port;
   3800 		break;
   3801 	}
   3802 #ifdef INET6
   3803 	case AF_INET6: {
   3804 		port = saddr->sin6.sin6_port;
   3805 		break;
   3806 	}
   3807 #endif
   3808 	default:
   3809 		printf("%s: unexpected address family\n", __func__);
   3810 		port = 0;
   3811 		break;
   3812 	}
   3813 
   3814 	return port;
   3815 }
   3816 
   3817 
   3818 /*
   3819  * Set port is struct sockaddr. port is in network order
   3820  */
   3821 static void
   3822 key_porttosaddr(union sockaddr_union *saddr, u_int16_t port)
   3823 {
   3824 	switch (saddr->sa.sa_family) {
   3825 	case AF_INET: {
   3826 		saddr->sin.sin_port = port;
   3827 		break;
   3828 	}
   3829 #ifdef INET6
   3830 	case AF_INET6: {
   3831 		saddr->sin6.sin6_port = port;
   3832 		break;
   3833 	}
   3834 #endif
   3835 	default:
   3836 		printf("%s: unexpected address family %d\n", __func__,
   3837 		    saddr->sa.sa_family);
   3838 		break;
   3839 	}
   3840 
   3841 	return;
   3842 }
   3843 
   3844 /*
   3845  * Safety check sa_len
   3846  */
   3847 static int
   3848 key_checksalen(const union sockaddr_union *saddr)
   3849 {
   3850         switch (saddr->sa.sa_family) {
   3851         case AF_INET:
   3852                 if (saddr->sa.sa_len != sizeof(struct sockaddr_in))
   3853                         return -1;
   3854                 break;
   3855 #ifdef INET6
   3856         case AF_INET6:
   3857                 if (saddr->sa.sa_len != sizeof(struct sockaddr_in6))
   3858                         return -1;
   3859                 break;
   3860 #endif
   3861         default:
   3862                 printf("%s: unexpected sa_family %d\n", __func__,
   3863                     saddr->sa.sa_family);
   3864                 return -1;
   3865                 break;
   3866         }
   3867 	return 0;
   3868 }
   3869 
   3870 
   3871 /*
   3872  * set data into sadb_msg.
   3873  */
   3874 static struct mbuf *
   3875 key_setsadbmsg(u_int8_t type,  u_int16_t tlen, u_int8_t satype,
   3876 	       u_int32_t seq, pid_t pid, u_int16_t reserved)
   3877 {
   3878 	struct mbuf *m;
   3879 	struct sadb_msg *p;
   3880 	int len;
   3881 
   3882 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
   3883 	if (len > MCLBYTES)
   3884 		return NULL;
   3885 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   3886 	if (m && len > MHLEN) {
   3887 		MCLGET(m, M_DONTWAIT);
   3888 		if ((m->m_flags & M_EXT) == 0) {
   3889 			m_freem(m);
   3890 			m = NULL;
   3891 		}
   3892 	}
   3893 	if (!m)
   3894 		return NULL;
   3895 	m->m_pkthdr.len = m->m_len = len;
   3896 	m->m_next = NULL;
   3897 
   3898 	p = mtod(m, struct sadb_msg *);
   3899 
   3900 	memset(p, 0, len);
   3901 	p->sadb_msg_version = PF_KEY_V2;
   3902 	p->sadb_msg_type = type;
   3903 	p->sadb_msg_errno = 0;
   3904 	p->sadb_msg_satype = satype;
   3905 	p->sadb_msg_len = PFKEY_UNIT64(tlen);
   3906 	p->sadb_msg_reserved = reserved;
   3907 	p->sadb_msg_seq = seq;
   3908 	p->sadb_msg_pid = (u_int32_t)pid;
   3909 
   3910 	return m;
   3911 }
   3912 
   3913 /*
   3914  * copy secasvar data into sadb_address.
   3915  */
   3916 static struct mbuf *
   3917 key_setsadbsa(struct secasvar *sav)
   3918 {
   3919 	struct mbuf *m;
   3920 	struct sadb_sa *p;
   3921 	int len;
   3922 
   3923 	len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
   3924 	m = key_alloc_mbuf(len);
   3925 	if (!m || m->m_next) {	/*XXX*/
   3926 		if (m)
   3927 			m_freem(m);
   3928 		return NULL;
   3929 	}
   3930 
   3931 	p = mtod(m, struct sadb_sa *);
   3932 
   3933 	memset(p, 0, len);
   3934 	p->sadb_sa_len = PFKEY_UNIT64(len);
   3935 	p->sadb_sa_exttype = SADB_EXT_SA;
   3936 	p->sadb_sa_spi = sav->spi;
   3937 	p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
   3938 	p->sadb_sa_state = sav->state;
   3939 	p->sadb_sa_auth = sav->alg_auth;
   3940 	p->sadb_sa_encrypt = sav->alg_enc;
   3941 	p->sadb_sa_flags = sav->flags;
   3942 
   3943 	return m;
   3944 }
   3945 
   3946 /*
   3947  * set data into sadb_address.
   3948  */
   3949 static struct mbuf *
   3950 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
   3951 		u_int8_t prefixlen, u_int16_t ul_proto)
   3952 {
   3953 	struct mbuf *m;
   3954 	struct sadb_address *p;
   3955 	size_t len;
   3956 
   3957 	len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
   3958 	    PFKEY_ALIGN8(saddr->sa_len);
   3959 	m = key_alloc_mbuf(len);
   3960 	if (!m || m->m_next) {	/*XXX*/
   3961 		if (m)
   3962 			m_freem(m);
   3963 		return NULL;
   3964 	}
   3965 
   3966 	p = mtod(m, struct sadb_address *);
   3967 
   3968 	memset(p, 0, len);
   3969 	p->sadb_address_len = PFKEY_UNIT64(len);
   3970 	p->sadb_address_exttype = exttype;
   3971 	p->sadb_address_proto = ul_proto;
   3972 	if (prefixlen == FULLMASK) {
   3973 		switch (saddr->sa_family) {
   3974 		case AF_INET:
   3975 			prefixlen = sizeof(struct in_addr) << 3;
   3976 			break;
   3977 		case AF_INET6:
   3978 			prefixlen = sizeof(struct in6_addr) << 3;
   3979 			break;
   3980 		default:
   3981 			; /*XXX*/
   3982 		}
   3983 	}
   3984 	p->sadb_address_prefixlen = prefixlen;
   3985 	p->sadb_address_reserved = 0;
   3986 
   3987 	memcpy(mtod(m, char *) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
   3988 		   saddr, saddr->sa_len);
   3989 
   3990 	return m;
   3991 }
   3992 
   3993 #if 0
   3994 /*
   3995  * set data into sadb_ident.
   3996  */
   3997 static struct mbuf *
   3998 key_setsadbident(u_int16_t exttype, u_int16_t idtype,
   3999 		 void *string, int stringlen, u_int64_t id)
   4000 {
   4001 	struct mbuf *m;
   4002 	struct sadb_ident *p;
   4003 	size_t len;
   4004 
   4005 	len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
   4006 	m = key_alloc_mbuf(len);
   4007 	if (!m || m->m_next) {	/*XXX*/
   4008 		if (m)
   4009 			m_freem(m);
   4010 		return NULL;
   4011 	}
   4012 
   4013 	p = mtod(m, struct sadb_ident *);
   4014 
   4015 	memset(p, 0, len);
   4016 	p->sadb_ident_len = PFKEY_UNIT64(len);
   4017 	p->sadb_ident_exttype = exttype;
   4018 	p->sadb_ident_type = idtype;
   4019 	p->sadb_ident_reserved = 0;
   4020 	p->sadb_ident_id = id;
   4021 
   4022 	memcpy(mtod(m, void *) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
   4023 	   	   string, stringlen);
   4024 
   4025 	return m;
   4026 }
   4027 #endif
   4028 
   4029 /*
   4030  * set data into sadb_x_sa2.
   4031  */
   4032 static struct mbuf *
   4033 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int16_t reqid)
   4034 {
   4035 	struct mbuf *m;
   4036 	struct sadb_x_sa2 *p;
   4037 	size_t len;
   4038 
   4039 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
   4040 	m = key_alloc_mbuf(len);
   4041 	if (!m || m->m_next) {	/*XXX*/
   4042 		if (m)
   4043 			m_freem(m);
   4044 		return NULL;
   4045 	}
   4046 
   4047 	p = mtod(m, struct sadb_x_sa2 *);
   4048 
   4049 	memset(p, 0, len);
   4050 	p->sadb_x_sa2_len = PFKEY_UNIT64(len);
   4051 	p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
   4052 	p->sadb_x_sa2_mode = mode;
   4053 	p->sadb_x_sa2_reserved1 = 0;
   4054 	p->sadb_x_sa2_reserved2 = 0;
   4055 	p->sadb_x_sa2_sequence = seq;
   4056 	p->sadb_x_sa2_reqid = reqid;
   4057 
   4058 	return m;
   4059 }
   4060 
   4061 /*
   4062  * set data into sadb_x_policy
   4063  */
   4064 static struct mbuf *
   4065 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
   4066 {
   4067 	struct mbuf *m;
   4068 	struct sadb_x_policy *p;
   4069 	size_t len;
   4070 
   4071 	len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
   4072 	m = key_alloc_mbuf(len);
   4073 	if (!m || m->m_next) {	/*XXX*/
   4074 		if (m)
   4075 			m_freem(m);
   4076 		return NULL;
   4077 	}
   4078 
   4079 	p = mtod(m, struct sadb_x_policy *);
   4080 
   4081 	memset(p, 0, len);
   4082 	p->sadb_x_policy_len = PFKEY_UNIT64(len);
   4083 	p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
   4084 	p->sadb_x_policy_type = type;
   4085 	p->sadb_x_policy_dir = dir;
   4086 	p->sadb_x_policy_id = id;
   4087 
   4088 	return m;
   4089 }
   4090 
   4091 /* %%% utilities */
   4092 /*
   4093  * copy a buffer into the new buffer allocated.
   4094  */
   4095 static void *
   4096 key_newbuf(const void *src, u_int len)
   4097 {
   4098 	void *new;
   4099 
   4100 	KMALLOC(new, void *, len);
   4101 	if (new == NULL) {
   4102 		ipseclog((LOG_DEBUG, "key_newbuf: No more memory.\n"));
   4103 		return NULL;
   4104 	}
   4105 	memcpy(new, src, len);
   4106 
   4107 	return new;
   4108 }
   4109 
   4110 /* compare my own address
   4111  * OUT:	1: true, i.e. my address.
   4112  *	0: false
   4113  */
   4114 int
   4115 key_ismyaddr(const struct sockaddr *sa)
   4116 {
   4117 #ifdef INET
   4118 	const struct sockaddr_in *sin;
   4119 	const struct in_ifaddr *ia;
   4120 #endif
   4121 
   4122 	/* sanity check */
   4123 	if (sa == NULL)
   4124 		panic("key_ismyaddr: NULL pointer is passed");
   4125 
   4126 	switch (sa->sa_family) {
   4127 #ifdef INET
   4128 	case AF_INET:
   4129 		sin = (const struct sockaddr_in *)sa;
   4130 		IN_ADDRLIST_READER_FOREACH(ia) {
   4131 			if (sin->sin_family == ia->ia_addr.sin_family &&
   4132 			    sin->sin_len == ia->ia_addr.sin_len &&
   4133 			    sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
   4134 			{
   4135 				return 1;
   4136 			}
   4137 		}
   4138 		break;
   4139 #endif
   4140 #ifdef INET6
   4141 	case AF_INET6:
   4142 		return key_ismyaddr6((const struct sockaddr_in6 *)sa);
   4143 #endif
   4144 	}
   4145 
   4146 	return 0;
   4147 }
   4148 
   4149 #ifdef INET6
   4150 /*
   4151  * compare my own address for IPv6.
   4152  * 1: ours
   4153  * 0: other
   4154  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
   4155  */
   4156 #include <netinet6/in6_var.h>
   4157 
   4158 static int
   4159 key_ismyaddr6(const struct sockaddr_in6 *sin6)
   4160 {
   4161 	struct in6_ifaddr *ia;
   4162 	const struct in6_multi *in6m;
   4163 
   4164 	IN6_ADDRLIST_READER_FOREACH(ia) {
   4165 		if (key_sockaddrcmp((const struct sockaddr *)&sin6,
   4166 		    (const struct sockaddr *)&ia->ia_addr, 0) == 0)
   4167 			return 1;
   4168 
   4169 		/*
   4170 		 * XXX Multicast
   4171 		 * XXX why do we care about multlicast here while we don't care
   4172 		 * about IPv4 multicast??
   4173 		 * XXX scope
   4174 		 */
   4175 		in6m = NULL;
   4176 #ifdef __FreeBSD__
   4177 		IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
   4178 #else
   4179 		for ((in6m) = ia->ia6_multiaddrs.lh_first;
   4180 		     (in6m) != NULL &&
   4181 		     !IN6_ARE_ADDR_EQUAL(&(in6m)->in6m_addr, &sin6->sin6_addr);
   4182 		     (in6m) = in6m->in6m_entry.le_next)
   4183 			continue;
   4184 #endif
   4185 		if (in6m)
   4186 			return 1;
   4187 	}
   4188 
   4189 	/* loopback, just for safety */
   4190 	if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
   4191 		return 1;
   4192 
   4193 	return 0;
   4194 }
   4195 #endif /*INET6*/
   4196 
   4197 /*
   4198  * compare two secasindex structure.
   4199  * flag can specify to compare 2 saidxes.
   4200  * compare two secasindex structure without both mode and reqid.
   4201  * don't compare port.
   4202  * IN:
   4203  *      saidx0: source, it can be in SAD.
   4204  *      saidx1: object.
   4205  * OUT:
   4206  *      1 : equal
   4207  *      0 : not equal
   4208  */
   4209 static int
   4210 key_cmpsaidx(
   4211 	const struct secasindex *saidx0,
   4212 	const struct secasindex *saidx1,
   4213 	int flag)
   4214 {
   4215 	int chkport;
   4216 	const struct sockaddr *sa0src, *sa0dst, *sa1src, *sa1dst;
   4217 
   4218 	/* sanity */
   4219 	if (saidx0 == NULL && saidx1 == NULL)
   4220 		return 1;
   4221 
   4222 	if (saidx0 == NULL || saidx1 == NULL)
   4223 		return 0;
   4224 
   4225 	if (saidx0->proto != saidx1->proto)
   4226 		return 0;
   4227 
   4228 	if (flag == CMP_EXACTLY) {
   4229 		if (saidx0->mode != saidx1->mode)
   4230 			return 0;
   4231 		if (saidx0->reqid != saidx1->reqid)
   4232 			return 0;
   4233 		if (memcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
   4234 		    memcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
   4235 			return 0;
   4236 	} else {
   4237 
   4238 		/* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
   4239 		if (flag == CMP_MODE_REQID
   4240 		  ||flag == CMP_REQID) {
   4241 			/*
   4242 			 * If reqid of SPD is non-zero, unique SA is required.
   4243 			 * The result must be of same reqid in this case.
   4244 			 */
   4245 			if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
   4246 				return 0;
   4247 		}
   4248 
   4249 		if (flag == CMP_MODE_REQID) {
   4250 			if (saidx0->mode != IPSEC_MODE_ANY
   4251 			 && saidx0->mode != saidx1->mode)
   4252 				return 0;
   4253 		}
   4254 
   4255 
   4256 		sa0src = &saidx0->src.sa;
   4257 		sa0dst = &saidx0->dst.sa;
   4258 		sa1src = &saidx1->src.sa;
   4259 		sa1dst = &saidx1->dst.sa;
   4260 		/*
   4261 		 * If NAT-T is enabled, check ports for tunnel mode.
   4262 		 * Don't do it for transport mode, as there is no
   4263 		 * port information available in the SP.
   4264 		 * Also don't check ports if they are set to zero
   4265 		 * in the SPD: This means we have a non-generated
   4266 		 * SPD which can't know UDP ports.
   4267 		 */
   4268 		if (saidx1->mode == IPSEC_MODE_TUNNEL)
   4269 			chkport = PORT_LOOSE;
   4270 		else
   4271 			chkport = PORT_NONE;
   4272 
   4273 		if (key_sockaddrcmp(sa0src, sa1src, chkport) != 0) {
   4274 			return 0;
   4275 		}
   4276 		if (key_sockaddrcmp(sa0dst, sa1dst, chkport) != 0) {
   4277 			return 0;
   4278 		}
   4279 	}
   4280 
   4281 	return 1;
   4282 }
   4283 
   4284 /*
   4285  * compare two secindex structure exactly.
   4286  * IN:
   4287  *	spidx0: source, it is often in SPD.
   4288  *	spidx1: object, it is often from PFKEY message.
   4289  * OUT:
   4290  *	1 : equal
   4291  *	0 : not equal
   4292  */
   4293 int
   4294 key_cmpspidx_exactly(
   4295 	const struct secpolicyindex *spidx0,
   4296 	const struct secpolicyindex *spidx1)
   4297 {
   4298 	/* sanity */
   4299 	if (spidx0 == NULL && spidx1 == NULL)
   4300 		return 1;
   4301 
   4302 	if (spidx0 == NULL || spidx1 == NULL)
   4303 		return 0;
   4304 
   4305 	if (spidx0->prefs != spidx1->prefs
   4306 	 || spidx0->prefd != spidx1->prefd
   4307 	 || spidx0->ul_proto != spidx1->ul_proto)
   4308 		return 0;
   4309 
   4310 	return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, PORT_STRICT) == 0 &&
   4311 	       key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, PORT_STRICT) == 0;
   4312 }
   4313 
   4314 /*
   4315  * compare two secindex structure with mask.
   4316  * IN:
   4317  *	spidx0: source, it is often in SPD.
   4318  *	spidx1: object, it is often from IP header.
   4319  * OUT:
   4320  *	1 : equal
   4321  *	0 : not equal
   4322  */
   4323 int
   4324 key_cmpspidx_withmask(
   4325 	const struct secpolicyindex *spidx0,
   4326 	const struct secpolicyindex *spidx1)
   4327 {
   4328 	/* sanity */
   4329 	if (spidx0 == NULL && spidx1 == NULL)
   4330 		return 1;
   4331 
   4332 	if (spidx0 == NULL || spidx1 == NULL)
   4333 		return 0;
   4334 
   4335 	if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
   4336 	    spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
   4337 	    spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
   4338 	    spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
   4339 		return 0;
   4340 
   4341 	/* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
   4342 	if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
   4343 	 && spidx0->ul_proto != spidx1->ul_proto)
   4344 		return 0;
   4345 
   4346 	switch (spidx0->src.sa.sa_family) {
   4347 	case AF_INET:
   4348 		if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
   4349 		 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
   4350 			return 0;
   4351 		if (!key_bbcmp(&spidx0->src.sin.sin_addr,
   4352 		    &spidx1->src.sin.sin_addr, spidx0->prefs))
   4353 			return 0;
   4354 		break;
   4355 	case AF_INET6:
   4356 		if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
   4357 		 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
   4358 			return 0;
   4359 		/*
   4360 		 * scope_id check. if sin6_scope_id is 0, we regard it
   4361 		 * as a wildcard scope, which matches any scope zone ID.
   4362 		 */
   4363 		if (spidx0->src.sin6.sin6_scope_id &&
   4364 		    spidx1->src.sin6.sin6_scope_id &&
   4365 		    spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
   4366 			return 0;
   4367 		if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
   4368 		    &spidx1->src.sin6.sin6_addr, spidx0->prefs))
   4369 			return 0;
   4370 		break;
   4371 	default:
   4372 		/* XXX */
   4373 		if (memcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
   4374 			return 0;
   4375 		break;
   4376 	}
   4377 
   4378 	switch (spidx0->dst.sa.sa_family) {
   4379 	case AF_INET:
   4380 		if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
   4381 		 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
   4382 			return 0;
   4383 		if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
   4384 		    &spidx1->dst.sin.sin_addr, spidx0->prefd))
   4385 			return 0;
   4386 		break;
   4387 	case AF_INET6:
   4388 		if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
   4389 		 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
   4390 			return 0;
   4391 		/*
   4392 		 * scope_id check. if sin6_scope_id is 0, we regard it
   4393 		 * as a wildcard scope, which matches any scope zone ID.
   4394 		 */
   4395 		if (spidx0->src.sin6.sin6_scope_id &&
   4396 		    spidx1->src.sin6.sin6_scope_id &&
   4397 		    spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
   4398 			return 0;
   4399 		if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
   4400 		    &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
   4401 			return 0;
   4402 		break;
   4403 	default:
   4404 		/* XXX */
   4405 		if (memcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
   4406 			return 0;
   4407 		break;
   4408 	}
   4409 
   4410 	/* XXX Do we check other field ?  e.g. flowinfo */
   4411 
   4412 	return 1;
   4413 }
   4414 
   4415 /* returns 0 on match */
   4416 static int
   4417 key_portcomp(in_port_t port1, in_port_t port2, int howport)
   4418 {
   4419 	switch (howport) {
   4420 	case PORT_NONE:
   4421 		return 0;
   4422 	case PORT_LOOSE:
   4423 		if (port1 == 0 || port2 == 0)
   4424 			return 0;
   4425 		/*FALLTHROUGH*/
   4426 	case PORT_STRICT:
   4427 		if (port1 != port2) {
   4428 			KEYDEBUG(KEYDEBUG_MATCH,
   4429 			    printf("port fail %d != %d\n", port1, port2));
   4430 			return 1;
   4431 		}
   4432 		return 0;
   4433 	default:
   4434 		KASSERT(0);
   4435 		return 1;
   4436 	}
   4437 }
   4438 
   4439 /* returns 0 on match */
   4440 static int
   4441 key_sockaddrcmp(
   4442 	const struct sockaddr *sa1,
   4443 	const struct sockaddr *sa2,
   4444 	int howport)
   4445 {
   4446 	const struct sockaddr_in *sin1, *sin2;
   4447 	const struct sockaddr_in6 *sin61, *sin62;
   4448 
   4449 	if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len) {
   4450 		KEYDEBUG(KEYDEBUG_MATCH,
   4451 		    printf("fam/len fail %d != %d || %d != %d\n",
   4452 			sa1->sa_family, sa2->sa_family, sa1->sa_len,
   4453 			sa2->sa_len));
   4454 		return 1;
   4455 	}
   4456 
   4457 	switch (sa1->sa_family) {
   4458 	case AF_INET:
   4459 		if (sa1->sa_len != sizeof(struct sockaddr_in)) {
   4460 			KEYDEBUG(KEYDEBUG_MATCH,
   4461 			    printf("len fail %d != %zu\n",
   4462 				sa1->sa_len, sizeof(struct sockaddr_in)));
   4463 			return 1;
   4464 		}
   4465 		sin1 = (const struct sockaddr_in *)sa1;
   4466 		sin2 = (const struct sockaddr_in *)sa2;
   4467 		if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr) {
   4468 			KEYDEBUG(KEYDEBUG_MATCH,
   4469 			    printf("addr fail %#x != %#x\n",
   4470 				sin1->sin_addr.s_addr,
   4471 				sin2->sin_addr.s_addr));
   4472 			return 1;
   4473 		}
   4474 		if (key_portcomp(sin1->sin_port, sin2->sin_port, howport)) {
   4475 			return 1;
   4476 		}
   4477 		KEYDEBUG(KEYDEBUG_MATCH,
   4478 		    printf("addr success %#x[%d] == %#x[%d]\n",
   4479 			sin1->sin_addr.s_addr,
   4480 			sin1->sin_port,
   4481 			sin2->sin_addr.s_addr,
   4482 			sin2->sin_port));
   4483 		break;
   4484 	case AF_INET6:
   4485 		sin61 = (const struct sockaddr_in6 *)sa1;
   4486 		sin62 = (const struct sockaddr_in6 *)sa2;
   4487 		if (sa1->sa_len != sizeof(struct sockaddr_in6))
   4488 			return 1;	/*EINVAL*/
   4489 
   4490 		if (sin61->sin6_scope_id != sin62->sin6_scope_id) {
   4491 			return 1;
   4492 		}
   4493 		if (!IN6_ARE_ADDR_EQUAL(&sin61->sin6_addr, &sin62->sin6_addr)) {
   4494 			return 1;
   4495 		}
   4496 		if (key_portcomp(sin61->sin6_port, sin62->sin6_port, howport)) {
   4497 			return 1;
   4498 		}
   4499 		break;
   4500 	default:
   4501 		if (memcmp(sa1, sa2, sa1->sa_len) != 0)
   4502 			return 1;
   4503 		break;
   4504 	}
   4505 
   4506 	return 0;
   4507 }
   4508 
   4509 /*
   4510  * compare two buffers with mask.
   4511  * IN:
   4512  *	addr1: source
   4513  *	addr2: object
   4514  *	bits:  Number of bits to compare
   4515  * OUT:
   4516  *	1 : equal
   4517  *	0 : not equal
   4518  */
   4519 static int
   4520 key_bbcmp(const void *a1, const void *a2, u_int bits)
   4521 {
   4522 	const unsigned char *p1 = a1;
   4523 	const unsigned char *p2 = a2;
   4524 
   4525 	/* XXX: This could be considerably faster if we compare a word
   4526 	 * at a time, but it is complicated on LSB Endian machines */
   4527 
   4528 	/* Handle null pointers */
   4529 	if (p1 == NULL || p2 == NULL)
   4530 		return (p1 == p2);
   4531 
   4532 	while (bits >= 8) {
   4533 		if (*p1++ != *p2++)
   4534 			return 0;
   4535 		bits -= 8;
   4536 	}
   4537 
   4538 	if (bits > 0) {
   4539 		u_int8_t mask = ~((1<<(8-bits))-1);
   4540 		if ((*p1 & mask) != (*p2 & mask))
   4541 			return 0;
   4542 	}
   4543 	return 1;	/* Match! */
   4544 }
   4545 
   4546 /*
   4547  * time handler.
   4548  * scanning SPD and SAD to check status for each entries,
   4549  * and do to remove or to expire.
   4550  */
   4551 void
   4552 key_timehandler(void* arg)
   4553 {
   4554 	u_int dir;
   4555 	int s;
   4556 	time_t now = time_uptime;
   4557 
   4558 	s = splsoftnet();	/*called from softclock()*/
   4559 	mutex_enter(softnet_lock);
   4560 
   4561 	/* SPD */
   4562     {
   4563 	struct secpolicy *sp, *nextsp;
   4564 
   4565 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   4566 		for (sp = LIST_FIRST(&sptree[dir]);
   4567 		     sp != NULL;
   4568 		     sp = nextsp) {
   4569 
   4570 			nextsp = LIST_NEXT(sp, chain);
   4571 
   4572 			if (sp->state == IPSEC_SPSTATE_DEAD) {
   4573 				key_sp_unlink(sp);	/*XXX*/
   4574 
   4575 				/* 'sp' dead; continue transfers to
   4576 				 * 'sp = nextsp'
   4577 				 */
   4578 				continue;
   4579 			}
   4580 
   4581 			if (sp->lifetime == 0 && sp->validtime == 0)
   4582 				continue;
   4583 
   4584 			/* the deletion will occur next time */
   4585 			if ((sp->lifetime && now - sp->created > sp->lifetime)
   4586 			 || (sp->validtime && now - sp->lastused > sp->validtime)) {
   4587 			  	key_sp_dead(sp);
   4588 				key_spdexpire(sp);
   4589 				continue;
   4590 			}
   4591 		}
   4592 	}
   4593     }
   4594 
   4595 	/* SAD */
   4596     {
   4597 	struct secashead *sah, *nextsah;
   4598 	struct secasvar *sav, *nextsav;
   4599 
   4600 	for (sah = LIST_FIRST(&sahtree);
   4601 	     sah != NULL;
   4602 	     sah = nextsah) {
   4603 
   4604 		nextsah = LIST_NEXT(sah, chain);
   4605 
   4606 		/* if sah has been dead, then delete it and process next sah. */
   4607 		if (sah->state == SADB_SASTATE_DEAD) {
   4608 			key_delsah(sah);
   4609 			continue;
   4610 		}
   4611 
   4612 		/* if LARVAL entry doesn't become MATURE, delete it. */
   4613 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]);
   4614 		     sav != NULL;
   4615 		     sav = nextsav) {
   4616 
   4617 			nextsav = LIST_NEXT(sav, chain);
   4618 
   4619 			if (now - sav->created > key_larval_lifetime) {
   4620 				KEY_FREESAV(&sav);
   4621 			}
   4622 		}
   4623 
   4624 		/*
   4625 		 * check MATURE entry to start to send expire message
   4626 		 * whether or not.
   4627 		 */
   4628 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
   4629 		     sav != NULL;
   4630 		     sav = nextsav) {
   4631 
   4632 			nextsav = LIST_NEXT(sav, chain);
   4633 
   4634 			/* we don't need to check. */
   4635 			if (sav->lft_s == NULL)
   4636 				continue;
   4637 
   4638 			/* sanity check */
   4639 			if (sav->lft_c == NULL) {
   4640 				ipseclog((LOG_DEBUG,"key_timehandler: "
   4641 					"There is no CURRENT time, why?\n"));
   4642 				continue;
   4643 			}
   4644 
   4645 			/* check SOFT lifetime */
   4646 			if (sav->lft_s->sadb_lifetime_addtime != 0
   4647 			 && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
   4648 				/*
   4649 				 * check SA to be used whether or not.
   4650 				 * when SA hasn't been used, delete it.
   4651 				 */
   4652 				if (sav->lft_c->sadb_lifetime_usetime == 0) {
   4653 					key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4654 					KEY_FREESAV(&sav);
   4655 				} else {
   4656 					key_sa_chgstate(sav, SADB_SASTATE_DYING);
   4657 					/*
   4658 					 * XXX If we keep to send expire
   4659 					 * message in the status of
   4660 					 * DYING. Do remove below code.
   4661 					 */
   4662 					key_expire(sav);
   4663 				}
   4664 			}
   4665 			/* check SOFT lifetime by bytes */
   4666 			/*
   4667 			 * XXX I don't know the way to delete this SA
   4668 			 * when new SA is installed.  Caution when it's
   4669 			 * installed too big lifetime by time.
   4670 			 */
   4671 			else if (sav->lft_s->sadb_lifetime_bytes != 0
   4672 			      && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
   4673 
   4674 				key_sa_chgstate(sav, SADB_SASTATE_DYING);
   4675 				/*
   4676 				 * XXX If we keep to send expire
   4677 				 * message in the status of
   4678 				 * DYING. Do remove below code.
   4679 				 */
   4680 				key_expire(sav);
   4681 			}
   4682 		}
   4683 
   4684 		/* check DYING entry to change status to DEAD. */
   4685 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]);
   4686 		     sav != NULL;
   4687 		     sav = nextsav) {
   4688 
   4689 			nextsav = LIST_NEXT(sav, chain);
   4690 
   4691 			/* we don't need to check. */
   4692 			if (sav->lft_h == NULL)
   4693 				continue;
   4694 
   4695 			/* sanity check */
   4696 			if (sav->lft_c == NULL) {
   4697 				ipseclog((LOG_DEBUG, "key_timehandler: "
   4698 					"There is no CURRENT time, why?\n"));
   4699 				continue;
   4700 			}
   4701 
   4702 			if (sav->lft_h->sadb_lifetime_addtime != 0
   4703 			 && now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
   4704 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4705 				KEY_FREESAV(&sav);
   4706 			}
   4707 #if 0	/* XXX Should we keep to send expire message until HARD lifetime ? */
   4708 			else if (sav->lft_s != NULL
   4709 			      && sav->lft_s->sadb_lifetime_addtime != 0
   4710 			      && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
   4711 				/*
   4712 				 * XXX: should be checked to be
   4713 				 * installed the valid SA.
   4714 				 */
   4715 
   4716 				/*
   4717 				 * If there is no SA then sending
   4718 				 * expire message.
   4719 				 */
   4720 				key_expire(sav);
   4721 			}
   4722 #endif
   4723 			/* check HARD lifetime by bytes */
   4724 			else if (sav->lft_h->sadb_lifetime_bytes != 0
   4725 			      && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
   4726 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   4727 				KEY_FREESAV(&sav);
   4728 			}
   4729 		}
   4730 
   4731 		/* delete entry in DEAD */
   4732 		for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]);
   4733 		     sav != NULL;
   4734 		     sav = nextsav) {
   4735 
   4736 			nextsav = LIST_NEXT(sav, chain);
   4737 
   4738 			/* sanity check */
   4739 			if (sav->state != SADB_SASTATE_DEAD) {
   4740 				ipseclog((LOG_DEBUG, "key_timehandler: "
   4741 					"invalid sav->state "
   4742 					"(queue: %d SA: %d): "
   4743 					"kill it anyway\n",
   4744 					SADB_SASTATE_DEAD, sav->state));
   4745 			}
   4746 
   4747 			/*
   4748 			 * do not call key_freesav() here.
   4749 			 * sav should already be freed, and sav->refcnt
   4750 			 * shows other references to sav
   4751 			 * (such as from SPD).
   4752 			 */
   4753 		}
   4754 	}
   4755     }
   4756 
   4757 #ifndef IPSEC_NONBLOCK_ACQUIRE
   4758 	/* ACQ tree */
   4759     {
   4760 	struct secacq *acq, *nextacq;
   4761 
   4762 	for (acq = LIST_FIRST(&acqtree);
   4763 	     acq != NULL;
   4764 	     acq = nextacq) {
   4765 
   4766 		nextacq = LIST_NEXT(acq, chain);
   4767 
   4768 		if (now - acq->created > key_blockacq_lifetime
   4769 		 && __LIST_CHAINED(acq)) {
   4770 			LIST_REMOVE(acq, chain);
   4771 			KFREE(acq);
   4772 		}
   4773 	}
   4774     }
   4775 #endif
   4776 
   4777 	/* SP ACQ tree */
   4778     {
   4779 	struct secspacq *acq, *nextacq;
   4780 
   4781 	for (acq = LIST_FIRST(&spacqtree);
   4782 	     acq != NULL;
   4783 	     acq = nextacq) {
   4784 
   4785 		nextacq = LIST_NEXT(acq, chain);
   4786 
   4787 		if (now - acq->created > key_blockacq_lifetime
   4788 		 && __LIST_CHAINED(acq)) {
   4789 			LIST_REMOVE(acq, chain);
   4790 			KFREE(acq);
   4791 		}
   4792 	}
   4793     }
   4794 
   4795 #ifndef IPSEC_DEBUG2
   4796 	/* do exchange to tick time !! */
   4797 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
   4798 #endif /* IPSEC_DEBUG2 */
   4799 
   4800 	mutex_exit(softnet_lock);
   4801 	splx(s);
   4802 	return;
   4803 }
   4804 
   4805 u_long
   4806 key_random(void)
   4807 {
   4808 	u_long value;
   4809 
   4810 	key_randomfill(&value, sizeof(value));
   4811 	return value;
   4812 }
   4813 
   4814 void
   4815 key_randomfill(void *p, size_t l)
   4816 {
   4817 
   4818 	cprng_fast(p, l);
   4819 }
   4820 
   4821 /*
   4822  * map SADB_SATYPE_* to IPPROTO_*.
   4823  * if satype == SADB_SATYPE then satype is mapped to ~0.
   4824  * OUT:
   4825  *	0: invalid satype.
   4826  */
   4827 static u_int16_t
   4828 key_satype2proto(u_int8_t satype)
   4829 {
   4830 	switch (satype) {
   4831 	case SADB_SATYPE_UNSPEC:
   4832 		return IPSEC_PROTO_ANY;
   4833 	case SADB_SATYPE_AH:
   4834 		return IPPROTO_AH;
   4835 	case SADB_SATYPE_ESP:
   4836 		return IPPROTO_ESP;
   4837 	case SADB_X_SATYPE_IPCOMP:
   4838 		return IPPROTO_IPCOMP;
   4839 	case SADB_X_SATYPE_TCPSIGNATURE:
   4840 		return IPPROTO_TCP;
   4841 	default:
   4842 		return 0;
   4843 	}
   4844 	/* NOTREACHED */
   4845 }
   4846 
   4847 /*
   4848  * map IPPROTO_* to SADB_SATYPE_*
   4849  * OUT:
   4850  *	0: invalid protocol type.
   4851  */
   4852 static u_int8_t
   4853 key_proto2satype(u_int16_t proto)
   4854 {
   4855 	switch (proto) {
   4856 	case IPPROTO_AH:
   4857 		return SADB_SATYPE_AH;
   4858 	case IPPROTO_ESP:
   4859 		return SADB_SATYPE_ESP;
   4860 	case IPPROTO_IPCOMP:
   4861 		return SADB_X_SATYPE_IPCOMP;
   4862 	case IPPROTO_TCP:
   4863 		return SADB_X_SATYPE_TCPSIGNATURE;
   4864 	default:
   4865 		return 0;
   4866 	}
   4867 	/* NOTREACHED */
   4868 }
   4869 
   4870 static int
   4871 key_setsecasidx(int proto, int mode, int reqid,
   4872 	        const struct sadb_address * src,
   4873 	 	const struct sadb_address * dst,
   4874 		struct secasindex * saidx)
   4875 {
   4876 	const union sockaddr_union * src_u =
   4877 		(const union sockaddr_union *) src;
   4878 	const union sockaddr_union * dst_u =
   4879 		(const union sockaddr_union *) dst;
   4880 
   4881 	/* sa len safety check */
   4882 	if (key_checksalen(src_u) != 0)
   4883 		return -1;
   4884 	if (key_checksalen(dst_u) != 0)
   4885 		return -1;
   4886 
   4887 	memset(saidx, 0, sizeof(*saidx));
   4888 	saidx->proto = proto;
   4889 	saidx->mode = mode;
   4890 	saidx->reqid = reqid;
   4891 	memcpy(&saidx->src, src_u, src_u->sa.sa_len);
   4892 	memcpy(&saidx->dst, dst_u, dst_u->sa.sa_len);
   4893 
   4894 	key_porttosaddr(&((saidx)->src),0);
   4895 	key_porttosaddr(&((saidx)->dst),0);
   4896 	return 0;
   4897 }
   4898 
   4899 /* %%% PF_KEY */
   4900 /*
   4901  * SADB_GETSPI processing is to receive
   4902  *	<base, (SA2), src address, dst address, (SPI range)>
   4903  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
   4904  * tree with the status of LARVAL, and send
   4905  *	<base, SA(*), address(SD)>
   4906  * to the IKMPd.
   4907  *
   4908  * IN:	mhp: pointer to the pointer to each header.
   4909  * OUT:	NULL if fail.
   4910  *	other if success, return pointer to the message to send.
   4911  */
   4912 static int
   4913 key_getspi(struct socket *so, struct mbuf *m,
   4914 	   const struct sadb_msghdr *mhp)
   4915 {
   4916 	struct sadb_address *src0, *dst0;
   4917 	struct secasindex saidx;
   4918 	struct secashead *newsah;
   4919 	struct secasvar *newsav;
   4920 	u_int8_t proto;
   4921 	u_int32_t spi;
   4922 	u_int8_t mode;
   4923 	u_int16_t reqid;
   4924 	int error;
   4925 
   4926 	/* sanity check */
   4927 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   4928 		panic("key_getspi: NULL pointer is passed");
   4929 
   4930 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   4931 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   4932 		ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
   4933 		return key_senderror(so, m, EINVAL);
   4934 	}
   4935 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   4936 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   4937 		ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
   4938 		return key_senderror(so, m, EINVAL);
   4939 	}
   4940 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   4941 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   4942 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   4943 	} else {
   4944 		mode = IPSEC_MODE_ANY;
   4945 		reqid = 0;
   4946 	}
   4947 
   4948 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
   4949 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
   4950 
   4951 	/* map satype to proto */
   4952 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   4953 		ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
   4954 		return key_senderror(so, m, EINVAL);
   4955 	}
   4956 
   4957 
   4958 	if ((error = key_setsecasidx(proto, mode, reqid, src0 + 1,
   4959 				     dst0 + 1, &saidx)) != 0)
   4960 		return key_senderror(so, m, EINVAL);
   4961 
   4962 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   4963 		return key_senderror(so, m, EINVAL);
   4964 
   4965 	/* SPI allocation */
   4966 	spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
   4967 	                       &saidx);
   4968 	if (spi == 0)
   4969 		return key_senderror(so, m, EINVAL);
   4970 
   4971 	/* get a SA index */
   4972 	if ((newsah = key_getsah(&saidx)) == NULL) {
   4973 		/* create a new SA index */
   4974 		if ((newsah = key_newsah(&saidx)) == NULL) {
   4975 			ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
   4976 			return key_senderror(so, m, ENOBUFS);
   4977 		}
   4978 	}
   4979 
   4980 	/* get a new SA */
   4981 	/* XXX rewrite */
   4982 	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
   4983 	if (newsav == NULL) {
   4984 		/* XXX don't free new SA index allocated in above. */
   4985 		return key_senderror(so, m, error);
   4986 	}
   4987 
   4988 	/* set spi */
   4989 	newsav->spi = htonl(spi);
   4990 
   4991 #ifndef IPSEC_NONBLOCK_ACQUIRE
   4992 	/* delete the entry in acqtree */
   4993 	if (mhp->msg->sadb_msg_seq != 0) {
   4994 		struct secacq *acq;
   4995 		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
   4996 			/* reset counter in order to deletion by timehandler. */
   4997 			acq->created = time_uptime;
   4998 			acq->count = 0;
   4999 		}
   5000     	}
   5001 #endif
   5002 
   5003     {
   5004 	struct mbuf *n, *nn;
   5005 	struct sadb_sa *m_sa;
   5006 	struct sadb_msg *newmsg;
   5007 	int off, len;
   5008 
   5009 	/* create new sadb_msg to reply. */
   5010 	len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
   5011 	    PFKEY_ALIGN8(sizeof(struct sadb_sa));
   5012 	if (len > MCLBYTES)
   5013 		return key_senderror(so, m, ENOBUFS);
   5014 
   5015 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   5016 	if (len > MHLEN) {
   5017 		MCLGET(n, M_DONTWAIT);
   5018 		if ((n->m_flags & M_EXT) == 0) {
   5019 			m_freem(n);
   5020 			n = NULL;
   5021 		}
   5022 	}
   5023 	if (!n)
   5024 		return key_senderror(so, m, ENOBUFS);
   5025 
   5026 	n->m_len = len;
   5027 	n->m_next = NULL;
   5028 	off = 0;
   5029 
   5030 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   5031 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   5032 
   5033 	m_sa = (struct sadb_sa *)(mtod(n, char *) + off);
   5034 	m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
   5035 	m_sa->sadb_sa_exttype = SADB_EXT_SA;
   5036 	m_sa->sadb_sa_spi = htonl(spi);
   5037 	off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
   5038 
   5039 #ifdef DIAGNOSTIC
   5040 	if (off != len)
   5041 		panic("length inconsistency in key_getspi");
   5042 #endif
   5043 
   5044 	n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
   5045 	    SADB_EXT_ADDRESS_DST);
   5046 	if (!n->m_next) {
   5047 		m_freem(n);
   5048 		return key_senderror(so, m, ENOBUFS);
   5049 	}
   5050 
   5051 	if (n->m_len < sizeof(struct sadb_msg)) {
   5052 		n = m_pullup(n, sizeof(struct sadb_msg));
   5053 		if (n == NULL)
   5054 			return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
   5055 	}
   5056 
   5057 	n->m_pkthdr.len = 0;
   5058 	for (nn = n; nn; nn = nn->m_next)
   5059 		n->m_pkthdr.len += nn->m_len;
   5060 
   5061 	newmsg = mtod(n, struct sadb_msg *);
   5062 	newmsg->sadb_msg_seq = newsav->seq;
   5063 	newmsg->sadb_msg_errno = 0;
   5064 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
   5065 
   5066 	m_freem(m);
   5067 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   5068     }
   5069 }
   5070 
   5071 /*
   5072  * allocating new SPI
   5073  * called by key_getspi().
   5074  * OUT:
   5075  *	0:	failure.
   5076  *	others: success.
   5077  */
   5078 static u_int32_t
   5079 key_do_getnewspi(const struct sadb_spirange *spirange,
   5080 		 const struct secasindex *saidx)
   5081 {
   5082 	u_int32_t newspi;
   5083 	u_int32_t spmin, spmax;
   5084 	int count = key_spi_trycnt;
   5085 
   5086 	/* set spi range to allocate */
   5087 	if (spirange != NULL) {
   5088 		spmin = spirange->sadb_spirange_min;
   5089 		spmax = spirange->sadb_spirange_max;
   5090 	} else {
   5091 		spmin = key_spi_minval;
   5092 		spmax = key_spi_maxval;
   5093 	}
   5094 	/* IPCOMP needs 2-byte SPI */
   5095 	if (saidx->proto == IPPROTO_IPCOMP) {
   5096 		u_int32_t t;
   5097 		if (spmin >= 0x10000)
   5098 			spmin = 0xffff;
   5099 		if (spmax >= 0x10000)
   5100 			spmax = 0xffff;
   5101 		if (spmin > spmax) {
   5102 			t = spmin; spmin = spmax; spmax = t;
   5103 		}
   5104 	}
   5105 
   5106 	if (spmin == spmax) {
   5107 		if (key_checkspidup(saidx, htonl(spmin)) != NULL) {
   5108 			ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", spmin));
   5109 			return 0;
   5110 		}
   5111 
   5112 		count--; /* taking one cost. */
   5113 		newspi = spmin;
   5114 
   5115 	} else {
   5116 
   5117 		/* init SPI */
   5118 		newspi = 0;
   5119 
   5120 		/* when requesting to allocate spi ranged */
   5121 		while (count--) {
   5122 			/* generate pseudo-random SPI value ranged. */
   5123 			newspi = spmin + (key_random() % (spmax - spmin + 1));
   5124 
   5125 			if (key_checkspidup(saidx, htonl(newspi)) == NULL)
   5126 				break;
   5127 		}
   5128 
   5129 		if (count == 0 || newspi == 0) {
   5130 			ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
   5131 			return 0;
   5132 		}
   5133 	}
   5134 
   5135 	/* statistics */
   5136 	keystat.getspi_count =
   5137 		(keystat.getspi_count + key_spi_trycnt - count) / 2;
   5138 
   5139 	return newspi;
   5140 }
   5141 
   5142 static int
   5143 key_handle_natt_info(struct secasvar *sav,
   5144       		     const struct sadb_msghdr *mhp)
   5145 {
   5146 	const char *msg = "?" ;
   5147 	struct sadb_x_nat_t_type *type;
   5148 	struct sadb_x_nat_t_port *sport, *dport;
   5149 	struct sadb_address *iaddr, *raddr;
   5150 	struct sadb_x_nat_t_frag *frag;
   5151 
   5152 	if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] == NULL ||
   5153 	    mhp->ext[SADB_X_EXT_NAT_T_SPORT] == NULL ||
   5154 	    mhp->ext[SADB_X_EXT_NAT_T_DPORT] == NULL)
   5155 		return 0;
   5156 
   5157 	if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) {
   5158 		msg = "TYPE";
   5159 		goto bad;
   5160 	}
   5161 
   5162 	if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) {
   5163 		msg = "SPORT";
   5164 		goto bad;
   5165 	}
   5166 
   5167 	if (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
   5168 		msg = "DPORT";
   5169 		goto bad;
   5170 	}
   5171 
   5172 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL) {
   5173 		ipseclog((LOG_DEBUG,"%s: NAT-T OAi present\n", __func__));
   5174 		if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr)) {
   5175 			msg = "OAI";
   5176 			goto bad;
   5177 		}
   5178 	}
   5179 
   5180 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
   5181 		ipseclog((LOG_DEBUG,"%s: NAT-T OAr present\n", __func__));
   5182 		if (mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
   5183 			msg = "OAR";
   5184 			goto bad;
   5185 		}
   5186 	}
   5187 
   5188 	if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
   5189 	    if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
   5190 		    msg = "FRAG";
   5191 		    goto bad;
   5192 	    }
   5193 	}
   5194 
   5195 	type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
   5196 	sport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   5197 	dport = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   5198 	iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
   5199 	raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
   5200 	frag = (struct sadb_x_nat_t_frag *)mhp->ext[SADB_X_EXT_NAT_T_FRAG];
   5201 
   5202 	ipseclog((LOG_DEBUG, "%s: type %d, sport = %d, dport = %d\n",
   5203 	    __func__, type->sadb_x_nat_t_type_type,
   5204 	    ntohs(sport->sadb_x_nat_t_port_port),
   5205 	    ntohs(dport->sadb_x_nat_t_port_port)));
   5206 
   5207 	sav->natt_type = type->sadb_x_nat_t_type_type;
   5208 	key_porttosaddr(&sav->sah->saidx.src,
   5209 	    sport->sadb_x_nat_t_port_port);
   5210 	key_porttosaddr(&sav->sah->saidx.dst,
   5211 	    dport->sadb_x_nat_t_port_port);
   5212 	if (frag)
   5213 		sav->esp_frag = frag->sadb_x_nat_t_frag_fraglen;
   5214 	else
   5215 		sav->esp_frag = IP_MAXPACKET;
   5216 
   5217 	return 0;
   5218 bad:
   5219 	ipseclog((LOG_DEBUG, "%s: invalid message %s\n", __func__, msg));
   5220 	__USE(msg);
   5221 	return -1;
   5222 }
   5223 
   5224 /* Just update the IPSEC_NAT_T ports if present */
   5225 static int
   5226 key_set_natt_ports(union sockaddr_union *src, union sockaddr_union *dst,
   5227       		     const struct sadb_msghdr *mhp)
   5228 {
   5229 	if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
   5230 		ipseclog((LOG_DEBUG,"%s: NAT-T OAi present\n", __func__));
   5231 	if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
   5232 		ipseclog((LOG_DEBUG,"%s: NAT-T OAr present\n", __func__));
   5233 
   5234 	if ((mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL) &&
   5235 	    (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL) &&
   5236 	    (mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL)) {
   5237 		struct sadb_x_nat_t_type *type;
   5238 		struct sadb_x_nat_t_port *sport;
   5239 		struct sadb_x_nat_t_port *dport;
   5240 
   5241 		if ((mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type)) ||
   5242 		    (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport)) ||
   5243 		    (mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport))) {
   5244 			ipseclog((LOG_DEBUG, "%s: invalid message\n",
   5245 			    __func__));
   5246 			return -1;
   5247 		}
   5248 
   5249 		type = (struct sadb_x_nat_t_type *)
   5250 		    mhp->ext[SADB_X_EXT_NAT_T_TYPE];
   5251 		sport = (struct sadb_x_nat_t_port *)
   5252 		    mhp->ext[SADB_X_EXT_NAT_T_SPORT];
   5253 		dport = (struct sadb_x_nat_t_port *)
   5254 		    mhp->ext[SADB_X_EXT_NAT_T_DPORT];
   5255 
   5256 		key_porttosaddr(src, sport->sadb_x_nat_t_port_port);
   5257 		key_porttosaddr(dst, dport->sadb_x_nat_t_port_port);
   5258 
   5259 		ipseclog((LOG_DEBUG, "%s: type %d, sport = %d, dport = %d\n",
   5260 		    __func__, type->sadb_x_nat_t_type_type,
   5261 		    ntohs(sport->sadb_x_nat_t_port_port),
   5262 		    ntohs(dport->sadb_x_nat_t_port_port)));
   5263 	}
   5264 
   5265 	return 0;
   5266 }
   5267 
   5268 
   5269 /*
   5270  * SADB_UPDATE processing
   5271  * receive
   5272  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5273  *       key(AE), (identity(SD),) (sensitivity)>
   5274  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
   5275  * and send
   5276  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5277  *       (identity(SD),) (sensitivity)>
   5278  * to the ikmpd.
   5279  *
   5280  * m will always be freed.
   5281  */
   5282 static int
   5283 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
   5284 {
   5285 	struct sadb_sa *sa0;
   5286 	struct sadb_address *src0, *dst0;
   5287 	struct secasindex saidx;
   5288 	struct secashead *sah;
   5289 	struct secasvar *sav;
   5290 	u_int16_t proto;
   5291 	u_int8_t mode;
   5292 	u_int16_t reqid;
   5293 	int error;
   5294 
   5295 	/* sanity check */
   5296 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5297 		panic("key_update: NULL pointer is passed");
   5298 
   5299 	/* map satype to proto */
   5300 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5301 		ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
   5302 		return key_senderror(so, m, EINVAL);
   5303 	}
   5304 
   5305 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5306 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5307 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   5308 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
   5309 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
   5310 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
   5311 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
   5312 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
   5313 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
   5314 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
   5315 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
   5316 		ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
   5317 		return key_senderror(so, m, EINVAL);
   5318 	}
   5319 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5320 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5321 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5322 		ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
   5323 		return key_senderror(so, m, EINVAL);
   5324 	}
   5325 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   5326 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   5327 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   5328 	} else {
   5329 		mode = IPSEC_MODE_ANY;
   5330 		reqid = 0;
   5331 	}
   5332 	/* XXX boundary checking for other extensions */
   5333 
   5334 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5335 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
   5336 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
   5337 
   5338 	if ((error = key_setsecasidx(proto, mode, reqid, src0 + 1,
   5339 				     dst0 + 1, &saidx)) != 0)
   5340 		return key_senderror(so, m, EINVAL);
   5341 
   5342 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5343 		return key_senderror(so, m, EINVAL);
   5344 
   5345 	/* get a SA header */
   5346 	if ((sah = key_getsah(&saidx)) == NULL) {
   5347 		ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
   5348 		return key_senderror(so, m, ENOENT);
   5349 	}
   5350 
   5351 	/* set spidx if there */
   5352 	/* XXX rewrite */
   5353 	error = key_setident(sah, m, mhp);
   5354 	if (error)
   5355 		return key_senderror(so, m, error);
   5356 
   5357 	/* find a SA with sequence number. */
   5358 #ifdef IPSEC_DOSEQCHECK
   5359 	if (mhp->msg->sadb_msg_seq != 0
   5360 	 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
   5361 		ipseclog((LOG_DEBUG,
   5362 		    "key_update: no larval SA with sequence %u exists.\n",
   5363 		    mhp->msg->sadb_msg_seq));
   5364 		return key_senderror(so, m, ENOENT);
   5365 	}
   5366 #else
   5367 	if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
   5368 		ipseclog((LOG_DEBUG,
   5369 		    "key_update: no such a SA found (spi:%u)\n",
   5370 		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
   5371 		return key_senderror(so, m, EINVAL);
   5372 	}
   5373 #endif
   5374 
   5375 	/* validity check */
   5376 	if (sav->sah->saidx.proto != proto) {
   5377 		ipseclog((LOG_DEBUG,
   5378 		    "key_update: protocol mismatched (DB=%u param=%u)\n",
   5379 		    sav->sah->saidx.proto, proto));
   5380 		return key_senderror(so, m, EINVAL);
   5381 	}
   5382 #ifdef IPSEC_DOSEQCHECK
   5383 	if (sav->spi != sa0->sadb_sa_spi) {
   5384 		ipseclog((LOG_DEBUG,
   5385 		    "key_update: SPI mismatched (DB:%u param:%u)\n",
   5386 		    (u_int32_t)ntohl(sav->spi),
   5387 		    (u_int32_t)ntohl(sa0->sadb_sa_spi)));
   5388 		return key_senderror(so, m, EINVAL);
   5389 	}
   5390 #endif
   5391 	if (sav->pid != mhp->msg->sadb_msg_pid) {
   5392 		ipseclog((LOG_DEBUG,
   5393 		    "key_update: pid mismatched (DB:%u param:%u)\n",
   5394 		    sav->pid, mhp->msg->sadb_msg_pid));
   5395 		return key_senderror(so, m, EINVAL);
   5396 	}
   5397 
   5398 	/* copy sav values */
   5399 	error = key_setsaval(sav, m, mhp);
   5400 	if (error) {
   5401 		KEY_FREESAV(&sav);
   5402 		return key_senderror(so, m, error);
   5403 	}
   5404 
   5405 	if ((error = key_handle_natt_info(sav,mhp)) != 0)
   5406 		return key_senderror(so, m, EINVAL);
   5407 
   5408 	/* check SA values to be mature. */
   5409 	if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
   5410 		KEY_FREESAV(&sav);
   5411 		return key_senderror(so, m, 0);
   5412 	}
   5413 
   5414     {
   5415 	struct mbuf *n;
   5416 
   5417 	/* set msg buf from mhp */
   5418 	n = key_getmsgbuf_x1(m, mhp);
   5419 	if (n == NULL) {
   5420 		ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
   5421 		return key_senderror(so, m, ENOBUFS);
   5422 	}
   5423 
   5424 	m_freem(m);
   5425 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5426     }
   5427 }
   5428 
   5429 /*
   5430  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
   5431  * only called by key_update().
   5432  * OUT:
   5433  *	NULL	: not found
   5434  *	others	: found, pointer to a SA.
   5435  */
   5436 #ifdef IPSEC_DOSEQCHECK
   5437 static struct secasvar *
   5438 key_getsavbyseq(struct secashead *sah, u_int32_t seq)
   5439 {
   5440 	struct secasvar *sav;
   5441 	u_int state;
   5442 
   5443 	state = SADB_SASTATE_LARVAL;
   5444 
   5445 	/* search SAD with sequence number ? */
   5446 	LIST_FOREACH(sav, &sah->savtree[state], chain) {
   5447 
   5448 		KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");
   5449 
   5450 		if (sav->seq == seq) {
   5451 			SA_ADDREF(sav);
   5452 			KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
   5453 				printf("DP %s cause refcnt++:%d SA:%p\n",
   5454 				    __func__, sav->refcnt, sav));
   5455 			return sav;
   5456 		}
   5457 	}
   5458 
   5459 	return NULL;
   5460 }
   5461 #endif
   5462 
   5463 /*
   5464  * SADB_ADD processing
   5465  * add an entry to SA database, when received
   5466  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5467  *       key(AE), (identity(SD),) (sensitivity)>
   5468  * from the ikmpd,
   5469  * and send
   5470  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
   5471  *       (identity(SD),) (sensitivity)>
   5472  * to the ikmpd.
   5473  *
   5474  * IGNORE identity and sensitivity messages.
   5475  *
   5476  * m will always be freed.
   5477  */
   5478 static int
   5479 key_add(struct socket *so, struct mbuf *m,
   5480 	const struct sadb_msghdr *mhp)
   5481 {
   5482 	struct sadb_sa *sa0;
   5483 	struct sadb_address *src0, *dst0;
   5484 	struct secasindex saidx;
   5485 	struct secashead *newsah;
   5486 	struct secasvar *newsav;
   5487 	u_int16_t proto;
   5488 	u_int8_t mode;
   5489 	u_int16_t reqid;
   5490 	int error;
   5491 
   5492 	/* sanity check */
   5493 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5494 		panic("key_add: NULL pointer is passed");
   5495 
   5496 	/* map satype to proto */
   5497 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5498 		ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
   5499 		return key_senderror(so, m, EINVAL);
   5500 	}
   5501 
   5502 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5503 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5504 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   5505 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
   5506 	     mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
   5507 	    (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
   5508 	     mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
   5509 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
   5510 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
   5511 	    (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
   5512 	     mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
   5513 		ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
   5514 		return key_senderror(so, m, EINVAL);
   5515 	}
   5516 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5517 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5518 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5519 		/* XXX need more */
   5520 		ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
   5521 		return key_senderror(so, m, EINVAL);
   5522 	}
   5523 	if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
   5524 		mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
   5525 		reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
   5526 	} else {
   5527 		mode = IPSEC_MODE_ANY;
   5528 		reqid = 0;
   5529 	}
   5530 
   5531 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5532 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
   5533 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
   5534 
   5535 	if ((error = key_setsecasidx(proto, mode, reqid, src0 + 1,
   5536 				     dst0 + 1, &saidx)) != 0)
   5537 		return key_senderror(so, m, EINVAL);
   5538 
   5539 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5540 		return key_senderror(so, m, EINVAL);
   5541 
   5542 	/* get a SA header */
   5543 	if ((newsah = key_getsah(&saidx)) == NULL) {
   5544 		/* create a new SA header */
   5545 		if ((newsah = key_newsah(&saidx)) == NULL) {
   5546 			ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
   5547 			return key_senderror(so, m, ENOBUFS);
   5548 		}
   5549 	}
   5550 
   5551 	/* set spidx if there */
   5552 	/* XXX rewrite */
   5553 	error = key_setident(newsah, m, mhp);
   5554 	if (error) {
   5555 		return key_senderror(so, m, error);
   5556 	}
   5557 
   5558 	/* create new SA entry. */
   5559 	/* We can create new SA only if SPI is differenct. */
   5560 	if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
   5561 		ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
   5562 		return key_senderror(so, m, EEXIST);
   5563 	}
   5564 	newsav = KEY_NEWSAV(m, mhp, newsah, &error);
   5565 	if (newsav == NULL) {
   5566 		return key_senderror(so, m, error);
   5567 	}
   5568 
   5569 	if ((error = key_handle_natt_info(newsav, mhp)) != 0)
   5570 		return key_senderror(so, m, EINVAL);
   5571 
   5572 	/* check SA values to be mature. */
   5573 	if ((error = key_mature(newsav)) != 0) {
   5574 		KEY_FREESAV(&newsav);
   5575 		return key_senderror(so, m, error);
   5576 	}
   5577 
   5578 	/*
   5579 	 * don't call key_freesav() here, as we would like to keep the SA
   5580 	 * in the database on success.
   5581 	 */
   5582 
   5583     {
   5584 	struct mbuf *n;
   5585 
   5586 	/* set msg buf from mhp */
   5587 	n = key_getmsgbuf_x1(m, mhp);
   5588 	if (n == NULL) {
   5589 		ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
   5590 		return key_senderror(so, m, ENOBUFS);
   5591 	}
   5592 
   5593 	m_freem(m);
   5594 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5595     }
   5596 }
   5597 
   5598 /* m is retained */
   5599 static int
   5600 key_setident(struct secashead *sah, struct mbuf *m,
   5601 	     const struct sadb_msghdr *mhp)
   5602 {
   5603 	const struct sadb_ident *idsrc, *iddst;
   5604 	int idsrclen, iddstlen;
   5605 
   5606 	/* sanity check */
   5607 	if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5608 		panic("key_setident: NULL pointer is passed");
   5609 
   5610 	/* don't make buffer if not there */
   5611 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
   5612 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
   5613 		sah->idents = NULL;
   5614 		sah->identd = NULL;
   5615 		return 0;
   5616 	}
   5617 
   5618 	if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
   5619 	    mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
   5620 		ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
   5621 		return EINVAL;
   5622 	}
   5623 
   5624 	idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
   5625 	iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
   5626 	idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
   5627 	iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
   5628 
   5629 	/* validity check */
   5630 	if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
   5631 		ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
   5632 		return EINVAL;
   5633 	}
   5634 
   5635 	switch (idsrc->sadb_ident_type) {
   5636 	case SADB_IDENTTYPE_PREFIX:
   5637 	case SADB_IDENTTYPE_FQDN:
   5638 	case SADB_IDENTTYPE_USERFQDN:
   5639 	default:
   5640 		/* XXX do nothing */
   5641 		sah->idents = NULL;
   5642 		sah->identd = NULL;
   5643 	 	return 0;
   5644 	}
   5645 
   5646 	/* make structure */
   5647 	KMALLOC(sah->idents, struct sadb_ident *, idsrclen);
   5648 	if (sah->idents == NULL) {
   5649 		ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
   5650 		return ENOBUFS;
   5651 	}
   5652 	KMALLOC(sah->identd, struct sadb_ident *, iddstlen);
   5653 	if (sah->identd == NULL) {
   5654 		KFREE(sah->idents);
   5655 		sah->idents = NULL;
   5656 		ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
   5657 		return ENOBUFS;
   5658 	}
   5659 	memcpy(sah->idents, idsrc, idsrclen);
   5660 	memcpy(sah->identd, iddst, iddstlen);
   5661 
   5662 	return 0;
   5663 }
   5664 
   5665 /*
   5666  * m will not be freed on return.
   5667  * it is caller's responsibility to free the result.
   5668  */
   5669 static struct mbuf *
   5670 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
   5671 {
   5672 	struct mbuf *n;
   5673 
   5674 	/* sanity check */
   5675 	if (m == NULL || mhp == NULL || mhp->msg == NULL)
   5676 		panic("key_getmsgbuf_x1: NULL pointer is passed");
   5677 
   5678 	/* create new sadb_msg to reply. */
   5679 	n = key_gather_mbuf(m, mhp, 1, 15, SADB_EXT_RESERVED,
   5680 	    SADB_EXT_SA, SADB_X_EXT_SA2,
   5681 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
   5682 	    SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
   5683 	    SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
   5684 	    SADB_X_EXT_NAT_T_TYPE, SADB_X_EXT_NAT_T_SPORT,
   5685 	    SADB_X_EXT_NAT_T_DPORT, SADB_X_EXT_NAT_T_OAI,
   5686 	    SADB_X_EXT_NAT_T_OAR, SADB_X_EXT_NAT_T_FRAG);
   5687 	if (!n)
   5688 		return NULL;
   5689 
   5690 	if (n->m_len < sizeof(struct sadb_msg)) {
   5691 		n = m_pullup(n, sizeof(struct sadb_msg));
   5692 		if (n == NULL)
   5693 			return NULL;
   5694 	}
   5695 	mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
   5696 	mtod(n, struct sadb_msg *)->sadb_msg_len =
   5697 	    PFKEY_UNIT64(n->m_pkthdr.len);
   5698 
   5699 	return n;
   5700 }
   5701 
   5702 static int key_delete_all (struct socket *, struct mbuf *,
   5703 			   const struct sadb_msghdr *, u_int16_t);
   5704 
   5705 /*
   5706  * SADB_DELETE processing
   5707  * receive
   5708  *   <base, SA(*), address(SD)>
   5709  * from the ikmpd, and set SADB_SASTATE_DEAD,
   5710  * and send,
   5711  *   <base, SA(*), address(SD)>
   5712  * to the ikmpd.
   5713  *
   5714  * m will always be freed.
   5715  */
   5716 static int
   5717 key_delete(struct socket *so, struct mbuf *m,
   5718 	   const struct sadb_msghdr *mhp)
   5719 {
   5720 	struct sadb_sa *sa0;
   5721 	struct sadb_address *src0, *dst0;
   5722 	struct secasindex saidx;
   5723 	struct secashead *sah;
   5724 	struct secasvar *sav = NULL;
   5725 	u_int16_t proto;
   5726 	int error;
   5727 
   5728 	/* sanity check */
   5729 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5730 		panic("key_delete: NULL pointer is passed");
   5731 
   5732 	/* map satype to proto */
   5733 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5734 		ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
   5735 		return key_senderror(so, m, EINVAL);
   5736 	}
   5737 
   5738 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5739 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   5740 		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
   5741 		return key_senderror(so, m, EINVAL);
   5742 	}
   5743 
   5744 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5745 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5746 		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
   5747 		return key_senderror(so, m, EINVAL);
   5748 	}
   5749 
   5750 	if (mhp->ext[SADB_EXT_SA] == NULL) {
   5751 		/*
   5752 		 * Caller wants us to delete all non-LARVAL SAs
   5753 		 * that match the src/dst.  This is used during
   5754 		 * IKE INITIAL-CONTACT.
   5755 		 */
   5756 		ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
   5757 		return key_delete_all(so, m, mhp, proto);
   5758 	} else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
   5759 		ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
   5760 		return key_senderror(so, m, EINVAL);
   5761 	}
   5762 
   5763 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5764 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
   5765 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
   5766 
   5767 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
   5768 				     dst0 + 1, &saidx)) != 0)
   5769 		return key_senderror(so, m, EINVAL);
   5770 
   5771 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5772 		return key_senderror(so, m, EINVAL);
   5773 
   5774 	/* get a SA header */
   5775 	LIST_FOREACH(sah, &sahtree, chain) {
   5776 		if (sah->state == SADB_SASTATE_DEAD)
   5777 			continue;
   5778 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
   5779 			continue;
   5780 
   5781 		/* get a SA with SPI. */
   5782 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5783 		if (sav)
   5784 			break;
   5785 	}
   5786 	if (sah == NULL) {
   5787 		ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
   5788 		return key_senderror(so, m, ENOENT);
   5789 	}
   5790 
   5791 	key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5792 	KEY_FREESAV(&sav);
   5793 
   5794     {
   5795 	struct mbuf *n;
   5796 	struct sadb_msg *newmsg;
   5797 
   5798 	/* create new sadb_msg to reply. */
   5799 	n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
   5800 	    SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   5801 	if (!n)
   5802 		return key_senderror(so, m, ENOBUFS);
   5803 
   5804 	if (n->m_len < sizeof(struct sadb_msg)) {
   5805 		n = m_pullup(n, sizeof(struct sadb_msg));
   5806 		if (n == NULL)
   5807 			return key_senderror(so, m, ENOBUFS);
   5808 	}
   5809 	newmsg = mtod(n, struct sadb_msg *);
   5810 	newmsg->sadb_msg_errno = 0;
   5811 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
   5812 
   5813 	m_freem(m);
   5814 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5815     }
   5816 }
   5817 
   5818 /*
   5819  * delete all SAs for src/dst.  Called from key_delete().
   5820  */
   5821 static int
   5822 key_delete_all(struct socket *so, struct mbuf *m,
   5823 	       const struct sadb_msghdr *mhp, u_int16_t proto)
   5824 {
   5825 	struct sadb_address *src0, *dst0;
   5826 	struct secasindex saidx;
   5827 	struct secashead *sah;
   5828 	struct secasvar *sav, *nextsav;
   5829 	u_int stateidx, state;
   5830 	int error;
   5831 
   5832 	src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
   5833 	dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
   5834 
   5835 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
   5836 				     dst0 + 1, &saidx)) != 0)
   5837 		return key_senderror(so, m, EINVAL);
   5838 
   5839 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5840 		return key_senderror(so, m, EINVAL);
   5841 
   5842 	LIST_FOREACH(sah, &sahtree, chain) {
   5843 		if (sah->state == SADB_SASTATE_DEAD)
   5844 			continue;
   5845 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
   5846 			continue;
   5847 
   5848 		/* Delete all non-LARVAL SAs. */
   5849 		for (stateidx = 0;
   5850 		     stateidx < _ARRAYLEN(saorder_state_alive);
   5851 		     stateidx++) {
   5852 			state = saorder_state_alive[stateidx];
   5853 			if (state == SADB_SASTATE_LARVAL)
   5854 				continue;
   5855 			for (sav = LIST_FIRST(&sah->savtree[state]);
   5856 			     sav != NULL; sav = nextsav) {
   5857 				nextsav = LIST_NEXT(sav, chain);
   5858 				/* sanity check */
   5859 				if (sav->state != state) {
   5860 					ipseclog((LOG_DEBUG, "key_delete_all: "
   5861 					       "invalid sav->state "
   5862 					       "(queue: %d SA: %d)\n",
   5863 					       state, sav->state));
   5864 					continue;
   5865 				}
   5866 
   5867 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   5868 				KEY_FREESAV(&sav);
   5869 			}
   5870 		}
   5871 	}
   5872     {
   5873 	struct mbuf *n;
   5874 	struct sadb_msg *newmsg;
   5875 
   5876 	/* create new sadb_msg to reply. */
   5877 	n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
   5878 	    SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
   5879 	if (!n)
   5880 		return key_senderror(so, m, ENOBUFS);
   5881 
   5882 	if (n->m_len < sizeof(struct sadb_msg)) {
   5883 		n = m_pullup(n, sizeof(struct sadb_msg));
   5884 		if (n == NULL)
   5885 			return key_senderror(so, m, ENOBUFS);
   5886 	}
   5887 	newmsg = mtod(n, struct sadb_msg *);
   5888 	newmsg->sadb_msg_errno = 0;
   5889 	newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
   5890 
   5891 	m_freem(m);
   5892 	return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
   5893     }
   5894 }
   5895 
   5896 /*
   5897  * SADB_GET processing
   5898  * receive
   5899  *   <base, SA(*), address(SD)>
   5900  * from the ikmpd, and get a SP and a SA to respond,
   5901  * and send,
   5902  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
   5903  *       (identity(SD),) (sensitivity)>
   5904  * to the ikmpd.
   5905  *
   5906  * m will always be freed.
   5907  */
   5908 static int
   5909 key_get(struct socket *so, struct mbuf *m,
   5910 	const struct sadb_msghdr *mhp)
   5911 {
   5912 	struct sadb_sa *sa0;
   5913 	struct sadb_address *src0, *dst0;
   5914 	struct secasindex saidx;
   5915 	struct secashead *sah;
   5916 	struct secasvar *sav = NULL;
   5917 	u_int16_t proto;
   5918 	int error;
   5919 
   5920 	/* sanity check */
   5921 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   5922 		panic("key_get: NULL pointer is passed");
   5923 
   5924 	/* map satype to proto */
   5925 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   5926 		ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
   5927 		return key_senderror(so, m, EINVAL);
   5928 	}
   5929 
   5930 	if (mhp->ext[SADB_EXT_SA] == NULL ||
   5931 	    mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   5932 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
   5933 		ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
   5934 		return key_senderror(so, m, EINVAL);
   5935 	}
   5936 	if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
   5937 	    mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   5938 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
   5939 		ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
   5940 		return key_senderror(so, m, EINVAL);
   5941 	}
   5942 
   5943 	sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
   5944 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
   5945 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
   5946 
   5947 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
   5948 				     dst0 + 1, &saidx)) != 0)
   5949 		return key_senderror(so, m, EINVAL);
   5950 
   5951 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   5952 		return key_senderror(so, m, EINVAL);
   5953 
   5954 	/* get a SA header */
   5955 	LIST_FOREACH(sah, &sahtree, chain) {
   5956 		if (sah->state == SADB_SASTATE_DEAD)
   5957 			continue;
   5958 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
   5959 			continue;
   5960 
   5961 		/* get a SA with SPI. */
   5962 		sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
   5963 		if (sav)
   5964 			break;
   5965 	}
   5966 	if (sah == NULL) {
   5967 		ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
   5968 		return key_senderror(so, m, ENOENT);
   5969 	}
   5970 
   5971     {
   5972 	struct mbuf *n;
   5973 	u_int8_t satype;
   5974 
   5975 	/* map proto to satype */
   5976 	if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
   5977 		ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
   5978 		return key_senderror(so, m, EINVAL);
   5979 	}
   5980 
   5981 	/* create new sadb_msg to reply. */
   5982 	n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
   5983 	    mhp->msg->sadb_msg_pid);
   5984 	if (!n)
   5985 		return key_senderror(so, m, ENOBUFS);
   5986 
   5987 	m_freem(m);
   5988 	return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
   5989     }
   5990 }
   5991 
   5992 /* XXX make it sysctl-configurable? */
   5993 static void
   5994 key_getcomb_setlifetime(struct sadb_comb *comb)
   5995 {
   5996 
   5997 	comb->sadb_comb_soft_allocations = 1;
   5998 	comb->sadb_comb_hard_allocations = 1;
   5999 	comb->sadb_comb_soft_bytes = 0;
   6000 	comb->sadb_comb_hard_bytes = 0;
   6001 	comb->sadb_comb_hard_addtime = 86400;	/* 1 day */
   6002 	comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
   6003 	comb->sadb_comb_soft_usetime = 28800;	/* 8 hours */
   6004 	comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
   6005 }
   6006 
   6007 /*
   6008  * XXX reorder combinations by preference
   6009  * XXX no idea if the user wants ESP authentication or not
   6010  */
   6011 static struct mbuf *
   6012 key_getcomb_esp(void)
   6013 {
   6014 	struct sadb_comb *comb;
   6015 	const struct enc_xform *algo;
   6016 	struct mbuf *result = NULL, *m, *n;
   6017 	int encmin;
   6018 	int i, off, o;
   6019 	int totlen;
   6020 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   6021 
   6022 	m = NULL;
   6023 	for (i = 1; i <= SADB_EALG_MAX; i++) {
   6024 		algo = esp_algorithm_lookup(i);
   6025 		if (algo == NULL)
   6026 			continue;
   6027 
   6028 		/* discard algorithms with key size smaller than system min */
   6029 		if (_BITS(algo->maxkey) < ipsec_esp_keymin)
   6030 			continue;
   6031 		if (_BITS(algo->minkey) < ipsec_esp_keymin)
   6032 			encmin = ipsec_esp_keymin;
   6033 		else
   6034 			encmin = _BITS(algo->minkey);
   6035 
   6036 		if (ipsec_esp_auth)
   6037 			m = key_getcomb_ah();
   6038 		else {
   6039 			IPSEC_ASSERT(l <= MLEN,
   6040 				("key_getcomb_esp: l=%u > MLEN=%lu",
   6041 				l, (u_long) MLEN));
   6042 			MGET(m, M_DONTWAIT, MT_DATA);
   6043 			if (m) {
   6044 				M_ALIGN(m, l);
   6045 				m->m_len = l;
   6046 				m->m_next = NULL;
   6047 				memset(mtod(m, void *), 0, m->m_len);
   6048 			}
   6049 		}
   6050 		if (!m)
   6051 			goto fail;
   6052 
   6053 		totlen = 0;
   6054 		for (n = m; n; n = n->m_next)
   6055 			totlen += n->m_len;
   6056 		IPSEC_ASSERT((totlen % l) == 0,
   6057 			("key_getcomb_esp: totlen=%u, l=%u", totlen, l));
   6058 
   6059 		for (off = 0; off < totlen; off += l) {
   6060 			n = m_pulldown(m, off, l, &o);
   6061 			if (!n) {
   6062 				/* m is already freed */
   6063 				goto fail;
   6064 			}
   6065 			comb = (struct sadb_comb *)(mtod(n, char *) + o);
   6066 			memset(comb, 0, sizeof(*comb));
   6067 			key_getcomb_setlifetime(comb);
   6068 			comb->sadb_comb_encrypt = i;
   6069 			comb->sadb_comb_encrypt_minbits = encmin;
   6070 			comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
   6071 		}
   6072 
   6073 		if (!result)
   6074 			result = m;
   6075 		else
   6076 			m_cat(result, m);
   6077 	}
   6078 
   6079 	return result;
   6080 
   6081  fail:
   6082 	if (result)
   6083 		m_freem(result);
   6084 	return NULL;
   6085 }
   6086 
   6087 static void
   6088 key_getsizes_ah(const struct auth_hash *ah, int alg,
   6089 	        u_int16_t* ksmin, u_int16_t* ksmax)
   6090 {
   6091 	*ksmin = *ksmax = ah->keysize;
   6092 	if (ah->keysize == 0) {
   6093 		/*
   6094 		 * Transform takes arbitrary key size but algorithm
   6095 		 * key size is restricted.  Enforce this here.
   6096 		 */
   6097 		switch (alg) {
   6098 		case SADB_X_AALG_MD5:	*ksmin = *ksmax = 16; break;
   6099 		case SADB_X_AALG_SHA:	*ksmin = *ksmax = 20; break;
   6100 		case SADB_X_AALG_NULL:	*ksmin = 1; *ksmax = 256; break;
   6101 		default:
   6102 			DPRINTF(("key_getsizes_ah: unknown AH algorithm %u\n",
   6103 				alg));
   6104 			break;
   6105 		}
   6106 	}
   6107 }
   6108 
   6109 /*
   6110  * XXX reorder combinations by preference
   6111  */
   6112 static struct mbuf *
   6113 key_getcomb_ah(void)
   6114 {
   6115 	struct sadb_comb *comb;
   6116 	const struct auth_hash *algo;
   6117 	struct mbuf *m;
   6118 	u_int16_t minkeysize, maxkeysize;
   6119 	int i;
   6120 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   6121 
   6122 	m = NULL;
   6123 	for (i = 1; i <= SADB_AALG_MAX; i++) {
   6124 #if 1
   6125 		/* we prefer HMAC algorithms, not old algorithms */
   6126 		if (i != SADB_AALG_SHA1HMAC &&
   6127 		    i != SADB_AALG_MD5HMAC &&
   6128 		    i != SADB_X_AALG_SHA2_256 &&
   6129 		    i != SADB_X_AALG_SHA2_384 &&
   6130 		    i != SADB_X_AALG_SHA2_512)
   6131 			continue;
   6132 #endif
   6133 		algo = ah_algorithm_lookup(i);
   6134 		if (!algo)
   6135 			continue;
   6136 		key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
   6137 		/* discard algorithms with key size smaller than system min */
   6138 		if (_BITS(minkeysize) < ipsec_ah_keymin)
   6139 			continue;
   6140 
   6141 		if (!m) {
   6142 			IPSEC_ASSERT(l <= MLEN,
   6143 				("key_getcomb_ah: l=%u > MLEN=%lu",
   6144 				l, (u_long) MLEN));
   6145 			MGET(m, M_DONTWAIT, MT_DATA);
   6146 			if (m) {
   6147 				M_ALIGN(m, l);
   6148 				m->m_len = l;
   6149 				m->m_next = NULL;
   6150 			}
   6151 		} else
   6152 			M_PREPEND(m, l, M_DONTWAIT);
   6153 		if (!m)
   6154 			return NULL;
   6155 
   6156 		comb = mtod(m, struct sadb_comb *);
   6157 		memset(comb, 0, sizeof(*comb));
   6158 		key_getcomb_setlifetime(comb);
   6159 		comb->sadb_comb_auth = i;
   6160 		comb->sadb_comb_auth_minbits = _BITS(minkeysize);
   6161 		comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
   6162 	}
   6163 
   6164 	return m;
   6165 }
   6166 
   6167 /*
   6168  * not really an official behavior.  discussed in pf_key (at) inner.net in Sep2000.
   6169  * XXX reorder combinations by preference
   6170  */
   6171 static struct mbuf *
   6172 key_getcomb_ipcomp(void)
   6173 {
   6174 	struct sadb_comb *comb;
   6175 	const struct comp_algo *algo;
   6176 	struct mbuf *m;
   6177 	int i;
   6178 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
   6179 
   6180 	m = NULL;
   6181 	for (i = 1; i <= SADB_X_CALG_MAX; i++) {
   6182 		algo = ipcomp_algorithm_lookup(i);
   6183 		if (!algo)
   6184 			continue;
   6185 
   6186 		if (!m) {
   6187 			IPSEC_ASSERT(l <= MLEN,
   6188 				("key_getcomb_ipcomp: l=%u > MLEN=%lu",
   6189 				l, (u_long) MLEN));
   6190 			MGET(m, M_DONTWAIT, MT_DATA);
   6191 			if (m) {
   6192 				M_ALIGN(m, l);
   6193 				m->m_len = l;
   6194 				m->m_next = NULL;
   6195 			}
   6196 		} else
   6197 			M_PREPEND(m, l, M_DONTWAIT);
   6198 		if (!m)
   6199 			return NULL;
   6200 
   6201 		comb = mtod(m, struct sadb_comb *);
   6202 		memset(comb, 0, sizeof(*comb));
   6203 		key_getcomb_setlifetime(comb);
   6204 		comb->sadb_comb_encrypt = i;
   6205 		/* what should we set into sadb_comb_*_{min,max}bits? */
   6206 	}
   6207 
   6208 	return m;
   6209 }
   6210 
   6211 /*
   6212  * XXX no way to pass mode (transport/tunnel) to userland
   6213  * XXX replay checking?
   6214  * XXX sysctl interface to ipsec_{ah,esp}_keymin
   6215  */
   6216 static struct mbuf *
   6217 key_getprop(const struct secasindex *saidx)
   6218 {
   6219 	struct sadb_prop *prop;
   6220 	struct mbuf *m, *n;
   6221 	const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
   6222 	int totlen;
   6223 
   6224 	switch (saidx->proto)  {
   6225 	case IPPROTO_ESP:
   6226 		m = key_getcomb_esp();
   6227 		break;
   6228 	case IPPROTO_AH:
   6229 		m = key_getcomb_ah();
   6230 		break;
   6231 	case IPPROTO_IPCOMP:
   6232 		m = key_getcomb_ipcomp();
   6233 		break;
   6234 	default:
   6235 		return NULL;
   6236 	}
   6237 
   6238 	if (!m)
   6239 		return NULL;
   6240 	M_PREPEND(m, l, M_DONTWAIT);
   6241 	if (!m)
   6242 		return NULL;
   6243 
   6244 	totlen = 0;
   6245 	for (n = m; n; n = n->m_next)
   6246 		totlen += n->m_len;
   6247 
   6248 	prop = mtod(m, struct sadb_prop *);
   6249 	memset(prop, 0, sizeof(*prop));
   6250 	prop->sadb_prop_len = PFKEY_UNIT64(totlen);
   6251 	prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
   6252 	prop->sadb_prop_replay = 32;	/* XXX */
   6253 
   6254 	return m;
   6255 }
   6256 
   6257 /*
   6258  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
   6259  * send
   6260  *   <base, SA, address(SD), (address(P)), x_policy,
   6261  *       (identity(SD),) (sensitivity,) proposal>
   6262  * to KMD, and expect to receive
   6263  *   <base> with SADB_ACQUIRE if error occurred,
   6264  * or
   6265  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
   6266  * from KMD by PF_KEY.
   6267  *
   6268  * XXX x_policy is outside of RFC2367 (KAME extension).
   6269  * XXX sensitivity is not supported.
   6270  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
   6271  * see comment for key_getcomb_ipcomp().
   6272  *
   6273  * OUT:
   6274  *    0     : succeed
   6275  *    others: error number
   6276  */
   6277 static int
   6278 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
   6279 {
   6280 	struct mbuf *result = NULL, *m;
   6281 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6282 	struct secacq *newacq;
   6283 #endif
   6284 	u_int8_t satype;
   6285 	int error = -1;
   6286 	u_int32_t seq;
   6287 
   6288 	/* sanity check */
   6289 	IPSEC_ASSERT(saidx != NULL, ("key_acquire: null saidx"));
   6290 	satype = key_proto2satype(saidx->proto);
   6291 	IPSEC_ASSERT(satype != 0,
   6292 		("key_acquire: null satype, protocol %u", saidx->proto));
   6293 
   6294 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6295 	/*
   6296 	 * We never do anything about acquirng SA.  There is anather
   6297 	 * solution that kernel blocks to send SADB_ACQUIRE message until
   6298 	 * getting something message from IKEd.  In later case, to be
   6299 	 * managed with ACQUIRING list.
   6300 	 */
   6301 	/* Get an entry to check whether sending message or not. */
   6302 	if ((newacq = key_getacq(saidx)) != NULL) {
   6303 		if (key_blockacq_count < newacq->count) {
   6304 			/* reset counter and do send message. */
   6305 			newacq->count = 0;
   6306 		} else {
   6307 			/* increment counter and do nothing. */
   6308 			newacq->count++;
   6309 			return 0;
   6310 		}
   6311 	} else {
   6312 		/* make new entry for blocking to send SADB_ACQUIRE. */
   6313 		if ((newacq = key_newacq(saidx)) == NULL)
   6314 			return ENOBUFS;
   6315 
   6316 		/* add to acqtree */
   6317 		LIST_INSERT_HEAD(&acqtree, newacq, chain);
   6318 	}
   6319 #endif
   6320 
   6321 
   6322 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6323 	seq = newacq->seq;
   6324 #else
   6325 	seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
   6326 #endif
   6327 	m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
   6328 	if (!m) {
   6329 		error = ENOBUFS;
   6330 		goto fail;
   6331 	}
   6332 	result = m;
   6333 
   6334 	/* set sadb_address for saidx's. */
   6335 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   6336 	    &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
   6337 	if (!m) {
   6338 		error = ENOBUFS;
   6339 		goto fail;
   6340 	}
   6341 	m_cat(result, m);
   6342 
   6343 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   6344 	    &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
   6345 	if (!m) {
   6346 		error = ENOBUFS;
   6347 		goto fail;
   6348 	}
   6349 	m_cat(result, m);
   6350 
   6351 	/* XXX proxy address (optional) */
   6352 
   6353 	/* set sadb_x_policy */
   6354 	if (sp) {
   6355 		m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
   6356 		if (!m) {
   6357 			error = ENOBUFS;
   6358 			goto fail;
   6359 		}
   6360 		m_cat(result, m);
   6361 	}
   6362 
   6363 	/* XXX identity (optional) */
   6364 #if 0
   6365 	if (idexttype && fqdn) {
   6366 		/* create identity extension (FQDN) */
   6367 		struct sadb_ident *id;
   6368 		int fqdnlen;
   6369 
   6370 		fqdnlen = strlen(fqdn) + 1;	/* +1 for terminating-NUL */
   6371 		id = (struct sadb_ident *)p;
   6372 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
   6373 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
   6374 		id->sadb_ident_exttype = idexttype;
   6375 		id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
   6376 		memcpy(id + 1, fqdn, fqdnlen);
   6377 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
   6378 	}
   6379 
   6380 	if (idexttype) {
   6381 		/* create identity extension (USERFQDN) */
   6382 		struct sadb_ident *id;
   6383 		int userfqdnlen;
   6384 
   6385 		if (userfqdn) {
   6386 			/* +1 for terminating-NUL */
   6387 			userfqdnlen = strlen(userfqdn) + 1;
   6388 		} else
   6389 			userfqdnlen = 0;
   6390 		id = (struct sadb_ident *)p;
   6391 		memset(id, 0, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
   6392 		id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
   6393 		id->sadb_ident_exttype = idexttype;
   6394 		id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
   6395 		/* XXX is it correct? */
   6396 		if (curlwp)
   6397 			id->sadb_ident_id = kauth_cred_getuid(curlwp->l_cred);
   6398 		if (userfqdn && userfqdnlen)
   6399 			memcpy(id + 1, userfqdn, userfqdnlen);
   6400 		p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
   6401 	}
   6402 #endif
   6403 
   6404 	/* XXX sensitivity (optional) */
   6405 
   6406 	/* create proposal/combination extension */
   6407 	m = key_getprop(saidx);
   6408 #if 0
   6409 	/*
   6410 	 * spec conformant: always attach proposal/combination extension,
   6411 	 * the problem is that we have no way to attach it for ipcomp,
   6412 	 * due to the way sadb_comb is declared in RFC2367.
   6413 	 */
   6414 	if (!m) {
   6415 		error = ENOBUFS;
   6416 		goto fail;
   6417 	}
   6418 	m_cat(result, m);
   6419 #else
   6420 	/*
   6421 	 * outside of spec; make proposal/combination extension optional.
   6422 	 */
   6423 	if (m)
   6424 		m_cat(result, m);
   6425 #endif
   6426 
   6427 	if ((result->m_flags & M_PKTHDR) == 0) {
   6428 		error = EINVAL;
   6429 		goto fail;
   6430 	}
   6431 
   6432 	if (result->m_len < sizeof(struct sadb_msg)) {
   6433 		result = m_pullup(result, sizeof(struct sadb_msg));
   6434 		if (result == NULL) {
   6435 			error = ENOBUFS;
   6436 			goto fail;
   6437 		}
   6438 	}
   6439 
   6440 	result->m_pkthdr.len = 0;
   6441 	for (m = result; m; m = m->m_next)
   6442 		result->m_pkthdr.len += m->m_len;
   6443 
   6444 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   6445 	    PFKEY_UNIT64(result->m_pkthdr.len);
   6446 
   6447 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   6448 
   6449  fail:
   6450 	if (result)
   6451 		m_freem(result);
   6452 	return error;
   6453 }
   6454 
   6455 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6456 static struct secacq *
   6457 key_newacq(const struct secasindex *saidx)
   6458 {
   6459 	struct secacq *newacq;
   6460 
   6461 	/* get new entry */
   6462 	KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
   6463 	if (newacq == NULL) {
   6464 		ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
   6465 		return NULL;
   6466 	}
   6467 	memset(newacq, 0, sizeof(*newacq));
   6468 
   6469 	/* copy secindex */
   6470 	memcpy(&newacq->saidx, saidx, sizeof(newacq->saidx));
   6471 	newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
   6472 	newacq->created = time_uptime;
   6473 	newacq->count = 0;
   6474 
   6475 	return newacq;
   6476 }
   6477 
   6478 static struct secacq *
   6479 key_getacq(const struct secasindex *saidx)
   6480 {
   6481 	struct secacq *acq;
   6482 
   6483 	LIST_FOREACH(acq, &acqtree, chain) {
   6484 		if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
   6485 			return acq;
   6486 	}
   6487 
   6488 	return NULL;
   6489 }
   6490 
   6491 static struct secacq *
   6492 key_getacqbyseq(u_int32_t seq)
   6493 {
   6494 	struct secacq *acq;
   6495 
   6496 	LIST_FOREACH(acq, &acqtree, chain) {
   6497 		if (acq->seq == seq)
   6498 			return acq;
   6499 	}
   6500 
   6501 	return NULL;
   6502 }
   6503 #endif
   6504 
   6505 static struct secspacq *
   6506 key_newspacq(const struct secpolicyindex *spidx)
   6507 {
   6508 	struct secspacq *acq;
   6509 
   6510 	/* get new entry */
   6511 	KMALLOC(acq, struct secspacq *, sizeof(struct secspacq));
   6512 	if (acq == NULL) {
   6513 		ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
   6514 		return NULL;
   6515 	}
   6516 	memset(acq, 0, sizeof(*acq));
   6517 
   6518 	/* copy secindex */
   6519 	memcpy(&acq->spidx, spidx, sizeof(acq->spidx));
   6520 	acq->created = time_uptime;
   6521 	acq->count = 0;
   6522 
   6523 	return acq;
   6524 }
   6525 
   6526 static struct secspacq *
   6527 key_getspacq(const struct secpolicyindex *spidx)
   6528 {
   6529 	struct secspacq *acq;
   6530 
   6531 	LIST_FOREACH(acq, &spacqtree, chain) {
   6532 		if (key_cmpspidx_exactly(spidx, &acq->spidx))
   6533 			return acq;
   6534 	}
   6535 
   6536 	return NULL;
   6537 }
   6538 
   6539 /*
   6540  * SADB_ACQUIRE processing,
   6541  * in first situation, is receiving
   6542  *   <base>
   6543  * from the ikmpd, and clear sequence of its secasvar entry.
   6544  *
   6545  * In second situation, is receiving
   6546  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
   6547  * from a user land process, and return
   6548  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
   6549  * to the socket.
   6550  *
   6551  * m will always be freed.
   6552  */
   6553 static int
   6554 key_acquire2(struct socket *so, struct mbuf *m,
   6555       	     const struct sadb_msghdr *mhp)
   6556 {
   6557 	const struct sadb_address *src0, *dst0;
   6558 	struct secasindex saidx;
   6559 	struct secashead *sah;
   6560 	u_int16_t proto;
   6561 	int error;
   6562 
   6563 	/* sanity check */
   6564 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   6565 		panic("key_acquire2: NULL pointer is passed");
   6566 
   6567 	/*
   6568 	 * Error message from KMd.
   6569 	 * We assume that if error was occurred in IKEd, the length of PFKEY
   6570 	 * message is equal to the size of sadb_msg structure.
   6571 	 * We do not raise error even if error occurred in this function.
   6572 	 */
   6573 	if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
   6574 #ifndef IPSEC_NONBLOCK_ACQUIRE
   6575 		struct secacq *acq;
   6576 
   6577 		/* check sequence number */
   6578 		if (mhp->msg->sadb_msg_seq == 0) {
   6579 			ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
   6580 			m_freem(m);
   6581 			return 0;
   6582 		}
   6583 
   6584 		if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
   6585 			/*
   6586 			 * the specified larval SA is already gone, or we got
   6587 			 * a bogus sequence number.  we can silently ignore it.
   6588 			 */
   6589 			m_freem(m);
   6590 			return 0;
   6591 		}
   6592 
   6593 		/* reset acq counter in order to deletion by timehander. */
   6594 		acq->created = time_uptime;
   6595 		acq->count = 0;
   6596 #endif
   6597 		m_freem(m);
   6598 		return 0;
   6599 	}
   6600 
   6601 	/*
   6602 	 * This message is from user land.
   6603 	 */
   6604 
   6605 	/* map satype to proto */
   6606 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   6607 		ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
   6608 		return key_senderror(so, m, EINVAL);
   6609 	}
   6610 
   6611 	if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
   6612 	    mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
   6613 	    mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
   6614 		/* error */
   6615 		ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
   6616 		return key_senderror(so, m, EINVAL);
   6617 	}
   6618 	if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
   6619 	    mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
   6620 	    mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
   6621 		/* error */
   6622 		ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
   6623 		return key_senderror(so, m, EINVAL);
   6624 	}
   6625 
   6626 	src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
   6627 	dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
   6628 
   6629 	if ((error = key_setsecasidx(proto, IPSEC_MODE_ANY, 0, src0 + 1,
   6630 				     dst0 + 1, &saidx)) != 0)
   6631 		return key_senderror(so, m, EINVAL);
   6632 
   6633 	if ((error = key_set_natt_ports(&saidx.src, &saidx.dst, mhp)) != 0)
   6634 		return key_senderror(so, m, EINVAL);
   6635 
   6636 	/* get a SA index */
   6637 	LIST_FOREACH(sah, &sahtree, chain) {
   6638 		if (sah->state == SADB_SASTATE_DEAD)
   6639 			continue;
   6640 		if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
   6641 			break;
   6642 	}
   6643 	if (sah != NULL) {
   6644 		ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
   6645 		return key_senderror(so, m, EEXIST);
   6646 	}
   6647 
   6648 	error = key_acquire(&saidx, NULL);
   6649 	if (error != 0) {
   6650 		ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
   6651 			"from key_acquire.\n", mhp->msg->sadb_msg_errno));
   6652 		return key_senderror(so, m, error);
   6653 	}
   6654 
   6655 	return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
   6656 }
   6657 
   6658 /*
   6659  * SADB_REGISTER processing.
   6660  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
   6661  * receive
   6662  *   <base>
   6663  * from the ikmpd, and register a socket to send PF_KEY messages,
   6664  * and send
   6665  *   <base, supported>
   6666  * to KMD by PF_KEY.
   6667  * If socket is detached, must free from regnode.
   6668  *
   6669  * m will always be freed.
   6670  */
   6671 static int
   6672 key_register(struct socket *so, struct mbuf *m,
   6673 	     const struct sadb_msghdr *mhp)
   6674 {
   6675 	struct secreg *reg, *newreg = 0;
   6676 
   6677 	/* sanity check */
   6678 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   6679 		panic("key_register: NULL pointer is passed");
   6680 
   6681 	/* check for invalid register message */
   6682 	if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
   6683 		return key_senderror(so, m, EINVAL);
   6684 
   6685 	/* When SATYPE_UNSPEC is specified, only return sabd_supported. */
   6686 	if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
   6687 		goto setmsg;
   6688 
   6689 	/* check whether existing or not */
   6690 	LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
   6691 		if (reg->so == so) {
   6692 			ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
   6693 			return key_senderror(so, m, EEXIST);
   6694 		}
   6695 	}
   6696 
   6697 	/* create regnode */
   6698 	KMALLOC(newreg, struct secreg *, sizeof(*newreg));
   6699 	if (newreg == NULL) {
   6700 		ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
   6701 		return key_senderror(so, m, ENOBUFS);
   6702 	}
   6703 	memset(newreg, 0, sizeof(*newreg));
   6704 
   6705 	newreg->so = so;
   6706 	((struct keycb *)sotorawcb(so))->kp_registered++;
   6707 
   6708 	/* add regnode to regtree. */
   6709 	LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
   6710 
   6711   setmsg:
   6712     {
   6713 	struct mbuf *n;
   6714 	struct sadb_msg *newmsg;
   6715 	struct sadb_supported *sup;
   6716 	u_int len, alen, elen;
   6717 	int off;
   6718 	int i;
   6719 	struct sadb_alg *alg;
   6720 
   6721 	/* create new sadb_msg to reply. */
   6722 	alen = 0;
   6723 	for (i = 1; i <= SADB_AALG_MAX; i++) {
   6724 		if (ah_algorithm_lookup(i))
   6725 			alen += sizeof(struct sadb_alg);
   6726 	}
   6727 	if (alen)
   6728 		alen += sizeof(struct sadb_supported);
   6729 	elen = 0;
   6730 	for (i = 1; i <= SADB_EALG_MAX; i++) {
   6731 		if (esp_algorithm_lookup(i))
   6732 			elen += sizeof(struct sadb_alg);
   6733 	}
   6734 	if (elen)
   6735 		elen += sizeof(struct sadb_supported);
   6736 
   6737 	len = sizeof(struct sadb_msg) + alen + elen;
   6738 
   6739 	if (len > MCLBYTES)
   6740 		return key_senderror(so, m, ENOBUFS);
   6741 
   6742 	MGETHDR(n, M_DONTWAIT, MT_DATA);
   6743 	if (len > MHLEN) {
   6744 		MCLGET(n, M_DONTWAIT);
   6745 		if ((n->m_flags & M_EXT) == 0) {
   6746 			m_freem(n);
   6747 			n = NULL;
   6748 		}
   6749 	}
   6750 	if (!n)
   6751 		return key_senderror(so, m, ENOBUFS);
   6752 
   6753 	n->m_pkthdr.len = n->m_len = len;
   6754 	n->m_next = NULL;
   6755 	off = 0;
   6756 
   6757 	m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, char *) + off);
   6758 	newmsg = mtod(n, struct sadb_msg *);
   6759 	newmsg->sadb_msg_errno = 0;
   6760 	newmsg->sadb_msg_len = PFKEY_UNIT64(len);
   6761 	off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
   6762 
   6763 	/* for authentication algorithm */
   6764 	if (alen) {
   6765 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
   6766 		sup->sadb_supported_len = PFKEY_UNIT64(alen);
   6767 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
   6768 		off += PFKEY_ALIGN8(sizeof(*sup));
   6769 
   6770 		for (i = 1; i <= SADB_AALG_MAX; i++) {
   6771 			const struct auth_hash *aalgo;
   6772 			u_int16_t minkeysize, maxkeysize;
   6773 
   6774 			aalgo = ah_algorithm_lookup(i);
   6775 			if (!aalgo)
   6776 				continue;
   6777 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
   6778 			alg->sadb_alg_id = i;
   6779 			alg->sadb_alg_ivlen = 0;
   6780 			key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
   6781 			alg->sadb_alg_minbits = _BITS(minkeysize);
   6782 			alg->sadb_alg_maxbits = _BITS(maxkeysize);
   6783 			off += PFKEY_ALIGN8(sizeof(*alg));
   6784 		}
   6785 	}
   6786 
   6787 	/* for encryption algorithm */
   6788 	if (elen) {
   6789 		sup = (struct sadb_supported *)(mtod(n, char *) + off);
   6790 		sup->sadb_supported_len = PFKEY_UNIT64(elen);
   6791 		sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
   6792 		off += PFKEY_ALIGN8(sizeof(*sup));
   6793 
   6794 		for (i = 1; i <= SADB_EALG_MAX; i++) {
   6795 			const struct enc_xform *ealgo;
   6796 
   6797 			ealgo = esp_algorithm_lookup(i);
   6798 			if (!ealgo)
   6799 				continue;
   6800 			alg = (struct sadb_alg *)(mtod(n, char *) + off);
   6801 			alg->sadb_alg_id = i;
   6802 			alg->sadb_alg_ivlen = ealgo->blocksize;
   6803 			alg->sadb_alg_minbits = _BITS(ealgo->minkey);
   6804 			alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
   6805 			off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
   6806 		}
   6807 	}
   6808 
   6809 #ifdef DIAGNOSTIC
   6810 	if (off != len)
   6811 		panic("length assumption failed in key_register");
   6812 #endif
   6813 
   6814 	m_freem(m);
   6815 	return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
   6816     }
   6817 }
   6818 
   6819 /*
   6820  * free secreg entry registered.
   6821  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
   6822  */
   6823 void
   6824 key_freereg(struct socket *so)
   6825 {
   6826 	struct secreg *reg;
   6827 	int i;
   6828 
   6829 	/* sanity check */
   6830 	if (so == NULL)
   6831 		panic("key_freereg: NULL pointer is passed");
   6832 
   6833 	/*
   6834 	 * check whether existing or not.
   6835 	 * check all type of SA, because there is a potential that
   6836 	 * one socket is registered to multiple type of SA.
   6837 	 */
   6838 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
   6839 		LIST_FOREACH(reg, &regtree[i], chain) {
   6840 			if (reg->so == so
   6841 			 && __LIST_CHAINED(reg)) {
   6842 				LIST_REMOVE(reg, chain);
   6843 				KFREE(reg);
   6844 				break;
   6845 			}
   6846 		}
   6847 	}
   6848 
   6849 	return;
   6850 }
   6851 
   6852 /*
   6853  * SADB_EXPIRE processing
   6854  * send
   6855  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
   6856  * to KMD by PF_KEY.
   6857  * NOTE: We send only soft lifetime extension.
   6858  *
   6859  * OUT:	0	: succeed
   6860  *	others	: error number
   6861  */
   6862 static int
   6863 key_expire(struct secasvar *sav)
   6864 {
   6865 	int s;
   6866 	int satype;
   6867 	struct mbuf *result = NULL, *m;
   6868 	int len;
   6869 	int error = -1;
   6870 	struct sadb_lifetime *lt;
   6871 
   6872 	/* XXX: Why do we lock ? */
   6873 	s = splsoftnet();	/*called from softclock()*/
   6874 
   6875 	/* sanity check */
   6876 	if (sav == NULL)
   6877 		panic("key_expire: NULL pointer is passed");
   6878 	if (sav->sah == NULL)
   6879 		panic("key_expire: Why was SA index in SA NULL");
   6880 	if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
   6881 		panic("key_expire: invalid proto is passed");
   6882 
   6883 	/* set msg header */
   6884 	m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
   6885 	if (!m) {
   6886 		error = ENOBUFS;
   6887 		goto fail;
   6888 	}
   6889 	result = m;
   6890 
   6891 	/* create SA extension */
   6892 	m = key_setsadbsa(sav);
   6893 	if (!m) {
   6894 		error = ENOBUFS;
   6895 		goto fail;
   6896 	}
   6897 	m_cat(result, m);
   6898 
   6899 	/* create SA extension */
   6900 	m = key_setsadbxsa2(sav->sah->saidx.mode,
   6901 			sav->replay ? sav->replay->count : 0,
   6902 			sav->sah->saidx.reqid);
   6903 	if (!m) {
   6904 		error = ENOBUFS;
   6905 		goto fail;
   6906 	}
   6907 	m_cat(result, m);
   6908 
   6909 	/* create lifetime extension (current and soft) */
   6910 	len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
   6911 	m = key_alloc_mbuf(len);
   6912 	if (!m || m->m_next) {	/*XXX*/
   6913 		if (m)
   6914 			m_freem(m);
   6915 		error = ENOBUFS;
   6916 		goto fail;
   6917 	}
   6918 	memset(mtod(m, void *), 0, len);
   6919 	lt = mtod(m, struct sadb_lifetime *);
   6920 	lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
   6921 	lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
   6922 	lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
   6923 	lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
   6924 	lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime
   6925 		+ time_second - time_uptime;
   6926 	lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime
   6927 		+ time_second - time_uptime;
   6928 	lt = (struct sadb_lifetime *)(mtod(m, char *) + len / 2);
   6929 	memcpy(lt, sav->lft_s, sizeof(*lt));
   6930 	m_cat(result, m);
   6931 
   6932 	/* set sadb_address for source */
   6933 	m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
   6934 	    &sav->sah->saidx.src.sa,
   6935 	    FULLMASK, IPSEC_ULPROTO_ANY);
   6936 	if (!m) {
   6937 		error = ENOBUFS;
   6938 		goto fail;
   6939 	}
   6940 	m_cat(result, m);
   6941 
   6942 	/* set sadb_address for destination */
   6943 	m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
   6944 	    &sav->sah->saidx.dst.sa,
   6945 	    FULLMASK, IPSEC_ULPROTO_ANY);
   6946 	if (!m) {
   6947 		error = ENOBUFS;
   6948 		goto fail;
   6949 	}
   6950 	m_cat(result, m);
   6951 
   6952 	if ((result->m_flags & M_PKTHDR) == 0) {
   6953 		error = EINVAL;
   6954 		goto fail;
   6955 	}
   6956 
   6957 	if (result->m_len < sizeof(struct sadb_msg)) {
   6958 		result = m_pullup(result, sizeof(struct sadb_msg));
   6959 		if (result == NULL) {
   6960 			error = ENOBUFS;
   6961 			goto fail;
   6962 		}
   6963 	}
   6964 
   6965 	result->m_pkthdr.len = 0;
   6966 	for (m = result; m; m = m->m_next)
   6967 		result->m_pkthdr.len += m->m_len;
   6968 
   6969 	mtod(result, struct sadb_msg *)->sadb_msg_len =
   6970 	    PFKEY_UNIT64(result->m_pkthdr.len);
   6971 
   6972 	splx(s);
   6973 	return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
   6974 
   6975  fail:
   6976 	if (result)
   6977 		m_freem(result);
   6978 	splx(s);
   6979 	return error;
   6980 }
   6981 
   6982 /*
   6983  * SADB_FLUSH processing
   6984  * receive
   6985  *   <base>
   6986  * from the ikmpd, and free all entries in secastree.
   6987  * and send,
   6988  *   <base>
   6989  * to the ikmpd.
   6990  * NOTE: to do is only marking SADB_SASTATE_DEAD.
   6991  *
   6992  * m will always be freed.
   6993  */
   6994 static int
   6995 key_flush(struct socket *so, struct mbuf *m,
   6996           const struct sadb_msghdr *mhp)
   6997 {
   6998 	struct sadb_msg *newmsg;
   6999 	struct secashead *sah, *nextsah;
   7000 	struct secasvar *sav, *nextsav;
   7001 	u_int16_t proto;
   7002 	u_int8_t state;
   7003 	u_int stateidx;
   7004 
   7005 	/* sanity check */
   7006 	if (so == NULL || mhp == NULL || mhp->msg == NULL)
   7007 		panic("key_flush: NULL pointer is passed");
   7008 
   7009 	/* map satype to proto */
   7010 	if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
   7011 		ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
   7012 		return key_senderror(so, m, EINVAL);
   7013 	}
   7014 
   7015 	/* no SATYPE specified, i.e. flushing all SA. */
   7016 	for (sah = LIST_FIRST(&sahtree);
   7017 	     sah != NULL;
   7018 	     sah = nextsah) {
   7019 		nextsah = LIST_NEXT(sah, chain);
   7020 
   7021 		if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
   7022 		 && proto != sah->saidx.proto)
   7023 			continue;
   7024 
   7025 		for (stateidx = 0;
   7026 		     stateidx < _ARRAYLEN(saorder_state_alive);
   7027 		     stateidx++) {
   7028 			state = saorder_state_any[stateidx];
   7029 			for (sav = LIST_FIRST(&sah->savtree[state]);
   7030 			     sav != NULL;
   7031 			     sav = nextsav) {
   7032 
   7033 				nextsav = LIST_NEXT(sav, chain);
   7034 
   7035 				key_sa_chgstate(sav, SADB_SASTATE_DEAD);
   7036 				KEY_FREESAV(&sav);
   7037 			}
   7038 		}
   7039 
   7040 		sah->state = SADB_SASTATE_DEAD;
   7041 	}
   7042 
   7043 	if (m->m_len < sizeof(struct sadb_msg) ||
   7044 	    sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
   7045 		ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
   7046 		return key_senderror(so, m, ENOBUFS);
   7047 	}
   7048 
   7049 	if (m->m_next)
   7050 		m_freem(m->m_next);
   7051 	m->m_next = NULL;
   7052 	m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
   7053 	newmsg = mtod(m, struct sadb_msg *);
   7054 	newmsg->sadb_msg_errno = 0;
   7055 	newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
   7056 
   7057 	return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7058 }
   7059 
   7060 
   7061 static struct mbuf *
   7062 key_setdump_chain(u_int8_t req_satype, int *errorp, int *lenp, pid_t pid)
   7063 {
   7064 	struct secashead *sah;
   7065 	struct secasvar *sav;
   7066 	u_int16_t proto;
   7067 	u_int stateidx;
   7068 	u_int8_t satype;
   7069 	u_int8_t state;
   7070 	int cnt;
   7071 	struct mbuf *m, *n, *prev;
   7072 
   7073 	*lenp = 0;
   7074 
   7075 	/* map satype to proto */
   7076 	if ((proto = key_satype2proto(req_satype)) == 0) {
   7077 		*errorp = EINVAL;
   7078 		return (NULL);
   7079 	}
   7080 
   7081 	/* count sav entries to be sent to userland. */
   7082 	cnt = 0;
   7083 	LIST_FOREACH(sah, &sahtree, chain) {
   7084 		if (req_satype != SADB_SATYPE_UNSPEC &&
   7085 		    proto != sah->saidx.proto)
   7086 			continue;
   7087 
   7088 		for (stateidx = 0;
   7089 		     stateidx < _ARRAYLEN(saorder_state_any);
   7090 		     stateidx++) {
   7091 			state = saorder_state_any[stateidx];
   7092 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   7093 				cnt++;
   7094 			}
   7095 		}
   7096 	}
   7097 
   7098 	if (cnt == 0) {
   7099 		*errorp = ENOENT;
   7100 		return (NULL);
   7101 	}
   7102 
   7103 	/* send this to the userland, one at a time. */
   7104 	m = NULL;
   7105 	prev = m;
   7106 	LIST_FOREACH(sah, &sahtree, chain) {
   7107 		if (req_satype != SADB_SATYPE_UNSPEC &&
   7108 		    proto != sah->saidx.proto)
   7109 			continue;
   7110 
   7111 		/* map proto to satype */
   7112 		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
   7113 			m_freem(m);
   7114 			*errorp = EINVAL;
   7115 			return (NULL);
   7116 		}
   7117 
   7118 		for (stateidx = 0;
   7119 		     stateidx < _ARRAYLEN(saorder_state_any);
   7120 		     stateidx++) {
   7121 			state = saorder_state_any[stateidx];
   7122 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   7123 				n = key_setdumpsa(sav, SADB_DUMP, satype,
   7124 				    --cnt, pid);
   7125 				if (!n) {
   7126 					m_freem(m);
   7127 					*errorp = ENOBUFS;
   7128 					return (NULL);
   7129 				}
   7130 
   7131 				if (!m)
   7132 					m = n;
   7133 				else
   7134 					prev->m_nextpkt = n;
   7135 				prev = n;
   7136 			}
   7137 		}
   7138 	}
   7139 
   7140 	if (!m) {
   7141 		*errorp = EINVAL;
   7142 		return (NULL);
   7143 	}
   7144 
   7145 	if ((m->m_flags & M_PKTHDR) != 0) {
   7146 		m->m_pkthdr.len = 0;
   7147 		for (n = m; n; n = n->m_next)
   7148 			m->m_pkthdr.len += n->m_len;
   7149 	}
   7150 
   7151 	*errorp = 0;
   7152 	return (m);
   7153 }
   7154 
   7155 /*
   7156  * SADB_DUMP processing
   7157  * dump all entries including status of DEAD in SAD.
   7158  * receive
   7159  *   <base>
   7160  * from the ikmpd, and dump all secasvar leaves
   7161  * and send,
   7162  *   <base> .....
   7163  * to the ikmpd.
   7164  *
   7165  * m will always be freed.
   7166  */
   7167 static int
   7168 key_dump(struct socket *so, struct mbuf *m0,
   7169 	 const struct sadb_msghdr *mhp)
   7170 {
   7171 	u_int16_t proto;
   7172 	u_int8_t satype;
   7173 	struct mbuf *n;
   7174 	int s;
   7175 	int error, len, ok;
   7176 
   7177 	/* sanity check */
   7178 	if (so == NULL || m0 == NULL || mhp == NULL || mhp->msg == NULL)
   7179 		panic("key_dump: NULL pointer is passed");
   7180 
   7181 	/* map satype to proto */
   7182 	satype = mhp->msg->sadb_msg_satype;
   7183 	if ((proto = key_satype2proto(satype)) == 0) {
   7184 		ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
   7185 		return key_senderror(so, m0, EINVAL);
   7186 	}
   7187 
   7188 	/*
   7189 	 * If the requestor has insufficient socket-buffer space
   7190 	 * for the entire chain, nobody gets any response to the DUMP.
   7191 	 * XXX For now, only the requestor ever gets anything.
   7192 	 * Moreover, if the requestor has any space at all, they receive
   7193 	 * the entire chain, otherwise the request is refused with ENOBUFS.
   7194 	 */
   7195 	if (sbspace(&so->so_rcv) <= 0) {
   7196 		return key_senderror(so, m0, ENOBUFS);
   7197 	}
   7198 
   7199 	s = splsoftnet();
   7200 	n = key_setdump_chain(satype, &error, &len, mhp->msg->sadb_msg_pid);
   7201 	splx(s);
   7202 
   7203 	if (n == NULL) {
   7204 		return key_senderror(so, m0, ENOENT);
   7205 	}
   7206 	{
   7207 		uint64_t *ps = PFKEY_STAT_GETREF();
   7208 		ps[PFKEY_STAT_IN_TOTAL]++;
   7209 		ps[PFKEY_STAT_IN_BYTES] += len;
   7210 		PFKEY_STAT_PUTREF();
   7211 	}
   7212 
   7213 	/*
   7214 	 * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
   7215 	 * The requestor receives either the entire chain, or an
   7216 	 * error message with ENOBUFS.
   7217 	 *
   7218 	 * sbappendaddrchain() takes the chain of entries, one
   7219 	 * packet-record per SPD entry, prepends the key_src sockaddr
   7220 	 * to each packet-record, links the sockaddr mbufs into a new
   7221 	 * list of records, then   appends the entire resulting
   7222 	 * list to the requesting socket.
   7223 	 */
   7224 	ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src,
   7225 	        n, SB_PRIO_ONESHOT_OVERFLOW);
   7226 
   7227 	if (!ok) {
   7228 		PFKEY_STATINC(PFKEY_STAT_IN_NOMEM);
   7229 		m_freem(n);
   7230 		return key_senderror(so, m0, ENOBUFS);
   7231 	}
   7232 
   7233 	m_freem(m0);
   7234 	return 0;
   7235 }
   7236 
   7237 /*
   7238  * SADB_X_PROMISC processing
   7239  *
   7240  * m will always be freed.
   7241  */
   7242 static int
   7243 key_promisc(struct socket *so, struct mbuf *m,
   7244 	    const struct sadb_msghdr *mhp)
   7245 {
   7246 	int olen;
   7247 
   7248 	/* sanity check */
   7249 	if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
   7250 		panic("key_promisc: NULL pointer is passed");
   7251 
   7252 	olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
   7253 
   7254 	if (olen < sizeof(struct sadb_msg)) {
   7255 #if 1
   7256 		return key_senderror(so, m, EINVAL);
   7257 #else
   7258 		m_freem(m);
   7259 		return 0;
   7260 #endif
   7261 	} else if (olen == sizeof(struct sadb_msg)) {
   7262 		/* enable/disable promisc mode */
   7263 		struct keycb *kp;
   7264 
   7265 		if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
   7266 			return key_senderror(so, m, EINVAL);
   7267 		mhp->msg->sadb_msg_errno = 0;
   7268 		switch (mhp->msg->sadb_msg_satype) {
   7269 		case 0:
   7270 		case 1:
   7271 			kp->kp_promisc = mhp->msg->sadb_msg_satype;
   7272 			break;
   7273 		default:
   7274 			return key_senderror(so, m, EINVAL);
   7275 		}
   7276 
   7277 		/* send the original message back to everyone */
   7278 		mhp->msg->sadb_msg_errno = 0;
   7279 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7280 	} else {
   7281 		/* send packet as is */
   7282 
   7283 		m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
   7284 
   7285 		/* TODO: if sadb_msg_seq is specified, send to specific pid */
   7286 		return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
   7287 	}
   7288 }
   7289 
   7290 static int (*key_typesw[]) (struct socket *, struct mbuf *,
   7291 		const struct sadb_msghdr *) = {
   7292 	NULL,		/* SADB_RESERVED */
   7293 	key_getspi,	/* SADB_GETSPI */
   7294 	key_update,	/* SADB_UPDATE */
   7295 	key_add,	/* SADB_ADD */
   7296 	key_delete,	/* SADB_DELETE */
   7297 	key_get,	/* SADB_GET */
   7298 	key_acquire2,	/* SADB_ACQUIRE */
   7299 	key_register,	/* SADB_REGISTER */
   7300 	NULL,		/* SADB_EXPIRE */
   7301 	key_flush,	/* SADB_FLUSH */
   7302 	key_dump,	/* SADB_DUMP */
   7303 	key_promisc,	/* SADB_X_PROMISC */
   7304 	NULL,		/* SADB_X_PCHANGE */
   7305 	key_spdadd,	/* SADB_X_SPDUPDATE */
   7306 	key_spdadd,	/* SADB_X_SPDADD */
   7307 	key_spddelete,	/* SADB_X_SPDDELETE */
   7308 	key_spdget,	/* SADB_X_SPDGET */
   7309 	NULL,		/* SADB_X_SPDACQUIRE */
   7310 	key_spddump,	/* SADB_X_SPDDUMP */
   7311 	key_spdflush,	/* SADB_X_SPDFLUSH */
   7312 	key_spdadd,	/* SADB_X_SPDSETIDX */
   7313 	NULL,		/* SADB_X_SPDEXPIRE */
   7314 	key_spddelete2,	/* SADB_X_SPDDELETE2 */
   7315 	key_nat_map,	/* SADB_X_NAT_T_NEW_MAPPING */
   7316 };
   7317 
   7318 /*
   7319  * parse sadb_msg buffer to process PFKEYv2,
   7320  * and create a data to response if needed.
   7321  * I think to be dealed with mbuf directly.
   7322  * IN:
   7323  *     msgp  : pointer to pointer to a received buffer pulluped.
   7324  *             This is rewrited to response.
   7325  *     so    : pointer to socket.
   7326  * OUT:
   7327  *    length for buffer to send to user process.
   7328  */
   7329 int
   7330 key_parse(struct mbuf *m, struct socket *so)
   7331 {
   7332 	struct sadb_msg *msg;
   7333 	struct sadb_msghdr mh;
   7334 	u_int orglen;
   7335 	int error;
   7336 	int target;
   7337 
   7338 	/* sanity check */
   7339 	if (m == NULL || so == NULL)
   7340 		panic("key_parse: NULL pointer is passed");
   7341 
   7342 #if 0	/*kdebug_sadb assumes msg in linear buffer*/
   7343 	KEYDEBUG(KEYDEBUG_KEY_DUMP,
   7344 		ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
   7345 		kdebug_sadb(msg));
   7346 #endif
   7347 
   7348 	if (m->m_len < sizeof(struct sadb_msg)) {
   7349 		m = m_pullup(m, sizeof(struct sadb_msg));
   7350 		if (!m)
   7351 			return ENOBUFS;
   7352 	}
   7353 	msg = mtod(m, struct sadb_msg *);
   7354 	orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
   7355 	target = KEY_SENDUP_ONE;
   7356 
   7357 	if ((m->m_flags & M_PKTHDR) == 0 ||
   7358 	    m->m_pkthdr.len != orglen) {
   7359 		ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
   7360 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7361 		error = EINVAL;
   7362 		goto senderror;
   7363 	}
   7364 
   7365 	if (msg->sadb_msg_version != PF_KEY_V2) {
   7366 		ipseclog((LOG_DEBUG,
   7367 		    "key_parse: PF_KEY version %u is mismatched.\n",
   7368 		    msg->sadb_msg_version));
   7369 		PFKEY_STATINC(PFKEY_STAT_OUT_INVVER);
   7370 		error = EINVAL;
   7371 		goto senderror;
   7372 	}
   7373 
   7374 	if (msg->sadb_msg_type > SADB_MAX) {
   7375 		ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
   7376 		    msg->sadb_msg_type));
   7377 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
   7378 		error = EINVAL;
   7379 		goto senderror;
   7380 	}
   7381 
   7382 	/* for old-fashioned code - should be nuked */
   7383 	if (m->m_pkthdr.len > MCLBYTES) {
   7384 		m_freem(m);
   7385 		return ENOBUFS;
   7386 	}
   7387 	if (m->m_next) {
   7388 		struct mbuf *n;
   7389 
   7390 		MGETHDR(n, M_DONTWAIT, MT_DATA);
   7391 		if (n && m->m_pkthdr.len > MHLEN) {
   7392 			MCLGET(n, M_DONTWAIT);
   7393 			if ((n->m_flags & M_EXT) == 0) {
   7394 				m_free(n);
   7395 				n = NULL;
   7396 			}
   7397 		}
   7398 		if (!n) {
   7399 			m_freem(m);
   7400 			return ENOBUFS;
   7401 		}
   7402 		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, void *));
   7403 		n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
   7404 		n->m_next = NULL;
   7405 		m_freem(m);
   7406 		m = n;
   7407 	}
   7408 
   7409 	/* align the mbuf chain so that extensions are in contiguous region. */
   7410 	error = key_align(m, &mh);
   7411 	if (error)
   7412 		return error;
   7413 
   7414 	if (m->m_next) {	/*XXX*/
   7415 		m_freem(m);
   7416 		return ENOBUFS;
   7417 	}
   7418 
   7419 	msg = mh.msg;
   7420 
   7421 	/* check SA type */
   7422 	switch (msg->sadb_msg_satype) {
   7423 	case SADB_SATYPE_UNSPEC:
   7424 		switch (msg->sadb_msg_type) {
   7425 		case SADB_GETSPI:
   7426 		case SADB_UPDATE:
   7427 		case SADB_ADD:
   7428 		case SADB_DELETE:
   7429 		case SADB_GET:
   7430 		case SADB_ACQUIRE:
   7431 		case SADB_EXPIRE:
   7432 			ipseclog((LOG_DEBUG, "key_parse: must specify satype "
   7433 			    "when msg type=%u.\n", msg->sadb_msg_type));
   7434 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7435 			error = EINVAL;
   7436 			goto senderror;
   7437 		}
   7438 		break;
   7439 	case SADB_SATYPE_AH:
   7440 	case SADB_SATYPE_ESP:
   7441 	case SADB_X_SATYPE_IPCOMP:
   7442 	case SADB_X_SATYPE_TCPSIGNATURE:
   7443 		switch (msg->sadb_msg_type) {
   7444 		case SADB_X_SPDADD:
   7445 		case SADB_X_SPDDELETE:
   7446 		case SADB_X_SPDGET:
   7447 		case SADB_X_SPDDUMP:
   7448 		case SADB_X_SPDFLUSH:
   7449 		case SADB_X_SPDSETIDX:
   7450 		case SADB_X_SPDUPDATE:
   7451 		case SADB_X_SPDDELETE2:
   7452 			ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
   7453 			    msg->sadb_msg_type));
   7454 			PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7455 			error = EINVAL;
   7456 			goto senderror;
   7457 		}
   7458 		break;
   7459 	case SADB_SATYPE_RSVP:
   7460 	case SADB_SATYPE_OSPFV2:
   7461 	case SADB_SATYPE_RIPV2:
   7462 	case SADB_SATYPE_MIP:
   7463 		ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
   7464 		    msg->sadb_msg_satype));
   7465 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7466 		error = EOPNOTSUPP;
   7467 		goto senderror;
   7468 	case 1:	/* XXX: What does it do? */
   7469 		if (msg->sadb_msg_type == SADB_X_PROMISC)
   7470 			break;
   7471 		/*FALLTHROUGH*/
   7472 	default:
   7473 		ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
   7474 		    msg->sadb_msg_satype));
   7475 		PFKEY_STATINC(PFKEY_STAT_OUT_INVSATYPE);
   7476 		error = EINVAL;
   7477 		goto senderror;
   7478 	}
   7479 
   7480 	/* check field of upper layer protocol and address family */
   7481 	if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
   7482 	 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
   7483 		struct sadb_address *src0, *dst0;
   7484 		u_int plen;
   7485 
   7486 		src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
   7487 		dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
   7488 
   7489 		/* check upper layer protocol */
   7490 		if (src0->sadb_address_proto != dst0->sadb_address_proto) {
   7491 			ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
   7492 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7493 			error = EINVAL;
   7494 			goto senderror;
   7495 		}
   7496 
   7497 		/* check family */
   7498 		if (PFKEY_ADDR_SADDR(src0)->sa_family !=
   7499 		    PFKEY_ADDR_SADDR(dst0)->sa_family) {
   7500 			ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
   7501 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7502 			error = EINVAL;
   7503 			goto senderror;
   7504 		}
   7505 		if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7506 		    PFKEY_ADDR_SADDR(dst0)->sa_len) {
   7507 			ipseclog((LOG_DEBUG,
   7508 			    "key_parse: address struct size mismatched.\n"));
   7509 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7510 			error = EINVAL;
   7511 			goto senderror;
   7512 		}
   7513 
   7514 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
   7515 		case AF_INET:
   7516 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7517 			    sizeof(struct sockaddr_in)) {
   7518 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7519 				error = EINVAL;
   7520 				goto senderror;
   7521 			}
   7522 			break;
   7523 		case AF_INET6:
   7524 			if (PFKEY_ADDR_SADDR(src0)->sa_len !=
   7525 			    sizeof(struct sockaddr_in6)) {
   7526 				PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7527 				error = EINVAL;
   7528 				goto senderror;
   7529 			}
   7530 			break;
   7531 		default:
   7532 			ipseclog((LOG_DEBUG,
   7533 			    "key_parse: unsupported address family.\n"));
   7534 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7535 			error = EAFNOSUPPORT;
   7536 			goto senderror;
   7537 		}
   7538 
   7539 		switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
   7540 		case AF_INET:
   7541 			plen = sizeof(struct in_addr) << 3;
   7542 			break;
   7543 		case AF_INET6:
   7544 			plen = sizeof(struct in6_addr) << 3;
   7545 			break;
   7546 		default:
   7547 			plen = 0;	/*fool gcc*/
   7548 			break;
   7549 		}
   7550 
   7551 		/* check max prefix length */
   7552 		if (src0->sadb_address_prefixlen > plen ||
   7553 		    dst0->sadb_address_prefixlen > plen) {
   7554 			ipseclog((LOG_DEBUG,
   7555 			    "key_parse: illegal prefixlen.\n"));
   7556 			PFKEY_STATINC(PFKEY_STAT_OUT_INVADDR);
   7557 			error = EINVAL;
   7558 			goto senderror;
   7559 		}
   7560 
   7561 		/*
   7562 		 * prefixlen == 0 is valid because there can be a case when
   7563 		 * all addresses are matched.
   7564 		 */
   7565 	}
   7566 
   7567 	if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
   7568 	    key_typesw[msg->sadb_msg_type] == NULL) {
   7569 		PFKEY_STATINC(PFKEY_STAT_OUT_INVMSGTYPE);
   7570 		error = EINVAL;
   7571 		goto senderror;
   7572 	}
   7573 
   7574 	return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
   7575 
   7576 senderror:
   7577 	msg->sadb_msg_errno = error;
   7578 	return key_sendup_mbuf(so, m, target);
   7579 }
   7580 
   7581 static int
   7582 key_senderror(struct socket *so, struct mbuf *m, int code)
   7583 {
   7584 	struct sadb_msg *msg;
   7585 
   7586 	if (m->m_len < sizeof(struct sadb_msg))
   7587 		panic("invalid mbuf passed to key_senderror");
   7588 
   7589 	msg = mtod(m, struct sadb_msg *);
   7590 	msg->sadb_msg_errno = code;
   7591 	return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
   7592 }
   7593 
   7594 /*
   7595  * set the pointer to each header into message buffer.
   7596  * m will be freed on error.
   7597  * XXX larger-than-MCLBYTES extension?
   7598  */
   7599 static int
   7600 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
   7601 {
   7602 	struct mbuf *n;
   7603 	struct sadb_ext *ext;
   7604 	size_t off, end;
   7605 	int extlen;
   7606 	int toff;
   7607 
   7608 	/* sanity check */
   7609 	if (m == NULL || mhp == NULL)
   7610 		panic("key_align: NULL pointer is passed");
   7611 	if (m->m_len < sizeof(struct sadb_msg))
   7612 		panic("invalid mbuf passed to key_align");
   7613 
   7614 	/* initialize */
   7615 	memset(mhp, 0, sizeof(*mhp));
   7616 
   7617 	mhp->msg = mtod(m, struct sadb_msg *);
   7618 	mhp->ext[0] = (struct sadb_ext *)mhp->msg;	/*XXX backward compat */
   7619 
   7620 	end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
   7621 	extlen = end;	/*just in case extlen is not updated*/
   7622 	for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
   7623 		n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
   7624 		if (!n) {
   7625 			/* m is already freed */
   7626 			return ENOBUFS;
   7627 		}
   7628 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
   7629 
   7630 		/* set pointer */
   7631 		switch (ext->sadb_ext_type) {
   7632 		case SADB_EXT_SA:
   7633 		case SADB_EXT_ADDRESS_SRC:
   7634 		case SADB_EXT_ADDRESS_DST:
   7635 		case SADB_EXT_ADDRESS_PROXY:
   7636 		case SADB_EXT_LIFETIME_CURRENT:
   7637 		case SADB_EXT_LIFETIME_HARD:
   7638 		case SADB_EXT_LIFETIME_SOFT:
   7639 		case SADB_EXT_KEY_AUTH:
   7640 		case SADB_EXT_KEY_ENCRYPT:
   7641 		case SADB_EXT_IDENTITY_SRC:
   7642 		case SADB_EXT_IDENTITY_DST:
   7643 		case SADB_EXT_SENSITIVITY:
   7644 		case SADB_EXT_PROPOSAL:
   7645 		case SADB_EXT_SUPPORTED_AUTH:
   7646 		case SADB_EXT_SUPPORTED_ENCRYPT:
   7647 		case SADB_EXT_SPIRANGE:
   7648 		case SADB_X_EXT_POLICY:
   7649 		case SADB_X_EXT_SA2:
   7650 		case SADB_X_EXT_NAT_T_TYPE:
   7651 		case SADB_X_EXT_NAT_T_SPORT:
   7652 		case SADB_X_EXT_NAT_T_DPORT:
   7653 		case SADB_X_EXT_NAT_T_OAI:
   7654 		case SADB_X_EXT_NAT_T_OAR:
   7655 		case SADB_X_EXT_NAT_T_FRAG:
   7656 			/* duplicate check */
   7657 			/*
   7658 			 * XXX Are there duplication payloads of either
   7659 			 * KEY_AUTH or KEY_ENCRYPT ?
   7660 			 */
   7661 			if (mhp->ext[ext->sadb_ext_type] != NULL) {
   7662 				ipseclog((LOG_DEBUG,
   7663 				    "key_align: duplicate ext_type %u "
   7664 				    "is passed.\n", ext->sadb_ext_type));
   7665 				m_freem(m);
   7666 				PFKEY_STATINC(PFKEY_STAT_OUT_DUPEXT);
   7667 				return EINVAL;
   7668 			}
   7669 			break;
   7670 		default:
   7671 			ipseclog((LOG_DEBUG,
   7672 			    "key_align: invalid ext_type %u is passed.\n",
   7673 			    ext->sadb_ext_type));
   7674 			m_freem(m);
   7675 			PFKEY_STATINC(PFKEY_STAT_OUT_INVEXTTYPE);
   7676 			return EINVAL;
   7677 		}
   7678 
   7679 		extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
   7680 
   7681 		if (key_validate_ext(ext, extlen)) {
   7682 			m_freem(m);
   7683 			PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7684 			return EINVAL;
   7685 		}
   7686 
   7687 		n = m_pulldown(m, off, extlen, &toff);
   7688 		if (!n) {
   7689 			/* m is already freed */
   7690 			return ENOBUFS;
   7691 		}
   7692 		ext = (struct sadb_ext *)(mtod(n, char *) + toff);
   7693 
   7694 		mhp->ext[ext->sadb_ext_type] = ext;
   7695 		mhp->extoff[ext->sadb_ext_type] = off;
   7696 		mhp->extlen[ext->sadb_ext_type] = extlen;
   7697 	}
   7698 
   7699 	if (off != end) {
   7700 		m_freem(m);
   7701 		PFKEY_STATINC(PFKEY_STAT_OUT_INVLEN);
   7702 		return EINVAL;
   7703 	}
   7704 
   7705 	return 0;
   7706 }
   7707 
   7708 static int
   7709 key_validate_ext(const struct sadb_ext *ext, int len)
   7710 {
   7711 	const struct sockaddr *sa;
   7712 	enum { NONE, ADDR } checktype = NONE;
   7713 	int baselen = 0;
   7714 	const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
   7715 
   7716 	if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
   7717 		return EINVAL;
   7718 
   7719 	/* if it does not match minimum/maximum length, bail */
   7720 	if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
   7721 	    ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
   7722 		return EINVAL;
   7723 	if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
   7724 		return EINVAL;
   7725 	if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
   7726 		return EINVAL;
   7727 
   7728 	/* more checks based on sadb_ext_type XXX need more */
   7729 	switch (ext->sadb_ext_type) {
   7730 	case SADB_EXT_ADDRESS_SRC:
   7731 	case SADB_EXT_ADDRESS_DST:
   7732 	case SADB_EXT_ADDRESS_PROXY:
   7733 		baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
   7734 		checktype = ADDR;
   7735 		break;
   7736 	case SADB_EXT_IDENTITY_SRC:
   7737 	case SADB_EXT_IDENTITY_DST:
   7738 		if (((const struct sadb_ident *)ext)->sadb_ident_type ==
   7739 		    SADB_X_IDENTTYPE_ADDR) {
   7740 			baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
   7741 			checktype = ADDR;
   7742 		} else
   7743 			checktype = NONE;
   7744 		break;
   7745 	default:
   7746 		checktype = NONE;
   7747 		break;
   7748 	}
   7749 
   7750 	switch (checktype) {
   7751 	case NONE:
   7752 		break;
   7753 	case ADDR:
   7754 		sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
   7755 		if (len < baselen + sal)
   7756 			return EINVAL;
   7757 		if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
   7758 			return EINVAL;
   7759 		break;
   7760 	}
   7761 
   7762 	return 0;
   7763 }
   7764 
   7765 static int
   7766 key_do_init(void)
   7767 {
   7768 	int i;
   7769 
   7770 	pfkeystat_percpu = percpu_alloc(sizeof(uint64_t) * PFKEY_NSTATS);
   7771 
   7772 	callout_init(&key_timehandler_ch, 0);
   7773 
   7774 	for (i = 0; i < IPSEC_DIR_MAX; i++) {
   7775 		LIST_INIT(&sptree[i]);
   7776 	}
   7777 
   7778 	LIST_INIT(&sahtree);
   7779 
   7780 	for (i = 0; i <= SADB_SATYPE_MAX; i++) {
   7781 		LIST_INIT(&regtree[i]);
   7782 	}
   7783 
   7784 #ifndef IPSEC_NONBLOCK_ACQUIRE
   7785 	LIST_INIT(&acqtree);
   7786 #endif
   7787 	LIST_INIT(&spacqtree);
   7788 
   7789 	/* system default */
   7790 	ip4_def_policy.policy = IPSEC_POLICY_NONE;
   7791 	ip4_def_policy.refcnt++;	/*never reclaim this*/
   7792 
   7793 #ifdef INET6
   7794 	ip6_def_policy.policy = IPSEC_POLICY_NONE;
   7795 	ip6_def_policy.refcnt++;	/*never reclaim this*/
   7796 #endif
   7797 
   7798 
   7799 #ifndef IPSEC_DEBUG2
   7800 	callout_reset(&key_timehandler_ch, hz, key_timehandler, NULL);
   7801 #endif /*IPSEC_DEBUG2*/
   7802 
   7803 	/* initialize key statistics */
   7804 	keystat.getspi_count = 1;
   7805 
   7806 	aprint_verbose("IPsec: Initialized Security Association Processing.\n");
   7807 
   7808 	return (0);
   7809 }
   7810 
   7811 void
   7812 key_init(void)
   7813 {
   7814 	static ONCE_DECL(key_init_once);
   7815 
   7816 	RUN_ONCE(&key_init_once, key_do_init);
   7817 }
   7818 
   7819 /*
   7820  * XXX: maybe This function is called after INBOUND IPsec processing.
   7821  *
   7822  * Special check for tunnel-mode packets.
   7823  * We must make some checks for consistency between inner and outer IP header.
   7824  *
   7825  * xxx more checks to be provided
   7826  */
   7827 int
   7828 key_checktunnelsanity(
   7829     struct secasvar *sav,
   7830     u_int family,
   7831     void *src,
   7832     void *dst
   7833 )
   7834 {
   7835 	/* sanity check */
   7836 	if (sav->sah == NULL)
   7837 		panic("sav->sah == NULL at key_checktunnelsanity");
   7838 
   7839 	/* XXX: check inner IP header */
   7840 
   7841 	return 1;
   7842 }
   7843 
   7844 #if 0
   7845 #define hostnamelen	strlen(hostname)
   7846 
   7847 /*
   7848  * Get FQDN for the host.
   7849  * If the administrator configured hostname (by hostname(1)) without
   7850  * domain name, returns nothing.
   7851  */
   7852 static const char *
   7853 key_getfqdn(void)
   7854 {
   7855 	int i;
   7856 	int hasdot;
   7857 	static char fqdn[MAXHOSTNAMELEN + 1];
   7858 
   7859 	if (!hostnamelen)
   7860 		return NULL;
   7861 
   7862 	/* check if it comes with domain name. */
   7863 	hasdot = 0;
   7864 	for (i = 0; i < hostnamelen; i++) {
   7865 		if (hostname[i] == '.')
   7866 			hasdot++;
   7867 	}
   7868 	if (!hasdot)
   7869 		return NULL;
   7870 
   7871 	/* NOTE: hostname may not be NUL-terminated. */
   7872 	memset(fqdn, 0, sizeof(fqdn));
   7873 	memcpy(fqdn, hostname, hostnamelen);
   7874 	fqdn[hostnamelen] = '\0';
   7875 	return fqdn;
   7876 }
   7877 
   7878 /*
   7879  * get username@FQDN for the host/user.
   7880  */
   7881 static const char *
   7882 key_getuserfqdn(void)
   7883 {
   7884 	const char *host;
   7885 	static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
   7886 	struct proc *p = curproc;
   7887 	char *q;
   7888 
   7889 	if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
   7890 		return NULL;
   7891 	if (!(host = key_getfqdn()))
   7892 		return NULL;
   7893 
   7894 	/* NOTE: s_login may not be-NUL terminated. */
   7895 	memset(userfqdn, 0, sizeof(userfqdn));
   7896 	memcpy(userfqdn, Mp->p_pgrp->pg_session->s_login, AXLOGNAME);
   7897 	userfqdn[MAXLOGNAME] = '\0';	/* safeguard */
   7898 	q = userfqdn + strlen(userfqdn);
   7899 	*q++ = '@';
   7900 	memcpy(q, host, strlen(host));
   7901 	q += strlen(host);
   7902 	*q++ = '\0';
   7903 
   7904 	return userfqdn;
   7905 }
   7906 #endif
   7907 
   7908 /* record data transfer on SA, and update timestamps */
   7909 void
   7910 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
   7911 {
   7912 	IPSEC_ASSERT(sav != NULL, ("key_sa_recordxfer: Null secasvar"));
   7913 	IPSEC_ASSERT(m != NULL, ("key_sa_recordxfer: Null mbuf"));
   7914 	if (!sav->lft_c)
   7915 		return;
   7916 
   7917 	/*
   7918 	 * XXX Currently, there is a difference of bytes size
   7919 	 * between inbound and outbound processing.
   7920 	 */
   7921 	sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
   7922 	/* to check bytes lifetime is done in key_timehandler(). */
   7923 
   7924 	/*
   7925 	 * We use the number of packets as the unit of
   7926 	 * sadb_lifetime_allocations.  We increment the variable
   7927 	 * whenever {esp,ah}_{in,out}put is called.
   7928 	 */
   7929 	sav->lft_c->sadb_lifetime_allocations++;
   7930 	/* XXX check for expires? */
   7931 
   7932 	/*
   7933 	 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
   7934 	 * in seconds.  HARD and SOFT lifetime are measured by the time
   7935 	 * difference (again in seconds) from sadb_lifetime_usetime.
   7936 	 *
   7937 	 *	usetime
   7938 	 *	v     expire   expire
   7939 	 * -----+-----+--------+---> t
   7940 	 *	<--------------> HARD
   7941 	 *	<-----> SOFT
   7942 	 */
   7943 	sav->lft_c->sadb_lifetime_usetime = time_uptime;
   7944 	/* XXX check for expires? */
   7945 
   7946 	return;
   7947 }
   7948 
   7949 /* dumb version */
   7950 void
   7951 key_sa_routechange(struct sockaddr *dst)
   7952 {
   7953 	struct secashead *sah;
   7954 	struct route *ro;
   7955 	const struct sockaddr *sa;
   7956 
   7957 	LIST_FOREACH(sah, &sahtree, chain) {
   7958 		ro = &sah->sa_route;
   7959 		sa = rtcache_getdst(ro);
   7960 		if (sa != NULL && dst->sa_len == sa->sa_len &&
   7961 		    memcmp(dst, sa, dst->sa_len) == 0)
   7962 			rtcache_free(ro);
   7963 	}
   7964 
   7965 	return;
   7966 }
   7967 
   7968 static void
   7969 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
   7970 {
   7971 	if (sav == NULL)
   7972 		panic("key_sa_chgstate called with sav == NULL");
   7973 
   7974 	if (sav->state == state)
   7975 		return;
   7976 
   7977 	if (__LIST_CHAINED(sav))
   7978 		LIST_REMOVE(sav, chain);
   7979 
   7980 	sav->state = state;
   7981 	LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
   7982 }
   7983 
   7984 /* XXX too much? */
   7985 static struct mbuf *
   7986 key_alloc_mbuf(int l)
   7987 {
   7988 	struct mbuf *m = NULL, *n;
   7989 	int len, t;
   7990 
   7991 	len = l;
   7992 	while (len > 0) {
   7993 		MGET(n, M_DONTWAIT, MT_DATA);
   7994 		if (n && len > MLEN)
   7995 			MCLGET(n, M_DONTWAIT);
   7996 		if (!n) {
   7997 			m_freem(m);
   7998 			return NULL;
   7999 		}
   8000 
   8001 		n->m_next = NULL;
   8002 		n->m_len = 0;
   8003 		n->m_len = M_TRAILINGSPACE(n);
   8004 		/* use the bottom of mbuf, hoping we can prepend afterwards */
   8005 		if (n->m_len > len) {
   8006 			t = (n->m_len - len) & ~(sizeof(long) - 1);
   8007 			n->m_data += t;
   8008 			n->m_len = len;
   8009 		}
   8010 
   8011 		len -= n->m_len;
   8012 
   8013 		if (m)
   8014 			m_cat(m, n);
   8015 		else
   8016 			m = n;
   8017 	}
   8018 
   8019 	return m;
   8020 }
   8021 
   8022 static struct mbuf *
   8023 key_setdump(u_int8_t req_satype, int *errorp, uint32_t pid)
   8024 {
   8025 	struct secashead *sah;
   8026 	struct secasvar *sav;
   8027 	u_int16_t proto;
   8028 	u_int stateidx;
   8029 	u_int8_t satype;
   8030 	u_int8_t state;
   8031 	int cnt;
   8032 	struct mbuf *m, *n;
   8033 
   8034 	/* map satype to proto */
   8035 	if ((proto = key_satype2proto(req_satype)) == 0) {
   8036 		*errorp = EINVAL;
   8037 		return (NULL);
   8038 	}
   8039 
   8040 	/* count sav entries to be sent to the userland. */
   8041 	cnt = 0;
   8042 	LIST_FOREACH(sah, &sahtree, chain) {
   8043 		if (req_satype != SADB_SATYPE_UNSPEC &&
   8044 		    proto != sah->saidx.proto)
   8045 			continue;
   8046 
   8047 		for (stateidx = 0;
   8048 		     stateidx < _ARRAYLEN(saorder_state_any);
   8049 		     stateidx++) {
   8050 			state = saorder_state_any[stateidx];
   8051 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   8052 				cnt++;
   8053 			}
   8054 		}
   8055 	}
   8056 
   8057 	if (cnt == 0) {
   8058 		*errorp = ENOENT;
   8059 		return (NULL);
   8060 	}
   8061 
   8062 	/* send this to the userland, one at a time. */
   8063 	m = NULL;
   8064 	LIST_FOREACH(sah, &sahtree, chain) {
   8065 		if (req_satype != SADB_SATYPE_UNSPEC &&
   8066 		    proto != sah->saidx.proto)
   8067 			continue;
   8068 
   8069 		/* map proto to satype */
   8070 		if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
   8071 			m_freem(m);
   8072 			*errorp = EINVAL;
   8073 			return (NULL);
   8074 		}
   8075 
   8076 		for (stateidx = 0;
   8077 		     stateidx < _ARRAYLEN(saorder_state_any);
   8078 		     stateidx++) {
   8079 			state = saorder_state_any[stateidx];
   8080 			LIST_FOREACH(sav, &sah->savtree[state], chain) {
   8081 				n = key_setdumpsa(sav, SADB_DUMP, satype,
   8082 				    --cnt, pid);
   8083 				if (!n) {
   8084 					m_freem(m);
   8085 					*errorp = ENOBUFS;
   8086 					return (NULL);
   8087 				}
   8088 
   8089 				if (!m)
   8090 					m = n;
   8091 				else
   8092 					m_cat(m, n);
   8093 			}
   8094 		}
   8095 	}
   8096 
   8097 	if (!m) {
   8098 		*errorp = EINVAL;
   8099 		return (NULL);
   8100 	}
   8101 
   8102 	if ((m->m_flags & M_PKTHDR) != 0) {
   8103 		m->m_pkthdr.len = 0;
   8104 		for (n = m; n; n = n->m_next)
   8105 			m->m_pkthdr.len += n->m_len;
   8106 	}
   8107 
   8108 	*errorp = 0;
   8109 	return (m);
   8110 }
   8111 
   8112 static struct mbuf *
   8113 key_setspddump(int *errorp, pid_t pid)
   8114 {
   8115 	struct secpolicy *sp;
   8116 	int cnt;
   8117 	u_int dir;
   8118 	struct mbuf *m, *n;
   8119 
   8120 	/* search SPD entry and get buffer size. */
   8121 	cnt = 0;
   8122 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   8123 		LIST_FOREACH(sp, &sptree[dir], chain) {
   8124 			cnt++;
   8125 		}
   8126 	}
   8127 
   8128 	if (cnt == 0) {
   8129 		*errorp = ENOENT;
   8130 		return (NULL);
   8131 	}
   8132 
   8133 	m = NULL;
   8134 	for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
   8135 		LIST_FOREACH(sp, &sptree[dir], chain) {
   8136 			--cnt;
   8137 			n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
   8138 
   8139 			if (!n) {
   8140 				*errorp = ENOBUFS;
   8141 				m_freem(m);
   8142 				return (NULL);
   8143 			}
   8144 			if (!m)
   8145 				m = n;
   8146 			else {
   8147 				m->m_pkthdr.len += n->m_pkthdr.len;
   8148 				m_cat(m, n);
   8149 			}
   8150 		}
   8151 	}
   8152 
   8153 	*errorp = 0;
   8154 	return (m);
   8155 }
   8156 
   8157 int
   8158 key_get_used(void) {
   8159 	return !LIST_EMPTY(&sptree[IPSEC_DIR_INBOUND]) ||
   8160 	    !LIST_EMPTY(&sptree[IPSEC_DIR_OUTBOUND]);
   8161 }
   8162 
   8163 void
   8164 key_update_used(void)
   8165 {
   8166 	switch (ipsec_enabled) {
   8167 	default:
   8168 	case 0:
   8169 #ifdef notyet
   8170 		/* XXX: racy */
   8171 		ipsec_used = 0;
   8172 #endif
   8173 		break;
   8174 	case 1:
   8175 #ifndef notyet
   8176 		/* XXX: racy */
   8177 		if (!ipsec_used)
   8178 #endif
   8179 		ipsec_used = key_get_used();
   8180 		break;
   8181 	case 2:
   8182 		ipsec_used = 1;
   8183 		break;
   8184 	}
   8185 }
   8186 
   8187 static int
   8188 sysctl_net_key_dumpsa(SYSCTLFN_ARGS)
   8189 {
   8190 	struct mbuf *m, *n;
   8191 	int err2 = 0;
   8192 	char *p, *ep;
   8193 	size_t len;
   8194 	int s, error;
   8195 
   8196 	if (newp)
   8197 		return (EPERM);
   8198 	if (namelen != 1)
   8199 		return (EINVAL);
   8200 
   8201 	s = splsoftnet();
   8202 	m = key_setdump(name[0], &error, l->l_proc->p_pid);
   8203 	splx(s);
   8204 	if (!m)
   8205 		return (error);
   8206 	if (!oldp)
   8207 		*oldlenp = m->m_pkthdr.len;
   8208 	else {
   8209 		p = oldp;
   8210 		if (*oldlenp < m->m_pkthdr.len) {
   8211 			err2 = ENOMEM;
   8212 			ep = p + *oldlenp;
   8213 		} else {
   8214 			*oldlenp = m->m_pkthdr.len;
   8215 			ep = p + m->m_pkthdr.len;
   8216 		}
   8217 		for (n = m; n; n = n->m_next) {
   8218 			len =  (ep - p < n->m_len) ?
   8219 				ep - p : n->m_len;
   8220 			error = copyout(mtod(n, const void *), p, len);
   8221 			p += len;
   8222 			if (error)
   8223 				break;
   8224 		}
   8225 		if (error == 0)
   8226 			error = err2;
   8227 	}
   8228 	m_freem(m);
   8229 
   8230 	return (error);
   8231 }
   8232 
   8233 static int
   8234 sysctl_net_key_dumpsp(SYSCTLFN_ARGS)
   8235 {
   8236 	struct mbuf *m, *n;
   8237 	int err2 = 0;
   8238 	char *p, *ep;
   8239 	size_t len;
   8240 	int s, error;
   8241 
   8242 	if (newp)
   8243 		return (EPERM);
   8244 	if (namelen != 0)
   8245 		return (EINVAL);
   8246 
   8247 	s = splsoftnet();
   8248 	m = key_setspddump(&error, l->l_proc->p_pid);
   8249 	splx(s);
   8250 	if (!m)
   8251 		return (error);
   8252 	if (!oldp)
   8253 		*oldlenp = m->m_pkthdr.len;
   8254 	else {
   8255 		p = oldp;
   8256 		if (*oldlenp < m->m_pkthdr.len) {
   8257 			err2 = ENOMEM;
   8258 			ep = p + *oldlenp;
   8259 		} else {
   8260 			*oldlenp = m->m_pkthdr.len;
   8261 			ep = p + m->m_pkthdr.len;
   8262 		}
   8263 		for (n = m; n; n = n->m_next) {
   8264 			len =  (ep - p < n->m_len) ?
   8265 				ep - p : n->m_len;
   8266 			error = copyout(mtod(n, const void *), p, len);
   8267 			p += len;
   8268 			if (error)
   8269 				break;
   8270 		}
   8271 		if (error == 0)
   8272 			error = err2;
   8273 	}
   8274 	m_freem(m);
   8275 
   8276 	return (error);
   8277 }
   8278 
   8279 /*
   8280  * Create sysctl tree for native IPSEC key knobs, originally
   8281  * under name "net.keyv2"  * with MIB number { CTL_NET, PF_KEY_V2. }.
   8282  * However, sysctl(8) never checked for nodes under { CTL_NET, PF_KEY_V2 };
   8283  * and in any case the part of our sysctl namespace used for dumping the
   8284  * SPD and SA database  *HAS* to be compatible with the KAME sysctl
   8285  * namespace, for API reasons.
   8286  *
   8287  * Pending a consensus on the right way  to fix this, add a level of
   8288  * indirection in how we number the `native' IPSEC key nodes;
   8289  * and (as requested by Andrew Brown)  move registration of the
   8290  * KAME-compatible names  to a separate function.
   8291  */
   8292 #if 0
   8293 #  define IPSEC_PFKEY PF_KEY_V2
   8294 # define IPSEC_PFKEY_NAME "keyv2"
   8295 #else
   8296 #  define IPSEC_PFKEY PF_KEY
   8297 # define IPSEC_PFKEY_NAME "key"
   8298 #endif
   8299 
   8300 static int
   8301 sysctl_net_key_stats(SYSCTLFN_ARGS)
   8302 {
   8303 
   8304 	return (NETSTAT_SYSCTL(pfkeystat_percpu, PFKEY_NSTATS));
   8305 }
   8306 
   8307 SYSCTL_SETUP(sysctl_net_keyv2_setup, "sysctl net.keyv2 subtree setup")
   8308 {
   8309 
   8310 	sysctl_createv(clog, 0, NULL, NULL,
   8311 		       CTLFLAG_PERMANENT,
   8312 		       CTLTYPE_NODE, IPSEC_PFKEY_NAME, NULL,
   8313 		       NULL, 0, NULL, 0,
   8314 		       CTL_NET, IPSEC_PFKEY, CTL_EOL);
   8315 
   8316 	sysctl_createv(clog, 0, NULL, NULL,
   8317 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8318 		       CTLTYPE_INT, "debug", NULL,
   8319 		       NULL, 0, &key_debug_level, 0,
   8320 		       CTL_NET, IPSEC_PFKEY, KEYCTL_DEBUG_LEVEL, CTL_EOL);
   8321 	sysctl_createv(clog, 0, NULL, NULL,
   8322 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8323 		       CTLTYPE_INT, "spi_try", NULL,
   8324 		       NULL, 0, &key_spi_trycnt, 0,
   8325 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_TRY, CTL_EOL);
   8326 	sysctl_createv(clog, 0, NULL, NULL,
   8327 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8328 		       CTLTYPE_INT, "spi_min_value", NULL,
   8329 		       NULL, 0, &key_spi_minval, 0,
   8330 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_MIN_VALUE, CTL_EOL);
   8331 	sysctl_createv(clog, 0, NULL, NULL,
   8332 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8333 		       CTLTYPE_INT, "spi_max_value", NULL,
   8334 		       NULL, 0, &key_spi_maxval, 0,
   8335 		       CTL_NET, IPSEC_PFKEY, KEYCTL_SPI_MAX_VALUE, CTL_EOL);
   8336 	sysctl_createv(clog, 0, NULL, NULL,
   8337 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8338 		       CTLTYPE_INT, "random_int", NULL,
   8339 		       NULL, 0, &key_int_random, 0,
   8340 		       CTL_NET, IPSEC_PFKEY, KEYCTL_RANDOM_INT, CTL_EOL);
   8341 	sysctl_createv(clog, 0, NULL, NULL,
   8342 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8343 		       CTLTYPE_INT, "larval_lifetime", NULL,
   8344 		       NULL, 0, &key_larval_lifetime, 0,
   8345 		       CTL_NET, IPSEC_PFKEY, KEYCTL_LARVAL_LIFETIME, CTL_EOL);
   8346 	sysctl_createv(clog, 0, NULL, NULL,
   8347 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8348 		       CTLTYPE_INT, "blockacq_count", NULL,
   8349 		       NULL, 0, &key_blockacq_count, 0,
   8350 		       CTL_NET, IPSEC_PFKEY, KEYCTL_BLOCKACQ_COUNT, CTL_EOL);
   8351 	sysctl_createv(clog, 0, NULL, NULL,
   8352 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8353 		       CTLTYPE_INT, "blockacq_lifetime", NULL,
   8354 		       NULL, 0, &key_blockacq_lifetime, 0,
   8355 		       CTL_NET, IPSEC_PFKEY, KEYCTL_BLOCKACQ_LIFETIME, CTL_EOL);
   8356 	sysctl_createv(clog, 0, NULL, NULL,
   8357 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8358 		       CTLTYPE_INT, "esp_keymin", NULL,
   8359 		       NULL, 0, &ipsec_esp_keymin, 0,
   8360 		       CTL_NET, IPSEC_PFKEY, KEYCTL_ESP_KEYMIN, CTL_EOL);
   8361 	sysctl_createv(clog, 0, NULL, NULL,
   8362 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8363 		       CTLTYPE_INT, "prefered_oldsa", NULL,
   8364 		       NULL, 0, &key_prefered_oldsa, 0,
   8365 		       CTL_NET, PF_KEY, KEYCTL_PREFERED_OLDSA, CTL_EOL);
   8366 	sysctl_createv(clog, 0, NULL, NULL,
   8367 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8368 		       CTLTYPE_INT, "esp_auth", NULL,
   8369 		       NULL, 0, &ipsec_esp_auth, 0,
   8370 		       CTL_NET, IPSEC_PFKEY, KEYCTL_ESP_AUTH, CTL_EOL);
   8371 	sysctl_createv(clog, 0, NULL, NULL,
   8372 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   8373 		       CTLTYPE_INT, "ah_keymin", NULL,
   8374 		       NULL, 0, &ipsec_ah_keymin, 0,
   8375 		       CTL_NET, IPSEC_PFKEY, KEYCTL_AH_KEYMIN, CTL_EOL);
   8376 	sysctl_createv(clog, 0, NULL, NULL,
   8377 		       CTLFLAG_PERMANENT,
   8378 		       CTLTYPE_STRUCT, "stats",
   8379 		       SYSCTL_DESCR("PF_KEY statistics"),
   8380 		       sysctl_net_key_stats, 0, NULL, 0,
   8381 		       CTL_NET, IPSEC_PFKEY, CTL_CREATE, CTL_EOL);
   8382 }
   8383 
   8384 /*
   8385  * Register sysctl names used by setkey(8). For historical reasons,
   8386  * and to share a single API, these names appear under { CTL_NET, PF_KEY }
   8387  * for both IPSEC and KAME IPSEC.
   8388  */
   8389 SYSCTL_SETUP(sysctl_net_key_compat_setup, "sysctl net.key subtree setup for IPSEC")
   8390 {
   8391 
   8392 	sysctl_createv(clog, 0, NULL, NULL,
   8393 		       CTLFLAG_PERMANENT,
   8394 		       CTLTYPE_NODE, "key", NULL,
   8395 		       NULL, 0, NULL, 0,
   8396 		       CTL_NET, PF_KEY, CTL_EOL);
   8397 
   8398 	/* Register the net.key.dump{sa,sp} nodes used by setkey(8). */
   8399 	sysctl_createv(clog, 0, NULL, NULL,
   8400 		       CTLFLAG_PERMANENT,
   8401 		       CTLTYPE_STRUCT, "dumpsa", NULL,
   8402 		       sysctl_net_key_dumpsa, 0, NULL, 0,
   8403 		       CTL_NET, PF_KEY, KEYCTL_DUMPSA, CTL_EOL);
   8404 	sysctl_createv(clog, 0, NULL, NULL,
   8405 		       CTLFLAG_PERMANENT,
   8406 		       CTLTYPE_STRUCT, "dumpsp", NULL,
   8407 		       sysctl_net_key_dumpsp, 0, NULL, 0,
   8408 		       CTL_NET, PF_KEY, KEYCTL_DUMPSP, CTL_EOL);
   8409 }
   8410