2 /* $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $ */
5 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the project nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * This code is referd to RFC 2367
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
41 #include <sys/types.h>
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
46 #include <sys/mutex.h>
48 #include <sys/domain.h>
49 #include <sys/protosw.h>
50 #include <sys/malloc.h>
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 #include <sys/sysctl.h>
54 #include <sys/errno.h>
56 #include <sys/queue.h>
57 #include <sys/refcount.h>
58 #include <sys/syslog.h>
61 #include <net/route.h>
62 #include <net/raw_cb.h>
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/ip.h>
68 #include <netinet/in_var.h>
71 #include <netinet/ip6.h>
72 #include <netinet6/in6_var.h>
73 #include <netinet6/ip6_var.h>
76 #if defined(INET) || defined(INET6)
77 #include <netinet/in_pcb.h>
80 #include <netinet6/in6_pcb.h>
83 #include <net/pfkeyv2.h>
84 #include <netipsec/keydb.h>
85 #include <netipsec/key.h>
86 #include <netipsec/keysock.h>
87 #include <netipsec/key_debug.h>
89 #include <netipsec/ipsec.h>
91 #include <netipsec/ipsec6.h>
94 #include <netipsec/xform.h>
96 #include <machine/stdarg.h>
99 #include <sys/random.h>
101 #define FULLMASK 0xff
102 #define _BITS(bytes) ((bytes) << 3)
105 * Note on SA reference counting:
106 * - SAs that are not in DEAD state will have (total external reference + 1)
107 * following value in reference count field. they cannot be freed and are
108 * referenced from SA header.
109 * - SAs that are in DEAD state will have (total external reference)
110 * in reference count field. they are ready to be freed. reference from
111 * SA header will be removed in key_delsav(), when the reference count
112 * field hits 0 (= no external reference other than from SA header.
115 VNET_DEFINE(u_int32_t, key_debug_level) = 0;
116 static VNET_DEFINE(u_int, key_spi_trycnt) = 1000;
117 static VNET_DEFINE(u_int32_t, key_spi_minval) = 0x100;
118 static VNET_DEFINE(u_int32_t, key_spi_maxval) = 0x0fffffff; /* XXX */
119 static VNET_DEFINE(u_int32_t, policy_id) = 0;
120 /*interval to initialize randseed,1(m)*/
121 static VNET_DEFINE(u_int, key_int_random) = 60;
122 /* interval to expire acquiring, 30(s)*/
123 static VNET_DEFINE(u_int, key_larval_lifetime) = 30;
124 /* counter for blocking SADB_ACQUIRE.*/
125 static VNET_DEFINE(int, key_blockacq_count) = 10;
126 /* lifetime for blocking SADB_ACQUIRE.*/
127 static VNET_DEFINE(int, key_blockacq_lifetime) = 20;
128 /* preferred old sa rather than new sa.*/
129 static VNET_DEFINE(int, key_preferred_oldsa) = 1;
130 #define V_key_spi_trycnt VNET(key_spi_trycnt)
131 #define V_key_spi_minval VNET(key_spi_minval)
132 #define V_key_spi_maxval VNET(key_spi_maxval)
133 #define V_policy_id VNET(policy_id)
134 #define V_key_int_random VNET(key_int_random)
135 #define V_key_larval_lifetime VNET(key_larval_lifetime)
136 #define V_key_blockacq_count VNET(key_blockacq_count)
137 #define V_key_blockacq_lifetime VNET(key_blockacq_lifetime)
138 #define V_key_preferred_oldsa VNET(key_preferred_oldsa)
140 static VNET_DEFINE(u_int32_t, acq_seq) = 0;
141 #define V_acq_seq VNET(acq_seq)
144 static VNET_DEFINE(LIST_HEAD(_sptree, secpolicy), sptree[IPSEC_DIR_MAX]);
145 #define V_sptree VNET(sptree)
146 static struct mtx sptree_lock;
147 #define SPTREE_LOCK_INIT() \
148 mtx_init(&sptree_lock, "sptree", \
149 "fast ipsec security policy database", MTX_DEF)
150 #define SPTREE_LOCK_DESTROY() mtx_destroy(&sptree_lock)
151 #define SPTREE_LOCK() mtx_lock(&sptree_lock)
152 #define SPTREE_UNLOCK() mtx_unlock(&sptree_lock)
153 #define SPTREE_LOCK_ASSERT() mtx_assert(&sptree_lock, MA_OWNED)
155 static VNET_DEFINE(LIST_HEAD(_sahtree, secashead), sahtree); /* SAD */
156 #define V_sahtree VNET(sahtree)
157 static struct mtx sahtree_lock;
158 #define SAHTREE_LOCK_INIT() \
159 mtx_init(&sahtree_lock, "sahtree", \
160 "fast ipsec security association database", MTX_DEF)
161 #define SAHTREE_LOCK_DESTROY() mtx_destroy(&sahtree_lock)
162 #define SAHTREE_LOCK() mtx_lock(&sahtree_lock)
163 #define SAHTREE_UNLOCK() mtx_unlock(&sahtree_lock)
164 #define SAHTREE_LOCK_ASSERT() mtx_assert(&sahtree_lock, MA_OWNED)
167 static VNET_DEFINE(LIST_HEAD(_regtree, secreg), regtree[SADB_SATYPE_MAX + 1]);
168 #define V_regtree VNET(regtree)
169 static struct mtx regtree_lock;
170 #define REGTREE_LOCK_INIT() \
171 mtx_init(®tree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
172 #define REGTREE_LOCK_DESTROY() mtx_destroy(®tree_lock)
173 #define REGTREE_LOCK() mtx_lock(®tree_lock)
174 #define REGTREE_UNLOCK() mtx_unlock(®tree_lock)
175 #define REGTREE_LOCK_ASSERT() mtx_assert(®tree_lock, MA_OWNED)
177 static VNET_DEFINE(LIST_HEAD(_acqtree, secacq), acqtree); /* acquiring list */
178 #define V_acqtree VNET(acqtree)
179 static struct mtx acq_lock;
180 #define ACQ_LOCK_INIT() \
181 mtx_init(&acq_lock, "acqtree", "fast ipsec acquire list", MTX_DEF)
182 #define ACQ_LOCK_DESTROY() mtx_destroy(&acq_lock)
183 #define ACQ_LOCK() mtx_lock(&acq_lock)
184 #define ACQ_UNLOCK() mtx_unlock(&acq_lock)
185 #define ACQ_LOCK_ASSERT() mtx_assert(&acq_lock, MA_OWNED)
187 /* SP acquiring list */
188 static VNET_DEFINE(LIST_HEAD(_spacqtree, secspacq), spacqtree);
189 #define V_spacqtree VNET(spacqtree)
190 static struct mtx spacq_lock;
191 #define SPACQ_LOCK_INIT() \
192 mtx_init(&spacq_lock, "spacqtree", \
193 "fast ipsec security policy acquire list", MTX_DEF)
194 #define SPACQ_LOCK_DESTROY() mtx_destroy(&spacq_lock)
195 #define SPACQ_LOCK() mtx_lock(&spacq_lock)
196 #define SPACQ_UNLOCK() mtx_unlock(&spacq_lock)
197 #define SPACQ_LOCK_ASSERT() mtx_assert(&spacq_lock, MA_OWNED)
199 /* search order for SAs */
200 static const u_int saorder_state_valid_prefer_old[] = {
201 SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
203 static const u_int saorder_state_valid_prefer_new[] = {
204 SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
206 static const u_int saorder_state_alive[] = {
208 SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
210 static const u_int saorder_state_any[] = {
211 SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
212 SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
215 static const int minsize[] = {
216 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
217 sizeof(struct sadb_sa), /* SADB_EXT_SA */
218 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
219 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
220 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
221 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_SRC */
222 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_DST */
223 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_PROXY */
224 sizeof(struct sadb_key), /* SADB_EXT_KEY_AUTH */
225 sizeof(struct sadb_key), /* SADB_EXT_KEY_ENCRYPT */
226 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_SRC */
227 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_DST */
228 sizeof(struct sadb_sens), /* SADB_EXT_SENSITIVITY */
229 sizeof(struct sadb_prop), /* SADB_EXT_PROPOSAL */
230 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_AUTH */
231 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_ENCRYPT */
232 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
233 0, /* SADB_X_EXT_KMPRIVATE */
234 sizeof(struct sadb_x_policy), /* SADB_X_EXT_POLICY */
235 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
236 sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
237 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
238 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
239 sizeof(struct sadb_address), /* SADB_X_EXT_NAT_T_OAI */
240 sizeof(struct sadb_address), /* SADB_X_EXT_NAT_T_OAR */
241 sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
243 static const int maxsize[] = {
244 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
245 sizeof(struct sadb_sa), /* SADB_EXT_SA */
246 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
247 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
248 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
249 0, /* SADB_EXT_ADDRESS_SRC */
250 0, /* SADB_EXT_ADDRESS_DST */
251 0, /* SADB_EXT_ADDRESS_PROXY */
252 0, /* SADB_EXT_KEY_AUTH */
253 0, /* SADB_EXT_KEY_ENCRYPT */
254 0, /* SADB_EXT_IDENTITY_SRC */
255 0, /* SADB_EXT_IDENTITY_DST */
256 0, /* SADB_EXT_SENSITIVITY */
257 0, /* SADB_EXT_PROPOSAL */
258 0, /* SADB_EXT_SUPPORTED_AUTH */
259 0, /* SADB_EXT_SUPPORTED_ENCRYPT */
260 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
261 0, /* SADB_X_EXT_KMPRIVATE */
262 0, /* SADB_X_EXT_POLICY */
263 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
264 sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
265 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
266 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
267 0, /* SADB_X_EXT_NAT_T_OAI */
268 0, /* SADB_X_EXT_NAT_T_OAR */
269 sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
272 static VNET_DEFINE(int, ipsec_esp_keymin) = 256;
273 static VNET_DEFINE(int, ipsec_esp_auth) = 0;
274 static VNET_DEFINE(int, ipsec_ah_keymin) = 128;
276 #define V_ipsec_esp_keymin VNET(ipsec_esp_keymin)
277 #define V_ipsec_esp_auth VNET(ipsec_esp_auth)
278 #define V_ipsec_ah_keymin VNET(ipsec_ah_keymin)
281 SYSCTL_DECL(_net_key);
284 SYSCTL_VNET_INT(_net_key, KEYCTL_DEBUG_LEVEL, debug,
285 CTLFLAG_RW, &VNET_NAME(key_debug_level), 0, "");
287 /* max count of trial for the decision of spi value */
288 SYSCTL_VNET_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt,
289 CTLFLAG_RW, &VNET_NAME(key_spi_trycnt), 0, "");
291 /* minimum spi value to allocate automatically. */
292 SYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MIN_VALUE,
293 spi_minval, CTLFLAG_RW, &VNET_NAME(key_spi_minval), 0, "");
295 /* maximun spi value to allocate automatically. */
296 SYSCTL_VNET_INT(_net_key, KEYCTL_SPI_MAX_VALUE,
297 spi_maxval, CTLFLAG_RW, &VNET_NAME(key_spi_maxval), 0, "");
299 /* interval to initialize randseed */
300 SYSCTL_VNET_INT(_net_key, KEYCTL_RANDOM_INT,
301 int_random, CTLFLAG_RW, &VNET_NAME(key_int_random), 0, "");
303 /* lifetime for larval SA */
304 SYSCTL_VNET_INT(_net_key, KEYCTL_LARVAL_LIFETIME,
305 larval_lifetime, CTLFLAG_RW, &VNET_NAME(key_larval_lifetime), 0, "");
307 /* counter for blocking to send SADB_ACQUIRE to IKEd */
308 SYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,
309 blockacq_count, CTLFLAG_RW, &VNET_NAME(key_blockacq_count), 0, "");
311 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
312 SYSCTL_VNET_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,
313 blockacq_lifetime, CTLFLAG_RW, &VNET_NAME(key_blockacq_lifetime), 0, "");
316 SYSCTL_VNET_INT(_net_key, KEYCTL_ESP_AUTH, esp_auth,
317 CTLFLAG_RW, &VNET_NAME(ipsec_esp_auth), 0, "");
319 /* minimum ESP key length */
320 SYSCTL_VNET_INT(_net_key, KEYCTL_ESP_KEYMIN,
321 esp_keymin, CTLFLAG_RW, &VNET_NAME(ipsec_esp_keymin), 0, "");
323 /* minimum AH key length */
324 SYSCTL_VNET_INT(_net_key, KEYCTL_AH_KEYMIN, ah_keymin,
325 CTLFLAG_RW, &VNET_NAME(ipsec_ah_keymin), 0, "");
327 /* perfered old SA rather than new SA */
328 SYSCTL_VNET_INT(_net_key, KEYCTL_PREFERED_OLDSA,
329 preferred_oldsa, CTLFLAG_RW, &VNET_NAME(key_preferred_oldsa), 0, "");
331 #define __LIST_CHAINED(elm) \
332 (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
333 #define LIST_INSERT_TAIL(head, elm, type, field) \
335 struct type *curelm = LIST_FIRST(head); \
336 if (curelm == NULL) {\
337 LIST_INSERT_HEAD(head, elm, field); \
339 while (LIST_NEXT(curelm, field)) \
340 curelm = LIST_NEXT(curelm, field);\
341 LIST_INSERT_AFTER(curelm, elm, field);\
345 #define KEY_CHKSASTATE(head, sav, name) \
347 if ((head) != (sav)) { \
348 ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
349 (name), (head), (sav))); \
354 #define KEY_CHKSPDIR(head, sp, name) \
356 if ((head) != (sp)) { \
357 ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
358 "anyway continue.\n", \
359 (name), (head), (sp))); \
363 MALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
364 MALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
365 MALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
366 MALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
367 MALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
368 MALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
369 MALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
372 * set parameters into secpolicyindex buffer.
373 * Must allocate secpolicyindex buffer passed to this function.
375 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
377 bzero((idx), sizeof(struct secpolicyindex)); \
378 (idx)->dir = (_dir); \
379 (idx)->prefs = (ps); \
380 (idx)->prefd = (pd); \
381 (idx)->ul_proto = (ulp); \
382 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
383 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
387 * set parameters into secasindex buffer.
388 * Must allocate secasindex buffer before calling this function.
390 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
392 bzero((idx), sizeof(struct secasindex)); \
393 (idx)->proto = (p); \
395 (idx)->reqid = (r); \
396 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
397 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
402 u_long getspi_count; /* the avarage of count to try to get new SPI */
406 struct sadb_msg *msg;
407 struct sadb_ext *ext[SADB_EXT_MAX + 1];
408 int extoff[SADB_EXT_MAX + 1];
409 int extlen[SADB_EXT_MAX + 1];
412 static struct secasvar *key_allocsa_policy __P((const struct secasindex *));
413 static void key_freesp_so __P((struct secpolicy **));
414 static struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
415 static void key_delsp __P((struct secpolicy *));
416 static struct secpolicy *key_getsp __P((struct secpolicyindex *));
417 static void _key_delsp(struct secpolicy *sp);
418 static struct secpolicy *key_getspbyid __P((u_int32_t));
419 static u_int32_t key_newreqid __P((void));
420 static struct mbuf *key_gather_mbuf __P((struct mbuf *,
421 const struct sadb_msghdr *, int, int, ...));
422 static int key_spdadd __P((struct socket *, struct mbuf *,
423 const struct sadb_msghdr *));
424 static u_int32_t key_getnewspid __P((void));
425 static int key_spddelete __P((struct socket *, struct mbuf *,
426 const struct sadb_msghdr *));
427 static int key_spddelete2 __P((struct socket *, struct mbuf *,
428 const struct sadb_msghdr *));
429 static int key_spdget __P((struct socket *, struct mbuf *,
430 const struct sadb_msghdr *));
431 static int key_spdflush __P((struct socket *, struct mbuf *,
432 const struct sadb_msghdr *));
433 static int key_spddump __P((struct socket *, struct mbuf *,
434 const struct sadb_msghdr *));
435 static struct mbuf *key_setdumpsp __P((struct secpolicy *,
436 u_int8_t, u_int32_t, u_int32_t));
437 static u_int key_getspreqmsglen __P((struct secpolicy *));
438 static int key_spdexpire __P((struct secpolicy *));
439 static struct secashead *key_newsah __P((struct secasindex *));
440 static void key_delsah __P((struct secashead *));
441 static struct secasvar *key_newsav __P((struct mbuf *,
442 const struct sadb_msghdr *, struct secashead *, int *,
444 #define KEY_NEWSAV(m, sadb, sah, e) \
445 key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
446 static void key_delsav __P((struct secasvar *));
447 static struct secashead *key_getsah __P((struct secasindex *));
448 static struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
449 static struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
450 static int key_setsaval __P((struct secasvar *, struct mbuf *,
451 const struct sadb_msghdr *));
452 static int key_mature __P((struct secasvar *));
453 static struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
454 u_int8_t, u_int32_t, u_int32_t));
455 static struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
456 u_int32_t, pid_t, u_int16_t));
457 static struct mbuf *key_setsadbsa __P((struct secasvar *));
458 static struct mbuf *key_setsadbaddr __P((u_int16_t,
459 const struct sockaddr *, u_int8_t, u_int16_t));
461 static struct mbuf *key_setsadbxport(u_int16_t, u_int16_t);
462 static struct mbuf *key_setsadbxtype(u_int16_t);
464 static void key_porttosaddr(struct sockaddr *, u_int16_t);
465 #define KEY_PORTTOSADDR(saddr, port) \
466 key_porttosaddr((struct sockaddr *)(saddr), (port))
467 static struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
468 static struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
470 static struct seckey *key_dup_keymsg(const struct sadb_key *, u_int,
471 struct malloc_type *);
472 static struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
473 struct malloc_type *type);
475 static int key_ismyaddr6 __P((struct sockaddr_in6 *));
478 /* flags for key_cmpsaidx() */
479 #define CMP_HEAD 1 /* protocol, addresses. */
480 #define CMP_MODE_REQID 2 /* additionally HEAD, reqid, mode. */
481 #define CMP_REQID 3 /* additionally HEAD, reaid. */
482 #define CMP_EXACTLY 4 /* all elements. */
483 static int key_cmpsaidx
484 __P((const struct secasindex *, const struct secasindex *, int));
486 static int key_cmpspidx_exactly
487 __P((struct secpolicyindex *, struct secpolicyindex *));
488 static int key_cmpspidx_withmask
489 __P((struct secpolicyindex *, struct secpolicyindex *));
490 static int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
491 static int key_bbcmp __P((const void *, const void *, u_int));
492 static u_int16_t key_satype2proto __P((u_int8_t));
493 static u_int8_t key_proto2satype __P((u_int16_t));
495 static int key_getspi __P((struct socket *, struct mbuf *,
496 const struct sadb_msghdr *));
497 static u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
498 struct secasindex *));
499 static int key_update __P((struct socket *, struct mbuf *,
500 const struct sadb_msghdr *));
501 #ifdef IPSEC_DOSEQCHECK
502 static struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
504 static int key_add __P((struct socket *, struct mbuf *,
505 const struct sadb_msghdr *));
506 static int key_setident __P((struct secashead *, struct mbuf *,
507 const struct sadb_msghdr *));
508 static struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
509 const struct sadb_msghdr *));
510 static int key_delete __P((struct socket *, struct mbuf *,
511 const struct sadb_msghdr *));
512 static int key_get __P((struct socket *, struct mbuf *,
513 const struct sadb_msghdr *));
515 static void key_getcomb_setlifetime __P((struct sadb_comb *));
516 static struct mbuf *key_getcomb_esp __P((void));
517 static struct mbuf *key_getcomb_ah __P((void));
518 static struct mbuf *key_getcomb_ipcomp __P((void));
519 static struct mbuf *key_getprop __P((const struct secasindex *));
521 static int key_acquire __P((const struct secasindex *, struct secpolicy *));
522 static struct secacq *key_newacq __P((const struct secasindex *));
523 static struct secacq *key_getacq __P((const struct secasindex *));
524 static struct secacq *key_getacqbyseq __P((u_int32_t));
525 static struct secspacq *key_newspacq __P((struct secpolicyindex *));
526 static struct secspacq *key_getspacq __P((struct secpolicyindex *));
527 static int key_acquire2 __P((struct socket *, struct mbuf *,
528 const struct sadb_msghdr *));
529 static int key_register __P((struct socket *, struct mbuf *,
530 const struct sadb_msghdr *));
531 static int key_expire __P((struct secasvar *));
532 static int key_flush __P((struct socket *, struct mbuf *,
533 const struct sadb_msghdr *));
534 static int key_dump __P((struct socket *, struct mbuf *,
535 const struct sadb_msghdr *));
536 static int key_promisc __P((struct socket *, struct mbuf *,
537 const struct sadb_msghdr *));
538 static int key_senderror __P((struct socket *, struct mbuf *, int));
539 static int key_validate_ext __P((const struct sadb_ext *, int));
540 static int key_align __P((struct mbuf *, struct sadb_msghdr *));
541 static struct mbuf *key_setlifetime(struct seclifetime *src,
543 static struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
546 static const char *key_getfqdn __P((void));
547 static const char *key_getuserfqdn __P((void));
549 static void key_sa_chgstate __P((struct secasvar *, u_int8_t));
552 sa_initref(struct secasvar *sav)
555 refcount_init(&sav->refcnt, 1);
558 sa_addref(struct secasvar *sav)
561 refcount_acquire(&sav->refcnt);
562 IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
565 sa_delref(struct secasvar *sav)
568 IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
569 return (refcount_release(&sav->refcnt));
572 #define SP_ADDREF(p) do { \
574 IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow")); \
576 #define SP_DELREF(p) do { \
577 IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow")); \
583 * Update the refcnt while holding the SPTREE lock.
586 key_addref(struct secpolicy *sp)
594 * Return 0 when there are known to be no SP's for the specified
595 * direction. Otherwise return 1. This is used by IPsec code
596 * to optimize performance.
599 key_havesp(u_int dir)
602 return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
603 LIST_FIRST(&V_sptree[dir]) != NULL : 1);
606 /* %%% IPsec policy management */
608 * allocating a SP for OUTBOUND or INBOUND packet.
609 * Must call key_freesp() later.
610 * OUT: NULL: not found
611 * others: found and return the pointer.
614 key_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
616 struct secpolicy *sp;
618 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
619 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
620 ("invalid direction %u", dir));
622 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
623 printf("DP %s from %s:%u\n", __func__, where, tag));
626 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
627 printf("*** objects\n");
628 kdebug_secpolicyindex(spidx));
631 LIST_FOREACH(sp, &V_sptree[dir], chain) {
632 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
633 printf("*** in SPD\n");
634 kdebug_secpolicyindex(&sp->spidx));
636 if (sp->state == IPSEC_SPSTATE_DEAD)
638 if (key_cmpspidx_withmask(&sp->spidx, spidx))
645 KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
647 /* found a SPD entry */
648 sp->lastused = time_second;
653 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
654 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
655 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
660 * allocating a SP for OUTBOUND or INBOUND packet.
661 * Must call key_freesp() later.
662 * OUT: NULL: not found
663 * others: found and return the pointer.
666 key_allocsp2(u_int32_t spi,
667 union sockaddr_union *dst,
670 const char* where, int tag)
672 struct secpolicy *sp;
674 IPSEC_ASSERT(dst != NULL, ("null dst"));
675 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
676 ("invalid direction %u", dir));
678 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
679 printf("DP %s from %s:%u\n", __func__, where, tag));
682 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
683 printf("*** objects\n");
684 printf("spi %u proto %u dir %u\n", spi, proto, dir);
685 kdebug_sockaddr(&dst->sa));
688 LIST_FOREACH(sp, &V_sptree[dir], chain) {
689 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
690 printf("*** in SPD\n");
691 kdebug_secpolicyindex(&sp->spidx));
693 if (sp->state == IPSEC_SPSTATE_DEAD)
695 /* compare simple values, then dst address */
696 if (sp->spidx.ul_proto != proto)
698 /* NB: spi's must exist and match */
699 if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
701 if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
708 KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
710 /* found a SPD entry */
711 sp->lastused = time_second;
716 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
717 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
718 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
724 * return a policy that matches this particular inbound packet.
728 key_gettunnel(const struct sockaddr *osrc,
729 const struct sockaddr *odst,
730 const struct sockaddr *isrc,
731 const struct sockaddr *idst,
732 const char* where, int tag)
734 struct secpolicy *sp;
735 const int dir = IPSEC_DIR_INBOUND;
736 struct ipsecrequest *r1, *r2, *p;
737 struct secpolicyindex spidx;
739 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
740 printf("DP %s from %s:%u\n", __func__, where, tag));
742 if (isrc->sa_family != idst->sa_family) {
743 ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
744 __func__, isrc->sa_family, idst->sa_family));
750 LIST_FOREACH(sp, &V_sptree[dir], chain) {
751 if (sp->state == IPSEC_SPSTATE_DEAD)
755 for (p = sp->req; p; p = p->next) {
756 if (p->saidx.mode != IPSEC_MODE_TUNNEL)
763 /* here we look at address matches only */
765 if (isrc->sa_len > sizeof(spidx.src) ||
766 idst->sa_len > sizeof(spidx.dst))
768 bcopy(isrc, &spidx.src, isrc->sa_len);
769 bcopy(idst, &spidx.dst, idst->sa_len);
770 if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
773 if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
774 key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
778 if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
779 key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
788 sp->lastused = time_second;
793 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
794 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
795 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
801 * allocating an SA entry for an *OUTBOUND* packet.
802 * checking each request entries in SP, and acquire an SA if need.
803 * OUT: 0: there are valid requests.
804 * ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
807 key_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
811 struct secasvar *sav;
813 IPSEC_ASSERT(isr != NULL, ("null isr"));
814 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
815 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
816 saidx->mode == IPSEC_MODE_TUNNEL,
817 ("unexpected policy %u", saidx->mode));
820 * XXX guard against protocol callbacks from the crypto
821 * thread as they reference ipsecrequest.sav which we
822 * temporarily null out below. Need to rethink how we
823 * handle bundled SA's in the callback thread.
825 IPSECREQUEST_LOCK_ASSERT(isr);
827 /* get current level */
828 level = ipsec_get_reqlevel(isr);
831 * We check new SA in the IPsec request because a different
832 * SA may be involved each time this request is checked, either
833 * because new SAs are being configured, or this request is
834 * associated with an unconnected datagram socket, or this request
835 * is associated with a system default policy.
837 * key_allocsa_policy should allocate the oldest SA available.
838 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
840 sav = key_allocsa_policy(saidx);
841 if (sav != isr->sav) {
842 /* SA need to be updated. */
843 if (!IPSECREQUEST_UPGRADE(isr)) {
844 /* Kick everyone off. */
845 IPSECREQUEST_UNLOCK(isr);
846 IPSECREQUEST_WLOCK(isr);
848 if (isr->sav != NULL)
849 KEY_FREESAV(&isr->sav);
851 IPSECREQUEST_DOWNGRADE(isr);
852 } else if (sav != NULL)
855 /* When there is SA. */
856 if (isr->sav != NULL) {
857 if (isr->sav->state != SADB_SASTATE_MATURE &&
858 isr->sav->state != SADB_SASTATE_DYING)
864 error = key_acquire(saidx, isr->sp);
866 /* XXX What should I do ? */
867 ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
872 if (level != IPSEC_LEVEL_REQUIRE) {
873 /* XXX sigh, the interface to this routine is botched */
874 IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
882 * allocating a SA for policy entry from SAD.
883 * NOTE: searching SAD of aliving state.
884 * OUT: NULL: not found.
885 * others: found and return the pointer.
887 static struct secasvar *
888 key_allocsa_policy(const struct secasindex *saidx)
890 #define N(a) _ARRAYLEN(a)
891 struct secashead *sah;
892 struct secasvar *sav;
893 u_int stateidx, arraysize;
894 const u_int *state_valid;
896 state_valid = NULL; /* silence gcc */
897 arraysize = 0; /* silence gcc */
900 LIST_FOREACH(sah, &V_sahtree, chain) {
901 if (sah->state == SADB_SASTATE_DEAD)
903 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
904 if (V_key_preferred_oldsa) {
905 state_valid = saorder_state_valid_prefer_old;
906 arraysize = N(saorder_state_valid_prefer_old);
908 state_valid = saorder_state_valid_prefer_new;
909 arraysize = N(saorder_state_valid_prefer_new);
918 /* search valid state */
919 for (stateidx = 0; stateidx < arraysize; stateidx++) {
920 sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
930 * searching SAD with direction, protocol, mode and state.
931 * called by key_allocsa_policy().
934 * others : found, pointer to a SA.
936 static struct secasvar *
937 key_do_allocsa_policy(struct secashead *sah, u_int state)
939 struct secasvar *sav, *nextsav, *candidate, *d;
945 for (sav = LIST_FIRST(&sah->savtree[state]);
949 nextsav = LIST_NEXT(sav, chain);
952 KEY_CHKSASTATE(sav->state, state, __func__);
955 if (candidate == NULL) {
960 /* Which SA is the better ? */
962 IPSEC_ASSERT(candidate->lft_c != NULL,
963 ("null candidate lifetime"));
964 IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
966 /* What the best method is to compare ? */
967 if (V_key_preferred_oldsa) {
968 if (candidate->lft_c->addtime >
969 sav->lft_c->addtime) {
976 /* preferred new sa rather than old sa */
977 if (candidate->lft_c->addtime <
978 sav->lft_c->addtime) {
985 * prepared to delete the SA when there is more
986 * suitable candidate and the lifetime of the SA is not
989 if (d->lft_h->addtime != 0) {
990 struct mbuf *m, *result;
993 key_sa_chgstate(d, SADB_SASTATE_DEAD);
995 IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
997 satype = key_proto2satype(d->sah->saidx.proto);
1001 m = key_setsadbmsg(SADB_DELETE, 0,
1002 satype, 0, 0, d->refcnt - 1);
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,
1016 /* set sadb_address for saidx's. */
1017 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
1018 &d->sah->saidx.dst.sa,
1019 d->sah->saidx.dst.sa.sa_len << 3,
1025 /* create SA extension */
1026 m = key_setsadbsa(d);
1031 if (result->m_len < sizeof(struct sadb_msg)) {
1032 result = m_pullup(result,
1033 sizeof(struct sadb_msg));
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);
1044 if (key_sendup_mbuf(NULL, result,
1045 KEY_SENDUP_REGISTERED))
1052 sa_addref(candidate);
1053 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1054 printf("DP %s cause refcnt++:%d SA:%p\n",
1055 __func__, candidate->refcnt, candidate));
1063 * allocating a usable SA entry for a *INBOUND* packet.
1064 * Must call key_freesav() later.
1065 * OUT: positive: pointer to a usable sav (i.e. MATURE or DYING state).
1066 * NULL: not found, or error occured.
1068 * In the comparison, no source address is used--for RFC2401 conformance.
1069 * To quote, from section 4.1:
1070 * A security association is uniquely identified by a triple consisting
1071 * of a Security Parameter Index (SPI), an IP Destination Address, and a
1072 * security protocol (AH or ESP) identifier.
1073 * Note that, however, we do need to keep source address in IPsec SA.
1074 * IKE specification and PF_KEY specification do assume that we
1075 * keep source address in IPsec SA. We see a tricky situation here.
1079 union sockaddr_union *dst,
1082 const char* where, int tag)
1084 struct secashead *sah;
1085 struct secasvar *sav;
1086 u_int stateidx, arraysize, state;
1087 const u_int *saorder_state_valid;
1092 IPSEC_ASSERT(dst != NULL, ("null dst address"));
1094 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1095 printf("DP %s from %s:%u\n", __func__, where, tag));
1098 natt_chkport = (dst->sa.sa_family == AF_INET &&
1099 dst->sa.sa_len == sizeof(struct sockaddr_in) &&
1100 dst->sin.sin_port != 0);
1105 * XXX: to be checked internal IP header somewhere. Also when
1106 * IPsec tunnel packet is received. But ESP tunnel mode is
1107 * encrypted so we can't check internal IP header.
1110 if (V_key_preferred_oldsa) {
1111 saorder_state_valid = saorder_state_valid_prefer_old;
1112 arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1114 saorder_state_valid = saorder_state_valid_prefer_new;
1115 arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1117 LIST_FOREACH(sah, &V_sahtree, chain) {
1120 /* search valid state */
1121 for (stateidx = 0; stateidx < arraysize; stateidx++) {
1122 state = saorder_state_valid[stateidx];
1123 LIST_FOREACH(sav, &sah->savtree[state], chain) {
1125 KEY_CHKSASTATE(sav->state, state, __func__);
1126 /* do not return entries w/ unusable state */
1127 if (sav->state != SADB_SASTATE_MATURE &&
1128 sav->state != SADB_SASTATE_DYING)
1130 if (proto != sav->sah->saidx.proto)
1132 if (spi != sav->spi)
1137 * Really only check ports when this is a NAT-T
1138 * SA. Otherwise other lookups providing ports
1141 if (sav->natt_type && natt_chkport)
1144 #if 0 /* don't check src */
1145 /* check src address */
1146 if (key_sockaddrcmp(&src->sa,
1147 &sav->sah->saidx.src.sa, checkport) != 0)
1150 /* check dst address */
1151 if (key_sockaddrcmp(&dst->sa,
1152 &sav->sah->saidx.dst.sa, checkport) != 0)
1163 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1164 printf("DP %s return SA:%p; refcnt %u\n", __func__,
1165 sav, sav ? sav->refcnt : 0));
1170 * Must be called after calling key_allocsp().
1171 * For both the packet without socket and key_freeso().
1174 _key_freesp(struct secpolicy **spp, const char* where, int tag)
1176 struct secpolicy *sp = *spp;
1178 IPSEC_ASSERT(sp != NULL, ("null sp"));
1183 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1184 printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1185 __func__, sp, sp->id, where, tag, sp->refcnt));
1187 if (sp->refcnt == 0) {
1195 * Must be called after calling key_allocsp().
1196 * For the packet with socket.
1199 key_freeso(struct socket *so)
1201 IPSEC_ASSERT(so != NULL, ("null so"));
1203 switch (so->so_proto->pr_domain->dom_family) {
1204 #if defined(INET) || defined(INET6)
1212 struct inpcb *pcb = sotoinpcb(so);
1214 /* Does it have a PCB ? */
1217 key_freesp_so(&pcb->inp_sp->sp_in);
1218 key_freesp_so(&pcb->inp_sp->sp_out);
1221 #endif /* INET || INET6 */
1223 ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
1224 __func__, so->so_proto->pr_domain->dom_family));
1230 key_freesp_so(struct secpolicy **sp)
1232 IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
1234 if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1235 (*sp)->policy == IPSEC_POLICY_BYPASS)
1238 IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1239 ("invalid policy %u", (*sp)->policy));
1244 key_addrefsa(struct secasvar *sav, const char* where, int tag)
1247 IPSEC_ASSERT(sav != NULL, ("null sav"));
1248 IPSEC_ASSERT(sav->refcnt > 0, ("refcount must exist"));
1254 * Must be called after calling key_allocsa().
1255 * This function is called by key_freesp() to free some SA allocated
1259 key_freesav(struct secasvar **psav, const char* where, int tag)
1261 struct secasvar *sav = *psav;
1263 IPSEC_ASSERT(sav != NULL, ("null sav"));
1265 if (sa_delref(sav)) {
1266 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1267 printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1268 __func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1272 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1273 printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1274 __func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1278 /* %%% SPD management */
1280 * free security policy entry.
1283 key_delsp(struct secpolicy *sp)
1285 struct ipsecrequest *isr, *nextisr;
1287 IPSEC_ASSERT(sp != NULL, ("null sp"));
1288 SPTREE_LOCK_ASSERT();
1290 sp->state = IPSEC_SPSTATE_DEAD;
1292 IPSEC_ASSERT(sp->refcnt == 0,
1293 ("SP with references deleted (refcnt %u)", sp->refcnt));
1295 /* remove from SP index */
1296 if (__LIST_CHAINED(sp))
1297 LIST_REMOVE(sp, chain);
1299 for (isr = sp->req; isr != NULL; isr = nextisr) {
1300 if (isr->sav != NULL) {
1301 KEY_FREESAV(&isr->sav);
1305 nextisr = isr->next;
1313 * OUT: NULL : not found
1314 * others : found, pointer to a SP.
1316 static struct secpolicy *
1317 key_getsp(struct secpolicyindex *spidx)
1319 struct secpolicy *sp;
1321 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1324 LIST_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1325 if (sp->state == IPSEC_SPSTATE_DEAD)
1327 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1339 * OUT: NULL : not found
1340 * others : found, pointer to a SP.
1342 static struct secpolicy *
1343 key_getspbyid(u_int32_t id)
1345 struct secpolicy *sp;
1348 LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_INBOUND], chain) {
1349 if (sp->state == IPSEC_SPSTATE_DEAD)
1357 LIST_FOREACH(sp, &V_sptree[IPSEC_DIR_OUTBOUND], chain) {
1358 if (sp->state == IPSEC_SPSTATE_DEAD)
1372 key_newsp(const char* where, int tag)
1374 struct secpolicy *newsp = NULL;
1376 newsp = (struct secpolicy *)
1377 malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
1379 SECPOLICY_LOCK_INIT(newsp);
1384 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1385 printf("DP %s from %s:%u return SP:%p\n", __func__,
1386 where, tag, newsp));
1391 _key_delsp(struct secpolicy *sp)
1393 SECPOLICY_LOCK_DESTROY(sp);
1394 free(sp, M_IPSEC_SP);
1398 * create secpolicy structure from sadb_x_policy structure.
1399 * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1400 * so must be set properly later.
1403 key_msg2sp(xpl0, len, error)
1404 struct sadb_x_policy *xpl0;
1408 struct secpolicy *newsp;
1410 IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1411 IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1413 if (len != PFKEY_EXTLEN(xpl0)) {
1414 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1419 if ((newsp = KEY_NEWSP()) == NULL) {
1424 newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1425 newsp->policy = xpl0->sadb_x_policy_type;
1428 switch (xpl0->sadb_x_policy_type) {
1429 case IPSEC_POLICY_DISCARD:
1430 case IPSEC_POLICY_NONE:
1431 case IPSEC_POLICY_ENTRUST:
1432 case IPSEC_POLICY_BYPASS:
1436 case IPSEC_POLICY_IPSEC:
1439 struct sadb_x_ipsecrequest *xisr;
1440 struct ipsecrequest **p_isr = &newsp->req;
1442 /* validity check */
1443 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1444 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1451 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1452 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1456 if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1457 ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1458 "length.\n", __func__));
1464 /* allocate request buffer */
1465 /* NB: data structure is zero'd */
1466 *p_isr = ipsec_newisr();
1467 if ((*p_isr) == NULL) {
1468 ipseclog((LOG_DEBUG,
1469 "%s: No more memory.\n", __func__));
1476 switch (xisr->sadb_x_ipsecrequest_proto) {
1479 case IPPROTO_IPCOMP:
1482 ipseclog((LOG_DEBUG,
1483 "%s: invalid proto type=%u\n", __func__,
1484 xisr->sadb_x_ipsecrequest_proto));
1486 *error = EPROTONOSUPPORT;
1489 (*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1491 switch (xisr->sadb_x_ipsecrequest_mode) {
1492 case IPSEC_MODE_TRANSPORT:
1493 case IPSEC_MODE_TUNNEL:
1495 case IPSEC_MODE_ANY:
1497 ipseclog((LOG_DEBUG,
1498 "%s: invalid mode=%u\n", __func__,
1499 xisr->sadb_x_ipsecrequest_mode));
1504 (*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1506 switch (xisr->sadb_x_ipsecrequest_level) {
1507 case IPSEC_LEVEL_DEFAULT:
1508 case IPSEC_LEVEL_USE:
1509 case IPSEC_LEVEL_REQUIRE:
1511 case IPSEC_LEVEL_UNIQUE:
1512 /* validity check */
1514 * If range violation of reqid, kernel will
1515 * update it, don't refuse it.
1517 if (xisr->sadb_x_ipsecrequest_reqid
1518 > IPSEC_MANUAL_REQID_MAX) {
1519 ipseclog((LOG_DEBUG,
1520 "%s: reqid=%d range "
1521 "violation, updated by kernel.\n",
1523 xisr->sadb_x_ipsecrequest_reqid));
1524 xisr->sadb_x_ipsecrequest_reqid = 0;
1527 /* allocate new reqid id if reqid is zero. */
1528 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1530 if ((reqid = key_newreqid()) == 0) {
1535 (*p_isr)->saidx.reqid = reqid;
1536 xisr->sadb_x_ipsecrequest_reqid = reqid;
1538 /* set it for manual keying. */
1539 (*p_isr)->saidx.reqid =
1540 xisr->sadb_x_ipsecrequest_reqid;
1545 ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1547 xisr->sadb_x_ipsecrequest_level));
1552 (*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1554 /* set IP addresses if there */
1555 if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1556 struct sockaddr *paddr;
1558 paddr = (struct sockaddr *)(xisr + 1);
1560 /* validity check */
1562 > sizeof((*p_isr)->saidx.src)) {
1563 ipseclog((LOG_DEBUG, "%s: invalid "
1564 "request address length.\n",
1570 bcopy(paddr, &(*p_isr)->saidx.src,
1573 paddr = (struct sockaddr *)((caddr_t)paddr
1576 /* validity check */
1578 > sizeof((*p_isr)->saidx.dst)) {
1579 ipseclog((LOG_DEBUG, "%s: invalid "
1580 "request address length.\n",
1586 bcopy(paddr, &(*p_isr)->saidx.dst,
1590 (*p_isr)->sp = newsp;
1592 /* initialization for the next. */
1593 p_isr = &(*p_isr)->next;
1594 tlen -= xisr->sadb_x_ipsecrequest_len;
1596 /* validity check */
1598 ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1605 xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1606 + xisr->sadb_x_ipsecrequest_len);
1611 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1624 static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1626 auto_reqid = (auto_reqid == ~0
1627 ? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1629 /* XXX should be unique check */
1635 * copy secpolicy struct to sadb_x_policy structure indicated.
1639 struct secpolicy *sp;
1641 struct sadb_x_policy *xpl;
1646 IPSEC_ASSERT(sp != NULL, ("null policy"));
1648 tlen = key_getspreqmsglen(sp);
1650 m = m_get2(tlen, M_NOWAIT, MT_DATA, 0);
1655 xpl = mtod(m, struct sadb_x_policy *);
1658 xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1659 xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1660 xpl->sadb_x_policy_type = sp->policy;
1661 xpl->sadb_x_policy_dir = sp->spidx.dir;
1662 xpl->sadb_x_policy_id = sp->id;
1663 p = (caddr_t)xpl + sizeof(*xpl);
1665 /* if is the policy for ipsec ? */
1666 if (sp->policy == IPSEC_POLICY_IPSEC) {
1667 struct sadb_x_ipsecrequest *xisr;
1668 struct ipsecrequest *isr;
1670 for (isr = sp->req; isr != NULL; isr = isr->next) {
1672 xisr = (struct sadb_x_ipsecrequest *)p;
1674 xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1675 xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1676 xisr->sadb_x_ipsecrequest_level = isr->level;
1677 xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1680 bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1681 p += isr->saidx.src.sa.sa_len;
1682 bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1683 p += isr->saidx.src.sa.sa_len;
1685 xisr->sadb_x_ipsecrequest_len =
1686 PFKEY_ALIGN8(sizeof(*xisr)
1687 + isr->saidx.src.sa.sa_len
1688 + isr->saidx.dst.sa.sa_len);
1695 /* m will not be freed nor modified */
1696 static struct mbuf *
1698 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1699 int ndeep, int nitem, ...)
1701 key_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
1703 const struct sadb_msghdr *mhp;
1712 struct mbuf *result = NULL, *n;
1715 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1716 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1718 va_start(ap, nitem);
1719 for (i = 0; i < nitem; i++) {
1720 idx = va_arg(ap, int);
1721 if (idx < 0 || idx > SADB_EXT_MAX)
1723 /* don't attempt to pull empty extension */
1724 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1726 if (idx != SADB_EXT_RESERVED &&
1727 (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1730 if (idx == SADB_EXT_RESERVED) {
1731 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1733 IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1735 MGETHDR(n, M_NOWAIT, MT_DATA);
1740 m_copydata(m, 0, sizeof(struct sadb_msg),
1742 } else if (i < ndeep) {
1743 len = mhp->extlen[idx];
1744 n = m_get2(len, M_NOWAIT, MT_DATA, 0);
1749 m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1752 n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1765 if ((result->m_flags & M_PKTHDR) != 0) {
1766 result->m_pkthdr.len = 0;
1767 for (n = result; n; n = n->m_next)
1768 result->m_pkthdr.len += n->m_len;
1780 * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1781 * add an entry to SP database, when received
1782 * <base, address(SD), (lifetime(H),) policy>
1784 * Adding to SP database,
1786 * <base, address(SD), (lifetime(H),) policy>
1787 * to the socket which was send.
1789 * SPDADD set a unique policy entry.
1790 * SPDSETIDX like SPDADD without a part of policy requests.
1791 * SPDUPDATE replace a unique policy entry.
1793 * m will always be freed.
1796 key_spdadd(so, m, mhp)
1799 const struct sadb_msghdr *mhp;
1801 struct sadb_address *src0, *dst0;
1802 struct sadb_x_policy *xpl0, *xpl;
1803 struct sadb_lifetime *lft = NULL;
1804 struct secpolicyindex spidx;
1805 struct secpolicy *newsp;
1808 IPSEC_ASSERT(so != NULL, ("null socket"));
1809 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1810 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1811 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1813 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1814 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1815 mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1816 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1817 return key_senderror(so, m, EINVAL);
1819 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1820 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1821 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1822 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1824 return key_senderror(so, m, EINVAL);
1826 if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1827 if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1828 < sizeof(struct sadb_lifetime)) {
1829 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1831 return key_senderror(so, m, EINVAL);
1833 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1836 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1837 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1838 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1841 * Note: do not parse SADB_X_EXT_NAT_T_* here:
1842 * we are processing traffic endpoints.
1846 /* XXX boundary check against sa_len */
1847 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1850 src0->sadb_address_prefixlen,
1851 dst0->sadb_address_prefixlen,
1852 src0->sadb_address_proto,
1855 /* checking the direciton. */
1856 switch (xpl0->sadb_x_policy_dir) {
1857 case IPSEC_DIR_INBOUND:
1858 case IPSEC_DIR_OUTBOUND:
1861 ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
1862 mhp->msg->sadb_msg_errno = EINVAL;
1867 /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1868 if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1869 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1870 ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
1871 return key_senderror(so, m, EINVAL);
1874 /* policy requests are mandatory when action is ipsec. */
1875 if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1876 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1877 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1878 ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
1880 return key_senderror(so, m, EINVAL);
1884 * checking there is SP already or not.
1885 * SPDUPDATE doesn't depend on whether there is a SP or not.
1886 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1889 newsp = key_getsp(&spidx);
1890 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1893 newsp->state = IPSEC_SPSTATE_DEAD;
1898 if (newsp != NULL) {
1900 ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1902 return key_senderror(so, m, EEXIST);
1906 /* allocation new SP entry */
1907 if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1908 return key_senderror(so, m, error);
1911 if ((newsp->id = key_getnewspid()) == 0) {
1913 return key_senderror(so, m, ENOBUFS);
1916 /* XXX boundary check against sa_len */
1917 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1920 src0->sadb_address_prefixlen,
1921 dst0->sadb_address_prefixlen,
1922 src0->sadb_address_proto,
1925 /* sanity check on addr pair */
1926 if (((struct sockaddr *)(src0 + 1))->sa_family !=
1927 ((struct sockaddr *)(dst0+ 1))->sa_family) {
1929 return key_senderror(so, m, EINVAL);
1931 if (((struct sockaddr *)(src0 + 1))->sa_len !=
1932 ((struct sockaddr *)(dst0+ 1))->sa_len) {
1934 return key_senderror(so, m, EINVAL);
1937 if (newsp->req && newsp->req->saidx.src.sa.sa_family && newsp->req->saidx.dst.sa.sa_family) {
1938 if (newsp->req->saidx.src.sa.sa_family != newsp->req->saidx.dst.sa.sa_family) {
1940 return key_senderror(so, m, EINVAL);
1945 newsp->created = time_second;
1946 newsp->lastused = newsp->created;
1947 newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1948 newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1950 newsp->refcnt = 1; /* do not reclaim until I say I do */
1951 newsp->state = IPSEC_SPSTATE_ALIVE;
1952 LIST_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1954 /* delete the entry in spacqtree */
1955 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1956 struct secspacq *spacq = key_getspacq(&spidx);
1957 if (spacq != NULL) {
1958 /* reset counter in order to deletion by timehandler. */
1959 spacq->created = time_second;
1966 struct mbuf *n, *mpolicy;
1967 struct sadb_msg *newmsg;
1971 * Note: do not send SADB_X_EXT_NAT_T_* here:
1972 * we are sending traffic endpoints.
1975 /* create new sadb_msg to reply. */
1977 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1978 SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1979 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1981 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1983 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1986 return key_senderror(so, m, ENOBUFS);
1988 if (n->m_len < sizeof(*newmsg)) {
1989 n = m_pullup(n, sizeof(*newmsg));
1991 return key_senderror(so, m, ENOBUFS);
1993 newmsg = mtod(n, struct sadb_msg *);
1994 newmsg->sadb_msg_errno = 0;
1995 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1998 mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1999 sizeof(*xpl), &off);
2000 if (mpolicy == NULL) {
2001 /* n is already freed */
2002 return key_senderror(so, m, ENOBUFS);
2004 xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
2005 if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
2007 return key_senderror(so, m, EINVAL);
2009 xpl->sadb_x_policy_id = newsp->id;
2012 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2017 * get new policy id.
2025 u_int32_t newid = 0;
2026 int count = V_key_spi_trycnt; /* XXX */
2027 struct secpolicy *sp;
2029 /* when requesting to allocate spi ranged */
2031 newid = (V_policy_id = (V_policy_id == ~0 ? 1 : V_policy_id + 1));
2033 if ((sp = key_getspbyid(newid)) == NULL)
2039 if (count == 0 || newid == 0) {
2040 ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
2049 * SADB_SPDDELETE processing
2051 * <base, address(SD), policy(*)>
2052 * from the user(?), and set SADB_SASTATE_DEAD,
2054 * <base, address(SD), policy(*)>
2056 * policy(*) including direction of policy.
2058 * m will always be freed.
2061 key_spddelete(so, m, mhp)
2064 const struct sadb_msghdr *mhp;
2066 struct sadb_address *src0, *dst0;
2067 struct sadb_x_policy *xpl0;
2068 struct secpolicyindex spidx;
2069 struct secpolicy *sp;
2071 IPSEC_ASSERT(so != NULL, ("null so"));
2072 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2073 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2074 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2076 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2077 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2078 mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2079 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2081 return key_senderror(so, m, EINVAL);
2083 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2084 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2085 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2086 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2088 return key_senderror(so, m, EINVAL);
2091 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2092 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2093 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2096 * Note: do not parse SADB_X_EXT_NAT_T_* here:
2097 * we are processing traffic endpoints.
2101 /* XXX boundary check against sa_len */
2102 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2105 src0->sadb_address_prefixlen,
2106 dst0->sadb_address_prefixlen,
2107 src0->sadb_address_proto,
2110 /* checking the direciton. */
2111 switch (xpl0->sadb_x_policy_dir) {
2112 case IPSEC_DIR_INBOUND:
2113 case IPSEC_DIR_OUTBOUND:
2116 ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2117 return key_senderror(so, m, EINVAL);
2120 /* Is there SP in SPD ? */
2121 if ((sp = key_getsp(&spidx)) == NULL) {
2122 ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2123 return key_senderror(so, m, EINVAL);
2126 /* save policy id to buffer to be returned. */
2127 xpl0->sadb_x_policy_id = sp->id;
2130 sp->state = IPSEC_SPSTATE_DEAD;
2136 struct sadb_msg *newmsg;
2139 * Note: do not send SADB_X_EXT_NAT_T_* here:
2140 * we are sending traffic endpoints.
2143 /* create new sadb_msg to reply. */
2144 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2145 SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2147 return key_senderror(so, m, ENOBUFS);
2149 newmsg = mtod(n, struct sadb_msg *);
2150 newmsg->sadb_msg_errno = 0;
2151 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2154 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2159 * SADB_SPDDELETE2 processing
2162 * from the user(?), and set SADB_SASTATE_DEAD,
2166 * policy(*) including direction of policy.
2168 * m will always be freed.
2171 key_spddelete2(so, m, mhp)
2174 const struct sadb_msghdr *mhp;
2177 struct secpolicy *sp;
2179 IPSEC_ASSERT(so != NULL, ("null socket"));
2180 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2181 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2182 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2184 if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2185 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2186 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2187 return key_senderror(so, m, EINVAL);
2190 id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2192 /* Is there SP in SPD ? */
2193 if ((sp = key_getspbyid(id)) == NULL) {
2194 ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2195 return key_senderror(so, m, EINVAL);
2199 sp->state = IPSEC_SPSTATE_DEAD;
2204 struct mbuf *n, *nn;
2205 struct sadb_msg *newmsg;
2208 /* create new sadb_msg to reply. */
2209 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2211 MGETHDR(n, M_NOWAIT, MT_DATA);
2212 if (n && len > MHLEN) {
2213 MCLGET(n, M_NOWAIT);
2214 if ((n->m_flags & M_EXT) == 0) {
2220 return key_senderror(so, m, ENOBUFS);
2226 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2227 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2229 IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2232 n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2233 mhp->extlen[SADB_X_EXT_POLICY], M_NOWAIT);
2236 return key_senderror(so, m, ENOBUFS);
2239 n->m_pkthdr.len = 0;
2240 for (nn = n; nn; nn = nn->m_next)
2241 n->m_pkthdr.len += nn->m_len;
2243 newmsg = mtod(n, struct sadb_msg *);
2244 newmsg->sadb_msg_errno = 0;
2245 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2248 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2253 * SADB_X_GET processing
2258 * <base, address(SD), policy>
2260 * policy(*) including direction of policy.
2262 * m will always be freed.
2265 key_spdget(so, m, mhp)
2268 const struct sadb_msghdr *mhp;
2271 struct secpolicy *sp;
2274 IPSEC_ASSERT(so != NULL, ("null socket"));
2275 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2276 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2277 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2279 if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2280 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2281 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2283 return key_senderror(so, m, EINVAL);
2286 id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2288 /* Is there SP in SPD ? */
2289 if ((sp = key_getspbyid(id)) == NULL) {
2290 ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2291 return key_senderror(so, m, ENOENT);
2294 n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2298 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2300 return key_senderror(so, m, ENOBUFS);
2304 * SADB_X_SPDACQUIRE processing.
2305 * Acquire policy and SA(s) for a *OUTBOUND* packet.
2308 * to KMD, and expect to receive
2309 * <base> with SADB_X_SPDACQUIRE if error occured,
2312 * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2313 * policy(*) is without policy requests.
2316 * others: error number
2320 struct secpolicy *sp;
2322 struct mbuf *result = NULL, *m;
2323 struct secspacq *newspacq;
2325 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2326 IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2327 IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2328 ("policy not IPSEC %u", sp->policy));
2330 /* Get an entry to check whether sent message or not. */
2331 newspacq = key_getspacq(&sp->spidx);
2332 if (newspacq != NULL) {
2333 if (V_key_blockacq_count < newspacq->count) {
2334 /* reset counter and do send message. */
2335 newspacq->count = 0;
2337 /* increment counter and do nothing. */
2343 /* make new entry for blocking to send SADB_ACQUIRE. */
2344 newspacq = key_newspacq(&sp->spidx);
2345 if (newspacq == NULL)
2349 /* create new sadb_msg to reply. */
2350 m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2356 result->m_pkthdr.len = 0;
2357 for (m = result; m; m = m->m_next)
2358 result->m_pkthdr.len += m->m_len;
2360 mtod(result, struct sadb_msg *)->sadb_msg_len =
2361 PFKEY_UNIT64(result->m_pkthdr.len);
2363 return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2367 * SADB_SPDFLUSH processing
2370 * from the user, and free all entries in secpctree.
2374 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2376 * m will always be freed.
2379 key_spdflush(so, m, mhp)
2382 const struct sadb_msghdr *mhp;
2384 struct sadb_msg *newmsg;
2385 struct secpolicy *sp;
2388 IPSEC_ASSERT(so != NULL, ("null socket"));
2389 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2390 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2391 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2393 if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2394 return key_senderror(so, m, EINVAL);
2396 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2398 LIST_FOREACH(sp, &V_sptree[dir], chain)
2399 sp->state = IPSEC_SPSTATE_DEAD;
2403 if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2404 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2405 return key_senderror(so, m, ENOBUFS);
2411 m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2412 newmsg = mtod(m, struct sadb_msg *);
2413 newmsg->sadb_msg_errno = 0;
2414 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2416 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2420 * SADB_SPDDUMP processing
2423 * from the user, and dump all SP leaves
2428 * m will always be freed.
2431 key_spddump(so, m, mhp)
2434 const struct sadb_msghdr *mhp;
2436 struct secpolicy *sp;
2441 IPSEC_ASSERT(so != NULL, ("null socket"));
2442 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2443 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2444 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2446 /* search SPD entry and get buffer size. */
2449 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2450 LIST_FOREACH(sp, &V_sptree[dir], chain) {
2457 return key_senderror(so, m, ENOENT);
2460 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2461 LIST_FOREACH(sp, &V_sptree[dir], chain) {
2463 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2464 mhp->msg->sadb_msg_pid);
2467 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2476 static struct mbuf *
2477 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, u_int32_t pid)
2479 struct mbuf *result = NULL, *m;
2480 struct seclifetime lt;
2482 m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2488 * Note: do not send SADB_X_EXT_NAT_T_* here:
2489 * we are sending traffic endpoints.
2491 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2492 &sp->spidx.src.sa, sp->spidx.prefs,
2493 sp->spidx.ul_proto);
2498 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2499 &sp->spidx.dst.sa, sp->spidx.prefd,
2500 sp->spidx.ul_proto);
2511 lt.addtime=sp->created;
2512 lt.usetime= sp->lastused;
2513 m = key_setlifetime(<, SADB_EXT_LIFETIME_CURRENT);
2518 lt.addtime=sp->lifetime;
2519 lt.usetime= sp->validtime;
2520 m = key_setlifetime(<, SADB_EXT_LIFETIME_HARD);
2526 if ((result->m_flags & M_PKTHDR) == 0)
2529 if (result->m_len < sizeof(struct sadb_msg)) {
2530 result = m_pullup(result, sizeof(struct sadb_msg));
2535 result->m_pkthdr.len = 0;
2536 for (m = result; m; m = m->m_next)
2537 result->m_pkthdr.len += m->m_len;
2539 mtod(result, struct sadb_msg *)->sadb_msg_len =
2540 PFKEY_UNIT64(result->m_pkthdr.len);
2550 * get PFKEY message length for security policy and request.
2553 key_getspreqmsglen(sp)
2554 struct secpolicy *sp;
2558 tlen = sizeof(struct sadb_x_policy);
2560 /* if is the policy for ipsec ? */
2561 if (sp->policy != IPSEC_POLICY_IPSEC)
2564 /* get length of ipsec requests */
2566 struct ipsecrequest *isr;
2569 for (isr = sp->req; isr != NULL; isr = isr->next) {
2570 len = sizeof(struct sadb_x_ipsecrequest)
2571 + isr->saidx.src.sa.sa_len
2572 + isr->saidx.dst.sa.sa_len;
2574 tlen += PFKEY_ALIGN8(len);
2582 * SADB_SPDEXPIRE processing
2584 * <base, address(SD), lifetime(CH), policy>
2588 * others : error number
2592 struct secpolicy *sp;
2594 struct mbuf *result = NULL, *m;
2597 struct sadb_lifetime *lt;
2599 /* XXX: Why do we lock ? */
2601 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2603 /* set msg header */
2604 m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2611 /* create lifetime extension (current and hard) */
2612 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2613 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
2620 bzero(mtod(m, caddr_t), len);
2621 lt = mtod(m, struct sadb_lifetime *);
2622 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2623 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2624 lt->sadb_lifetime_allocations = 0;
2625 lt->sadb_lifetime_bytes = 0;
2626 lt->sadb_lifetime_addtime = sp->created;
2627 lt->sadb_lifetime_usetime = sp->lastused;
2628 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2629 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2630 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2631 lt->sadb_lifetime_allocations = 0;
2632 lt->sadb_lifetime_bytes = 0;
2633 lt->sadb_lifetime_addtime = sp->lifetime;
2634 lt->sadb_lifetime_usetime = sp->validtime;
2638 * Note: do not send SADB_X_EXT_NAT_T_* here:
2639 * we are sending traffic endpoints.
2642 /* set sadb_address for source */
2643 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2645 sp->spidx.prefs, sp->spidx.ul_proto);
2652 /* set sadb_address for destination */
2653 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2655 sp->spidx.prefd, sp->spidx.ul_proto);
2670 if ((result->m_flags & M_PKTHDR) == 0) {
2675 if (result->m_len < sizeof(struct sadb_msg)) {
2676 result = m_pullup(result, sizeof(struct sadb_msg));
2677 if (result == NULL) {
2683 result->m_pkthdr.len = 0;
2684 for (m = result; m; m = m->m_next)
2685 result->m_pkthdr.len += m->m_len;
2687 mtod(result, struct sadb_msg *)->sadb_msg_len =
2688 PFKEY_UNIT64(result->m_pkthdr.len);
2690 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2698 /* %%% SAD management */
2700 * allocating a memory for new SA head, and copy from the values of mhp.
2701 * OUT: NULL : failure due to the lack of memory.
2702 * others : pointer to new SA head.
2704 static struct secashead *
2706 struct secasindex *saidx;
2708 struct secashead *newsah;
2710 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2712 newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2713 if (newsah != NULL) {
2715 for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2716 LIST_INIT(&newsah->savtree[i]);
2717 newsah->saidx = *saidx;
2719 /* add to saidxtree */
2720 newsah->state = SADB_SASTATE_MATURE;
2723 LIST_INSERT_HEAD(&V_sahtree, newsah, chain);
2730 * delete SA index and all SA registerd.
2734 struct secashead *sah;
2736 struct secasvar *sav, *nextsav;
2740 IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2741 SAHTREE_LOCK_ASSERT();
2743 /* searching all SA registerd in the secindex. */
2745 stateidx < _ARRAYLEN(saorder_state_any);
2747 u_int state = saorder_state_any[stateidx];
2748 LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2749 if (sav->refcnt == 0) {
2751 KEY_CHKSASTATE(state, sav->state, __func__);
2753 * do NOT call KEY_FREESAV here:
2754 * it will only delete the sav if refcnt == 1,
2755 * where we already know that refcnt == 0
2759 /* give up to delete this sa */
2764 if (!zombie) { /* delete only if there are savs */
2765 /* remove from tree of SA index */
2766 if (__LIST_CHAINED(sah))
2767 LIST_REMOVE(sah, chain);
2768 if (sah->route_cache.sa_route.ro_rt) {
2769 RTFREE(sah->route_cache.sa_route.ro_rt);
2770 sah->route_cache.sa_route.ro_rt = (struct rtentry *)NULL;
2772 free(sah, M_IPSEC_SAH);
2777 * allocating a new SA with LARVAL state. key_add() and key_getspi() call,
2778 * and copy the values of mhp into new buffer.
2779 * When SAD message type is GETSPI:
2780 * to set sequence number from acq_seq++,
2781 * to set zero to SPI.
2782 * not to call key_setsava().
2784 * others : pointer to new secasvar.
2786 * does not modify mbuf. does not free mbuf on error.
2788 static struct secasvar *
2789 key_newsav(m, mhp, sah, errp, where, tag)
2791 const struct sadb_msghdr *mhp;
2792 struct secashead *sah;
2797 struct secasvar *newsav;
2798 const struct sadb_sa *xsa;
2800 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2801 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2802 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2803 IPSEC_ASSERT(sah != NULL, ("null secashead"));
2805 newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2806 if (newsav == NULL) {
2807 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2812 switch (mhp->msg->sadb_msg_type) {
2816 #ifdef IPSEC_DOSEQCHECK
2817 /* sync sequence number */
2818 if (mhp->msg->sadb_msg_seq == 0)
2820 (V_acq_seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq));
2823 newsav->seq = mhp->msg->sadb_msg_seq;
2828 if (mhp->ext[SADB_EXT_SA] == NULL) {
2829 free(newsav, M_IPSEC_SA);
2831 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2836 xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2837 newsav->spi = xsa->sadb_sa_spi;
2838 newsav->seq = mhp->msg->sadb_msg_seq;
2841 free(newsav, M_IPSEC_SA);
2848 /* copy sav values */
2849 if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2850 *errp = key_setsaval(newsav, m, mhp);
2852 free(newsav, M_IPSEC_SA);
2858 SECASVAR_LOCK_INIT(newsav);
2861 newsav->created = time_second;
2862 newsav->pid = mhp->msg->sadb_msg_pid;
2867 newsav->state = SADB_SASTATE_LARVAL;
2870 LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2874 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2875 printf("DP %s from %s:%u return SP:%p\n", __func__,
2876 where, tag, newsav));
2882 * free() SA variable entry.
2885 key_cleansav(struct secasvar *sav)
2888 * Cleanup xform state. Note that zeroize'ing causes the
2889 * keys to be cleared; otherwise we must do it ourself.
2891 if (sav->tdb_xform != NULL) {
2892 sav->tdb_xform->xf_zeroize(sav);
2893 sav->tdb_xform = NULL;
2895 KASSERT(sav->iv == NULL, ("iv but no xform"));
2896 if (sav->key_auth != NULL)
2897 bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2898 if (sav->key_enc != NULL)
2899 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2901 if (sav->key_auth != NULL) {
2902 if (sav->key_auth->key_data != NULL)
2903 free(sav->key_auth->key_data, M_IPSEC_MISC);
2904 free(sav->key_auth, M_IPSEC_MISC);
2905 sav->key_auth = NULL;
2907 if (sav->key_enc != NULL) {
2908 if (sav->key_enc->key_data != NULL)
2909 free(sav->key_enc->key_data, M_IPSEC_MISC);
2910 free(sav->key_enc, M_IPSEC_MISC);
2911 sav->key_enc = NULL;
2914 bzero(sav->sched, sav->schedlen);
2915 free(sav->sched, M_IPSEC_MISC);
2918 if (sav->replay != NULL) {
2919 free(sav->replay, M_IPSEC_MISC);
2922 if (sav->lft_c != NULL) {
2923 free(sav->lft_c, M_IPSEC_MISC);
2926 if (sav->lft_h != NULL) {
2927 free(sav->lft_h, M_IPSEC_MISC);
2930 if (sav->lft_s != NULL) {
2931 free(sav->lft_s, M_IPSEC_MISC);
2937 * free() SA variable entry.
2941 struct secasvar *sav;
2943 IPSEC_ASSERT(sav != NULL, ("null sav"));
2944 IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2946 /* remove from SA header */
2947 if (__LIST_CHAINED(sav))
2948 LIST_REMOVE(sav, chain);
2950 SECASVAR_LOCK_DESTROY(sav);
2951 free(sav, M_IPSEC_SA);
2958 * others : found, pointer to a SA.
2960 static struct secashead *
2962 struct secasindex *saidx;
2964 struct secashead *sah;
2967 LIST_FOREACH(sah, &V_sahtree, chain) {
2968 if (sah->state == SADB_SASTATE_DEAD)
2970 if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2979 * check not to be duplicated SPI.
2980 * NOTE: this function is too slow due to searching all SAD.
2983 * others : found, pointer to a SA.
2985 static struct secasvar *
2986 key_checkspidup(saidx, spi)
2987 struct secasindex *saidx;
2990 struct secashead *sah;
2991 struct secasvar *sav;
2993 /* check address family */
2994 if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2995 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
3003 LIST_FOREACH(sah, &V_sahtree, chain) {
3004 if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
3006 sav = key_getsavbyspi(sah, spi);
3016 * search SAD litmited alive SA, protocol, SPI.
3019 * others : found, pointer to a SA.
3021 static struct secasvar *
3022 key_getsavbyspi(sah, spi)
3023 struct secashead *sah;
3026 struct secasvar *sav;
3027 u_int stateidx, state;
3030 SAHTREE_LOCK_ASSERT();
3031 /* search all status */
3033 stateidx < _ARRAYLEN(saorder_state_alive);
3036 state = saorder_state_alive[stateidx];
3037 LIST_FOREACH(sav, &sah->savtree[state], chain) {
3040 if (sav->state != state) {
3041 ipseclog((LOG_DEBUG, "%s: "
3042 "invalid sav->state (queue: %d SA: %d)\n",
3043 __func__, state, sav->state));
3047 if (sav->spi == spi)
3056 * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3057 * You must update these if need.
3061 * does not modify mbuf. does not free mbuf on error.
3064 key_setsaval(sav, m, mhp)
3065 struct secasvar *sav;
3067 const struct sadb_msghdr *mhp;
3071 IPSEC_ASSERT(m != NULL, ("null mbuf"));
3072 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3073 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3075 /* initialization */
3077 sav->key_auth = NULL;
3078 sav->key_enc = NULL;
3085 sav->tdb_xform = NULL; /* transform */
3086 sav->tdb_encalgxform = NULL; /* encoding algorithm */
3087 sav->tdb_authalgxform = NULL; /* authentication algorithm */
3088 sav->tdb_compalgxform = NULL; /* compression algorithm */
3089 /* Initialize even if NAT-T not compiled in: */
3091 sav->natt_esp_frag_len = 0;
3094 if (mhp->ext[SADB_EXT_SA] != NULL) {
3095 const struct sadb_sa *sa0;
3097 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3098 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3103 sav->alg_auth = sa0->sadb_sa_auth;
3104 sav->alg_enc = sa0->sadb_sa_encrypt;
3105 sav->flags = sa0->sadb_sa_flags;
3108 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3109 sav->replay = (struct secreplay *)
3110 malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
3111 if (sav->replay == NULL) {
3112 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3117 if (sa0->sadb_sa_replay != 0)
3118 sav->replay->bitmap = (caddr_t)(sav->replay+1);
3119 sav->replay->wsize = sa0->sadb_sa_replay;
3123 /* Authentication keys */
3124 if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3125 const struct sadb_key *key0;
3128 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3129 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3132 if (len < sizeof(*key0)) {
3136 switch (mhp->msg->sadb_msg_satype) {
3137 case SADB_SATYPE_AH:
3138 case SADB_SATYPE_ESP:
3139 case SADB_X_SATYPE_TCPSIGNATURE:
3140 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3141 sav->alg_auth != SADB_X_AALG_NULL)
3144 case SADB_X_SATYPE_IPCOMP:
3150 ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3155 sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
3157 if (sav->key_auth == NULL ) {
3158 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3165 /* Encryption key */
3166 if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3167 const struct sadb_key *key0;
3170 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3171 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3174 if (len < sizeof(*key0)) {
3178 switch (mhp->msg->sadb_msg_satype) {
3179 case SADB_SATYPE_ESP:
3180 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3181 sav->alg_enc != SADB_EALG_NULL) {
3185 sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
3188 if (sav->key_enc == NULL) {
3189 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3195 case SADB_X_SATYPE_IPCOMP:
3196 if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3198 sav->key_enc = NULL; /*just in case*/
3200 case SADB_SATYPE_AH:
3201 case SADB_X_SATYPE_TCPSIGNATURE:
3207 ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3216 switch (mhp->msg->sadb_msg_satype) {
3217 case SADB_SATYPE_AH:
3218 error = xform_init(sav, XF_AH);
3220 case SADB_SATYPE_ESP:
3221 error = xform_init(sav, XF_ESP);
3223 case SADB_X_SATYPE_IPCOMP:
3224 error = xform_init(sav, XF_IPCOMP);
3226 case SADB_X_SATYPE_TCPSIGNATURE:
3227 error = xform_init(sav, XF_TCPSIGNATURE);
3231 ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3232 __func__, mhp->msg->sadb_msg_satype));
3237 sav->created = time_second;
3239 /* make lifetime for CURRENT */
3240 sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
3241 if (sav->lft_c == NULL) {
3242 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3247 sav->lft_c->allocations = 0;
3248 sav->lft_c->bytes = 0;
3249 sav->lft_c->addtime = time_second;
3250 sav->lft_c->usetime = 0;
3252 /* lifetimes for HARD and SOFT */
3254 const struct sadb_lifetime *lft0;
3256 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3258 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3262 sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3263 if (sav->lft_h == NULL) {
3264 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3268 /* to be initialize ? */
3271 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3273 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3277 sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3278 if (sav->lft_s == NULL) {
3279 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3283 /* to be initialize ? */
3290 /* initialization */
3297 * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3302 key_mature(struct secasvar *sav)
3306 /* check SPI value */
3307 switch (sav->sah->saidx.proto) {
3311 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
3312 * 1-255 reserved by IANA for future use,
3313 * 0 for implementation specific, local use.
3315 if (ntohl(sav->spi) <= 255) {
3316 ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3317 __func__, (u_int32_t)ntohl(sav->spi)));
3324 switch (sav->sah->saidx.proto) {
3327 if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3328 (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3329 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3330 "given to old-esp.\n", __func__));
3333 error = xform_init(sav, XF_ESP);
3337 if (sav->flags & SADB_X_EXT_DERIV) {
3338 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3339 "given to AH SA.\n", __func__));
3342 if (sav->alg_enc != SADB_EALG_NONE) {
3343 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3344 "mismated.\n", __func__));
3347 error = xform_init(sav, XF_AH);
3349 case IPPROTO_IPCOMP:
3350 if (sav->alg_auth != SADB_AALG_NONE) {
3351 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3352 "mismated.\n", __func__));
3355 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3356 && ntohl(sav->spi) >= 0x10000) {
3357 ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3361 error = xform_init(sav, XF_IPCOMP);
3364 if (sav->alg_enc != SADB_EALG_NONE) {
3365 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3366 "mismated.\n", __func__));
3369 error = xform_init(sav, XF_TCPSIGNATURE);
3372 ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3373 error = EPROTONOSUPPORT;
3378 key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3385 * subroutine for SADB_GET and SADB_DUMP.
3387 static struct mbuf *
3388 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3389 u_int32_t seq, u_int32_t pid)
3391 struct mbuf *result = NULL, *tres = NULL, *m;
3394 SADB_EXT_SA, SADB_X_EXT_SA2,
3395 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3396 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3397 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3398 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3399 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3401 SADB_X_EXT_NAT_T_TYPE,
3402 SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3403 SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3404 SADB_X_EXT_NAT_T_FRAG,
3408 m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3413 for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3415 switch (dumporder[i]) {
3417 m = key_setsadbsa(sav);
3422 case SADB_X_EXT_SA2:
3423 m = key_setsadbxsa2(sav->sah->saidx.mode,
3424 sav->replay ? sav->replay->count : 0,
3425 sav->sah->saidx.reqid);
3430 case SADB_EXT_ADDRESS_SRC:
3431 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3432 &sav->sah->saidx.src.sa,
3433 FULLMASK, IPSEC_ULPROTO_ANY);
3438 case SADB_EXT_ADDRESS_DST:
3439 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3440 &sav->sah->saidx.dst.sa,
3441 FULLMASK, IPSEC_ULPROTO_ANY);
3446 case SADB_EXT_KEY_AUTH:
3449 m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3454 case SADB_EXT_KEY_ENCRYPT:
3457 m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3462 case SADB_EXT_LIFETIME_CURRENT:
3465 m = key_setlifetime(sav->lft_c,
3466 SADB_EXT_LIFETIME_CURRENT);
3471 case SADB_EXT_LIFETIME_HARD:
3474 m = key_setlifetime(sav->lft_h,
3475 SADB_EXT_LIFETIME_HARD);
3480 case SADB_EXT_LIFETIME_SOFT:
3483 m = key_setlifetime(sav->lft_s,
3484 SADB_EXT_LIFETIME_SOFT);
3491 case SADB_X_EXT_NAT_T_TYPE:
3492 m = key_setsadbxtype(sav->natt_type);
3497 case SADB_X_EXT_NAT_T_DPORT:
3498 m = key_setsadbxport(
3499 KEY_PORTFROMSADDR(&sav->sah->saidx.dst),
3500 SADB_X_EXT_NAT_T_DPORT);
3505 case SADB_X_EXT_NAT_T_SPORT:
3506 m = key_setsadbxport(
3507 KEY_PORTFROMSADDR(&sav->sah->saidx.src),
3508 SADB_X_EXT_NAT_T_SPORT);
3513 case SADB_X_EXT_NAT_T_OAI:
3514 case SADB_X_EXT_NAT_T_OAR:
3515 case SADB_X_EXT_NAT_T_FRAG:
3516 /* We do not (yet) support those. */
3520 case SADB_EXT_ADDRESS_PROXY:
3521 case SADB_EXT_IDENTITY_SRC:
3522 case SADB_EXT_IDENTITY_DST:
3523 /* XXX: should we brought from SPD ? */
3524 case SADB_EXT_SENSITIVITY:
3537 m_cat(result, tres);
3538 if (result->m_len < sizeof(struct sadb_msg)) {
3539 result = m_pullup(result, sizeof(struct sadb_msg));
3544 result->m_pkthdr.len = 0;
3545 for (m = result; m; m = m->m_next)
3546 result->m_pkthdr.len += m->m_len;
3548 mtod(result, struct sadb_msg *)->sadb_msg_len =
3549 PFKEY_UNIT64(result->m_pkthdr.len);
3560 * set data into sadb_msg.
3562 static struct mbuf *
3563 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3564 pid_t pid, u_int16_t reserved)
3570 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3573 MGETHDR(m, M_NOWAIT, MT_DATA);
3574 if (m && len > MHLEN) {
3575 MCLGET(m, M_NOWAIT);
3576 if ((m->m_flags & M_EXT) == 0) {
3583 m->m_pkthdr.len = m->m_len = len;
3586 p = mtod(m, struct sadb_msg *);
3589 p->sadb_msg_version = PF_KEY_V2;
3590 p->sadb_msg_type = type;
3591 p->sadb_msg_errno = 0;
3592 p->sadb_msg_satype = satype;
3593 p->sadb_msg_len = PFKEY_UNIT64(tlen);
3594 p->sadb_msg_reserved = reserved;
3595 p->sadb_msg_seq = seq;
3596 p->sadb_msg_pid = (u_int32_t)pid;
3602 * copy secasvar data into sadb_address.
3604 static struct mbuf *
3606 struct secasvar *sav;
3612 len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3613 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3618 p = mtod(m, struct sadb_sa *);
3620 p->sadb_sa_len = PFKEY_UNIT64(len);
3621 p->sadb_sa_exttype = SADB_EXT_SA;
3622 p->sadb_sa_spi = sav->spi;
3623 p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3624 p->sadb_sa_state = sav->state;
3625 p->sadb_sa_auth = sav->alg_auth;
3626 p->sadb_sa_encrypt = sav->alg_enc;
3627 p->sadb_sa_flags = sav->flags;
3633 * set data into sadb_address.
3635 static struct mbuf *
3636 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto)
3639 struct sadb_address *p;
3642 len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3643 PFKEY_ALIGN8(saddr->sa_len);
3644 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3649 p = mtod(m, struct sadb_address *);
3652 p->sadb_address_len = PFKEY_UNIT64(len);
3653 p->sadb_address_exttype = exttype;
3654 p->sadb_address_proto = ul_proto;
3655 if (prefixlen == FULLMASK) {
3656 switch (saddr->sa_family) {
3658 prefixlen = sizeof(struct in_addr) << 3;
3661 prefixlen = sizeof(struct in6_addr) << 3;
3667 p->sadb_address_prefixlen = prefixlen;
3668 p->sadb_address_reserved = 0;
3671 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3678 * set data into sadb_x_sa2.
3680 static struct mbuf *
3681 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3684 struct sadb_x_sa2 *p;
3687 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3688 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3693 p = mtod(m, struct sadb_x_sa2 *);
3696 p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3697 p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3698 p->sadb_x_sa2_mode = mode;
3699 p->sadb_x_sa2_reserved1 = 0;
3700 p->sadb_x_sa2_reserved2 = 0;
3701 p->sadb_x_sa2_sequence = seq;
3702 p->sadb_x_sa2_reqid = reqid;
3709 * Set a type in sadb_x_nat_t_type.
3711 static struct mbuf *
3712 key_setsadbxtype(u_int16_t type)
3716 struct sadb_x_nat_t_type *p;
3718 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3720 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3725 p = mtod(m, struct sadb_x_nat_t_type *);
3728 p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3729 p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3730 p->sadb_x_nat_t_type_type = type;
3735 * Set a port in sadb_x_nat_t_port.
3736 * In contrast to default RFC 2367 behaviour, port is in network byte order.
3738 static struct mbuf *
3739 key_setsadbxport(u_int16_t port, u_int16_t type)
3743 struct sadb_x_nat_t_port *p;
3745 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3747 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3752 p = mtod(m, struct sadb_x_nat_t_port *);
3755 p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3756 p->sadb_x_nat_t_port_exttype = type;
3757 p->sadb_x_nat_t_port_port = port;
3763 * Get port from sockaddr. Port is in network byte order.
3766 key_portfromsaddr(struct sockaddr *sa)
3769 switch (sa->sa_family) {
3772 return ((struct sockaddr_in *)sa)->sin_port;
3776 return ((struct sockaddr_in6 *)sa)->sin6_port;
3779 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
3780 printf("DP %s unexpected address family %d\n",
3781 __func__, sa->sa_family));
3784 #endif /* IPSEC_NAT_T */
3787 * Set port in struct sockaddr. Port is in network byte order.
3790 key_porttosaddr(struct sockaddr *sa, u_int16_t port)
3793 switch (sa->sa_family) {
3796 ((struct sockaddr_in *)sa)->sin_port = port;
3801 ((struct sockaddr_in6 *)sa)->sin6_port = port;
3805 ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
3806 __func__, sa->sa_family));
3812 * set data into sadb_x_policy
3814 static struct mbuf *
3815 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3818 struct sadb_x_policy *p;
3821 len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3822 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3827 p = mtod(m, struct sadb_x_policy *);
3830 p->sadb_x_policy_len = PFKEY_UNIT64(len);
3831 p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3832 p->sadb_x_policy_type = type;
3833 p->sadb_x_policy_dir = dir;
3834 p->sadb_x_policy_id = id;
3840 /* Take a key message (sadb_key) from the socket and turn it into one
3841 * of the kernel's key structures (seckey).
3843 * IN: pointer to the src
3844 * OUT: NULL no more memory
3847 key_dup_keymsg(const struct sadb_key *src, u_int len,
3848 struct malloc_type *type)
3851 dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
3853 dst->bits = src->sadb_key_bits;
3854 dst->key_data = (char *)malloc(len, type, M_NOWAIT);
3855 if (dst->key_data != NULL) {
3856 bcopy((const char *)src + sizeof(struct sadb_key),
3857 dst->key_data, len);
3859 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3865 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3872 /* Take a lifetime message (sadb_lifetime) passed in on a socket and
3873 * turn it into one of the kernel's lifetime structures (seclifetime).
3875 * IN: pointer to the destination, source and malloc type
3876 * OUT: NULL, no more memory
3879 static struct seclifetime *
3880 key_dup_lifemsg(const struct sadb_lifetime *src,
3881 struct malloc_type *type)
3883 struct seclifetime *dst = NULL;
3885 dst = (struct seclifetime *)malloc(sizeof(struct seclifetime),
3889 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3891 dst->allocations = src->sadb_lifetime_allocations;
3892 dst->bytes = src->sadb_lifetime_bytes;
3893 dst->addtime = src->sadb_lifetime_addtime;
3894 dst->usetime = src->sadb_lifetime_usetime;
3899 /* compare my own address
3900 * OUT: 1: true, i.e. my address.
3905 struct sockaddr *sa;
3908 struct sockaddr_in *sin;
3909 struct in_ifaddr *ia;
3912 IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3914 switch (sa->sa_family) {
3917 sin = (struct sockaddr_in *)sa;
3919 TAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link)
3921 if (sin->sin_family == ia->ia_addr.sin_family &&
3922 sin->sin_len == ia->ia_addr.sin_len &&
3923 sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3925 IN_IFADDR_RUNLOCK();
3929 IN_IFADDR_RUNLOCK();
3934 return key_ismyaddr6((struct sockaddr_in6 *)sa);
3943 * compare my own address for IPv6.
3946 * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3948 #include <netinet6/in6_var.h>
3952 struct sockaddr_in6 *sin6;
3954 struct in6_ifaddr *ia;
3956 struct in6_multi *in6m;
3960 TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
3961 if (key_sockaddrcmp((struct sockaddr *)&sin6,
3962 (struct sockaddr *)&ia->ia_addr, 0) == 0) {
3963 IN6_IFADDR_RUNLOCK();
3970 * XXX why do we care about multlicast here while we don't care
3971 * about IPv4 multicast??
3975 IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3977 IN6_IFADDR_RUNLOCK();
3982 IN6_IFADDR_RUNLOCK();
3984 /* loopback, just for safety */
3985 if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3993 * compare two secasindex structure.
3994 * flag can specify to compare 2 saidxes.
3995 * compare two secasindex structure without both mode and reqid.
3996 * don't compare port.
3998 * saidx0: source, it can be in SAD.
4006 const struct secasindex *saidx0,
4007 const struct secasindex *saidx1,
4013 if (saidx0 == NULL && saidx1 == NULL)
4016 if (saidx0 == NULL || saidx1 == NULL)
4019 if (saidx0->proto != saidx1->proto)
4022 if (flag == CMP_EXACTLY) {
4023 if (saidx0->mode != saidx1->mode)
4025 if (saidx0->reqid != saidx1->reqid)
4027 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
4028 bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
4032 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4033 if (flag == CMP_MODE_REQID
4034 ||flag == CMP_REQID) {
4036 * If reqid of SPD is non-zero, unique SA is required.
4037 * The result must be of same reqid in this case.
4039 if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
4043 if (flag == CMP_MODE_REQID) {
4044 if (saidx0->mode != IPSEC_MODE_ANY
4045 && saidx0->mode != saidx1->mode)
4051 * If NAT-T is enabled, check ports for tunnel mode.
4052 * Do not check ports if they are set to zero in the SPD.
4053 * Also do not do it for native transport mode, as there
4054 * is no port information available in the SP.
4056 if ((saidx1->mode == IPSEC_MODE_TUNNEL ||
4057 (saidx1->mode == IPSEC_MODE_TRANSPORT &&
4058 saidx1->proto == IPPROTO_ESP)) &&
4059 saidx1->src.sa.sa_family == AF_INET &&
4060 saidx1->dst.sa.sa_family == AF_INET &&
4061 ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
4062 ((const struct sockaddr_in *)(&saidx1->dst))->sin_port)
4064 #endif /* IPSEC_NAT_T */
4066 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
4069 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
4078 * compare two secindex structure exactly.
4080 * spidx0: source, it is often in SPD.
4081 * spidx1: object, it is often from PFKEY message.
4087 key_cmpspidx_exactly(
4088 struct secpolicyindex *spidx0,
4089 struct secpolicyindex *spidx1)
4092 if (spidx0 == NULL && spidx1 == NULL)
4095 if (spidx0 == NULL || spidx1 == NULL)
4098 if (spidx0->prefs != spidx1->prefs
4099 || spidx0->prefd != spidx1->prefd
4100 || spidx0->ul_proto != spidx1->ul_proto)
4103 return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4104 key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4108 * compare two secindex structure with mask.
4110 * spidx0: source, it is often in SPD.
4111 * spidx1: object, it is often from IP header.
4117 key_cmpspidx_withmask(
4118 struct secpolicyindex *spidx0,
4119 struct secpolicyindex *spidx1)
4122 if (spidx0 == NULL && spidx1 == NULL)
4125 if (spidx0 == NULL || spidx1 == NULL)
4128 if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4129 spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4130 spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4131 spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4134 /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4135 if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4136 && spidx0->ul_proto != spidx1->ul_proto)
4139 switch (spidx0->src.sa.sa_family) {
4141 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4142 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4144 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4145 &spidx1->src.sin.sin_addr, spidx0->prefs))
4149 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4150 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4153 * scope_id check. if sin6_scope_id is 0, we regard it
4154 * as a wildcard scope, which matches any scope zone ID.
4156 if (spidx0->src.sin6.sin6_scope_id &&
4157 spidx1->src.sin6.sin6_scope_id &&
4158 spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4160 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4161 &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4166 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4171 switch (spidx0->dst.sa.sa_family) {
4173 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4174 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4176 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4177 &spidx1->dst.sin.sin_addr, spidx0->prefd))
4181 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4182 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4185 * scope_id check. if sin6_scope_id is 0, we regard it
4186 * as a wildcard scope, which matches any scope zone ID.
4188 if (spidx0->dst.sin6.sin6_scope_id &&
4189 spidx1->dst.sin6.sin6_scope_id &&
4190 spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4192 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4193 &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4198 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4203 /* XXX Do we check other field ? e.g. flowinfo */
4208 /* returns 0 on match */
4211 const struct sockaddr *sa1,
4212 const struct sockaddr *sa2,
4218 #define satosin(s) ((const struct sockaddr_in *)s)
4222 #define satosin6(s) ((const struct sockaddr_in6 *)s)
4223 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4226 switch (sa1->sa_family) {
4228 if (sa1->sa_len != sizeof(struct sockaddr_in))
4230 if (satosin(sa1)->sin_addr.s_addr !=
4231 satosin(sa2)->sin_addr.s_addr) {
4234 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4238 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4239 return 1; /*EINVAL*/
4240 if (satosin6(sa1)->sin6_scope_id !=
4241 satosin6(sa2)->sin6_scope_id) {
4244 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4245 &satosin6(sa2)->sin6_addr)) {
4249 satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4254 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4265 * compare two buffers with mask.
4269 * bits: Number of bits to compare
4275 key_bbcmp(const void *a1, const void *a2, u_int bits)
4277 const unsigned char *p1 = a1;
4278 const unsigned char *p2 = a2;
4280 /* XXX: This could be considerably faster if we compare a word
4281 * at a time, but it is complicated on LSB Endian machines */
4283 /* Handle null pointers */
4284 if (p1 == NULL || p2 == NULL)
4294 u_int8_t mask = ~((1<<(8-bits))-1);
4295 if ((*p1 & mask) != (*p2 & mask))
4298 return 1; /* Match! */
4302 key_flush_spd(time_t now)
4304 static u_int16_t sptree_scangen = 0;
4305 u_int16_t gen = sptree_scangen++;
4306 struct secpolicy *sp;
4310 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4313 LIST_FOREACH(sp, &V_sptree[dir], chain) {
4314 if (sp->scangen == gen) /* previously handled */
4317 if (sp->state == IPSEC_SPSTATE_DEAD &&
4320 * Ensure that we only decrease refcnt once,
4321 * when we're the last consumer.
4322 * Directly call SP_DELREF/key_delsp instead
4323 * of KEY_FREESP to avoid unlocking/relocking
4324 * SPTREE_LOCK before key_delsp: may refcnt
4325 * be increased again during that time ?
4326 * NB: also clean entries created by
4334 if (sp->lifetime == 0 && sp->validtime == 0)
4336 if ((sp->lifetime && now - sp->created > sp->lifetime)
4337 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4338 sp->state = IPSEC_SPSTATE_DEAD;
4349 key_flush_sad(time_t now)
4351 struct secashead *sah, *nextsah;
4352 struct secasvar *sav, *nextsav;
4356 LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4357 /* if sah has been dead, then delete it and process next sah. */
4358 if (sah->state == SADB_SASTATE_DEAD) {
4363 /* if LARVAL entry doesn't become MATURE, delete it. */
4364 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4365 /* Need to also check refcnt for a larval SA ??? */
4366 if (now - sav->created > V_key_larval_lifetime)
4371 * check MATURE entry to start to send expire message
4374 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4375 /* we don't need to check. */
4376 if (sav->lft_s == NULL)
4380 if (sav->lft_c == NULL) {
4381 ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4382 "time, why?\n", __func__));
4386 /* check SOFT lifetime */
4387 if (sav->lft_s->addtime != 0 &&
4388 now - sav->created > sav->lft_s->addtime) {
4389 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4391 * Actually, only send expire message if
4392 * SA has been used, as it was done before,
4393 * but should we always send such message,
4394 * and let IKE daemon decide if it should be
4395 * renegotiated or not ?
4396 * XXX expire message will actually NOT be
4397 * sent if SA is only used after soft
4398 * lifetime has been reached, see below
4401 if (sav->lft_c->usetime != 0)
4404 /* check SOFT lifetime by bytes */
4406 * XXX I don't know the way to delete this SA
4407 * when new SA is installed. Caution when it's
4408 * installed too big lifetime by time.
4410 else if (sav->lft_s->bytes != 0 &&
4411 sav->lft_s->bytes < sav->lft_c->bytes) {
4413 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4415 * XXX If we keep to send expire
4416 * message in the status of
4417 * DYING. Do remove below code.
4423 /* check DYING entry to change status to DEAD. */
4424 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4425 /* we don't need to check. */
4426 if (sav->lft_h == NULL)
4430 if (sav->lft_c == NULL) {
4431 ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4432 "time, why?\n", __func__));
4436 if (sav->lft_h->addtime != 0 &&
4437 now - sav->created > sav->lft_h->addtime) {
4438 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4441 #if 0 /* XXX Should we keep to send expire message until HARD lifetime ? */
4442 else if (sav->lft_s != NULL
4443 && sav->lft_s->addtime != 0
4444 && now - sav->created > sav->lft_s->addtime) {
4446 * XXX: should be checked to be
4447 * installed the valid SA.
4451 * If there is no SA then sending
4457 /* check HARD lifetime by bytes */
4458 else if (sav->lft_h->bytes != 0 &&
4459 sav->lft_h->bytes < sav->lft_c->bytes) {
4460 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4465 /* delete entry in DEAD */
4466 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4468 if (sav->state != SADB_SASTATE_DEAD) {
4469 ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4470 "(queue: %d SA: %d): kill it anyway\n",
4472 SADB_SASTATE_DEAD, sav->state));
4475 * do not call key_freesav() here.
4476 * sav should already be freed, and sav->refcnt
4477 * shows other references to sav
4478 * (such as from SPD).
4486 key_flush_acq(time_t now)
4488 struct secacq *acq, *nextacq;
4492 for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4493 nextacq = LIST_NEXT(acq, chain);
4494 if (now - acq->created > V_key_blockacq_lifetime
4495 && __LIST_CHAINED(acq)) {
4496 LIST_REMOVE(acq, chain);
4497 free(acq, M_IPSEC_SAQ);
4504 key_flush_spacq(time_t now)
4506 struct secspacq *acq, *nextacq;
4510 for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4511 nextacq = LIST_NEXT(acq, chain);
4512 if (now - acq->created > V_key_blockacq_lifetime
4513 && __LIST_CHAINED(acq)) {
4514 LIST_REMOVE(acq, chain);
4515 free(acq, M_IPSEC_SAQ);
4523 * scanning SPD and SAD to check status for each entries,
4524 * and do to remove or to expire.
4525 * XXX: year 2038 problem may remain.
4528 key_timehandler(void)
4530 VNET_ITERATOR_DECL(vnet_iter);
4531 time_t now = time_second;
4533 VNET_LIST_RLOCK_NOSLEEP();
4534 VNET_FOREACH(vnet_iter) {
4535 CURVNET_SET(vnet_iter);
4539 key_flush_spacq(now);
4542 VNET_LIST_RUNLOCK_NOSLEEP();
4544 #ifndef IPSEC_DEBUG2
4545 /* do exchange to tick time !! */
4546 (void)timeout((void *)key_timehandler, (void *)0, hz);
4547 #endif /* IPSEC_DEBUG2 */
4555 key_randomfill(&value, sizeof(value));
4560 key_randomfill(p, l)
4566 static int warn = 1;
4569 n = (size_t)read_random(p, (u_int)l);
4573 bcopy(&v, (u_int8_t *)p + n,
4574 l - n < sizeof(v) ? l - n : sizeof(v));
4578 printf("WARNING: pseudo-random number generator "
4579 "used for IPsec processing\n");
4586 * map SADB_SATYPE_* to IPPROTO_*.
4587 * if satype == SADB_SATYPE then satype is mapped to ~0.
4589 * 0: invalid satype.
4592 key_satype2proto(u_int8_t satype)
4595 case SADB_SATYPE_UNSPEC:
4596 return IPSEC_PROTO_ANY;
4597 case SADB_SATYPE_AH:
4599 case SADB_SATYPE_ESP:
4601 case SADB_X_SATYPE_IPCOMP:
4602 return IPPROTO_IPCOMP;
4603 case SADB_X_SATYPE_TCPSIGNATURE:
4612 * map IPPROTO_* to SADB_SATYPE_*
4614 * 0: invalid protocol type.
4617 key_proto2satype(u_int16_t proto)
4621 return SADB_SATYPE_AH;
4623 return SADB_SATYPE_ESP;
4624 case IPPROTO_IPCOMP:
4625 return SADB_X_SATYPE_IPCOMP;
4627 return SADB_X_SATYPE_TCPSIGNATURE;
4636 * SADB_GETSPI processing is to receive
4637 * <base, (SA2), src address, dst address, (SPI range)>
4638 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4639 * tree with the status of LARVAL, and send
4640 * <base, SA(*), address(SD)>
4643 * IN: mhp: pointer to the pointer to each header.
4644 * OUT: NULL if fail.
4645 * other if success, return pointer to the message to send.
4648 key_getspi(so, m, mhp)
4651 const struct sadb_msghdr *mhp;
4653 struct sadb_address *src0, *dst0;
4654 struct secasindex saidx;
4655 struct secashead *newsah;
4656 struct secasvar *newsav;
4663 IPSEC_ASSERT(so != NULL, ("null socket"));
4664 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4665 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4666 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4668 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4669 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4670 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4672 return key_senderror(so, m, EINVAL);
4674 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4675 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4676 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4678 return key_senderror(so, m, EINVAL);
4680 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4681 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4682 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4684 mode = IPSEC_MODE_ANY;
4688 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4689 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4691 /* map satype to proto */
4692 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4693 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4695 return key_senderror(so, m, EINVAL);
4699 * Make sure the port numbers are zero.
4700 * In case of NAT-T we will update them later if needed.
4702 switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4704 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4705 sizeof(struct sockaddr_in))
4706 return key_senderror(so, m, EINVAL);
4707 ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4710 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4711 sizeof(struct sockaddr_in6))
4712 return key_senderror(so, m, EINVAL);
4713 ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4718 switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4720 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4721 sizeof(struct sockaddr_in))
4722 return key_senderror(so, m, EINVAL);
4723 ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4726 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4727 sizeof(struct sockaddr_in6))
4728 return key_senderror(so, m, EINVAL);
4729 ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4735 /* XXX boundary check against sa_len */
4736 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4740 * Handle NAT-T info if present.
4741 * We made sure the port numbers are zero above, so we do
4742 * not have to worry in case we do not update them.
4744 if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
4745 ipseclog((LOG_DEBUG, "%s: NAT-T OAi present\n", __func__));
4746 if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
4747 ipseclog((LOG_DEBUG, "%s: NAT-T OAr present\n", __func__));
4749 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4750 mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4751 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4752 struct sadb_x_nat_t_type *type;
4753 struct sadb_x_nat_t_port *sport, *dport;
4755 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4756 mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4757 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4758 ipseclog((LOG_DEBUG, "%s: invalid nat-t message "
4759 "passed.\n", __func__));
4760 return key_senderror(so, m, EINVAL);
4763 sport = (struct sadb_x_nat_t_port *)
4764 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4765 dport = (struct sadb_x_nat_t_port *)
4766 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4769 KEY_PORTTOSADDR(&saidx.src, sport->sadb_x_nat_t_port_port);
4771 KEY_PORTTOSADDR(&saidx.dst, dport->sadb_x_nat_t_port_port);
4775 /* SPI allocation */
4776 spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4779 return key_senderror(so, m, EINVAL);
4781 /* get a SA index */
4782 if ((newsah = key_getsah(&saidx)) == NULL) {
4783 /* create a new SA index */
4784 if ((newsah = key_newsah(&saidx)) == NULL) {
4785 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4786 return key_senderror(so, m, ENOBUFS);
4792 newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4793 if (newsav == NULL) {
4794 /* XXX don't free new SA index allocated in above. */
4795 return key_senderror(so, m, error);
4799 newsav->spi = htonl(spi);
4801 /* delete the entry in acqtree */
4802 if (mhp->msg->sadb_msg_seq != 0) {
4804 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4805 /* reset counter in order to deletion by timehandler. */
4806 acq->created = time_second;
4812 struct mbuf *n, *nn;
4813 struct sadb_sa *m_sa;
4814 struct sadb_msg *newmsg;
4817 /* create new sadb_msg to reply. */
4818 len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4819 PFKEY_ALIGN8(sizeof(struct sadb_sa));
4821 MGETHDR(n, M_NOWAIT, MT_DATA);
4823 MCLGET(n, M_NOWAIT);
4824 if ((n->m_flags & M_EXT) == 0) {
4830 return key_senderror(so, m, ENOBUFS);
4836 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4837 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4839 m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4840 m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4841 m_sa->sadb_sa_exttype = SADB_EXT_SA;
4842 m_sa->sadb_sa_spi = htonl(spi);
4843 off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4845 IPSEC_ASSERT(off == len,
4846 ("length inconsistency (off %u len %u)", off, len));
4848 n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4849 SADB_EXT_ADDRESS_DST);
4852 return key_senderror(so, m, ENOBUFS);
4855 if (n->m_len < sizeof(struct sadb_msg)) {
4856 n = m_pullup(n, sizeof(struct sadb_msg));
4858 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4861 n->m_pkthdr.len = 0;
4862 for (nn = n; nn; nn = nn->m_next)
4863 n->m_pkthdr.len += nn->m_len;
4865 newmsg = mtod(n, struct sadb_msg *);
4866 newmsg->sadb_msg_seq = newsav->seq;
4867 newmsg->sadb_msg_errno = 0;
4868 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4871 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4876 * allocating new SPI
4877 * called by key_getspi().
4883 key_do_getnewspi(spirange, saidx)
4884 struct sadb_spirange *spirange;
4885 struct secasindex *saidx;
4889 int count = V_key_spi_trycnt;
4891 /* set spi range to allocate */
4892 if (spirange != NULL) {
4893 min = spirange->sadb_spirange_min;
4894 max = spirange->sadb_spirange_max;
4896 min = V_key_spi_minval;
4897 max = V_key_spi_maxval;
4899 /* IPCOMP needs 2-byte SPI */
4900 if (saidx->proto == IPPROTO_IPCOMP) {
4907 t = min; min = max; max = t;
4912 if (key_checkspidup(saidx, min) != NULL) {
4913 ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4918 count--; /* taking one cost. */
4926 /* when requesting to allocate spi ranged */
4928 /* generate pseudo-random SPI value ranged. */
4929 newspi = min + (key_random() % (max - min + 1));
4931 if (key_checkspidup(saidx, newspi) == NULL)
4935 if (count == 0 || newspi == 0) {
4936 ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4943 keystat.getspi_count =
4944 (keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4950 * SADB_UPDATE processing
4952 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4953 * key(AE), (identity(SD),) (sensitivity)>
4954 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4956 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4957 * (identity(SD),) (sensitivity)>
4960 * m will always be freed.
4963 key_update(so, m, mhp)
4966 const struct sadb_msghdr *mhp;
4968 struct sadb_sa *sa0;
4969 struct sadb_address *src0, *dst0;
4971 struct sadb_x_nat_t_type *type;
4972 struct sadb_x_nat_t_port *sport, *dport;
4973 struct sadb_address *iaddr, *raddr;
4974 struct sadb_x_nat_t_frag *frag;
4976 struct secasindex saidx;
4977 struct secashead *sah;
4978 struct secasvar *sav;
4984 IPSEC_ASSERT(so != NULL, ("null socket"));
4985 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4986 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4987 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4989 /* map satype to proto */
4990 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4991 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4993 return key_senderror(so, m, EINVAL);
4996 if (mhp->ext[SADB_EXT_SA] == NULL ||
4997 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4998 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4999 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5000 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5001 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5002 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5003 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5004 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5005 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5006 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5007 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5009 return key_senderror(so, m, EINVAL);
5011 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5012 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5013 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5014 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5016 return key_senderror(so, m, EINVAL);
5018 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5019 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5020 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5022 mode = IPSEC_MODE_ANY;
5025 /* XXX boundary checking for other extensions */
5027 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5028 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5029 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5031 /* XXX boundary check against sa_len */
5032 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5035 * Make sure the port numbers are zero.
5036 * In case of NAT-T we will update them later if needed.
5038 KEY_PORTTOSADDR(&saidx.src, 0);
5039 KEY_PORTTOSADDR(&saidx.dst, 0);
5043 * Handle NAT-T info if present.
5045 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5046 mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5047 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5049 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5050 mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5051 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5052 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5054 return key_senderror(so, m, EINVAL);
5057 type = (struct sadb_x_nat_t_type *)
5058 mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5059 sport = (struct sadb_x_nat_t_port *)
5060 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5061 dport = (struct sadb_x_nat_t_port *)
5062 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5067 if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5068 mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5069 if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5070 mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5071 ipseclog((LOG_DEBUG, "%s: invalid message\n",
5073 return key_senderror(so, m, EINVAL);
5075 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5076 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5077 ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5079 iaddr = raddr = NULL;
5081 if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5082 if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5083 ipseclog((LOG_DEBUG, "%s: invalid message\n",
5085 return key_senderror(so, m, EINVAL);
5087 frag = (struct sadb_x_nat_t_frag *)
5088 mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5094 /* get a SA header */
5095 if ((sah = key_getsah(&saidx)) == NULL) {
5096 ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
5097 return key_senderror(so, m, ENOENT);
5100 /* set spidx if there */
5102 error = key_setident(sah, m, mhp);
5104 return key_senderror(so, m, error);
5106 /* find a SA with sequence number. */
5107 #ifdef IPSEC_DOSEQCHECK
5108 if (mhp->msg->sadb_msg_seq != 0
5109 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
5110 ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
5111 "exists.\n", __func__, mhp->msg->sadb_msg_seq));
5112 return key_senderror(so, m, ENOENT);
5116 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5119 ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
5120 __func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5121 return key_senderror(so, m, EINVAL);
5125 /* validity check */
5126 if (sav->sah->saidx.proto != proto) {
5127 ipseclog((LOG_DEBUG, "%s: protocol mismatched "
5128 "(DB=%u param=%u)\n", __func__,
5129 sav->sah->saidx.proto, proto));
5130 return key_senderror(so, m, EINVAL);
5132 #ifdef IPSEC_DOSEQCHECK
5133 if (sav->spi != sa0->sadb_sa_spi) {
5134 ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
5136 (u_int32_t)ntohl(sav->spi),
5137 (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5138 return key_senderror(so, m, EINVAL);
5141 if (sav->pid != mhp->msg->sadb_msg_pid) {
5142 ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
5143 __func__, sav->pid, mhp->msg->sadb_msg_pid));
5144 return key_senderror(so, m, EINVAL);
5147 /* copy sav values */
5148 error = key_setsaval(sav, m, mhp);
5151 return key_senderror(so, m, error);
5156 * Handle more NAT-T info if present,
5157 * now that we have a sav to fill.
5160 sav->natt_type = type->sadb_x_nat_t_type_type;
5163 KEY_PORTTOSADDR(&sav->sah->saidx.src,
5164 sport->sadb_x_nat_t_port_port);
5166 KEY_PORTTOSADDR(&sav->sah->saidx.dst,
5167 dport->sadb_x_nat_t_port_port);
5171 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5172 * We should actually check for a minimum MTU here, if we
5173 * want to support it in ip_output.
5176 sav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5180 /* check SA values to be mature. */
5181 if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
5183 return key_senderror(so, m, 0);
5189 /* set msg buf from mhp */
5190 n = key_getmsgbuf_x1(m, mhp);
5192 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5193 return key_senderror(so, m, ENOBUFS);
5197 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5202 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5203 * only called by key_update().
5206 * others : found, pointer to a SA.
5208 #ifdef IPSEC_DOSEQCHECK
5209 static struct secasvar *
5210 key_getsavbyseq(sah, seq)
5211 struct secashead *sah;
5214 struct secasvar *sav;
5217 state = SADB_SASTATE_LARVAL;
5219 /* search SAD with sequence number ? */
5220 LIST_FOREACH(sav, &sah->savtree[state], chain) {
5222 KEY_CHKSASTATE(state, sav->state, __func__);
5224 if (sav->seq == seq) {
5226 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
5227 printf("DP %s cause refcnt++:%d SA:%p\n",
5228 __func__, sav->refcnt, sav));
5238 * SADB_ADD processing
5239 * add an entry to SA database, when received
5240 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5241 * key(AE), (identity(SD),) (sensitivity)>
5244 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5245 * (identity(SD),) (sensitivity)>
5248 * IGNORE identity and sensitivity messages.
5250 * m will always be freed.
5256 const struct sadb_msghdr *mhp;
5258 struct sadb_sa *sa0;
5259 struct sadb_address *src0, *dst0;
5261 struct sadb_x_nat_t_type *type;
5262 struct sadb_address *iaddr, *raddr;
5263 struct sadb_x_nat_t_frag *frag;
5265 struct secasindex saidx;
5266 struct secashead *newsah;
5267 struct secasvar *newsav;
5273 IPSEC_ASSERT(so != NULL, ("null socket"));
5274 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5275 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5276 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5278 /* map satype to proto */
5279 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5280 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5282 return key_senderror(so, m, EINVAL);
5285 if (mhp->ext[SADB_EXT_SA] == NULL ||
5286 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5287 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5288 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5289 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5290 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5291 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5292 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5293 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5294 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5295 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5296 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5298 return key_senderror(so, m, EINVAL);
5300 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5301 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5302 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5304 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5306 return key_senderror(so, m, EINVAL);
5308 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5309 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5310 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5312 mode = IPSEC_MODE_ANY;
5316 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5317 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5318 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5320 /* XXX boundary check against sa_len */
5321 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5324 * Make sure the port numbers are zero.
5325 * In case of NAT-T we will update them later if needed.
5327 KEY_PORTTOSADDR(&saidx.src, 0);
5328 KEY_PORTTOSADDR(&saidx.dst, 0);
5332 * Handle NAT-T info if present.
5334 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5335 mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5336 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5337 struct sadb_x_nat_t_port *sport, *dport;
5339 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5340 mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5341 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5342 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5344 return key_senderror(so, m, EINVAL);
5347 type = (struct sadb_x_nat_t_type *)
5348 mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5349 sport = (struct sadb_x_nat_t_port *)
5350 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5351 dport = (struct sadb_x_nat_t_port *)
5352 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5355 KEY_PORTTOSADDR(&saidx.src,
5356 sport->sadb_x_nat_t_port_port);
5358 KEY_PORTTOSADDR(&saidx.dst,
5359 dport->sadb_x_nat_t_port_port);
5363 if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5364 mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5365 if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5366 mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5367 ipseclog((LOG_DEBUG, "%s: invalid message\n",
5369 return key_senderror(so, m, EINVAL);
5371 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5372 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5373 ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5375 iaddr = raddr = NULL;
5377 if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5378 if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5379 ipseclog((LOG_DEBUG, "%s: invalid message\n",
5381 return key_senderror(so, m, EINVAL);
5383 frag = (struct sadb_x_nat_t_frag *)
5384 mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5390 /* get a SA header */
5391 if ((newsah = key_getsah(&saidx)) == NULL) {
5392 /* create a new SA header */
5393 if ((newsah = key_newsah(&saidx)) == NULL) {
5394 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
5395 return key_senderror(so, m, ENOBUFS);
5399 /* set spidx if there */
5401 error = key_setident(newsah, m, mhp);
5403 return key_senderror(so, m, error);
5406 /* create new SA entry. */
5407 /* We can create new SA only if SPI is differenct. */
5409 newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5411 if (newsav != NULL) {
5412 ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5413 return key_senderror(so, m, EEXIST);
5415 newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5416 if (newsav == NULL) {
5417 return key_senderror(so, m, error);
5422 * Handle more NAT-T info if present,
5423 * now that we have a sav to fill.
5426 newsav->natt_type = type->sadb_x_nat_t_type_type;
5430 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5431 * We should actually check for a minimum MTU here, if we
5432 * want to support it in ip_output.
5435 newsav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5439 /* check SA values to be mature. */
5440 if ((error = key_mature(newsav)) != 0) {
5441 KEY_FREESAV(&newsav);
5442 return key_senderror(so, m, error);
5446 * don't call key_freesav() here, as we would like to keep the SA
5447 * in the database on success.
5453 /* set msg buf from mhp */
5454 n = key_getmsgbuf_x1(m, mhp);
5456 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5457 return key_senderror(so, m, ENOBUFS);
5461 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5467 key_setident(sah, m, mhp)
5468 struct secashead *sah;
5470 const struct sadb_msghdr *mhp;
5472 const struct sadb_ident *idsrc, *iddst;
5473 int idsrclen, iddstlen;
5475 IPSEC_ASSERT(sah != NULL, ("null secashead"));
5476 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5477 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5478 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5480 /* don't make buffer if not there */
5481 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5482 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5488 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5489 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5490 ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5494 idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5495 iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5496 idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5497 iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5499 /* validity check */
5500 if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5501 ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5505 switch (idsrc->sadb_ident_type) {
5506 case SADB_IDENTTYPE_PREFIX:
5507 case SADB_IDENTTYPE_FQDN:
5508 case SADB_IDENTTYPE_USERFQDN:
5510 /* XXX do nothing */
5516 /* make structure */
5517 sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5518 if (sah->idents == NULL) {
5519 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5522 sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5523 if (sah->identd == NULL) {
5524 free(sah->idents, M_IPSEC_MISC);
5526 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5529 sah->idents->type = idsrc->sadb_ident_type;
5530 sah->idents->id = idsrc->sadb_ident_id;
5532 sah->identd->type = iddst->sadb_ident_type;
5533 sah->identd->id = iddst->sadb_ident_id;
5539 * m will not be freed on return.
5540 * it is caller's responsibility to free the result.
5542 static struct mbuf *
5543 key_getmsgbuf_x1(m, mhp)
5545 const struct sadb_msghdr *mhp;
5549 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5550 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5551 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5553 /* create new sadb_msg to reply. */
5554 n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5555 SADB_EXT_SA, SADB_X_EXT_SA2,
5556 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5557 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5558 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5562 if (n->m_len < sizeof(struct sadb_msg)) {
5563 n = m_pullup(n, sizeof(struct sadb_msg));
5567 mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5568 mtod(n, struct sadb_msg *)->sadb_msg_len =
5569 PFKEY_UNIT64(n->m_pkthdr.len);
5574 static int key_delete_all __P((struct socket *, struct mbuf *,
5575 const struct sadb_msghdr *, u_int16_t));
5578 * SADB_DELETE processing
5580 * <base, SA(*), address(SD)>
5581 * from the ikmpd, and set SADB_SASTATE_DEAD,
5583 * <base, SA(*), address(SD)>
5586 * m will always be freed.
5589 key_delete(so, m, mhp)
5592 const struct sadb_msghdr *mhp;
5594 struct sadb_sa *sa0;
5595 struct sadb_address *src0, *dst0;
5596 struct secasindex saidx;
5597 struct secashead *sah;
5598 struct secasvar *sav = NULL;
5601 IPSEC_ASSERT(so != NULL, ("null socket"));
5602 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5603 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5604 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5606 /* map satype to proto */
5607 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5608 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5610 return key_senderror(so, m, EINVAL);
5613 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5614 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5615 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5617 return key_senderror(so, m, EINVAL);
5620 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5621 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5622 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5624 return key_senderror(so, m, EINVAL);
5627 if (mhp->ext[SADB_EXT_SA] == NULL) {
5629 * Caller wants us to delete all non-LARVAL SAs
5630 * that match the src/dst. This is used during
5631 * IKE INITIAL-CONTACT.
5633 ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5634 return key_delete_all(so, m, mhp, proto);
5635 } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5636 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5638 return key_senderror(so, m, EINVAL);
5641 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5642 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5643 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5645 /* XXX boundary check against sa_len */
5646 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5649 * Make sure the port numbers are zero.
5650 * In case of NAT-T we will update them later if needed.
5652 KEY_PORTTOSADDR(&saidx.src, 0);
5653 KEY_PORTTOSADDR(&saidx.dst, 0);
5657 * Handle NAT-T info if present.
5659 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5660 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5661 struct sadb_x_nat_t_port *sport, *dport;
5663 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5664 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5665 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5667 return key_senderror(so, m, EINVAL);
5670 sport = (struct sadb_x_nat_t_port *)
5671 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5672 dport = (struct sadb_x_nat_t_port *)
5673 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5676 KEY_PORTTOSADDR(&saidx.src,
5677 sport->sadb_x_nat_t_port_port);
5679 KEY_PORTTOSADDR(&saidx.dst,
5680 dport->sadb_x_nat_t_port_port);
5684 /* get a SA header */
5686 LIST_FOREACH(sah, &V_sahtree, chain) {
5687 if (sah->state == SADB_SASTATE_DEAD)
5689 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5692 /* get a SA with SPI. */
5693 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5699 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5700 return key_senderror(so, m, ENOENT);
5703 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5709 struct sadb_msg *newmsg;
5711 /* create new sadb_msg to reply. */
5712 /* XXX-BZ NAT-T extensions? */
5713 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5714 SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5716 return key_senderror(so, m, ENOBUFS);
5718 if (n->m_len < sizeof(struct sadb_msg)) {
5719 n = m_pullup(n, sizeof(struct sadb_msg));
5721 return key_senderror(so, m, ENOBUFS);
5723 newmsg = mtod(n, struct sadb_msg *);
5724 newmsg->sadb_msg_errno = 0;
5725 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5728 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5733 * delete all SAs for src/dst. Called from key_delete().
5736 key_delete_all(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp,
5739 struct sadb_address *src0, *dst0;
5740 struct secasindex saidx;
5741 struct secashead *sah;
5742 struct secasvar *sav, *nextsav;
5743 u_int stateidx, state;
5745 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5746 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5748 /* XXX boundary check against sa_len */
5749 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5752 * Make sure the port numbers are zero.
5753 * In case of NAT-T we will update them later if needed.
5755 KEY_PORTTOSADDR(&saidx.src, 0);
5756 KEY_PORTTOSADDR(&saidx.dst, 0);
5760 * Handle NAT-T info if present.
5763 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5764 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5765 struct sadb_x_nat_t_port *sport, *dport;
5767 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5768 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5769 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5771 return key_senderror(so, m, EINVAL);
5774 sport = (struct sadb_x_nat_t_port *)
5775 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5776 dport = (struct sadb_x_nat_t_port *)
5777 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5780 KEY_PORTTOSADDR(&saidx.src,
5781 sport->sadb_x_nat_t_port_port);
5783 KEY_PORTTOSADDR(&saidx.dst,
5784 dport->sadb_x_nat_t_port_port);
5789 LIST_FOREACH(sah, &V_sahtree, chain) {
5790 if (sah->state == SADB_SASTATE_DEAD)
5792 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5795 /* Delete all non-LARVAL SAs. */
5797 stateidx < _ARRAYLEN(saorder_state_alive);
5799 state = saorder_state_alive[stateidx];
5800 if (state == SADB_SASTATE_LARVAL)
5802 for (sav = LIST_FIRST(&sah->savtree[state]);
5803 sav != NULL; sav = nextsav) {
5804 nextsav = LIST_NEXT(sav, chain);
5806 if (sav->state != state) {
5807 ipseclog((LOG_DEBUG, "%s: invalid "
5808 "sav->state (queue %d SA %d)\n",
5809 __func__, state, sav->state));
5813 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5821 struct sadb_msg *newmsg;
5823 /* create new sadb_msg to reply. */
5824 /* XXX-BZ NAT-T extensions? */
5825 n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5826 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5828 return key_senderror(so, m, ENOBUFS);
5830 if (n->m_len < sizeof(struct sadb_msg)) {
5831 n = m_pullup(n, sizeof(struct sadb_msg));
5833 return key_senderror(so, m, ENOBUFS);
5835 newmsg = mtod(n, struct sadb_msg *);
5836 newmsg->sadb_msg_errno = 0;
5837 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5840 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5845 * SADB_GET processing
5847 * <base, SA(*), address(SD)>
5848 * from the ikmpd, and get a SP and a SA to respond,
5850 * <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5851 * (identity(SD),) (sensitivity)>
5854 * m will always be freed.
5860 const struct sadb_msghdr *mhp;
5862 struct sadb_sa *sa0;
5863 struct sadb_address *src0, *dst0;
5864 struct secasindex saidx;
5865 struct secashead *sah;
5866 struct secasvar *sav = NULL;
5869 IPSEC_ASSERT(so != NULL, ("null socket"));
5870 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5871 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5872 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5874 /* map satype to proto */
5875 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5876 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5878 return key_senderror(so, m, EINVAL);
5881 if (mhp->ext[SADB_EXT_SA] == NULL ||
5882 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5883 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5884 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5886 return key_senderror(so, m, EINVAL);
5888 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5889 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5890 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5891 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5893 return key_senderror(so, m, EINVAL);
5896 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5897 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5898 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5900 /* XXX boundary check against sa_len */
5901 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5904 * Make sure the port numbers are zero.
5905 * In case of NAT-T we will update them later if needed.
5907 KEY_PORTTOSADDR(&saidx.src, 0);
5908 KEY_PORTTOSADDR(&saidx.dst, 0);
5912 * Handle NAT-T info if present.
5915 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5916 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5917 struct sadb_x_nat_t_port *sport, *dport;
5919 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5920 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5921 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5923 return key_senderror(so, m, EINVAL);
5926 sport = (struct sadb_x_nat_t_port *)
5927 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5928 dport = (struct sadb_x_nat_t_port *)
5929 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5932 KEY_PORTTOSADDR(&saidx.src,
5933 sport->sadb_x_nat_t_port_port);
5935 KEY_PORTTOSADDR(&saidx.dst,
5936 dport->sadb_x_nat_t_port_port);
5940 /* get a SA header */
5942 LIST_FOREACH(sah, &V_sahtree, chain) {
5943 if (sah->state == SADB_SASTATE_DEAD)
5945 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5948 /* get a SA with SPI. */
5949 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5955 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5956 return key_senderror(so, m, ENOENT);
5963 /* map proto to satype */
5964 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5965 ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5967 return key_senderror(so, m, EINVAL);
5970 /* create new sadb_msg to reply. */
5971 n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5972 mhp->msg->sadb_msg_pid);
5974 return key_senderror(so, m, ENOBUFS);
5977 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5981 /* XXX make it sysctl-configurable? */
5983 key_getcomb_setlifetime(comb)
5984 struct sadb_comb *comb;
5987 comb->sadb_comb_soft_allocations = 1;
5988 comb->sadb_comb_hard_allocations = 1;
5989 comb->sadb_comb_soft_bytes = 0;
5990 comb->sadb_comb_hard_bytes = 0;
5991 comb->sadb_comb_hard_addtime = 86400; /* 1 day */
5992 comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5993 comb->sadb_comb_soft_usetime = 28800; /* 8 hours */
5994 comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5998 * XXX reorder combinations by preference
5999 * XXX no idea if the user wants ESP authentication or not
6001 static struct mbuf *
6004 struct sadb_comb *comb;
6005 struct enc_xform *algo;
6006 struct mbuf *result = NULL, *m, *n;
6010 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6013 for (i = 1; i <= SADB_EALG_MAX; i++) {
6014 algo = esp_algorithm_lookup(i);
6018 /* discard algorithms with key size smaller than system min */
6019 if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6021 if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6022 encmin = V_ipsec_esp_keymin;
6024 encmin = _BITS(algo->minkey);
6026 if (V_ipsec_esp_auth)
6027 m = key_getcomb_ah();
6029 IPSEC_ASSERT(l <= MLEN,
6030 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6031 MGET(m, M_NOWAIT, MT_DATA);
6036 bzero(mtod(m, caddr_t), m->m_len);
6043 for (n = m; n; n = n->m_next)
6045 IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6047 for (off = 0; off < totlen; off += l) {
6048 n = m_pulldown(m, off, l, &o);
6050 /* m is already freed */
6053 comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6054 bzero(comb, sizeof(*comb));
6055 key_getcomb_setlifetime(comb);
6056 comb->sadb_comb_encrypt = i;
6057 comb->sadb_comb_encrypt_minbits = encmin;
6058 comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6077 const struct auth_hash *ah,
6083 *min = *max = ah->keysize;
6084 if (ah->keysize == 0) {
6086 * Transform takes arbitrary key size but algorithm
6087 * key size is restricted. Enforce this here.
6090 case SADB_X_AALG_MD5: *min = *max = 16; break;
6091 case SADB_X_AALG_SHA: *min = *max = 20; break;
6092 case SADB_X_AALG_NULL: *min = 1; *max = 256; break;
6093 case SADB_X_AALG_SHA2_256: *min = *max = 32; break;
6094 case SADB_X_AALG_SHA2_384: *min = *max = 48; break;
6095 case SADB_X_AALG_SHA2_512: *min = *max = 64; break;
6097 DPRINTF(("%s: unknown AH algorithm %u\n",
6105 * XXX reorder combinations by preference
6107 static struct mbuf *
6110 struct sadb_comb *comb;
6111 struct auth_hash *algo;
6113 u_int16_t minkeysize, maxkeysize;
6115 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6118 for (i = 1; i <= SADB_AALG_MAX; i++) {
6120 /* we prefer HMAC algorithms, not old algorithms */
6121 if (i != SADB_AALG_SHA1HMAC &&
6122 i != SADB_AALG_MD5HMAC &&
6123 i != SADB_X_AALG_SHA2_256 &&
6124 i != SADB_X_AALG_SHA2_384 &&
6125 i != SADB_X_AALG_SHA2_512)
6128 algo = ah_algorithm_lookup(i);
6131 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6132 /* discard algorithms with key size smaller than system min */
6133 if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6137 IPSEC_ASSERT(l <= MLEN,
6138 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6139 MGET(m, M_NOWAIT, MT_DATA);
6146 M_PREPEND(m, l, M_NOWAIT);
6150 comb = mtod(m, struct sadb_comb *);
6151 bzero(comb, sizeof(*comb));
6152 key_getcomb_setlifetime(comb);
6153 comb->sadb_comb_auth = i;
6154 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6155 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6162 * not really an official behavior. discussed in pf_key@inner.net in Sep2000.
6163 * XXX reorder combinations by preference
6165 static struct mbuf *
6166 key_getcomb_ipcomp()
6168 struct sadb_comb *comb;
6169 struct comp_algo *algo;
6172 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6175 for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6176 algo = ipcomp_algorithm_lookup(i);
6181 IPSEC_ASSERT(l <= MLEN,
6182 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6183 MGET(m, M_NOWAIT, MT_DATA);
6190 M_PREPEND(m, l, M_NOWAIT);
6194 comb = mtod(m, struct sadb_comb *);
6195 bzero(comb, sizeof(*comb));
6196 key_getcomb_setlifetime(comb);
6197 comb->sadb_comb_encrypt = i;
6198 /* what should we set into sadb_comb_*_{min,max}bits? */
6205 * XXX no way to pass mode (transport/tunnel) to userland
6206 * XXX replay checking?
6207 * XXX sysctl interface to ipsec_{ah,esp}_keymin
6209 static struct mbuf *
6211 const struct secasindex *saidx;
6213 struct sadb_prop *prop;
6215 const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6218 switch (saidx->proto) {
6220 m = key_getcomb_esp();
6223 m = key_getcomb_ah();
6225 case IPPROTO_IPCOMP:
6226 m = key_getcomb_ipcomp();
6234 M_PREPEND(m, l, M_NOWAIT);
6239 for (n = m; n; n = n->m_next)
6242 prop = mtod(m, struct sadb_prop *);
6243 bzero(prop, sizeof(*prop));
6244 prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6245 prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6246 prop->sadb_prop_replay = 32; /* XXX */
6252 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6254 * <base, SA, address(SD), (address(P)), x_policy,
6255 * (identity(SD),) (sensitivity,) proposal>
6256 * to KMD, and expect to receive
6257 * <base> with SADB_ACQUIRE if error occured,
6259 * <base, src address, dst address, (SPI range)> with SADB_GETSPI
6260 * from KMD by PF_KEY.
6262 * XXX x_policy is outside of RFC2367 (KAME extension).
6263 * XXX sensitivity is not supported.
6264 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6265 * see comment for key_getcomb_ipcomp().
6269 * others: error number
6272 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6274 struct mbuf *result = NULL, *m;
6275 struct secacq *newacq;
6280 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6281 satype = key_proto2satype(saidx->proto);
6282 IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6285 * We never do anything about acquirng SA. There is anather
6286 * solution that kernel blocks to send SADB_ACQUIRE message until
6287 * getting something message from IKEd. In later case, to be
6288 * managed with ACQUIRING list.
6290 /* Get an entry to check whether sending message or not. */
6291 if ((newacq = key_getacq(saidx)) != NULL) {
6292 if (V_key_blockacq_count < newacq->count) {
6293 /* reset counter and do send message. */
6296 /* increment counter and do nothing. */
6301 /* make new entry for blocking to send SADB_ACQUIRE. */
6302 if ((newacq = key_newacq(saidx)) == NULL)
6308 m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6316 * No SADB_X_EXT_NAT_T_* here: we do not know
6317 * anything related to NAT-T at this time.
6320 /* set sadb_address for saidx's. */
6321 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6322 &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6329 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6330 &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6337 /* XXX proxy address (optional) */
6339 /* set sadb_x_policy */
6341 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6349 /* XXX identity (optional) */
6351 if (idexttype && fqdn) {
6352 /* create identity extension (FQDN) */
6353 struct sadb_ident *id;
6356 fqdnlen = strlen(fqdn) + 1; /* +1 for terminating-NUL */
6357 id = (struct sadb_ident *)p;
6358 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6359 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6360 id->sadb_ident_exttype = idexttype;
6361 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6362 bcopy(fqdn, id + 1, fqdnlen);
6363 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6367 /* create identity extension (USERFQDN) */
6368 struct sadb_ident *id;
6372 /* +1 for terminating-NUL */
6373 userfqdnlen = strlen(userfqdn) + 1;
6376 id = (struct sadb_ident *)p;
6377 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6378 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6379 id->sadb_ident_exttype = idexttype;
6380 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6381 /* XXX is it correct? */
6382 if (curproc && curproc->p_cred)
6383 id->sadb_ident_id = curproc->p_cred->p_ruid;
6384 if (userfqdn && userfqdnlen)
6385 bcopy(userfqdn, id + 1, userfqdnlen);
6386 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6390 /* XXX sensitivity (optional) */
6392 /* create proposal/combination extension */
6393 m = key_getprop(saidx);
6396 * spec conformant: always attach proposal/combination extension,
6397 * the problem is that we have no way to attach it for ipcomp,
6398 * due to the way sadb_comb is declared in RFC2367.
6407 * outside of spec; make proposal/combination extension optional.
6413 if ((result->m_flags & M_PKTHDR) == 0) {
6418 if (result->m_len < sizeof(struct sadb_msg)) {
6419 result = m_pullup(result, sizeof(struct sadb_msg));
6420 if (result == NULL) {
6426 result->m_pkthdr.len = 0;
6427 for (m = result; m; m = m->m_next)
6428 result->m_pkthdr.len += m->m_len;
6430 mtod(result, struct sadb_msg *)->sadb_msg_len =
6431 PFKEY_UNIT64(result->m_pkthdr.len);
6433 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6441 static struct secacq *
6442 key_newacq(const struct secasindex *saidx)
6444 struct secacq *newacq;
6447 newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6448 if (newacq == NULL) {
6449 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6454 bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
6455 newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6456 newacq->created = time_second;
6459 /* add to acqtree */
6461 LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
6467 static struct secacq *
6468 key_getacq(const struct secasindex *saidx)
6473 LIST_FOREACH(acq, &V_acqtree, chain) {
6474 if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6482 static struct secacq *
6483 key_getacqbyseq(seq)
6489 LIST_FOREACH(acq, &V_acqtree, chain) {
6490 if (acq->seq == seq)
6498 static struct secspacq *
6500 struct secpolicyindex *spidx;
6502 struct secspacq *acq;
6505 acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6507 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6512 bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6513 acq->created = time_second;
6516 /* add to spacqtree */
6518 LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6524 static struct secspacq *
6526 struct secpolicyindex *spidx;
6528 struct secspacq *acq;
6531 LIST_FOREACH(acq, &V_spacqtree, chain) {
6532 if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6533 /* NB: return holding spacq_lock */
6543 * SADB_ACQUIRE processing,
6544 * in first situation, is receiving
6546 * from the ikmpd, and clear sequence of its secasvar entry.
6548 * In second situation, is receiving
6549 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6550 * from a user land process, and return
6551 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6554 * m will always be freed.
6557 key_acquire2(so, m, mhp)
6560 const struct sadb_msghdr *mhp;
6562 const struct sadb_address *src0, *dst0;
6563 struct secasindex saidx;
6564 struct secashead *sah;
6568 IPSEC_ASSERT(so != NULL, ("null socket"));
6569 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6570 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6571 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6574 * Error message from KMd.
6575 * We assume that if error was occured in IKEd, the length of PFKEY
6576 * message is equal to the size of sadb_msg structure.
6577 * We do not raise error even if error occured in this function.
6579 if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6582 /* check sequence number */
6583 if (mhp->msg->sadb_msg_seq == 0) {
6584 ipseclog((LOG_DEBUG, "%s: must specify sequence "
6585 "number.\n", __func__));
6590 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6592 * the specified larval SA is already gone, or we got
6593 * a bogus sequence number. we can silently ignore it.
6599 /* reset acq counter in order to deletion by timehander. */
6600 acq->created = time_second;
6607 * This message is from user land.
6610 /* map satype to proto */
6611 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6612 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6614 return key_senderror(so, m, EINVAL);
6617 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6618 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6619 mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6621 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6623 return key_senderror(so, m, EINVAL);
6625 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6626 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6627 mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6629 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6631 return key_senderror(so, m, EINVAL);
6634 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6635 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6637 /* XXX boundary check against sa_len */
6638 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6641 * Make sure the port numbers are zero.
6642 * In case of NAT-T we will update them later if needed.
6644 KEY_PORTTOSADDR(&saidx.src, 0);
6645 KEY_PORTTOSADDR(&saidx.dst, 0);
6649 * Handle NAT-T info if present.
6652 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
6653 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
6654 struct sadb_x_nat_t_port *sport, *dport;
6656 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
6657 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
6658 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
6660 return key_senderror(so, m, EINVAL);
6663 sport = (struct sadb_x_nat_t_port *)
6664 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
6665 dport = (struct sadb_x_nat_t_port *)
6666 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
6669 KEY_PORTTOSADDR(&saidx.src,
6670 sport->sadb_x_nat_t_port_port);
6672 KEY_PORTTOSADDR(&saidx.dst,
6673 dport->sadb_x_nat_t_port_port);
6677 /* get a SA index */
6679 LIST_FOREACH(sah, &V_sahtree, chain) {
6680 if (sah->state == SADB_SASTATE_DEAD)
6682 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6687 ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6688 return key_senderror(so, m, EEXIST);
6691 error = key_acquire(&saidx, NULL);
6693 ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6694 __func__, mhp->msg->sadb_msg_errno));
6695 return key_senderror(so, m, error);
6698 return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6702 * SADB_REGISTER processing.
6703 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6706 * from the ikmpd, and register a socket to send PF_KEY messages,
6710 * If socket is detached, must free from regnode.
6712 * m will always be freed.
6715 key_register(so, m, mhp)
6718 const struct sadb_msghdr *mhp;
6720 struct secreg *reg, *newreg = 0;
6722 IPSEC_ASSERT(so != NULL, ("null socket"));
6723 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6724 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6725 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6727 /* check for invalid register message */
6728 if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6729 return key_senderror(so, m, EINVAL);
6731 /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6732 if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6735 /* check whether existing or not */
6737 LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6738 if (reg->so == so) {
6740 ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6742 return key_senderror(so, m, EEXIST);
6746 /* create regnode */
6747 newreg = malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6748 if (newreg == NULL) {
6750 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6751 return key_senderror(so, m, ENOBUFS);
6755 ((struct keycb *)sotorawcb(so))->kp_registered++;
6757 /* add regnode to regtree. */
6758 LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6764 struct sadb_msg *newmsg;
6765 struct sadb_supported *sup;
6766 u_int len, alen, elen;
6769 struct sadb_alg *alg;
6771 /* create new sadb_msg to reply. */
6773 for (i = 1; i <= SADB_AALG_MAX; i++) {
6774 if (ah_algorithm_lookup(i))
6775 alen += sizeof(struct sadb_alg);
6778 alen += sizeof(struct sadb_supported);
6780 for (i = 1; i <= SADB_EALG_MAX; i++) {
6781 if (esp_algorithm_lookup(i))
6782 elen += sizeof(struct sadb_alg);
6785 elen += sizeof(struct sadb_supported);
6787 len = sizeof(struct sadb_msg) + alen + elen;
6790 return key_senderror(so, m, ENOBUFS);
6792 MGETHDR(n, M_NOWAIT, MT_DATA);
6794 MCLGET(n, M_NOWAIT);
6795 if ((n->m_flags & M_EXT) == 0) {
6801 return key_senderror(so, m, ENOBUFS);
6803 n->m_pkthdr.len = n->m_len = len;
6807 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6808 newmsg = mtod(n, struct sadb_msg *);
6809 newmsg->sadb_msg_errno = 0;
6810 newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6811 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6813 /* for authentication algorithm */
6815 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6816 sup->sadb_supported_len = PFKEY_UNIT64(alen);
6817 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6818 off += PFKEY_ALIGN8(sizeof(*sup));
6820 for (i = 1; i <= SADB_AALG_MAX; i++) {
6821 struct auth_hash *aalgo;
6822 u_int16_t minkeysize, maxkeysize;
6824 aalgo = ah_algorithm_lookup(i);
6827 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6828 alg->sadb_alg_id = i;
6829 alg->sadb_alg_ivlen = 0;
6830 key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6831 alg->sadb_alg_minbits = _BITS(minkeysize);
6832 alg->sadb_alg_maxbits = _BITS(maxkeysize);
6833 off += PFKEY_ALIGN8(sizeof(*alg));
6837 /* for encryption algorithm */
6839 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6840 sup->sadb_supported_len = PFKEY_UNIT64(elen);
6841 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6842 off += PFKEY_ALIGN8(sizeof(*sup));
6844 for (i = 1; i <= SADB_EALG_MAX; i++) {
6845 struct enc_xform *ealgo;
6847 ealgo = esp_algorithm_lookup(i);
6850 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6851 alg->sadb_alg_id = i;
6852 alg->sadb_alg_ivlen = ealgo->blocksize;
6853 alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6854 alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6855 off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6859 IPSEC_ASSERT(off == len,
6860 ("length assumption failed (off %u len %u)", off, len));
6863 return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6868 * free secreg entry registered.
6869 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6872 key_freereg(struct socket *so)
6877 IPSEC_ASSERT(so != NULL, ("NULL so"));
6880 * check whether existing or not.
6881 * check all type of SA, because there is a potential that
6882 * one socket is registered to multiple type of SA.
6885 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6886 LIST_FOREACH(reg, &V_regtree[i], chain) {
6887 if (reg->so == so && __LIST_CHAINED(reg)) {
6888 LIST_REMOVE(reg, chain);
6889 free(reg, M_IPSEC_SAR);
6898 * SADB_EXPIRE processing
6900 * <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6902 * NOTE: We send only soft lifetime extension.
6905 * others : error number
6908 key_expire(struct secasvar *sav)
6911 struct mbuf *result = NULL, *m;
6914 struct sadb_lifetime *lt;
6916 IPSEC_ASSERT (sav != NULL, ("null sav"));
6917 IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6919 /* set msg header */
6920 satype = key_proto2satype(sav->sah->saidx.proto);
6921 IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6922 m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6929 /* create SA extension */
6930 m = key_setsadbsa(sav);
6937 /* create SA extension */
6938 m = key_setsadbxsa2(sav->sah->saidx.mode,
6939 sav->replay ? sav->replay->count : 0,
6940 sav->sah->saidx.reqid);
6947 /* create lifetime extension (current and soft) */
6948 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6949 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
6956 bzero(mtod(m, caddr_t), len);
6957 lt = mtod(m, struct sadb_lifetime *);
6958 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6959 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6960 lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6961 lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6962 lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6963 lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6964 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6965 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6966 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6967 lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6968 lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6969 lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6970 lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6973 /* set sadb_address for source */
6974 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6975 &sav->sah->saidx.src.sa,
6976 FULLMASK, IPSEC_ULPROTO_ANY);
6983 /* set sadb_address for destination */
6984 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6985 &sav->sah->saidx.dst.sa,
6986 FULLMASK, IPSEC_ULPROTO_ANY);
6994 * XXX-BZ Handle NAT-T extensions here.
6997 if ((result->m_flags & M_PKTHDR) == 0) {
7002 if (result->m_len < sizeof(struct sadb_msg)) {
7003 result = m_pullup(result, sizeof(struct sadb_msg));
7004 if (result == NULL) {
7010 result->m_pkthdr.len = 0;
7011 for (m = result; m; m = m->m_next)
7012 result->m_pkthdr.len += m->m_len;
7014 mtod(result, struct sadb_msg *)->sadb_msg_len =
7015 PFKEY_UNIT64(result->m_pkthdr.len);
7017 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7026 * SADB_FLUSH processing
7029 * from the ikmpd, and free all entries in secastree.
7033 * NOTE: to do is only marking SADB_SASTATE_DEAD.
7035 * m will always be freed.
7038 key_flush(so, m, mhp)
7041 const struct sadb_msghdr *mhp;
7043 struct sadb_msg *newmsg;
7044 struct secashead *sah, *nextsah;
7045 struct secasvar *sav, *nextsav;
7050 IPSEC_ASSERT(so != NULL, ("null socket"));
7051 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7052 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7054 /* map satype to proto */
7055 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7056 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7058 return key_senderror(so, m, EINVAL);
7061 /* no SATYPE specified, i.e. flushing all SA. */
7063 for (sah = LIST_FIRST(&V_sahtree);
7066 nextsah = LIST_NEXT(sah, chain);
7068 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7069 && proto != sah->saidx.proto)
7073 stateidx < _ARRAYLEN(saorder_state_alive);
7075 state = saorder_state_any[stateidx];
7076 for (sav = LIST_FIRST(&sah->savtree[state]);
7080 nextsav = LIST_NEXT(sav, chain);
7082 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
7087 sah->state = SADB_SASTATE_DEAD;
7091 if (m->m_len < sizeof(struct sadb_msg) ||
7092 sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7093 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7094 return key_senderror(so, m, ENOBUFS);
7100 m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7101 newmsg = mtod(m, struct sadb_msg *);
7102 newmsg->sadb_msg_errno = 0;
7103 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7105 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7109 * SADB_DUMP processing
7110 * dump all entries including status of DEAD in SAD.
7113 * from the ikmpd, and dump all secasvar leaves
7118 * m will always be freed.
7121 key_dump(so, m, mhp)
7124 const struct sadb_msghdr *mhp;
7126 struct secashead *sah;
7127 struct secasvar *sav;
7133 struct sadb_msg *newmsg;
7136 IPSEC_ASSERT(so != NULL, ("null socket"));
7137 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7138 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7139 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7141 /* map satype to proto */
7142 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7143 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7145 return key_senderror(so, m, EINVAL);
7148 /* count sav entries to be sent to the userland. */
7151 LIST_FOREACH(sah, &V_sahtree, chain) {
7152 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7153 && proto != sah->saidx.proto)
7157 stateidx < _ARRAYLEN(saorder_state_any);
7159 state = saorder_state_any[stateidx];
7160 LIST_FOREACH(sav, &sah->savtree[state], chain) {
7168 return key_senderror(so, m, ENOENT);
7171 /* send this to the userland, one at a time. */
7173 LIST_FOREACH(sah, &V_sahtree, chain) {
7174 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7175 && proto != sah->saidx.proto)
7178 /* map proto to satype */
7179 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7181 ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7182 "SAD.\n", __func__));
7183 return key_senderror(so, m, EINVAL);
7187 stateidx < _ARRAYLEN(saorder_state_any);
7189 state = saorder_state_any[stateidx];
7190 LIST_FOREACH(sav, &sah->savtree[state], chain) {
7191 n = key_setdumpsa(sav, SADB_DUMP, satype,
7192 --cnt, mhp->msg->sadb_msg_pid);
7195 return key_senderror(so, m, ENOBUFS);
7197 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7208 * SADB_X_PROMISC processing
7210 * m will always be freed.
7213 key_promisc(so, m, mhp)
7216 const struct sadb_msghdr *mhp;
7220 IPSEC_ASSERT(so != NULL, ("null socket"));
7221 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7222 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7223 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7225 olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7227 if (olen < sizeof(struct sadb_msg)) {
7229 return key_senderror(so, m, EINVAL);
7234 } else if (olen == sizeof(struct sadb_msg)) {
7235 /* enable/disable promisc mode */
7238 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7239 return key_senderror(so, m, EINVAL);
7240 mhp->msg->sadb_msg_errno = 0;
7241 switch (mhp->msg->sadb_msg_satype) {
7244 kp->kp_promisc = mhp->msg->sadb_msg_satype;
7247 return key_senderror(so, m, EINVAL);
7250 /* send the original message back to everyone */
7251 mhp->msg->sadb_msg_errno = 0;
7252 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7254 /* send packet as is */
7256 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7258 /* TODO: if sadb_msg_seq is specified, send to specific pid */
7259 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7263 static int (*key_typesw[]) __P((struct socket *, struct mbuf *,
7264 const struct sadb_msghdr *)) = {
7265 NULL, /* SADB_RESERVED */
7266 key_getspi, /* SADB_GETSPI */
7267 key_update, /* SADB_UPDATE */
7268 key_add, /* SADB_ADD */
7269 key_delete, /* SADB_DELETE */
7270 key_get, /* SADB_GET */
7271 key_acquire2, /* SADB_ACQUIRE */
7272 key_register, /* SADB_REGISTER */
7273 NULL, /* SADB_EXPIRE */
7274 key_flush, /* SADB_FLUSH */
7275 key_dump, /* SADB_DUMP */
7276 key_promisc, /* SADB_X_PROMISC */
7277 NULL, /* SADB_X_PCHANGE */
7278 key_spdadd, /* SADB_X_SPDUPDATE */
7279 key_spdadd, /* SADB_X_SPDADD */
7280 key_spddelete, /* SADB_X_SPDDELETE */
7281 key_spdget, /* SADB_X_SPDGET */
7282 NULL, /* SADB_X_SPDACQUIRE */
7283 key_spddump, /* SADB_X_SPDDUMP */
7284 key_spdflush, /* SADB_X_SPDFLUSH */
7285 key_spdadd, /* SADB_X_SPDSETIDX */
7286 NULL, /* SADB_X_SPDEXPIRE */
7287 key_spddelete2, /* SADB_X_SPDDELETE2 */
7291 * parse sadb_msg buffer to process PFKEYv2,
7292 * and create a data to response if needed.
7293 * I think to be dealed with mbuf directly.
7295 * msgp : pointer to pointer to a received buffer pulluped.
7296 * This is rewrited to response.
7297 * so : pointer to socket.
7299 * length for buffer to send to user process.
7306 struct sadb_msg *msg;
7307 struct sadb_msghdr mh;
7312 IPSEC_ASSERT(so != NULL, ("null socket"));
7313 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7315 #if 0 /*kdebug_sadb assumes msg in linear buffer*/
7316 KEYDEBUG(KEYDEBUG_KEY_DUMP,
7317 ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
7321 if (m->m_len < sizeof(struct sadb_msg)) {
7322 m = m_pullup(m, sizeof(struct sadb_msg));
7326 msg = mtod(m, struct sadb_msg *);
7327 orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7328 target = KEY_SENDUP_ONE;
7330 if ((m->m_flags & M_PKTHDR) == 0 ||
7331 m->m_pkthdr.len != m->m_pkthdr.len) {
7332 ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7333 PFKEYSTAT_INC(out_invlen);
7338 if (msg->sadb_msg_version != PF_KEY_V2) {
7339 ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7340 __func__, msg->sadb_msg_version));
7341 PFKEYSTAT_INC(out_invver);
7346 if (msg->sadb_msg_type > SADB_MAX) {
7347 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7348 __func__, msg->sadb_msg_type));
7349 PFKEYSTAT_INC(out_invmsgtype);
7354 /* for old-fashioned code - should be nuked */
7355 if (m->m_pkthdr.len > MCLBYTES) {
7362 MGETHDR(n, M_NOWAIT, MT_DATA);
7363 if (n && m->m_pkthdr.len > MHLEN) {
7364 MCLGET(n, M_NOWAIT);
7365 if ((n->m_flags & M_EXT) == 0) {
7374 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7375 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7381 /* align the mbuf chain so that extensions are in contiguous region. */
7382 error = key_align(m, &mh);
7389 switch (msg->sadb_msg_satype) {
7390 case SADB_SATYPE_UNSPEC:
7391 switch (msg->sadb_msg_type) {
7399 ipseclog((LOG_DEBUG, "%s: must specify satype "
7400 "when msg type=%u.\n", __func__,
7401 msg->sadb_msg_type));
7402 PFKEYSTAT_INC(out_invsatype);
7407 case SADB_SATYPE_AH:
7408 case SADB_SATYPE_ESP:
7409 case SADB_X_SATYPE_IPCOMP:
7410 case SADB_X_SATYPE_TCPSIGNATURE:
7411 switch (msg->sadb_msg_type) {
7413 case SADB_X_SPDDELETE:
7415 case SADB_X_SPDDUMP:
7416 case SADB_X_SPDFLUSH:
7417 case SADB_X_SPDSETIDX:
7418 case SADB_X_SPDUPDATE:
7419 case SADB_X_SPDDELETE2:
7420 ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7421 __func__, msg->sadb_msg_type));
7422 PFKEYSTAT_INC(out_invsatype);
7427 case SADB_SATYPE_RSVP:
7428 case SADB_SATYPE_OSPFV2:
7429 case SADB_SATYPE_RIPV2:
7430 case SADB_SATYPE_MIP:
7431 ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7432 __func__, msg->sadb_msg_satype));
7433 PFKEYSTAT_INC(out_invsatype);
7436 case 1: /* XXX: What does it do? */
7437 if (msg->sadb_msg_type == SADB_X_PROMISC)
7441 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7442 __func__, msg->sadb_msg_satype));
7443 PFKEYSTAT_INC(out_invsatype);
7448 /* check field of upper layer protocol and address family */
7449 if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7450 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7451 struct sadb_address *src0, *dst0;
7454 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7455 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7457 /* check upper layer protocol */
7458 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7459 ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7460 "mismatched.\n", __func__));
7461 PFKEYSTAT_INC(out_invaddr);
7467 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7468 PFKEY_ADDR_SADDR(dst0)->sa_family) {
7469 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7471 PFKEYSTAT_INC(out_invaddr);
7475 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7476 PFKEY_ADDR_SADDR(dst0)->sa_len) {
7477 ipseclog((LOG_DEBUG, "%s: address struct size "
7478 "mismatched.\n", __func__));
7479 PFKEYSTAT_INC(out_invaddr);
7484 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7486 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7487 sizeof(struct sockaddr_in)) {
7488 PFKEYSTAT_INC(out_invaddr);
7494 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7495 sizeof(struct sockaddr_in6)) {
7496 PFKEYSTAT_INC(out_invaddr);
7502 ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7504 PFKEYSTAT_INC(out_invaddr);
7505 error = EAFNOSUPPORT;
7509 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7511 plen = sizeof(struct in_addr) << 3;
7514 plen = sizeof(struct in6_addr) << 3;
7517 plen = 0; /*fool gcc*/
7521 /* check max prefix length */
7522 if (src0->sadb_address_prefixlen > plen ||
7523 dst0->sadb_address_prefixlen > plen) {
7524 ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7526 PFKEYSTAT_INC(out_invaddr);
7532 * prefixlen == 0 is valid because there can be a case when
7533 * all addresses are matched.
7537 if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7538 key_typesw[msg->sadb_msg_type] == NULL) {
7539 PFKEYSTAT_INC(out_invmsgtype);
7544 return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7547 msg->sadb_msg_errno = error;
7548 return key_sendup_mbuf(so, m, target);
7552 key_senderror(so, m, code)
7557 struct sadb_msg *msg;
7559 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7560 ("mbuf too small, len %u", m->m_len));
7562 msg = mtod(m, struct sadb_msg *);
7563 msg->sadb_msg_errno = code;
7564 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7568 * set the pointer to each header into message buffer.
7569 * m will be freed on error.
7570 * XXX larger-than-MCLBYTES extension?
7575 struct sadb_msghdr *mhp;
7578 struct sadb_ext *ext;
7583 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7584 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7585 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7586 ("mbuf too small, len %u", m->m_len));
7589 bzero(mhp, sizeof(*mhp));
7591 mhp->msg = mtod(m, struct sadb_msg *);
7592 mhp->ext[0] = (struct sadb_ext *)mhp->msg; /*XXX backward compat */
7594 end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7595 extlen = end; /*just in case extlen is not updated*/
7596 for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7597 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7599 /* m is already freed */
7602 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7605 switch (ext->sadb_ext_type) {
7607 case SADB_EXT_ADDRESS_SRC:
7608 case SADB_EXT_ADDRESS_DST:
7609 case SADB_EXT_ADDRESS_PROXY:
7610 case SADB_EXT_LIFETIME_CURRENT:
7611 case SADB_EXT_LIFETIME_HARD:
7612 case SADB_EXT_LIFETIME_SOFT:
7613 case SADB_EXT_KEY_AUTH:
7614 case SADB_EXT_KEY_ENCRYPT:
7615 case SADB_EXT_IDENTITY_SRC:
7616 case SADB_EXT_IDENTITY_DST:
7617 case SADB_EXT_SENSITIVITY:
7618 case SADB_EXT_PROPOSAL:
7619 case SADB_EXT_SUPPORTED_AUTH:
7620 case SADB_EXT_SUPPORTED_ENCRYPT:
7621 case SADB_EXT_SPIRANGE:
7622 case SADB_X_EXT_POLICY:
7623 case SADB_X_EXT_SA2:
7625 case SADB_X_EXT_NAT_T_TYPE:
7626 case SADB_X_EXT_NAT_T_SPORT:
7627 case SADB_X_EXT_NAT_T_DPORT:
7628 case SADB_X_EXT_NAT_T_OAI:
7629 case SADB_X_EXT_NAT_T_OAR:
7630 case SADB_X_EXT_NAT_T_FRAG:
7632 /* duplicate check */
7634 * XXX Are there duplication payloads of either
7635 * KEY_AUTH or KEY_ENCRYPT ?
7637 if (mhp->ext[ext->sadb_ext_type] != NULL) {
7638 ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7639 "%u\n", __func__, ext->sadb_ext_type));
7641 PFKEYSTAT_INC(out_dupext);
7646 ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7647 __func__, ext->sadb_ext_type));
7649 PFKEYSTAT_INC(out_invexttype);
7653 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7655 if (key_validate_ext(ext, extlen)) {
7657 PFKEYSTAT_INC(out_invlen);
7661 n = m_pulldown(m, off, extlen, &toff);
7663 /* m is already freed */
7666 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7668 mhp->ext[ext->sadb_ext_type] = ext;
7669 mhp->extoff[ext->sadb_ext_type] = off;
7670 mhp->extlen[ext->sadb_ext_type] = extlen;
7675 PFKEYSTAT_INC(out_invlen);
7683 key_validate_ext(ext, len)
7684 const struct sadb_ext *ext;
7687 const struct sockaddr *sa;
7688 enum { NONE, ADDR } checktype = NONE;
7690 const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7692 if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7695 /* if it does not match minimum/maximum length, bail */
7696 if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7697 ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7699 if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7701 if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7704 /* more checks based on sadb_ext_type XXX need more */
7705 switch (ext->sadb_ext_type) {
7706 case SADB_EXT_ADDRESS_SRC:
7707 case SADB_EXT_ADDRESS_DST:
7708 case SADB_EXT_ADDRESS_PROXY:
7709 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7712 case SADB_EXT_IDENTITY_SRC:
7713 case SADB_EXT_IDENTITY_DST:
7714 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7715 SADB_X_IDENTTYPE_ADDR) {
7716 baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7726 switch (checktype) {
7730 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7731 if (len < baselen + sal)
7733 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7746 for (i = 0; i < IPSEC_DIR_MAX; i++)
7747 LIST_INIT(&V_sptree[i]);
7749 LIST_INIT(&V_sahtree);
7751 for (i = 0; i <= SADB_SATYPE_MAX; i++)
7752 LIST_INIT(&V_regtree[i]);
7754 LIST_INIT(&V_acqtree);
7755 LIST_INIT(&V_spacqtree);
7757 /* system default */
7758 V_ip4_def_policy.policy = IPSEC_POLICY_NONE;
7759 V_ip4_def_policy.refcnt++; /*never reclaim this*/
7761 if (!IS_DEFAULT_VNET(curvnet))
7765 REGTREE_LOCK_INIT();
7766 SAHTREE_LOCK_INIT();
7770 #ifndef IPSEC_DEBUG2
7771 timeout((void *)key_timehandler, (void *)0, hz);
7772 #endif /*IPSEC_DEBUG2*/
7774 /* initialize key statistics */
7775 keystat.getspi_count = 1;
7777 printf("IPsec: Initialized Security Association Processing.\n");
7784 struct secpolicy *sp, *nextsp;
7785 struct secacq *acq, *nextacq;
7786 struct secspacq *spacq, *nextspacq;
7787 struct secashead *sah, *nextsah;
7792 for (i = 0; i < IPSEC_DIR_MAX; i++) {
7793 for (sp = LIST_FIRST(&V_sptree[i]);
7794 sp != NULL; sp = nextsp) {
7795 nextsp = LIST_NEXT(sp, chain);
7796 if (__LIST_CHAINED(sp)) {
7797 LIST_REMOVE(sp, chain);
7798 free(sp, M_IPSEC_SP);
7805 for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
7806 nextsah = LIST_NEXT(sah, chain);
7807 if (__LIST_CHAINED(sah)) {
7808 LIST_REMOVE(sah, chain);
7809 free(sah, M_IPSEC_SAH);
7815 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7816 LIST_FOREACH(reg, &V_regtree[i], chain) {
7817 if (__LIST_CHAINED(reg)) {
7818 LIST_REMOVE(reg, chain);
7819 free(reg, M_IPSEC_SAR);
7827 for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
7828 nextacq = LIST_NEXT(acq, chain);
7829 if (__LIST_CHAINED(acq)) {
7830 LIST_REMOVE(acq, chain);
7831 free(acq, M_IPSEC_SAQ);
7837 for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
7838 spacq = nextspacq) {
7839 nextspacq = LIST_NEXT(spacq, chain);
7840 if (__LIST_CHAINED(spacq)) {
7841 LIST_REMOVE(spacq, chain);
7842 free(spacq, M_IPSEC_SAQ);
7850 * XXX: maybe This function is called after INBOUND IPsec processing.
7852 * Special check for tunnel-mode packets.
7853 * We must make some checks for consistency between inner and outer IP header.
7855 * xxx more checks to be provided
7858 key_checktunnelsanity(sav, family, src, dst)
7859 struct secasvar *sav;
7864 IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7866 /* XXX: check inner IP header */
7871 /* record data transfer on SA, and update timestamps */
7873 key_sa_recordxfer(sav, m)
7874 struct secasvar *sav;
7877 IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7878 IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7883 * XXX Currently, there is a difference of bytes size
7884 * between inbound and outbound processing.
7886 sav->lft_c->bytes += m->m_pkthdr.len;
7887 /* to check bytes lifetime is done in key_timehandler(). */
7890 * We use the number of packets as the unit of
7891 * allocations. We increment the variable
7892 * whenever {esp,ah}_{in,out}put is called.
7894 sav->lft_c->allocations++;
7895 /* XXX check for expires? */
7898 * NOTE: We record CURRENT usetime by using wall clock,
7899 * in seconds. HARD and SOFT lifetime are measured by the time
7900 * difference (again in seconds) from usetime.
7904 * -----+-----+--------+---> t
7905 * <--------------> HARD
7908 sav->lft_c->usetime = time_second;
7909 /* XXX check for expires? */
7916 key_sa_routechange(dst)
7917 struct sockaddr *dst;
7919 struct secashead *sah;
7923 LIST_FOREACH(sah, &V_sahtree, chain) {
7924 ro = &sah->route_cache.sa_route;
7925 if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7926 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7928 ro->ro_rt = (struct rtentry *)NULL;
7935 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7937 IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7938 SAHTREE_LOCK_ASSERT();
7940 if (sav->state != state) {
7941 if (__LIST_CHAINED(sav))
7942 LIST_REMOVE(sav, chain);
7944 LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7950 struct secasvar *sav;
7953 IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7954 key_randomfill(sav->iv, sav->ivlen);
7958 * Take one of the kernel's security keys and convert it into a PF_KEY
7959 * structure within an mbuf, suitable for sending up to a waiting
7960 * application in user land.
7963 * src: A pointer to a kernel security key.
7964 * exttype: Which type of key this is. Refer to the PF_KEY data structures.
7966 * a valid mbuf or NULL indicating an error
7970 static struct mbuf *
7971 key_setkey(struct seckey *src, u_int16_t exttype)
7980 len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
7981 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
7986 p = mtod(m, struct sadb_key *);
7988 p->sadb_key_len = PFKEY_UNIT64(len);
7989 p->sadb_key_exttype = exttype;
7990 p->sadb_key_bits = src->bits;
7991 bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
7997 * Take one of the kernel's lifetime data structures and convert it
7998 * into a PF_KEY structure within an mbuf, suitable for sending up to
7999 * a waiting application in user land.
8002 * src: A pointer to a kernel lifetime structure.
8003 * exttype: Which type of lifetime this is. Refer to the PF_KEY
8004 * data structures for more information.
8006 * a valid mbuf or NULL indicating an error
8010 static struct mbuf *
8011 key_setlifetime(struct seclifetime *src, u_int16_t exttype)
8013 struct mbuf *m = NULL;
8014 struct sadb_lifetime *p;
8015 int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8020 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
8025 p = mtod(m, struct sadb_lifetime *);
8028 p->sadb_lifetime_len = PFKEY_UNIT64(len);
8029 p->sadb_lifetime_exttype = exttype;
8030 p->sadb_lifetime_allocations = src->allocations;
8031 p->sadb_lifetime_bytes = src->bytes;
8032 p->sadb_lifetime_addtime = src->addtime;
8033 p->sadb_lifetime_usetime = src->usetime;