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