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