2 /* $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $ */
5 * SPDX-License-Identifier: BSD-3-Clause
7 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the project nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * This code is referd to RFC 2367
40 #include "opt_inet6.h"
41 #include "opt_ipsec.h"
43 #include <sys/types.h>
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/fnv_hash.h>
49 #include <sys/mutex.h>
51 #include <sys/domain.h>
52 #include <sys/protosw.h>
53 #include <sys/malloc.h>
54 #include <sys/rmlock.h>
55 #include <sys/socket.h>
56 #include <sys/socketvar.h>
57 #include <sys/sysctl.h>
58 #include <sys/errno.h>
60 #include <sys/queue.h>
61 #include <sys/refcount.h>
62 #include <sys/syslog.h>
67 #include <net/if_var.h>
69 #include <net/raw_cb.h>
71 #include <netinet/in.h>
72 #include <netinet/in_systm.h>
73 #include <netinet/ip.h>
74 #include <netinet/in_var.h>
75 #include <netinet/udp.h>
78 #include <netinet/ip6.h>
79 #include <netinet6/in6_var.h>
80 #include <netinet6/ip6_var.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>
95 #include <machine/in_cksum.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 VNET_DEFINE_STATIC(u_int, key_spi_trycnt) = 1000;
117 VNET_DEFINE_STATIC(u_int32_t, key_spi_minval) = 0x100;
118 VNET_DEFINE_STATIC(u_int32_t, key_spi_maxval) = 0x0fffffff; /* XXX */
119 VNET_DEFINE_STATIC(u_int32_t, policy_id) = 0;
120 /*interval to initialize randseed,1(m)*/
121 VNET_DEFINE_STATIC(u_int, key_int_random) = 60;
122 /* interval to expire acquiring, 30(s)*/
123 VNET_DEFINE_STATIC(u_int, key_larval_lifetime) = 30;
124 /* counter for blocking SADB_ACQUIRE.*/
125 VNET_DEFINE_STATIC(int, key_blockacq_count) = 10;
126 /* lifetime for blocking SADB_ACQUIRE.*/
127 VNET_DEFINE_STATIC(int, key_blockacq_lifetime) = 20;
128 /* preferred old sa rather than new sa.*/
129 VNET_DEFINE_STATIC(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 VNET_DEFINE_STATIC(u_int32_t, acq_seq) = 0;
141 #define V_acq_seq VNET(acq_seq)
143 VNET_DEFINE_STATIC(uint32_t, sp_genid) = 0;
144 #define V_sp_genid VNET(sp_genid)
147 TAILQ_HEAD(secpolicy_queue, secpolicy);
148 LIST_HEAD(secpolicy_list, secpolicy);
149 VNET_DEFINE_STATIC(struct secpolicy_queue, sptree[IPSEC_DIR_MAX]);
150 VNET_DEFINE_STATIC(struct secpolicy_queue, sptree_ifnet[IPSEC_DIR_MAX]);
151 static struct rmlock sptree_lock;
152 #define V_sptree VNET(sptree)
153 #define V_sptree_ifnet VNET(sptree_ifnet)
154 #define SPTREE_LOCK_INIT() rm_init(&sptree_lock, "sptree")
155 #define SPTREE_LOCK_DESTROY() rm_destroy(&sptree_lock)
156 #define SPTREE_RLOCK_TRACKER struct rm_priotracker sptree_tracker
157 #define SPTREE_RLOCK() rm_rlock(&sptree_lock, &sptree_tracker)
158 #define SPTREE_RUNLOCK() rm_runlock(&sptree_lock, &sptree_tracker)
159 #define SPTREE_RLOCK_ASSERT() rm_assert(&sptree_lock, RA_RLOCKED)
160 #define SPTREE_WLOCK() rm_wlock(&sptree_lock)
161 #define SPTREE_WUNLOCK() rm_wunlock(&sptree_lock)
162 #define SPTREE_WLOCK_ASSERT() rm_assert(&sptree_lock, RA_WLOCKED)
163 #define SPTREE_UNLOCK_ASSERT() rm_assert(&sptree_lock, RA_UNLOCKED)
165 /* Hash table for lookup SP using unique id */
166 VNET_DEFINE_STATIC(struct secpolicy_list *, sphashtbl);
167 VNET_DEFINE_STATIC(u_long, sphash_mask);
168 #define V_sphashtbl VNET(sphashtbl)
169 #define V_sphash_mask VNET(sphash_mask)
171 #define SPHASH_NHASH_LOG2 7
172 #define SPHASH_NHASH (1 << SPHASH_NHASH_LOG2)
173 #define SPHASH_HASHVAL(id) (key_u32hash(id) & V_sphash_mask)
174 #define SPHASH_HASH(id) &V_sphashtbl[SPHASH_HASHVAL(id)]
177 struct spdcache_entry {
178 struct secpolicyindex spidx; /* secpolicyindex */
179 struct secpolicy *sp; /* cached policy to be used */
181 LIST_ENTRY(spdcache_entry) chain;
183 LIST_HEAD(spdcache_entry_list, spdcache_entry);
185 #define SPDCACHE_MAX_ENTRIES_PER_HASH 8
187 VNET_DEFINE_STATIC(u_int, key_spdcache_maxentries) = 0;
188 #define V_key_spdcache_maxentries VNET(key_spdcache_maxentries)
189 VNET_DEFINE_STATIC(u_int, key_spdcache_threshold) = 32;
190 #define V_key_spdcache_threshold VNET(key_spdcache_threshold)
191 VNET_DEFINE_STATIC(unsigned long, spd_size) = 0;
192 #define V_spd_size VNET(spd_size)
194 #define SPDCACHE_ENABLED() (V_key_spdcache_maxentries != 0)
195 #define SPDCACHE_ACTIVE() \
196 (SPDCACHE_ENABLED() && V_spd_size >= V_key_spdcache_threshold)
198 VNET_DEFINE_STATIC(struct spdcache_entry_list *, spdcachehashtbl);
199 VNET_DEFINE_STATIC(u_long, spdcachehash_mask);
200 #define V_spdcachehashtbl VNET(spdcachehashtbl)
201 #define V_spdcachehash_mask VNET(spdcachehash_mask)
203 #define SPDCACHE_HASHVAL(idx) \
204 (key_addrprotohash(&(idx)->src, &(idx)->dst, &(idx)->ul_proto) & \
207 /* Each cache line is protected by a mutex */
208 VNET_DEFINE_STATIC(struct mtx *, spdcache_lock);
209 #define V_spdcache_lock VNET(spdcache_lock)
211 #define SPDCACHE_LOCK_INIT(a) \
212 mtx_init(&V_spdcache_lock[a], "spdcache", \
213 "fast ipsec SPD cache", MTX_DEF|MTX_DUPOK)
214 #define SPDCACHE_LOCK_DESTROY(a) mtx_destroy(&V_spdcache_lock[a])
215 #define SPDCACHE_LOCK(a) mtx_lock(&V_spdcache_lock[a]);
216 #define SPDCACHE_UNLOCK(a) mtx_unlock(&V_spdcache_lock[a]);
219 TAILQ_HEAD(secashead_queue, secashead);
220 LIST_HEAD(secashead_list, secashead);
221 VNET_DEFINE_STATIC(struct secashead_queue, sahtree);
222 static struct rmlock sahtree_lock;
223 #define V_sahtree VNET(sahtree)
224 #define SAHTREE_LOCK_INIT() rm_init(&sahtree_lock, "sahtree")
225 #define SAHTREE_LOCK_DESTROY() rm_destroy(&sahtree_lock)
226 #define SAHTREE_RLOCK_TRACKER struct rm_priotracker sahtree_tracker
227 #define SAHTREE_RLOCK() rm_rlock(&sahtree_lock, &sahtree_tracker)
228 #define SAHTREE_RUNLOCK() rm_runlock(&sahtree_lock, &sahtree_tracker)
229 #define SAHTREE_RLOCK_ASSERT() rm_assert(&sahtree_lock, RA_RLOCKED)
230 #define SAHTREE_WLOCK() rm_wlock(&sahtree_lock)
231 #define SAHTREE_WUNLOCK() rm_wunlock(&sahtree_lock)
232 #define SAHTREE_WLOCK_ASSERT() rm_assert(&sahtree_lock, RA_WLOCKED)
233 #define SAHTREE_UNLOCK_ASSERT() rm_assert(&sahtree_lock, RA_UNLOCKED)
235 /* Hash table for lookup in SAD using SA addresses */
236 VNET_DEFINE_STATIC(struct secashead_list *, sahaddrhashtbl);
237 VNET_DEFINE_STATIC(u_long, sahaddrhash_mask);
238 #define V_sahaddrhashtbl VNET(sahaddrhashtbl)
239 #define V_sahaddrhash_mask VNET(sahaddrhash_mask)
241 #define SAHHASH_NHASH_LOG2 7
242 #define SAHHASH_NHASH (1 << SAHHASH_NHASH_LOG2)
243 #define SAHADDRHASH_HASHVAL(idx) \
244 (key_addrprotohash(&(idx)->src, &(idx)->dst, &(idx)->proto) & \
246 #define SAHADDRHASH_HASH(saidx) \
247 &V_sahaddrhashtbl[SAHADDRHASH_HASHVAL(saidx)]
249 /* Hash table for lookup in SAD using SPI */
250 LIST_HEAD(secasvar_list, secasvar);
251 VNET_DEFINE_STATIC(struct secasvar_list *, savhashtbl);
252 VNET_DEFINE_STATIC(u_long, savhash_mask);
253 #define V_savhashtbl VNET(savhashtbl)
254 #define V_savhash_mask VNET(savhash_mask)
255 #define SAVHASH_NHASH_LOG2 7
256 #define SAVHASH_NHASH (1 << SAVHASH_NHASH_LOG2)
257 #define SAVHASH_HASHVAL(spi) (key_u32hash(spi) & V_savhash_mask)
258 #define SAVHASH_HASH(spi) &V_savhashtbl[SAVHASH_HASHVAL(spi)]
261 key_addrprotohash(const union sockaddr_union *src,
262 const union sockaddr_union *dst, const uint8_t *proto)
266 hval = fnv_32_buf(proto, sizeof(*proto),
268 switch (dst->sa.sa_family) {
271 hval = fnv_32_buf(&src->sin.sin_addr,
272 sizeof(in_addr_t), hval);
273 hval = fnv_32_buf(&dst->sin.sin_addr,
274 sizeof(in_addr_t), hval);
279 hval = fnv_32_buf(&src->sin6.sin6_addr,
280 sizeof(struct in6_addr), hval);
281 hval = fnv_32_buf(&dst->sin6.sin6_addr,
282 sizeof(struct in6_addr), hval);
287 ipseclog((LOG_DEBUG, "%s: unknown address family %d\n",
288 __func__, dst->sa.sa_family));
294 key_u32hash(uint32_t val)
297 return (fnv_32_buf(&val, sizeof(val), FNV1_32_INIT));
301 VNET_DEFINE_STATIC(LIST_HEAD(_regtree, secreg), regtree[SADB_SATYPE_MAX + 1]);
302 #define V_regtree VNET(regtree)
303 static struct mtx regtree_lock;
304 #define REGTREE_LOCK_INIT() \
305 mtx_init(®tree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
306 #define REGTREE_LOCK_DESTROY() mtx_destroy(®tree_lock)
307 #define REGTREE_LOCK() mtx_lock(®tree_lock)
308 #define REGTREE_UNLOCK() mtx_unlock(®tree_lock)
309 #define REGTREE_LOCK_ASSERT() mtx_assert(®tree_lock, MA_OWNED)
312 LIST_HEAD(secacq_list, secacq);
313 VNET_DEFINE_STATIC(struct secacq_list, acqtree);
314 #define V_acqtree VNET(acqtree)
315 static struct mtx acq_lock;
316 #define ACQ_LOCK_INIT() \
317 mtx_init(&acq_lock, "acqtree", "ipsec SA acquiring list", MTX_DEF)
318 #define ACQ_LOCK_DESTROY() mtx_destroy(&acq_lock)
319 #define ACQ_LOCK() mtx_lock(&acq_lock)
320 #define ACQ_UNLOCK() mtx_unlock(&acq_lock)
321 #define ACQ_LOCK_ASSERT() mtx_assert(&acq_lock, MA_OWNED)
323 /* Hash table for lookup in ACQ list using SA addresses */
324 VNET_DEFINE_STATIC(struct secacq_list *, acqaddrhashtbl);
325 VNET_DEFINE_STATIC(u_long, acqaddrhash_mask);
326 #define V_acqaddrhashtbl VNET(acqaddrhashtbl)
327 #define V_acqaddrhash_mask VNET(acqaddrhash_mask)
329 /* Hash table for lookup in ACQ list using SEQ number */
330 VNET_DEFINE_STATIC(struct secacq_list *, acqseqhashtbl);
331 VNET_DEFINE_STATIC(u_long, acqseqhash_mask);
332 #define V_acqseqhashtbl VNET(acqseqhashtbl)
333 #define V_acqseqhash_mask VNET(acqseqhash_mask)
335 #define ACQHASH_NHASH_LOG2 7
336 #define ACQHASH_NHASH (1 << ACQHASH_NHASH_LOG2)
337 #define ACQADDRHASH_HASHVAL(idx) \
338 (key_addrprotohash(&(idx)->src, &(idx)->dst, &(idx)->proto) & \
340 #define ACQSEQHASH_HASHVAL(seq) \
341 (key_u32hash(seq) & V_acqseqhash_mask)
342 #define ACQADDRHASH_HASH(saidx) \
343 &V_acqaddrhashtbl[ACQADDRHASH_HASHVAL(saidx)]
344 #define ACQSEQHASH_HASH(seq) \
345 &V_acqseqhashtbl[ACQSEQHASH_HASHVAL(seq)]
346 /* SP acquiring list */
347 VNET_DEFINE_STATIC(LIST_HEAD(_spacqtree, secspacq), spacqtree);
348 #define V_spacqtree VNET(spacqtree)
349 static struct mtx spacq_lock;
350 #define SPACQ_LOCK_INIT() \
351 mtx_init(&spacq_lock, "spacqtree", \
352 "fast ipsec security policy acquire list", MTX_DEF)
353 #define SPACQ_LOCK_DESTROY() mtx_destroy(&spacq_lock)
354 #define SPACQ_LOCK() mtx_lock(&spacq_lock)
355 #define SPACQ_UNLOCK() mtx_unlock(&spacq_lock)
356 #define SPACQ_LOCK_ASSERT() mtx_assert(&spacq_lock, MA_OWNED)
358 static const int minsize[] = {
359 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
360 sizeof(struct sadb_sa), /* SADB_EXT_SA */
361 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
362 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
363 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
364 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_SRC */
365 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_DST */
366 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_PROXY */
367 sizeof(struct sadb_key), /* SADB_EXT_KEY_AUTH */
368 sizeof(struct sadb_key), /* SADB_EXT_KEY_ENCRYPT */
369 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_SRC */
370 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_DST */
371 sizeof(struct sadb_sens), /* SADB_EXT_SENSITIVITY */
372 sizeof(struct sadb_prop), /* SADB_EXT_PROPOSAL */
373 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_AUTH */
374 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_ENCRYPT */
375 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
376 0, /* SADB_X_EXT_KMPRIVATE */
377 sizeof(struct sadb_x_policy), /* SADB_X_EXT_POLICY */
378 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
379 sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
380 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
381 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
382 sizeof(struct sadb_address), /* SADB_X_EXT_NAT_T_OAI */
383 sizeof(struct sadb_address), /* SADB_X_EXT_NAT_T_OAR */
384 sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
385 sizeof(struct sadb_x_sa_replay), /* SADB_X_EXT_SA_REPLAY */
386 sizeof(struct sadb_address), /* SADB_X_EXT_NEW_ADDRESS_SRC */
387 sizeof(struct sadb_address), /* SADB_X_EXT_NEW_ADDRESS_DST */
389 _Static_assert(sizeof(minsize)/sizeof(int) == SADB_EXT_MAX + 1, "minsize size mismatch");
391 static const int maxsize[] = {
392 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
393 sizeof(struct sadb_sa), /* SADB_EXT_SA */
394 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
395 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
396 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
397 0, /* SADB_EXT_ADDRESS_SRC */
398 0, /* SADB_EXT_ADDRESS_DST */
399 0, /* SADB_EXT_ADDRESS_PROXY */
400 0, /* SADB_EXT_KEY_AUTH */
401 0, /* SADB_EXT_KEY_ENCRYPT */
402 0, /* SADB_EXT_IDENTITY_SRC */
403 0, /* SADB_EXT_IDENTITY_DST */
404 0, /* SADB_EXT_SENSITIVITY */
405 0, /* SADB_EXT_PROPOSAL */
406 0, /* SADB_EXT_SUPPORTED_AUTH */
407 0, /* SADB_EXT_SUPPORTED_ENCRYPT */
408 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
409 0, /* SADB_X_EXT_KMPRIVATE */
410 0, /* SADB_X_EXT_POLICY */
411 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
412 sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
413 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
414 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
415 0, /* SADB_X_EXT_NAT_T_OAI */
416 0, /* SADB_X_EXT_NAT_T_OAR */
417 sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
418 sizeof(struct sadb_x_sa_replay), /* SADB_X_EXT_SA_REPLAY */
419 0, /* SADB_X_EXT_NEW_ADDRESS_SRC */
420 0, /* SADB_X_EXT_NEW_ADDRESS_DST */
422 _Static_assert(sizeof(maxsize)/sizeof(int) == SADB_EXT_MAX + 1, "minsize size mismatch");
425 * Internal values for SA flags:
426 * SADB_X_EXT_F_CLONED means that SA was cloned by key_updateaddresses,
427 * thus we will not free the most of SA content in key_delsav().
429 #define SADB_X_EXT_F_CLONED 0x80000000
431 #define SADB_CHECKLEN(_mhp, _ext) \
432 ((_mhp)->extlen[(_ext)] < minsize[(_ext)] || (maxsize[(_ext)] != 0 && \
433 ((_mhp)->extlen[(_ext)] > maxsize[(_ext)])))
434 #define SADB_CHECKHDR(_mhp, _ext) ((_mhp)->ext[(_ext)] == NULL)
436 VNET_DEFINE_STATIC(int, ipsec_esp_keymin) = 256;
437 VNET_DEFINE_STATIC(int, ipsec_esp_auth) = 0;
438 VNET_DEFINE_STATIC(int, ipsec_ah_keymin) = 128;
440 #define V_ipsec_esp_keymin VNET(ipsec_esp_keymin)
441 #define V_ipsec_esp_auth VNET(ipsec_esp_auth)
442 #define V_ipsec_ah_keymin VNET(ipsec_ah_keymin)
445 VNET_DEFINE(int, ipsec_debug) = 1;
447 VNET_DEFINE(int, ipsec_debug) = 0;
451 SYSCTL_DECL(_net_inet_ipsec);
452 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEBUG, debug,
453 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_debug), 0,
454 "Enable IPsec debugging output when set.");
457 SYSCTL_DECL(_net_inet6_ipsec6);
458 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEBUG, debug,
459 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_debug), 0,
460 "Enable IPsec debugging output when set.");
463 SYSCTL_DECL(_net_key);
464 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL, debug,
465 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_debug_level), 0, "");
467 /* max count of trial for the decision of spi value */
468 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt,
469 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_trycnt), 0, "");
471 /* minimum spi value to allocate automatically. */
472 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE, spi_minval,
473 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_minval), 0, "");
475 /* maximun spi value to allocate automatically. */
476 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE, spi_maxval,
477 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_maxval), 0, "");
479 /* interval to initialize randseed */
480 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random,
481 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_int_random), 0, "");
483 /* lifetime for larval SA */
484 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME, larval_lifetime,
485 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_larval_lifetime), 0, "");
487 /* counter for blocking to send SADB_ACQUIRE to IKEd */
488 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT, blockacq_count,
489 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_blockacq_count), 0, "");
491 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
492 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME, blockacq_lifetime,
493 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_blockacq_lifetime), 0, "");
496 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH, esp_auth,
497 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_esp_auth), 0, "");
499 /* minimum ESP key length */
500 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin,
501 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_esp_keymin), 0, "");
503 /* minimum AH key length */
504 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN, ah_keymin,
505 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_ah_keymin), 0, "");
507 /* perfered old SA rather than new SA */
508 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA, preferred_oldsa,
509 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_preferred_oldsa), 0, "");
511 static SYSCTL_NODE(_net_key, OID_AUTO, spdcache,
512 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
515 SYSCTL_UINT(_net_key_spdcache, OID_AUTO, maxentries,
516 CTLFLAG_VNET | CTLFLAG_RDTUN, &VNET_NAME(key_spdcache_maxentries), 0,
517 "Maximum number of entries in the SPD cache"
518 " (power of 2, 0 to disable)");
520 SYSCTL_UINT(_net_key_spdcache, OID_AUTO, threshold,
521 CTLFLAG_VNET | CTLFLAG_RDTUN, &VNET_NAME(key_spdcache_threshold), 0,
522 "Number of SPs that make the SPD cache active");
524 #define __LIST_CHAINED(elm) \
525 (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
527 MALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
528 MALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
529 MALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
530 MALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
531 MALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
532 MALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
533 MALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
534 MALLOC_DEFINE(M_IPSEC_SPDCACHE, "ipsec-spdcache", "ipsec SPD cache");
536 VNET_DEFINE_STATIC(uma_zone_t, key_lft_zone);
537 #define V_key_lft_zone VNET(key_lft_zone)
540 * set parameters into secpolicyindex buffer.
541 * Must allocate secpolicyindex buffer passed to this function.
543 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
545 bzero((idx), sizeof(struct secpolicyindex)); \
546 (idx)->dir = (_dir); \
547 (idx)->prefs = (ps); \
548 (idx)->prefd = (pd); \
549 (idx)->ul_proto = (ulp); \
550 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
551 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
555 * set parameters into secasindex buffer.
556 * Must allocate secasindex buffer before calling this function.
558 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
560 bzero((idx), sizeof(struct secasindex)); \
561 (idx)->proto = (p); \
563 (idx)->reqid = (r); \
564 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
565 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
566 key_porttosaddr(&(idx)->src.sa, 0); \
567 key_porttosaddr(&(idx)->dst.sa, 0); \
572 u_long getspi_count; /* the avarage of count to try to get new SPI */
576 struct sadb_msg *msg;
577 struct sadb_ext *ext[SADB_EXT_MAX + 1];
578 int extoff[SADB_EXT_MAX + 1];
579 int extlen[SADB_EXT_MAX + 1];
582 static struct supported_ealgs {
584 const struct enc_xform *xform;
585 } supported_ealgs[] = {
586 { SADB_X_EALG_AES, &enc_xform_rijndael128 },
587 { SADB_EALG_NULL, &enc_xform_null },
588 { SADB_X_EALG_AESCTR, &enc_xform_aes_icm },
589 { SADB_X_EALG_AESGCM16, &enc_xform_aes_nist_gcm },
590 { SADB_X_EALG_AESGMAC, &enc_xform_aes_nist_gmac },
593 static struct supported_aalgs {
595 const struct auth_hash *xform;
596 } supported_aalgs[] = {
597 { SADB_X_AALG_NULL, &auth_hash_null },
598 { SADB_AALG_SHA1HMAC, &auth_hash_hmac_sha1 },
599 { SADB_X_AALG_SHA2_256, &auth_hash_hmac_sha2_256 },
600 { SADB_X_AALG_SHA2_384, &auth_hash_hmac_sha2_384 },
601 { SADB_X_AALG_SHA2_512, &auth_hash_hmac_sha2_512 },
602 { SADB_X_AALG_AES128GMAC, &auth_hash_nist_gmac_aes_128 },
603 { SADB_X_AALG_AES192GMAC, &auth_hash_nist_gmac_aes_192 },
604 { SADB_X_AALG_AES256GMAC, &auth_hash_nist_gmac_aes_256 },
607 static struct supported_calgs {
609 const struct comp_algo *xform;
610 } supported_calgs[] = {
611 { SADB_X_CALG_DEFLATE, &comp_algo_deflate },
615 static struct callout key_timer;
618 static void key_unlink(struct secpolicy *);
619 static struct secpolicy *key_do_allocsp(struct secpolicyindex *spidx, u_int dir);
620 static struct secpolicy *key_getsp(struct secpolicyindex *);
621 static struct secpolicy *key_getspbyid(u_int32_t);
622 static struct mbuf *key_gather_mbuf(struct mbuf *,
623 const struct sadb_msghdr *, int, int, ...);
624 static int key_spdadd(struct socket *, struct mbuf *,
625 const struct sadb_msghdr *);
626 static uint32_t key_getnewspid(void);
627 static int key_spddelete(struct socket *, struct mbuf *,
628 const struct sadb_msghdr *);
629 static int key_spddelete2(struct socket *, struct mbuf *,
630 const struct sadb_msghdr *);
631 static int key_spdget(struct socket *, struct mbuf *,
632 const struct sadb_msghdr *);
633 static int key_spdflush(struct socket *, struct mbuf *,
634 const struct sadb_msghdr *);
635 static int key_spddump(struct socket *, struct mbuf *,
636 const struct sadb_msghdr *);
637 static struct mbuf *key_setdumpsp(struct secpolicy *,
638 u_int8_t, u_int32_t, u_int32_t);
639 static struct mbuf *key_sp2mbuf(struct secpolicy *);
640 static size_t key_getspreqmsglen(struct secpolicy *);
641 static int key_spdexpire(struct secpolicy *);
642 static struct secashead *key_newsah(struct secasindex *);
643 static void key_freesah(struct secashead **);
644 static void key_delsah(struct secashead *);
645 static struct secasvar *key_newsav(const struct sadb_msghdr *,
646 struct secasindex *, uint32_t, int *);
647 static void key_delsav(struct secasvar *);
648 static void key_unlinksav(struct secasvar *);
649 static struct secashead *key_getsah(struct secasindex *);
650 static int key_checkspidup(uint32_t);
651 static struct secasvar *key_getsavbyspi(uint32_t);
652 static int key_setnatt(struct secasvar *, const struct sadb_msghdr *);
653 static int key_setsaval(struct secasvar *, const struct sadb_msghdr *);
654 static int key_updatelifetimes(struct secasvar *, const struct sadb_msghdr *);
655 static int key_updateaddresses(struct socket *, struct mbuf *,
656 const struct sadb_msghdr *, struct secasvar *, struct secasindex *);
658 static struct mbuf *key_setdumpsa(struct secasvar *, u_int8_t,
659 u_int8_t, u_int32_t, u_int32_t);
660 static struct mbuf *key_setsadbmsg(u_int8_t, u_int16_t, u_int8_t,
661 u_int32_t, pid_t, u_int16_t);
662 static struct mbuf *key_setsadbsa(struct secasvar *);
663 static struct mbuf *key_setsadbaddr(u_int16_t,
664 const struct sockaddr *, u_int8_t, u_int16_t);
665 static struct mbuf *key_setsadbxport(u_int16_t, u_int16_t);
666 static struct mbuf *key_setsadbxtype(u_int16_t);
667 static struct mbuf *key_setsadbxsa2(u_int8_t, u_int32_t, u_int32_t);
668 static struct mbuf *key_setsadbxsareplay(u_int32_t);
669 static struct mbuf *key_setsadbxpolicy(u_int16_t, u_int8_t,
670 u_int32_t, u_int32_t);
671 static struct seckey *key_dup_keymsg(const struct sadb_key *, size_t,
672 struct malloc_type *);
673 static struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
674 struct malloc_type *);
676 /* flags for key_cmpsaidx() */
677 #define CMP_HEAD 1 /* protocol, addresses. */
678 #define CMP_MODE_REQID 2 /* additionally HEAD, reqid, mode. */
679 #define CMP_REQID 3 /* additionally HEAD, reaid. */
680 #define CMP_EXACTLY 4 /* all elements. */
681 static int key_cmpsaidx(const struct secasindex *,
682 const struct secasindex *, int);
683 static int key_cmpspidx_exactly(struct secpolicyindex *,
684 struct secpolicyindex *);
685 static int key_cmpspidx_withmask(struct secpolicyindex *,
686 struct secpolicyindex *);
687 static int key_bbcmp(const void *, const void *, u_int);
688 static uint8_t key_satype2proto(uint8_t);
689 static uint8_t key_proto2satype(uint8_t);
691 static int key_getspi(struct socket *, struct mbuf *,
692 const struct sadb_msghdr *);
693 static uint32_t key_do_getnewspi(struct sadb_spirange *, struct secasindex *);
694 static int key_update(struct socket *, struct mbuf *,
695 const struct sadb_msghdr *);
696 static int key_add(struct socket *, struct mbuf *,
697 const struct sadb_msghdr *);
698 static int key_setident(struct secashead *, const struct sadb_msghdr *);
699 static struct mbuf *key_getmsgbuf_x1(struct mbuf *,
700 const struct sadb_msghdr *);
701 static int key_delete(struct socket *, struct mbuf *,
702 const struct sadb_msghdr *);
703 static int key_delete_all(struct socket *, struct mbuf *,
704 const struct sadb_msghdr *, struct secasindex *);
705 static int key_get(struct socket *, struct mbuf *,
706 const struct sadb_msghdr *);
708 static void key_getcomb_setlifetime(struct sadb_comb *);
709 static struct mbuf *key_getcomb_ealg(void);
710 static struct mbuf *key_getcomb_ah(void);
711 static struct mbuf *key_getcomb_ipcomp(void);
712 static struct mbuf *key_getprop(const struct secasindex *);
714 static int key_acquire(const struct secasindex *, struct secpolicy *);
715 static uint32_t key_newacq(const struct secasindex *, int *);
716 static uint32_t key_getacq(const struct secasindex *, int *);
717 static int key_acqdone(const struct secasindex *, uint32_t);
718 static int key_acqreset(uint32_t);
719 static struct secspacq *key_newspacq(struct secpolicyindex *);
720 static struct secspacq *key_getspacq(struct secpolicyindex *);
721 static int key_acquire2(struct socket *, struct mbuf *,
722 const struct sadb_msghdr *);
723 static int key_register(struct socket *, struct mbuf *,
724 const struct sadb_msghdr *);
725 static int key_expire(struct secasvar *, int);
726 static int key_flush(struct socket *, struct mbuf *,
727 const struct sadb_msghdr *);
728 static int key_dump(struct socket *, struct mbuf *,
729 const struct sadb_msghdr *);
730 static int key_promisc(struct socket *, struct mbuf *,
731 const struct sadb_msghdr *);
732 static int key_senderror(struct socket *, struct mbuf *, int);
733 static int key_validate_ext(const struct sadb_ext *, int);
734 static int key_align(struct mbuf *, struct sadb_msghdr *);
735 static struct mbuf *key_setlifetime(struct seclifetime *, uint16_t);
736 static struct mbuf *key_setkey(struct seckey *, uint16_t);
738 static void spdcache_init(void);
739 static void spdcache_clear(void);
740 static struct spdcache_entry *spdcache_entry_alloc(
741 const struct secpolicyindex *spidx,
742 struct secpolicy *policy);
743 static void spdcache_entry_free(struct spdcache_entry *entry);
745 static void spdcache_destroy(void);
748 #define DBG_IPSEC_INITREF(t, p) do { \
749 refcount_init(&(p)->refcnt, 1); \
751 printf("%s: Initialize refcnt %s(%p) = %u\n", \
752 __func__, #t, (p), (p)->refcnt)); \
754 #define DBG_IPSEC_ADDREF(t, p) do { \
755 refcount_acquire(&(p)->refcnt); \
757 printf("%s: Acquire refcnt %s(%p) -> %u\n", \
758 __func__, #t, (p), (p)->refcnt)); \
760 #define DBG_IPSEC_DELREF(t, p) do { \
762 printf("%s: Release refcnt %s(%p) -> %u\n", \
763 __func__, #t, (p), (p)->refcnt - 1)); \
764 refcount_release(&(p)->refcnt); \
767 #define IPSEC_INITREF(t, p) refcount_init(&(p)->refcnt, 1)
768 #define IPSEC_ADDREF(t, p) refcount_acquire(&(p)->refcnt)
769 #define IPSEC_DELREF(t, p) refcount_release(&(p)->refcnt)
771 #define SP_INITREF(p) IPSEC_INITREF(SP, p)
772 #define SP_ADDREF(p) IPSEC_ADDREF(SP, p)
773 #define SP_DELREF(p) IPSEC_DELREF(SP, p)
775 #define SAH_INITREF(p) IPSEC_INITREF(SAH, p)
776 #define SAH_ADDREF(p) IPSEC_ADDREF(SAH, p)
777 #define SAH_DELREF(p) IPSEC_DELREF(SAH, p)
779 #define SAV_INITREF(p) IPSEC_INITREF(SAV, p)
780 #define SAV_ADDREF(p) IPSEC_ADDREF(SAV, p)
781 #define SAV_DELREF(p) IPSEC_DELREF(SAV, p)
784 * Update the refcnt while holding the SPTREE lock.
787 key_addref(struct secpolicy *sp)
794 * Return 0 when there are known to be no SP's for the specified
795 * direction. Otherwise return 1. This is used by IPsec code
796 * to optimize performance.
799 key_havesp(u_int dir)
802 return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
803 TAILQ_FIRST(&V_sptree[dir]) != NULL : 1);
806 /* %%% IPsec policy management */
808 * Return current SPDB generation.
825 key_checksockaddrs(struct sockaddr *src, struct sockaddr *dst)
829 if (src->sa_family != dst->sa_family)
832 if (src->sa_len != dst->sa_len)
834 switch (src->sa_family) {
837 if (src->sa_len != sizeof(struct sockaddr_in))
843 if (src->sa_len != sizeof(struct sockaddr_in6))
848 return (EAFNOSUPPORT);
854 key_do_allocsp(struct secpolicyindex *spidx, u_int dir)
856 SPTREE_RLOCK_TRACKER;
857 struct secpolicy *sp;
859 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
860 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
861 ("invalid direction %u", dir));
864 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
865 if (key_cmpspidx_withmask(&sp->spidx, spidx)) {
876 * allocating a SP for OUTBOUND or INBOUND packet.
877 * Must call key_freesp() later.
878 * OUT: NULL: not found
879 * others: found and return the pointer.
882 key_allocsp(struct secpolicyindex *spidx, u_int dir)
884 struct spdcache_entry *entry, *lastentry, *tmpentry;
885 struct secpolicy *sp;
889 if (!SPDCACHE_ACTIVE()) {
890 sp = key_do_allocsp(spidx, dir);
894 hashv = SPDCACHE_HASHVAL(spidx);
895 SPDCACHE_LOCK(hashv);
897 LIST_FOREACH_SAFE(entry, &V_spdcachehashtbl[hashv], chain, tmpentry) {
898 /* Removed outdated entries */
899 if (entry->sp != NULL &&
900 entry->sp->state == IPSEC_SPSTATE_DEAD) {
901 LIST_REMOVE(entry, chain);
902 spdcache_entry_free(entry);
907 if (!key_cmpspidx_exactly(&entry->spidx, spidx)) {
913 if (entry->sp != NULL)
916 /* IPSECSTAT_INC(ips_spdcache_hits); */
918 SPDCACHE_UNLOCK(hashv);
922 /* IPSECSTAT_INC(ips_spdcache_misses); */
924 sp = key_do_allocsp(spidx, dir);
925 entry = spdcache_entry_alloc(spidx, sp);
927 if (nb_entries >= SPDCACHE_MAX_ENTRIES_PER_HASH) {
928 LIST_REMOVE(lastentry, chain);
929 spdcache_entry_free(lastentry);
932 LIST_INSERT_HEAD(&V_spdcachehashtbl[hashv], entry, chain);
935 SPDCACHE_UNLOCK(hashv);
938 if (sp != NULL) { /* found a SPD entry */
939 sp->lastused = time_second;
941 printf("%s: return SP(%p)\n", __func__, sp));
942 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
945 printf("%s: lookup failed for ", __func__);
946 kdebug_secpolicyindex(spidx, NULL));
952 * Allocating an SA entry for an *INBOUND* or *OUTBOUND* TCP packet, signed
953 * or should be signed by MD5 signature.
954 * We don't use key_allocsa() for such lookups, because we don't know SPI.
955 * Unlike ESP and AH protocols, SPI isn't transmitted in the TCP header with
956 * signed packet. We use SADB only as storage for password.
957 * OUT: positive: corresponding SA for given saidx found.
961 key_allocsa_tcpmd5(struct secasindex *saidx)
963 SAHTREE_RLOCK_TRACKER;
964 struct secashead *sah;
965 struct secasvar *sav;
967 IPSEC_ASSERT(saidx->proto == IPPROTO_TCP,
968 ("unexpected security protocol %u", saidx->proto));
969 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TCPMD5,
970 ("unexpected mode %u", saidx->mode));
973 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
975 printf("%s: checking SAH\n", __func__);
976 kdebug_secash(sah, " "));
977 if (sah->saidx.proto != IPPROTO_TCP)
979 if (!key_sockaddrcmp(&saidx->dst.sa, &sah->saidx.dst.sa, 0) &&
980 !key_sockaddrcmp(&saidx->src.sa, &sah->saidx.src.sa, 0))
984 if (V_key_preferred_oldsa)
985 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
987 sav = TAILQ_FIRST(&sah->savtree_alive);
996 printf("%s: return SA(%p)\n", __func__, sav));
997 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1000 printf("%s: SA not found\n", __func__));
1001 KEYDBG(IPSEC_DATA, kdebug_secasindex(saidx, NULL));
1007 * Allocating an SA entry for an *OUTBOUND* packet.
1008 * OUT: positive: corresponding SA for given saidx found.
1009 * NULL: SA not found, but will be acquired, check *error
1010 * for acquiring status.
1013 key_allocsa_policy(struct secpolicy *sp, const struct secasindex *saidx,
1016 SAHTREE_RLOCK_TRACKER;
1017 struct secashead *sah;
1018 struct secasvar *sav;
1020 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
1021 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
1022 saidx->mode == IPSEC_MODE_TUNNEL,
1023 ("unexpected policy %u", saidx->mode));
1026 * We check new SA in the IPsec request because a different
1027 * SA may be involved each time this request is checked, either
1028 * because new SAs are being configured, or this request is
1029 * associated with an unconnected datagram socket, or this request
1030 * is associated with a system default policy.
1033 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
1035 printf("%s: checking SAH\n", __func__);
1036 kdebug_secash(sah, " "));
1037 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID))
1043 * Allocate the oldest SA available according to
1044 * draft-jenkins-ipsec-rekeying-03.
1046 if (V_key_preferred_oldsa)
1047 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
1049 sav = TAILQ_FIRST(&sah->savtree_alive);
1059 printf("%s: chosen SA(%p) for SP(%p)\n", __func__,
1061 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1062 return (sav); /* return referenced SA */
1065 /* there is no SA */
1066 *error = key_acquire(saidx, sp);
1068 ipseclog((LOG_DEBUG,
1069 "%s: error %d returned from key_acquire()\n",
1072 printf("%s: acquire SA for SP(%p), error %d\n",
1073 __func__, sp, *error));
1074 KEYDBG(IPSEC_DATA, kdebug_secasindex(saidx, NULL));
1079 * allocating a usable SA entry for a *INBOUND* packet.
1080 * Must call key_freesav() later.
1081 * OUT: positive: pointer to a usable sav (i.e. MATURE or DYING state).
1082 * NULL: not found, or error occurred.
1084 * According to RFC 2401 SA is uniquely identified by a triple SPI,
1085 * destination address, and security protocol. But according to RFC 4301,
1086 * SPI by itself suffices to specify an SA.
1088 * Note that, however, we do need to keep source address in IPsec SA.
1089 * IKE specification and PF_KEY specification do assume that we
1090 * keep source address in IPsec SA. We see a tricky situation here.
1093 key_allocsa(union sockaddr_union *dst, uint8_t proto, uint32_t spi)
1095 SAHTREE_RLOCK_TRACKER;
1096 struct secasvar *sav;
1098 IPSEC_ASSERT(proto == IPPROTO_ESP || proto == IPPROTO_AH ||
1099 proto == IPPROTO_IPCOMP, ("unexpected security protocol %u",
1103 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
1104 if (sav->spi == spi)
1108 * We use single SPI namespace for all protocols, so it is
1109 * impossible to have SPI duplicates in the SAVHASH.
1112 if (sav->state != SADB_SASTATE_LARVAL &&
1113 sav->sah->saidx.proto == proto &&
1114 key_sockaddrcmp(&dst->sa,
1115 &sav->sah->saidx.dst.sa, 0) == 0)
1124 char buf[IPSEC_ADDRSTRLEN];
1125 printf("%s: SA not found for spi %u proto %u dst %s\n",
1126 __func__, ntohl(spi), proto, ipsec_address(dst, buf,
1130 printf("%s: return SA(%p)\n", __func__, sav));
1131 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1137 key_allocsa_tunnel(union sockaddr_union *src, union sockaddr_union *dst,
1140 SAHTREE_RLOCK_TRACKER;
1141 struct secasindex saidx;
1142 struct secashead *sah;
1143 struct secasvar *sav;
1145 IPSEC_ASSERT(src != NULL, ("null src address"));
1146 IPSEC_ASSERT(dst != NULL, ("null dst address"));
1148 KEY_SETSECASIDX(proto, IPSEC_MODE_TUNNEL, 0, &src->sa,
1153 LIST_FOREACH(sah, SAHADDRHASH_HASH(&saidx), addrhash) {
1154 if (IPSEC_MODE_TUNNEL != sah->saidx.mode)
1156 if (proto != sah->saidx.proto)
1158 if (key_sockaddrcmp(&src->sa, &sah->saidx.src.sa, 0) != 0)
1160 if (key_sockaddrcmp(&dst->sa, &sah->saidx.dst.sa, 0) != 0)
1162 /* XXXAE: is key_preferred_oldsa reasonably?*/
1163 if (V_key_preferred_oldsa)
1164 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
1166 sav = TAILQ_FIRST(&sah->savtree_alive);
1174 printf("%s: return SA(%p)\n", __func__, sav));
1176 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1181 * Must be called after calling key_allocsp().
1184 key_freesp(struct secpolicy **spp)
1186 struct secpolicy *sp = *spp;
1188 IPSEC_ASSERT(sp != NULL, ("null sp"));
1189 if (SP_DELREF(sp) == 0)
1193 printf("%s: last reference to SP(%p)\n", __func__, sp));
1194 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1197 while (sp->tcount > 0)
1198 ipsec_delisr(sp->req[--sp->tcount]);
1199 free(sp, M_IPSEC_SP);
1203 key_unlink(struct secpolicy *sp)
1206 IPSEC_ASSERT(sp->spidx.dir == IPSEC_DIR_INBOUND ||
1207 sp->spidx.dir == IPSEC_DIR_OUTBOUND,
1208 ("invalid direction %u", sp->spidx.dir));
1209 SPTREE_UNLOCK_ASSERT();
1212 printf("%s: SP(%p)\n", __func__, sp));
1214 if (sp->state != IPSEC_SPSTATE_ALIVE) {
1215 /* SP is already unlinked */
1219 sp->state = IPSEC_SPSTATE_DEAD;
1220 TAILQ_REMOVE(&V_sptree[sp->spidx.dir], sp, chain);
1222 LIST_REMOVE(sp, idhash);
1225 if (SPDCACHE_ENABLED())
1231 * insert a secpolicy into the SP database. Lower priorities first
1234 key_insertsp(struct secpolicy *newsp)
1236 struct secpolicy *sp;
1238 SPTREE_WLOCK_ASSERT();
1239 TAILQ_FOREACH(sp, &V_sptree[newsp->spidx.dir], chain) {
1240 if (newsp->priority < sp->priority) {
1241 TAILQ_INSERT_BEFORE(sp, newsp, chain);
1245 TAILQ_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, chain);
1247 LIST_INSERT_HEAD(SPHASH_HASH(newsp->id), newsp, idhash);
1248 newsp->state = IPSEC_SPSTATE_ALIVE;
1254 * Insert a bunch of VTI secpolicies into the SPDB.
1255 * We keep VTI policies in the separate list due to following reasons:
1256 * 1) they should be immutable to user's or some deamon's attempts to
1257 * delete. The only way delete such policies - destroy or unconfigure
1258 * corresponding virtual inteface.
1259 * 2) such policies have traffic selector that matches all traffic per
1261 * Since all VTI policies have the same priority, we don't care about
1265 key_register_ifnet(struct secpolicy **spp, u_int count)
1272 * First of try to acquire id for each SP.
1274 for (i = 0; i < count; i++) {
1275 IPSEC_ASSERT(spp[i]->spidx.dir == IPSEC_DIR_INBOUND ||
1276 spp[i]->spidx.dir == IPSEC_DIR_OUTBOUND,
1277 ("invalid direction %u", spp[i]->spidx.dir));
1279 if ((spp[i]->id = key_getnewspid()) == 0) {
1284 for (i = 0; i < count; i++) {
1285 TAILQ_INSERT_TAIL(&V_sptree_ifnet[spp[i]->spidx.dir],
1288 * NOTE: despite the fact that we keep VTI SP in the
1289 * separate list, SPHASH contains policies from both
1290 * sources. Thus SADB_X_SPDGET will correctly return
1291 * SP by id, because it uses SPHASH for lookups.
1293 LIST_INSERT_HEAD(SPHASH_HASH(spp[i]->id), spp[i], idhash);
1294 spp[i]->state = IPSEC_SPSTATE_IFNET;
1298 * Notify user processes about new SP.
1300 for (i = 0; i < count; i++) {
1301 m = key_setdumpsp(spp[i], SADB_X_SPDADD, 0, 0);
1303 key_sendup_mbuf(NULL, m, KEY_SENDUP_ALL);
1309 key_unregister_ifnet(struct secpolicy **spp, u_int count)
1315 for (i = 0; i < count; i++) {
1316 IPSEC_ASSERT(spp[i]->spidx.dir == IPSEC_DIR_INBOUND ||
1317 spp[i]->spidx.dir == IPSEC_DIR_OUTBOUND,
1318 ("invalid direction %u", spp[i]->spidx.dir));
1320 if (spp[i]->state != IPSEC_SPSTATE_IFNET)
1322 spp[i]->state = IPSEC_SPSTATE_DEAD;
1323 TAILQ_REMOVE(&V_sptree_ifnet[spp[i]->spidx.dir],
1326 LIST_REMOVE(spp[i], idhash);
1329 if (SPDCACHE_ENABLED())
1332 for (i = 0; i < count; i++) {
1333 m = key_setdumpsp(spp[i], SADB_X_SPDDELETE, 0, 0);
1335 key_sendup_mbuf(NULL, m, KEY_SENDUP_ALL);
1340 * Must be called after calling key_allocsa().
1341 * This function is called by key_freesp() to free some SA allocated
1345 key_freesav(struct secasvar **psav)
1347 struct secasvar *sav = *psav;
1349 IPSEC_ASSERT(sav != NULL, ("null sav"));
1350 if (SAV_DELREF(sav) == 0)
1354 printf("%s: last reference to SA(%p)\n", __func__, sav));
1361 * Unlink SA from SAH and SPI hash under SAHTREE_WLOCK.
1362 * Expect that SA has extra reference due to lookup.
1363 * Release this references, also release SAH reference after unlink.
1366 key_unlinksav(struct secasvar *sav)
1368 struct secashead *sah;
1371 printf("%s: SA(%p)\n", __func__, sav));
1373 SAHTREE_UNLOCK_ASSERT();
1375 if (sav->state == SADB_SASTATE_DEAD) {
1376 /* SA is already unlinked */
1380 /* Unlink from SAH */
1381 if (sav->state == SADB_SASTATE_LARVAL)
1382 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
1384 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
1385 /* Unlink from SPI hash */
1386 LIST_REMOVE(sav, spihash);
1387 sav->state = SADB_SASTATE_DEAD;
1391 /* Since we are unlinked, release reference to SAH */
1395 /* %%% SPD management */
1398 * OUT: NULL : not found
1399 * others : found, pointer to a SP.
1401 static struct secpolicy *
1402 key_getsp(struct secpolicyindex *spidx)
1404 SPTREE_RLOCK_TRACKER;
1405 struct secpolicy *sp;
1407 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1410 TAILQ_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1411 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1423 * OUT: NULL : not found
1424 * others : found, pointer to referenced SP.
1426 static struct secpolicy *
1427 key_getspbyid(uint32_t id)
1429 SPTREE_RLOCK_TRACKER;
1430 struct secpolicy *sp;
1433 LIST_FOREACH(sp, SPHASH_HASH(id), idhash) {
1446 struct secpolicy *sp;
1448 sp = malloc(sizeof(*sp), M_IPSEC_SP, M_NOWAIT | M_ZERO);
1454 struct ipsecrequest *
1458 return (malloc(sizeof(struct ipsecrequest), M_IPSEC_SR,
1459 M_NOWAIT | M_ZERO));
1463 ipsec_delisr(struct ipsecrequest *p)
1466 free(p, M_IPSEC_SR);
1470 * create secpolicy structure from sadb_x_policy structure.
1471 * NOTE: `state', `secpolicyindex' and 'id' in secpolicy structure
1472 * are not set, so must be set properly later.
1475 key_msg2sp(struct sadb_x_policy *xpl0, size_t len, int *error)
1477 struct secpolicy *newsp;
1479 IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1480 IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1482 if (len != PFKEY_EXTLEN(xpl0)) {
1483 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1488 if ((newsp = key_newsp()) == NULL) {
1493 newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1494 newsp->policy = xpl0->sadb_x_policy_type;
1495 newsp->priority = xpl0->sadb_x_policy_priority;
1499 switch (xpl0->sadb_x_policy_type) {
1500 case IPSEC_POLICY_DISCARD:
1501 case IPSEC_POLICY_NONE:
1502 case IPSEC_POLICY_ENTRUST:
1503 case IPSEC_POLICY_BYPASS:
1506 case IPSEC_POLICY_IPSEC:
1508 struct sadb_x_ipsecrequest *xisr;
1509 struct ipsecrequest *isr;
1512 /* validity check */
1513 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1514 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1521 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1522 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1526 if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr) ||
1527 xisr->sadb_x_ipsecrequest_len > tlen) {
1528 ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1529 "length.\n", __func__));
1535 if (newsp->tcount >= IPSEC_MAXREQ) {
1536 ipseclog((LOG_DEBUG,
1537 "%s: too many ipsecrequests.\n",
1544 /* allocate request buffer */
1545 /* NB: data structure is zero'd */
1546 isr = ipsec_newisr();
1548 ipseclog((LOG_DEBUG,
1549 "%s: No more memory.\n", __func__));
1555 newsp->req[newsp->tcount++] = isr;
1558 switch (xisr->sadb_x_ipsecrequest_proto) {
1561 case IPPROTO_IPCOMP:
1564 ipseclog((LOG_DEBUG,
1565 "%s: invalid proto type=%u\n", __func__,
1566 xisr->sadb_x_ipsecrequest_proto));
1568 *error = EPROTONOSUPPORT;
1572 (uint8_t)xisr->sadb_x_ipsecrequest_proto;
1574 switch (xisr->sadb_x_ipsecrequest_mode) {
1575 case IPSEC_MODE_TRANSPORT:
1576 case IPSEC_MODE_TUNNEL:
1578 case IPSEC_MODE_ANY:
1580 ipseclog((LOG_DEBUG,
1581 "%s: invalid mode=%u\n", __func__,
1582 xisr->sadb_x_ipsecrequest_mode));
1587 isr->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1589 switch (xisr->sadb_x_ipsecrequest_level) {
1590 case IPSEC_LEVEL_DEFAULT:
1591 case IPSEC_LEVEL_USE:
1592 case IPSEC_LEVEL_REQUIRE:
1594 case IPSEC_LEVEL_UNIQUE:
1595 /* validity check */
1597 * If range violation of reqid, kernel will
1598 * update it, don't refuse it.
1600 if (xisr->sadb_x_ipsecrequest_reqid
1601 > IPSEC_MANUAL_REQID_MAX) {
1602 ipseclog((LOG_DEBUG,
1603 "%s: reqid=%d range "
1604 "violation, updated by kernel.\n",
1606 xisr->sadb_x_ipsecrequest_reqid));
1607 xisr->sadb_x_ipsecrequest_reqid = 0;
1610 /* allocate new reqid id if reqid is zero. */
1611 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1613 if ((reqid = key_newreqid()) == 0) {
1618 isr->saidx.reqid = reqid;
1619 xisr->sadb_x_ipsecrequest_reqid = reqid;
1621 /* set it for manual keying. */
1623 xisr->sadb_x_ipsecrequest_reqid;
1628 ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1630 xisr->sadb_x_ipsecrequest_level));
1635 isr->level = xisr->sadb_x_ipsecrequest_level;
1637 /* set IP addresses if there */
1638 if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1639 struct sockaddr *paddr;
1641 len = tlen - sizeof(*xisr);
1642 paddr = (struct sockaddr *)(xisr + 1);
1643 /* validity check */
1644 if (len < sizeof(struct sockaddr) ||
1645 len < 2 * paddr->sa_len ||
1646 paddr->sa_len > sizeof(isr->saidx.src)) {
1647 ipseclog((LOG_DEBUG, "%s: invalid "
1648 "request address length.\n",
1655 * Request length should be enough to keep
1656 * source and destination addresses.
1658 if (xisr->sadb_x_ipsecrequest_len <
1659 sizeof(*xisr) + 2 * paddr->sa_len) {
1660 ipseclog((LOG_DEBUG, "%s: invalid "
1661 "ipsecrequest length.\n",
1667 bcopy(paddr, &isr->saidx.src, paddr->sa_len);
1668 paddr = (struct sockaddr *)((caddr_t)paddr +
1671 /* validity check */
1672 if (paddr->sa_len !=
1673 isr->saidx.src.sa.sa_len) {
1674 ipseclog((LOG_DEBUG, "%s: invalid "
1675 "request address length.\n",
1681 /* AF family should match */
1682 if (paddr->sa_family !=
1683 isr->saidx.src.sa.sa_family) {
1684 ipseclog((LOG_DEBUG, "%s: address "
1685 "family doesn't match.\n",
1691 bcopy(paddr, &isr->saidx.dst, paddr->sa_len);
1694 * Addresses for TUNNEL mode requests are
1697 if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
1698 ipseclog((LOG_DEBUG, "%s: missing "
1699 "request addresses.\n", __func__));
1705 tlen -= xisr->sadb_x_ipsecrequest_len;
1707 /* validity check */
1709 ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1716 xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1717 + xisr->sadb_x_ipsecrequest_len);
1719 /* XXXAE: LARVAL SP */
1720 if (newsp->tcount < 1) {
1721 ipseclog((LOG_DEBUG, "%s: valid IPSEC transforms "
1722 "not found.\n", __func__));
1730 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1743 static uint32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1745 if (auto_reqid == ~0)
1746 auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1750 /* XXX should be unique check */
1751 return (auto_reqid);
1755 * copy secpolicy struct to sadb_x_policy structure indicated.
1757 static struct mbuf *
1758 key_sp2mbuf(struct secpolicy *sp)
1763 tlen = key_getspreqmsglen(sp);
1764 m = m_get2(tlen, M_NOWAIT, MT_DATA, 0);
1769 if (key_sp2msg(sp, m->m_data, &tlen) != 0) {
1777 key_sp2msg(struct secpolicy *sp, void *request, size_t *len)
1779 struct sadb_x_ipsecrequest *xisr;
1780 struct sadb_x_policy *xpl;
1781 struct ipsecrequest *isr;
1786 IPSEC_ASSERT(sp != NULL, ("null policy"));
1788 xlen = sizeof(*xpl);
1793 bzero(request, *len);
1794 xpl = (struct sadb_x_policy *)request;
1795 xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1796 xpl->sadb_x_policy_type = sp->policy;
1797 xpl->sadb_x_policy_dir = sp->spidx.dir;
1798 xpl->sadb_x_policy_id = sp->id;
1799 xpl->sadb_x_policy_priority = sp->priority;
1800 switch (sp->state) {
1801 case IPSEC_SPSTATE_IFNET:
1802 xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_IFNET;
1804 case IPSEC_SPSTATE_PCB:
1805 xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_PCB;
1808 xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_GLOBAL;
1811 /* if is the policy for ipsec ? */
1812 if (sp->policy == IPSEC_POLICY_IPSEC) {
1813 p = (caddr_t)xpl + sizeof(*xpl);
1814 for (i = 0; i < sp->tcount; i++) {
1816 ilen = PFKEY_ALIGN8(sizeof(*xisr) +
1817 isr->saidx.src.sa.sa_len +
1818 isr->saidx.dst.sa.sa_len);
1822 /* Calculate needed size */
1825 xisr = (struct sadb_x_ipsecrequest *)p;
1826 xisr->sadb_x_ipsecrequest_len = ilen;
1827 xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1828 xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1829 xisr->sadb_x_ipsecrequest_level = isr->level;
1830 xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1833 bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1834 p += isr->saidx.src.sa.sa_len;
1835 bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1836 p += isr->saidx.dst.sa.sa_len;
1839 xpl->sadb_x_policy_len = PFKEY_UNIT64(xlen);
1843 *len = sizeof(*xpl);
1847 /* m will not be freed nor modified */
1848 static struct mbuf *
1849 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1850 int ndeep, int nitem, ...)
1855 struct mbuf *result = NULL, *n;
1858 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1859 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1861 va_start(ap, nitem);
1862 for (i = 0; i < nitem; i++) {
1863 idx = va_arg(ap, int);
1864 if (idx < 0 || idx > SADB_EXT_MAX)
1866 /* don't attempt to pull empty extension */
1867 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1869 if (idx != SADB_EXT_RESERVED &&
1870 (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1873 if (idx == SADB_EXT_RESERVED) {
1874 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1876 IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1878 MGETHDR(n, M_NOWAIT, MT_DATA);
1883 m_copydata(m, 0, sizeof(struct sadb_msg),
1885 } else if (i < ndeep) {
1886 len = mhp->extlen[idx];
1887 n = m_get2(len, M_NOWAIT, MT_DATA, 0);
1892 m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1895 n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1908 if ((result->m_flags & M_PKTHDR) != 0) {
1909 result->m_pkthdr.len = 0;
1910 for (n = result; n; n = n->m_next)
1911 result->m_pkthdr.len += n->m_len;
1923 * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1924 * add an entry to SP database, when received
1925 * <base, address(SD), (lifetime(H),) policy>
1927 * Adding to SP database,
1929 * <base, address(SD), (lifetime(H),) policy>
1930 * to the socket which was send.
1932 * SPDADD set a unique policy entry.
1933 * SPDSETIDX like SPDADD without a part of policy requests.
1934 * SPDUPDATE replace a unique policy entry.
1936 * XXXAE: serialize this in PF_KEY to avoid races.
1937 * m will always be freed.
1940 key_spdadd(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
1942 struct secpolicyindex spidx;
1943 struct sadb_address *src0, *dst0;
1944 struct sadb_x_policy *xpl0, *xpl;
1945 struct sadb_lifetime *lft = NULL;
1946 struct secpolicy *newsp;
1949 IPSEC_ASSERT(so != NULL, ("null socket"));
1950 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1951 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1952 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1954 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
1955 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
1956 SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY)) {
1957 ipseclog((LOG_DEBUG,
1958 "%s: invalid message: missing required header.\n",
1960 return key_senderror(so, m, EINVAL);
1962 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
1963 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
1964 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
1965 ipseclog((LOG_DEBUG,
1966 "%s: invalid message: wrong header size.\n", __func__));
1967 return key_senderror(so, m, EINVAL);
1969 if (!SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD)) {
1970 if (SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_HARD)) {
1971 ipseclog((LOG_DEBUG,
1972 "%s: invalid message: wrong header size.\n",
1974 return key_senderror(so, m, EINVAL);
1976 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1979 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1980 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1981 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1983 /* check the direciton */
1984 switch (xpl0->sadb_x_policy_dir) {
1985 case IPSEC_DIR_INBOUND:
1986 case IPSEC_DIR_OUTBOUND:
1989 ipseclog((LOG_DEBUG, "%s: invalid SP direction.\n", __func__));
1990 return key_senderror(so, m, EINVAL);
1992 /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1993 if (xpl0->sadb_x_policy_type != IPSEC_POLICY_DISCARD &&
1994 xpl0->sadb_x_policy_type != IPSEC_POLICY_NONE &&
1995 xpl0->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
1996 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1997 return key_senderror(so, m, EINVAL);
2000 /* policy requests are mandatory when action is ipsec. */
2001 if (xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
2002 mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
2003 ipseclog((LOG_DEBUG,
2004 "%s: policy requests required.\n", __func__));
2005 return key_senderror(so, m, EINVAL);
2008 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
2009 (struct sockaddr *)(dst0 + 1));
2011 src0->sadb_address_proto != dst0->sadb_address_proto) {
2012 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
2013 return key_senderror(so, m, error);
2016 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2019 src0->sadb_address_prefixlen,
2020 dst0->sadb_address_prefixlen,
2021 src0->sadb_address_proto,
2023 /* Checking there is SP already or not. */
2024 newsp = key_getsp(&spidx);
2025 if (newsp != NULL) {
2026 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
2028 printf("%s: unlink SP(%p) for SPDUPDATE\n",
2030 KEYDBG(KEY_DATA, kdebug_secpolicy(newsp));
2035 ipseclog((LOG_DEBUG,
2036 "%s: a SP entry exists already.\n", __func__));
2037 return (key_senderror(so, m, EEXIST));
2041 /* allocate new SP entry */
2042 if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
2043 return key_senderror(so, m, error);
2046 newsp->lastused = newsp->created = time_second;
2047 newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
2048 newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
2049 bcopy(&spidx, &newsp->spidx, sizeof(spidx));
2051 /* XXXAE: there is race between key_getsp() and key_insertsp() */
2053 if ((newsp->id = key_getnewspid()) == 0) {
2056 return key_senderror(so, m, ENOBUFS);
2058 key_insertsp(newsp);
2060 if (SPDCACHE_ENABLED())
2064 printf("%s: SP(%p)\n", __func__, newsp));
2065 KEYDBG(KEY_DATA, kdebug_secpolicy(newsp));
2068 struct mbuf *n, *mpolicy;
2069 struct sadb_msg *newmsg;
2072 /* create new sadb_msg to reply. */
2074 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
2075 SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
2076 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2078 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
2080 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2083 return key_senderror(so, m, ENOBUFS);
2085 if (n->m_len < sizeof(*newmsg)) {
2086 n = m_pullup(n, sizeof(*newmsg));
2088 return key_senderror(so, m, ENOBUFS);
2090 newmsg = mtod(n, struct sadb_msg *);
2091 newmsg->sadb_msg_errno = 0;
2092 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2095 mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
2096 sizeof(*xpl), &off);
2097 if (mpolicy == NULL) {
2098 /* n is already freed */
2099 return key_senderror(so, m, ENOBUFS);
2101 xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
2102 if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
2104 return key_senderror(so, m, EINVAL);
2106 xpl->sadb_x_policy_id = newsp->id;
2109 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2114 * get new policy id.
2120 key_getnewspid(void)
2122 struct secpolicy *sp;
2124 int count = V_key_spi_trycnt; /* XXX */
2126 SPTREE_WLOCK_ASSERT();
2128 if (V_policy_id == ~0) /* overflowed */
2129 newid = V_policy_id = 1;
2131 newid = ++V_policy_id;
2132 LIST_FOREACH(sp, SPHASH_HASH(newid), idhash) {
2133 if (sp->id == newid)
2139 if (count == 0 || newid == 0) {
2140 ipseclog((LOG_DEBUG, "%s: failed to allocate policy id.\n",
2148 * SADB_SPDDELETE processing
2150 * <base, address(SD), policy(*)>
2151 * from the user(?), and set SADB_SASTATE_DEAD,
2153 * <base, address(SD), policy(*)>
2155 * policy(*) including direction of policy.
2157 * m will always be freed.
2160 key_spddelete(struct socket *so, struct mbuf *m,
2161 const struct sadb_msghdr *mhp)
2163 struct secpolicyindex spidx;
2164 struct sadb_address *src0, *dst0;
2165 struct sadb_x_policy *xpl0;
2166 struct secpolicy *sp;
2168 IPSEC_ASSERT(so != NULL, ("null so"));
2169 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2170 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2171 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2173 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
2174 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
2175 SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY)) {
2176 ipseclog((LOG_DEBUG,
2177 "%s: invalid message: missing required header.\n",
2179 return key_senderror(so, m, EINVAL);
2181 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
2182 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
2183 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2184 ipseclog((LOG_DEBUG,
2185 "%s: invalid message: wrong header size.\n", __func__));
2186 return key_senderror(so, m, EINVAL);
2189 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2190 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2191 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2193 /* check the direciton */
2194 switch (xpl0->sadb_x_policy_dir) {
2195 case IPSEC_DIR_INBOUND:
2196 case IPSEC_DIR_OUTBOUND:
2199 ipseclog((LOG_DEBUG, "%s: invalid SP direction.\n", __func__));
2200 return key_senderror(so, m, EINVAL);
2202 /* Only DISCARD, NONE and IPSEC are allowed */
2203 if (xpl0->sadb_x_policy_type != IPSEC_POLICY_DISCARD &&
2204 xpl0->sadb_x_policy_type != IPSEC_POLICY_NONE &&
2205 xpl0->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
2206 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
2207 return key_senderror(so, m, EINVAL);
2209 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
2210 (struct sockaddr *)(dst0 + 1)) != 0 ||
2211 src0->sadb_address_proto != dst0->sadb_address_proto) {
2212 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
2213 return key_senderror(so, m, EINVAL);
2216 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2219 src0->sadb_address_prefixlen,
2220 dst0->sadb_address_prefixlen,
2221 src0->sadb_address_proto,
2224 /* Is there SP in SPD ? */
2225 if ((sp = key_getsp(&spidx)) == NULL) {
2226 ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2227 return key_senderror(so, m, EINVAL);
2230 /* save policy id to buffer to be returned. */
2231 xpl0->sadb_x_policy_id = sp->id;
2234 printf("%s: SP(%p)\n", __func__, sp));
2235 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2241 struct sadb_msg *newmsg;
2243 /* create new sadb_msg to reply. */
2244 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2245 SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2247 return key_senderror(so, m, ENOBUFS);
2249 newmsg = mtod(n, struct sadb_msg *);
2250 newmsg->sadb_msg_errno = 0;
2251 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2254 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2259 * SADB_SPDDELETE2 processing
2262 * from the user(?), and set SADB_SASTATE_DEAD,
2266 * policy(*) including direction of policy.
2268 * m will always be freed.
2271 key_spddelete2(struct socket *so, struct mbuf *m,
2272 const struct sadb_msghdr *mhp)
2274 struct secpolicy *sp;
2277 IPSEC_ASSERT(so != NULL, ("null socket"));
2278 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2279 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2280 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2282 if (SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY) ||
2283 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2284 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2286 return key_senderror(so, m, EINVAL);
2289 id = ((struct sadb_x_policy *)
2290 mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2292 /* Is there SP in SPD ? */
2293 if ((sp = key_getspbyid(id)) == NULL) {
2294 ipseclog((LOG_DEBUG, "%s: no SP found for id %u.\n",
2296 return key_senderror(so, m, EINVAL);
2300 printf("%s: SP(%p)\n", __func__, sp));
2301 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2303 if (sp->state != IPSEC_SPSTATE_DEAD) {
2304 ipseclog((LOG_DEBUG, "%s: failed to delete SP with id %u.\n",
2307 return (key_senderror(so, m, EACCES));
2312 struct mbuf *n, *nn;
2313 struct sadb_msg *newmsg;
2316 /* create new sadb_msg to reply. */
2317 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2319 MGETHDR(n, M_NOWAIT, MT_DATA);
2320 if (n && len > MHLEN) {
2321 if (!(MCLGET(n, M_NOWAIT))) {
2327 return key_senderror(so, m, ENOBUFS);
2333 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2334 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2336 IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2339 n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2340 mhp->extlen[SADB_X_EXT_POLICY], M_NOWAIT);
2343 return key_senderror(so, m, ENOBUFS);
2346 n->m_pkthdr.len = 0;
2347 for (nn = n; nn; nn = nn->m_next)
2348 n->m_pkthdr.len += nn->m_len;
2350 newmsg = mtod(n, struct sadb_msg *);
2351 newmsg->sadb_msg_errno = 0;
2352 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2355 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2360 * SADB_X_SPDGET processing
2365 * <base, address(SD), policy>
2367 * policy(*) including direction of policy.
2369 * m will always be freed.
2372 key_spdget(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2374 struct secpolicy *sp;
2378 IPSEC_ASSERT(so != NULL, ("null socket"));
2379 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2380 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2381 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2383 if (SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY) ||
2384 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2385 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2387 return key_senderror(so, m, EINVAL);
2390 id = ((struct sadb_x_policy *)
2391 mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2393 /* Is there SP in SPD ? */
2394 if ((sp = key_getspbyid(id)) == NULL) {
2395 ipseclog((LOG_DEBUG, "%s: no SP found for id %u.\n",
2397 return key_senderror(so, m, ENOENT);
2400 n = key_setdumpsp(sp, SADB_X_SPDGET, mhp->msg->sadb_msg_seq,
2401 mhp->msg->sadb_msg_pid);
2405 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2407 return key_senderror(so, m, ENOBUFS);
2411 * SADB_X_SPDACQUIRE processing.
2412 * Acquire policy and SA(s) for a *OUTBOUND* packet.
2415 * to KMD, and expect to receive
2416 * <base> with SADB_X_SPDACQUIRE if error occurred,
2419 * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2420 * policy(*) is without policy requests.
2423 * others: error number
2426 key_spdacquire(struct secpolicy *sp)
2428 struct mbuf *result = NULL, *m;
2429 struct secspacq *newspacq;
2431 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2432 IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2433 IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2434 ("policy not IPSEC %u", sp->policy));
2436 /* Get an entry to check whether sent message or not. */
2437 newspacq = key_getspacq(&sp->spidx);
2438 if (newspacq != NULL) {
2439 if (V_key_blockacq_count < newspacq->count) {
2440 /* reset counter and do send message. */
2441 newspacq->count = 0;
2443 /* increment counter and do nothing. */
2450 /* make new entry for blocking to send SADB_ACQUIRE. */
2451 newspacq = key_newspacq(&sp->spidx);
2452 if (newspacq == NULL)
2456 /* create new sadb_msg to reply. */
2457 m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2463 result->m_pkthdr.len = 0;
2464 for (m = result; m; m = m->m_next)
2465 result->m_pkthdr.len += m->m_len;
2467 mtod(result, struct sadb_msg *)->sadb_msg_len =
2468 PFKEY_UNIT64(result->m_pkthdr.len);
2470 return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2474 * SADB_SPDFLUSH processing
2477 * from the user, and free all entries in secpctree.
2481 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2483 * m will always be freed.
2486 key_spdflush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2488 struct secpolicy_queue drainq;
2489 struct sadb_msg *newmsg;
2490 struct secpolicy *sp, *nextsp;
2493 IPSEC_ASSERT(so != NULL, ("null socket"));
2494 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2495 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2496 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2498 if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2499 return key_senderror(so, m, EINVAL);
2501 TAILQ_INIT(&drainq);
2503 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2504 TAILQ_CONCAT(&drainq, &V_sptree[dir], chain);
2507 * We need to set state to DEAD for each policy to be sure,
2508 * that another thread won't try to unlink it.
2509 * Also remove SP from sphash.
2511 TAILQ_FOREACH(sp, &drainq, chain) {
2512 sp->state = IPSEC_SPSTATE_DEAD;
2513 LIST_REMOVE(sp, idhash);
2518 if (SPDCACHE_ENABLED())
2520 sp = TAILQ_FIRST(&drainq);
2521 while (sp != NULL) {
2522 nextsp = TAILQ_NEXT(sp, chain);
2527 if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2528 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2529 return key_senderror(so, m, ENOBUFS);
2535 m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2536 newmsg = mtod(m, struct sadb_msg *);
2537 newmsg->sadb_msg_errno = 0;
2538 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2540 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2544 key_satype2scopemask(uint8_t satype)
2547 if (satype == IPSEC_POLICYSCOPE_ANY)
2552 * SADB_SPDDUMP processing
2555 * from the user, and dump all SP leaves and send,
2560 * sadb_msg_satype is considered as mask of policy scopes.
2561 * m will always be freed.
2564 key_spddump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2566 SPTREE_RLOCK_TRACKER;
2567 struct secpolicy *sp;
2572 IPSEC_ASSERT(so != NULL, ("null socket"));
2573 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2574 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2575 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2577 /* search SPD entry and get buffer size. */
2579 scope = key_satype2scopemask(mhp->msg->sadb_msg_satype);
2581 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2582 if (scope & IPSEC_POLICYSCOPE_GLOBAL) {
2583 TAILQ_FOREACH(sp, &V_sptree[dir], chain)
2586 if (scope & IPSEC_POLICYSCOPE_IFNET) {
2587 TAILQ_FOREACH(sp, &V_sptree_ifnet[dir], chain)
2594 return key_senderror(so, m, ENOENT);
2597 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2598 if (scope & IPSEC_POLICYSCOPE_GLOBAL) {
2599 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
2601 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2602 mhp->msg->sadb_msg_pid);
2605 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2608 if (scope & IPSEC_POLICYSCOPE_IFNET) {
2609 TAILQ_FOREACH(sp, &V_sptree_ifnet[dir], chain) {
2611 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2612 mhp->msg->sadb_msg_pid);
2615 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2625 static struct mbuf *
2626 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq,
2629 struct mbuf *result = NULL, *m;
2630 struct seclifetime lt;
2632 m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2637 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2638 &sp->spidx.src.sa, sp->spidx.prefs,
2639 sp->spidx.ul_proto);
2644 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2645 &sp->spidx.dst.sa, sp->spidx.prefd,
2646 sp->spidx.ul_proto);
2651 m = key_sp2mbuf(sp);
2657 lt.addtime=sp->created;
2658 lt.usetime= sp->lastused;
2659 m = key_setlifetime(<, SADB_EXT_LIFETIME_CURRENT);
2664 lt.addtime=sp->lifetime;
2665 lt.usetime= sp->validtime;
2666 m = key_setlifetime(<, SADB_EXT_LIFETIME_HARD);
2672 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));
2681 result->m_pkthdr.len = 0;
2682 for (m = result; m; m = m->m_next)
2683 result->m_pkthdr.len += m->m_len;
2685 mtod(result, struct sadb_msg *)->sadb_msg_len =
2686 PFKEY_UNIT64(result->m_pkthdr.len);
2695 * get PFKEY message length for security policy and request.
2698 key_getspreqmsglen(struct secpolicy *sp)
2703 tlen = sizeof(struct sadb_x_policy);
2704 /* if is the policy for ipsec ? */
2705 if (sp->policy != IPSEC_POLICY_IPSEC)
2708 /* get length of ipsec requests */
2709 for (i = 0; i < sp->tcount; i++) {
2710 len = sizeof(struct sadb_x_ipsecrequest)
2711 + sp->req[i]->saidx.src.sa.sa_len
2712 + sp->req[i]->saidx.dst.sa.sa_len;
2714 tlen += PFKEY_ALIGN8(len);
2720 * SADB_SPDEXPIRE processing
2722 * <base, address(SD), lifetime(CH), policy>
2726 * others : error number
2729 key_spdexpire(struct secpolicy *sp)
2731 struct sadb_lifetime *lt;
2732 struct mbuf *result = NULL, *m;
2733 int len, error = -1;
2735 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2738 printf("%s: SP(%p)\n", __func__, sp));
2739 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2741 /* set msg header */
2742 m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2749 /* create lifetime extension (current and hard) */
2750 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2751 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
2758 bzero(mtod(m, caddr_t), len);
2759 lt = mtod(m, struct sadb_lifetime *);
2760 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2761 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2762 lt->sadb_lifetime_allocations = 0;
2763 lt->sadb_lifetime_bytes = 0;
2764 lt->sadb_lifetime_addtime = sp->created;
2765 lt->sadb_lifetime_usetime = sp->lastused;
2766 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2767 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2768 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2769 lt->sadb_lifetime_allocations = 0;
2770 lt->sadb_lifetime_bytes = 0;
2771 lt->sadb_lifetime_addtime = sp->lifetime;
2772 lt->sadb_lifetime_usetime = sp->validtime;
2775 /* set sadb_address for source */
2776 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2778 sp->spidx.prefs, sp->spidx.ul_proto);
2785 /* set sadb_address for destination */
2786 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2788 sp->spidx.prefd, sp->spidx.ul_proto);
2796 m = key_sp2mbuf(sp);
2803 if ((result->m_flags & M_PKTHDR) == 0) {
2808 if (result->m_len < sizeof(struct sadb_msg)) {
2809 result = m_pullup(result, sizeof(struct sadb_msg));
2810 if (result == NULL) {
2816 result->m_pkthdr.len = 0;
2817 for (m = result; m; m = m->m_next)
2818 result->m_pkthdr.len += m->m_len;
2820 mtod(result, struct sadb_msg *)->sadb_msg_len =
2821 PFKEY_UNIT64(result->m_pkthdr.len);
2823 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2831 /* %%% SAD management */
2833 * allocating and initialize new SA head.
2834 * OUT: NULL : failure due to the lack of memory.
2835 * others : pointer to new SA head.
2837 static struct secashead *
2838 key_newsah(struct secasindex *saidx)
2840 struct secashead *sah;
2842 sah = malloc(sizeof(struct secashead), M_IPSEC_SAH,
2845 PFKEYSTAT_INC(in_nomem);
2848 TAILQ_INIT(&sah->savtree_larval);
2849 TAILQ_INIT(&sah->savtree_alive);
2850 sah->saidx = *saidx;
2851 sah->state = SADB_SASTATE_DEAD;
2855 printf("%s: SAH(%p)\n", __func__, sah));
2856 KEYDBG(KEY_DATA, kdebug_secash(sah, NULL));
2861 key_freesah(struct secashead **psah)
2863 struct secashead *sah = *psah;
2865 if (SAH_DELREF(sah) == 0)
2869 printf("%s: last reference to SAH(%p)\n", __func__, sah));
2870 KEYDBG(KEY_DATA, kdebug_secash(sah, NULL));
2877 key_delsah(struct secashead *sah)
2879 IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2880 IPSEC_ASSERT(sah->state == SADB_SASTATE_DEAD,
2881 ("Attempt to free non DEAD SAH %p", sah));
2882 IPSEC_ASSERT(TAILQ_EMPTY(&sah->savtree_larval),
2883 ("Attempt to free SAH %p with LARVAL SA", sah));
2884 IPSEC_ASSERT(TAILQ_EMPTY(&sah->savtree_alive),
2885 ("Attempt to free SAH %p with ALIVE SA", sah));
2887 free(sah, M_IPSEC_SAH);
2891 * allocating a new SA for key_add() and key_getspi() call,
2892 * and copy the values of mhp into new buffer.
2893 * When SAD message type is SADB_GETSPI set SA state to LARVAL.
2894 * For SADB_ADD create and initialize SA with MATURE state.
2896 * others : pointer to new secasvar.
2898 static struct secasvar *
2899 key_newsav(const struct sadb_msghdr *mhp, struct secasindex *saidx,
2900 uint32_t spi, int *errp)
2902 struct secashead *sah;
2903 struct secasvar *sav;
2906 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2907 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2908 IPSEC_ASSERT(mhp->msg->sadb_msg_type == SADB_GETSPI ||
2909 mhp->msg->sadb_msg_type == SADB_ADD, ("wrong message type"));
2913 /* check SPI value */
2914 switch (saidx->proto) {
2918 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
2919 * 1-255 reserved by IANA for future use,
2920 * 0 for implementation specific, local use.
2922 if (ntohl(spi) <= 255) {
2923 ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
2924 __func__, ntohl(spi)));
2931 sav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT | M_ZERO);
2936 sav->lock = malloc(sizeof(struct mtx), M_IPSEC_MISC,
2938 if (sav->lock == NULL) {
2942 mtx_init(sav->lock, "ipsec association", NULL, MTX_DEF);
2943 sav->lft_c = uma_zalloc_pcpu(V_key_lft_zone, M_NOWAIT);
2944 if (sav->lft_c == NULL) {
2948 counter_u64_zero(sav->lft_c_allocations);
2949 counter_u64_zero(sav->lft_c_bytes);
2952 sav->seq = mhp->msg->sadb_msg_seq;
2953 sav->state = SADB_SASTATE_LARVAL;
2954 sav->pid = (pid_t)mhp->msg->sadb_msg_pid;
2957 sah = key_getsah(saidx);
2959 /* create a new SA index */
2960 sah = key_newsah(saidx);
2962 ipseclog((LOG_DEBUG,
2963 "%s: No more memory.\n", __func__));
2972 if (mhp->msg->sadb_msg_type == SADB_GETSPI) {
2973 sav->created = time_second;
2974 } else if (sav->state == SADB_SASTATE_LARVAL) {
2976 * Do not call key_setsaval() second time in case
2977 * of `goto again`. We will have MATURE state.
2979 *errp = key_setsaval(sav, mhp);
2982 sav->state = SADB_SASTATE_MATURE;
2987 * Check that existing SAH wasn't unlinked.
2988 * Since we didn't hold the SAHTREE lock, it is possible,
2989 * that callout handler or key_flush() or key_delete() could
2992 if (isnew == 0 && sah->state == SADB_SASTATE_DEAD) {
2994 key_freesah(&sah); /* reference from key_getsah() */
2999 * Add new SAH into SADB.
3001 * XXXAE: we can serialize key_add and key_getspi calls, so
3002 * several threads will not fight in the race.
3003 * Otherwise we should check under SAHTREE lock, that this
3004 * SAH would not added twice.
3006 TAILQ_INSERT_HEAD(&V_sahtree, sah, chain);
3007 /* Add new SAH into hash by addresses */
3008 LIST_INSERT_HEAD(SAHADDRHASH_HASH(saidx), sah, addrhash);
3009 /* Now we are linked in the chain */
3010 sah->state = SADB_SASTATE_MATURE;
3012 * SAV references this new SAH.
3013 * In case of existing SAH we reuse reference
3014 * from key_getsah().
3018 /* Link SAV with SAH */
3019 if (sav->state == SADB_SASTATE_MATURE)
3020 TAILQ_INSERT_HEAD(&sah->savtree_alive, sav, chain);
3022 TAILQ_INSERT_HEAD(&sah->savtree_larval, sav, chain);
3023 /* Add SAV into SPI hash */
3024 LIST_INSERT_HEAD(SAVHASH_HASH(sav->spi), sav, spihash);
3026 *errp = 0; /* success */
3030 if (sav->lock != NULL) {
3031 mtx_destroy(sav->lock);
3032 free(sav->lock, M_IPSEC_MISC);
3034 if (sav->lft_c != NULL)
3035 uma_zfree_pcpu(V_key_lft_zone, sav->lft_c);
3036 free(sav, M_IPSEC_SA), sav = NULL;
3040 if (*errp == ENOBUFS) {
3041 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3043 PFKEYSTAT_INC(in_nomem);
3050 * free() SA variable entry.
3053 key_cleansav(struct secasvar *sav)
3056 if (sav->natt != NULL) {
3057 free(sav->natt, M_IPSEC_MISC);
3060 if (sav->flags & SADB_X_EXT_F_CLONED)
3062 if (sav->tdb_xform != NULL) {
3063 sav->tdb_xform->xf_cleanup(sav);
3064 sav->tdb_xform = NULL;
3066 if (sav->key_auth != NULL) {
3067 zfree(sav->key_auth->key_data, M_IPSEC_MISC);
3068 free(sav->key_auth, M_IPSEC_MISC);
3069 sav->key_auth = NULL;
3071 if (sav->key_enc != NULL) {
3072 zfree(sav->key_enc->key_data, M_IPSEC_MISC);
3073 free(sav->key_enc, M_IPSEC_MISC);
3074 sav->key_enc = NULL;
3076 if (sav->replay != NULL) {
3077 if (sav->replay->bitmap != NULL)
3078 free(sav->replay->bitmap, M_IPSEC_MISC);
3079 free(sav->replay, M_IPSEC_MISC);
3082 if (sav->lft_h != NULL) {
3083 free(sav->lft_h, M_IPSEC_MISC);
3086 if (sav->lft_s != NULL) {
3087 free(sav->lft_s, M_IPSEC_MISC);
3093 * free() SA variable entry.
3096 key_delsav(struct secasvar *sav)
3098 IPSEC_ASSERT(sav != NULL, ("null sav"));
3099 IPSEC_ASSERT(sav->state == SADB_SASTATE_DEAD,
3100 ("attempt to free non DEAD SA %p", sav));
3101 IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0",
3105 * SA must be unlinked from the chain and hashtbl.
3106 * If SA was cloned, we leave all fields untouched,
3107 * except NAT-T config.
3110 if ((sav->flags & SADB_X_EXT_F_CLONED) == 0) {
3111 mtx_destroy(sav->lock);
3112 free(sav->lock, M_IPSEC_MISC);
3113 uma_zfree_pcpu(V_key_lft_zone, sav->lft_c);
3115 free(sav, M_IPSEC_SA);
3122 * others : found, referenced pointer to a SAH.
3124 static struct secashead *
3125 key_getsah(struct secasindex *saidx)
3127 SAHTREE_RLOCK_TRACKER;
3128 struct secashead *sah;
3131 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
3132 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID) != 0) {
3142 * Check not to be duplicated SPI.
3145 * 1 : found SA with given SPI.
3148 key_checkspidup(uint32_t spi)
3150 SAHTREE_RLOCK_TRACKER;
3151 struct secasvar *sav;
3153 /* Assume SPI is in network byte order */
3155 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
3156 if (sav->spi == spi)
3160 return (sav != NULL);
3167 * others : found, referenced pointer to a SA.
3169 static struct secasvar *
3170 key_getsavbyspi(uint32_t spi)
3172 SAHTREE_RLOCK_TRACKER;
3173 struct secasvar *sav;
3175 /* Assume SPI is in network byte order */
3177 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
3178 if (sav->spi != spi)
3188 key_updatelifetimes(struct secasvar *sav, const struct sadb_msghdr *mhp)
3190 struct seclifetime *lft_h, *lft_s, *tmp;
3192 /* Lifetime extension is optional, check that it is present. */
3193 if (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
3194 SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) {
3196 * In case of SADB_UPDATE we may need to change
3197 * existing lifetimes.
3199 if (sav->state == SADB_SASTATE_MATURE) {
3200 lft_h = lft_s = NULL;
3205 /* Both HARD and SOFT extensions must present */
3206 if ((SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
3207 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
3208 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
3209 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
3210 ipseclog((LOG_DEBUG,
3211 "%s: invalid message: missing required header.\n",
3215 if (SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_HARD) ||
3216 SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_SOFT)) {
3217 ipseclog((LOG_DEBUG,
3218 "%s: invalid message: wrong header size.\n", __func__));
3221 lft_h = key_dup_lifemsg((const struct sadb_lifetime *)
3222 mhp->ext[SADB_EXT_LIFETIME_HARD], M_IPSEC_MISC);
3223 if (lft_h == NULL) {
3224 PFKEYSTAT_INC(in_nomem);
3225 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3228 lft_s = key_dup_lifemsg((const struct sadb_lifetime *)
3229 mhp->ext[SADB_EXT_LIFETIME_SOFT], M_IPSEC_MISC);
3230 if (lft_s == NULL) {
3231 PFKEYSTAT_INC(in_nomem);
3232 free(lft_h, M_IPSEC_MISC);
3233 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3237 if (sav->state != SADB_SASTATE_LARVAL) {
3239 * key_update() holds reference to this SA,
3240 * so it won't be deleted in meanwhile.
3250 SECASVAR_UNLOCK(sav);
3252 free(lft_h, M_IPSEC_MISC);
3254 free(lft_s, M_IPSEC_MISC);
3257 /* We can update lifetime without holding a lock */
3258 IPSEC_ASSERT(sav->lft_h == NULL, ("lft_h is already initialized\n"));
3259 IPSEC_ASSERT(sav->lft_s == NULL, ("lft_s is already initialized\n"));
3266 * copy SA values from PF_KEY message except *SPI, SEQ, PID and TYPE*.
3267 * You must update these if need. Expects only LARVAL SAs.
3272 key_setsaval(struct secasvar *sav, const struct sadb_msghdr *mhp)
3274 const struct sadb_sa *sa0;
3275 const struct sadb_key *key0;
3280 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3281 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3282 IPSEC_ASSERT(sav->state == SADB_SASTATE_LARVAL,
3283 ("Attempt to update non LARVAL SA"));
3286 error = key_setident(sav->sah, mhp);
3291 if (!SADB_CHECKHDR(mhp, SADB_EXT_SA)) {
3292 if (SADB_CHECKLEN(mhp, SADB_EXT_SA)) {
3296 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3297 sav->alg_auth = sa0->sadb_sa_auth;
3298 sav->alg_enc = sa0->sadb_sa_encrypt;
3299 sav->flags = sa0->sadb_sa_flags;
3300 if ((sav->flags & SADB_KEY_FLAGS_MAX) != sav->flags) {
3301 ipseclog((LOG_DEBUG,
3302 "%s: invalid sa_flags 0x%08x.\n", __func__,
3308 /* Optional replay window */
3310 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0)
3311 replay = sa0->sadb_sa_replay;
3312 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_SA_REPLAY)) {
3313 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA_REPLAY)) {
3317 replay = ((const struct sadb_x_sa_replay *)
3318 mhp->ext[SADB_X_EXT_SA_REPLAY])->sadb_x_sa_replay_replay;
3320 if (replay > UINT32_MAX - 32) {
3321 ipseclog((LOG_DEBUG,
3322 "%s: replay window too big.\n", __func__));
3327 replay = (replay + 7) >> 3;
3330 sav->replay = malloc(sizeof(struct secreplay), M_IPSEC_MISC,
3332 if (sav->replay == NULL) {
3333 PFKEYSTAT_INC(in_nomem);
3334 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3341 /* number of 32b blocks to be allocated */
3342 uint32_t bitmap_size;
3345 * - the allocated replay window size must be
3347 * - use an extra 32b block as a redundant window.
3350 while (replay + 4 > bitmap_size)
3352 bitmap_size = bitmap_size / 4;
3354 sav->replay->bitmap = malloc(
3355 bitmap_size * sizeof(uint32_t), M_IPSEC_MISC,
3357 if (sav->replay->bitmap == NULL) {
3358 PFKEYSTAT_INC(in_nomem);
3359 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3364 sav->replay->bitmap_size = bitmap_size;
3365 sav->replay->wsize = replay;
3369 /* Authentication keys */
3370 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH)) {
3371 if (SADB_CHECKLEN(mhp, SADB_EXT_KEY_AUTH)) {
3376 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3377 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3378 switch (mhp->msg->sadb_msg_satype) {
3379 case SADB_SATYPE_AH:
3380 case SADB_SATYPE_ESP:
3381 case SADB_X_SATYPE_TCPSIGNATURE:
3382 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3383 sav->alg_auth != SADB_X_AALG_NULL)
3386 case SADB_X_SATYPE_IPCOMP:
3392 ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3397 sav->key_auth = key_dup_keymsg(key0, len, M_IPSEC_MISC);
3398 if (sav->key_auth == NULL ) {
3399 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3401 PFKEYSTAT_INC(in_nomem);
3407 /* Encryption key */
3408 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT)) {
3409 if (SADB_CHECKLEN(mhp, SADB_EXT_KEY_ENCRYPT)) {
3414 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3415 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3416 switch (mhp->msg->sadb_msg_satype) {
3417 case SADB_SATYPE_ESP:
3418 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3419 sav->alg_enc != SADB_EALG_NULL) {
3423 sav->key_enc = key_dup_keymsg(key0, len, M_IPSEC_MISC);
3424 if (sav->key_enc == NULL) {
3425 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3427 PFKEYSTAT_INC(in_nomem);
3432 case SADB_X_SATYPE_IPCOMP:
3433 if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3435 sav->key_enc = NULL; /*just in case*/
3437 case SADB_SATYPE_AH:
3438 case SADB_X_SATYPE_TCPSIGNATURE:
3444 ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3452 switch (mhp->msg->sadb_msg_satype) {
3453 case SADB_SATYPE_AH:
3454 if (sav->flags & SADB_X_EXT_DERIV) {
3455 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3456 "given to AH SA.\n", __func__));
3460 if (sav->alg_enc != SADB_EALG_NONE) {
3461 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3462 "mismated.\n", __func__));
3466 error = xform_init(sav, XF_AH);
3468 case SADB_SATYPE_ESP:
3469 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_DERIV)) ==
3470 (SADB_X_EXT_OLD | SADB_X_EXT_DERIV)) {
3471 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3472 "given to old-esp.\n", __func__));
3476 error = xform_init(sav, XF_ESP);
3478 case SADB_X_SATYPE_IPCOMP:
3479 if (sav->alg_auth != SADB_AALG_NONE) {
3480 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3481 "mismated.\n", __func__));
3485 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0 &&
3486 ntohl(sav->spi) >= 0x10000) {
3487 ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3492 error = xform_init(sav, XF_IPCOMP);
3494 case SADB_X_SATYPE_TCPSIGNATURE:
3495 if (sav->alg_enc != SADB_EALG_NONE) {
3496 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3497 "mismated.\n", __func__));
3501 error = xform_init(sav, XF_TCPSIGNATURE);
3504 ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3505 error = EPROTONOSUPPORT;
3509 ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3510 __func__, mhp->msg->sadb_msg_satype));
3514 /* Handle NAT-T headers */
3515 error = key_setnatt(sav, mhp);
3519 /* Initialize lifetime for CURRENT */
3521 sav->created = time_second;
3523 /* lifetimes for HARD and SOFT */
3524 error = key_updatelifetimes(sav, mhp);
3533 * subroutine for SADB_GET and SADB_DUMP.
3535 static struct mbuf *
3536 key_setdumpsa(struct secasvar *sav, uint8_t type, uint8_t satype,
3537 uint32_t seq, uint32_t pid)
3539 struct seclifetime lft_c;
3540 struct mbuf *result = NULL, *tres = NULL, *m;
3541 int i, dumporder[] = {
3542 SADB_EXT_SA, SADB_X_EXT_SA2, SADB_X_EXT_SA_REPLAY,
3543 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3544 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3545 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY,
3546 SADB_EXT_KEY_AUTH, SADB_EXT_KEY_ENCRYPT,
3547 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
3548 SADB_EXT_SENSITIVITY,
3549 SADB_X_EXT_NAT_T_TYPE,
3550 SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3551 SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3552 SADB_X_EXT_NAT_T_FRAG,
3554 uint32_t replay_count;
3556 m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3561 for (i = nitems(dumporder) - 1; i >= 0; i--) {
3563 switch (dumporder[i]) {
3565 m = key_setsadbsa(sav);
3570 case SADB_X_EXT_SA2:
3572 replay_count = sav->replay ? sav->replay->count : 0;
3573 SECASVAR_UNLOCK(sav);
3574 m = key_setsadbxsa2(sav->sah->saidx.mode, replay_count,
3575 sav->sah->saidx.reqid);
3580 case SADB_X_EXT_SA_REPLAY:
3581 if (sav->replay == NULL ||
3582 sav->replay->wsize <= UINT8_MAX)
3585 m = key_setsadbxsareplay(sav->replay->wsize);
3590 case SADB_EXT_ADDRESS_SRC:
3591 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3592 &sav->sah->saidx.src.sa,
3593 FULLMASK, IPSEC_ULPROTO_ANY);
3598 case SADB_EXT_ADDRESS_DST:
3599 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3600 &sav->sah->saidx.dst.sa,
3601 FULLMASK, IPSEC_ULPROTO_ANY);
3606 case SADB_EXT_KEY_AUTH:
3609 m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3614 case SADB_EXT_KEY_ENCRYPT:
3617 m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3622 case SADB_EXT_LIFETIME_CURRENT:
3623 lft_c.addtime = sav->created;
3624 lft_c.allocations = (uint32_t)counter_u64_fetch(
3625 sav->lft_c_allocations);
3626 lft_c.bytes = counter_u64_fetch(sav->lft_c_bytes);
3627 lft_c.usetime = sav->firstused;
3628 m = key_setlifetime(&lft_c, SADB_EXT_LIFETIME_CURRENT);
3633 case SADB_EXT_LIFETIME_HARD:
3636 m = key_setlifetime(sav->lft_h,
3637 SADB_EXT_LIFETIME_HARD);
3642 case SADB_EXT_LIFETIME_SOFT:
3645 m = key_setlifetime(sav->lft_s,
3646 SADB_EXT_LIFETIME_SOFT);
3652 case SADB_X_EXT_NAT_T_TYPE:
3653 if (sav->natt == NULL)
3655 m = key_setsadbxtype(UDP_ENCAP_ESPINUDP);
3660 case SADB_X_EXT_NAT_T_DPORT:
3661 if (sav->natt == NULL)
3663 m = key_setsadbxport(sav->natt->dport,
3664 SADB_X_EXT_NAT_T_DPORT);
3669 case SADB_X_EXT_NAT_T_SPORT:
3670 if (sav->natt == NULL)
3672 m = key_setsadbxport(sav->natt->sport,
3673 SADB_X_EXT_NAT_T_SPORT);
3678 case SADB_X_EXT_NAT_T_OAI:
3679 if (sav->natt == NULL ||
3680 (sav->natt->flags & IPSEC_NATT_F_OAI) == 0)
3682 m = key_setsadbaddr(SADB_X_EXT_NAT_T_OAI,
3683 &sav->natt->oai.sa, FULLMASK, IPSEC_ULPROTO_ANY);
3687 case SADB_X_EXT_NAT_T_OAR:
3688 if (sav->natt == NULL ||
3689 (sav->natt->flags & IPSEC_NATT_F_OAR) == 0)
3691 m = key_setsadbaddr(SADB_X_EXT_NAT_T_OAR,
3692 &sav->natt->oar.sa, FULLMASK, IPSEC_ULPROTO_ANY);
3696 case SADB_X_EXT_NAT_T_FRAG:
3697 /* We do not (yet) support those. */
3700 case SADB_EXT_ADDRESS_PROXY:
3701 case SADB_EXT_IDENTITY_SRC:
3702 case SADB_EXT_IDENTITY_DST:
3703 /* XXX: should we brought from SPD ? */
3704 case SADB_EXT_SENSITIVITY:
3716 m_cat(result, tres);
3718 if (result->m_len < sizeof(struct sadb_msg)) {
3719 result = m_pullup(result, sizeof(struct sadb_msg));
3724 result->m_pkthdr.len = 0;
3725 for (m = result; m; m = m->m_next)
3726 result->m_pkthdr.len += m->m_len;
3728 mtod(result, struct sadb_msg *)->sadb_msg_len =
3729 PFKEY_UNIT64(result->m_pkthdr.len);
3740 * set data into sadb_msg.
3742 static struct mbuf *
3743 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3744 pid_t pid, u_int16_t reserved)
3750 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3753 MGETHDR(m, M_NOWAIT, MT_DATA);
3754 if (m && len > MHLEN) {
3755 if (!(MCLGET(m, M_NOWAIT))) {
3762 m->m_pkthdr.len = m->m_len = len;
3765 p = mtod(m, struct sadb_msg *);
3768 p->sadb_msg_version = PF_KEY_V2;
3769 p->sadb_msg_type = type;
3770 p->sadb_msg_errno = 0;
3771 p->sadb_msg_satype = satype;
3772 p->sadb_msg_len = PFKEY_UNIT64(tlen);
3773 p->sadb_msg_reserved = reserved;
3774 p->sadb_msg_seq = seq;
3775 p->sadb_msg_pid = (u_int32_t)pid;
3781 * copy secasvar data into sadb_address.
3783 static struct mbuf *
3784 key_setsadbsa(struct secasvar *sav)
3790 len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3791 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3796 p = mtod(m, struct sadb_sa *);
3798 p->sadb_sa_len = PFKEY_UNIT64(len);
3799 p->sadb_sa_exttype = SADB_EXT_SA;
3800 p->sadb_sa_spi = sav->spi;
3801 p->sadb_sa_replay = sav->replay ?
3802 (sav->replay->wsize > UINT8_MAX ? UINT8_MAX :
3803 sav->replay->wsize): 0;
3804 p->sadb_sa_state = sav->state;
3805 p->sadb_sa_auth = sav->alg_auth;
3806 p->sadb_sa_encrypt = sav->alg_enc;
3807 p->sadb_sa_flags = sav->flags & SADB_KEY_FLAGS_MAX;
3812 * set data into sadb_address.
3814 static struct mbuf *
3815 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
3816 u_int8_t prefixlen, u_int16_t ul_proto)
3819 struct sadb_address *p;
3822 len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3823 PFKEY_ALIGN8(saddr->sa_len);
3824 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3829 p = mtod(m, struct sadb_address *);
3832 p->sadb_address_len = PFKEY_UNIT64(len);
3833 p->sadb_address_exttype = exttype;
3834 p->sadb_address_proto = ul_proto;
3835 if (prefixlen == FULLMASK) {
3836 switch (saddr->sa_family) {
3838 prefixlen = sizeof(struct in_addr) << 3;
3841 prefixlen = sizeof(struct in6_addr) << 3;
3847 p->sadb_address_prefixlen = prefixlen;
3848 p->sadb_address_reserved = 0;
3851 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3858 * set data into sadb_x_sa2.
3860 static struct mbuf *
3861 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3864 struct sadb_x_sa2 *p;
3867 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3868 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3873 p = mtod(m, struct sadb_x_sa2 *);
3876 p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3877 p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3878 p->sadb_x_sa2_mode = mode;
3879 p->sadb_x_sa2_reserved1 = 0;
3880 p->sadb_x_sa2_reserved2 = 0;
3881 p->sadb_x_sa2_sequence = seq;
3882 p->sadb_x_sa2_reqid = reqid;
3888 * Set data into sadb_x_sa_replay.
3890 static struct mbuf *
3891 key_setsadbxsareplay(u_int32_t replay)
3894 struct sadb_x_sa_replay *p;
3897 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa_replay));
3898 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3903 p = mtod(m, struct sadb_x_sa_replay *);
3906 p->sadb_x_sa_replay_len = PFKEY_UNIT64(len);
3907 p->sadb_x_sa_replay_exttype = SADB_X_EXT_SA_REPLAY;
3908 p->sadb_x_sa_replay_replay = (replay << 3);
3914 * Set a type in sadb_x_nat_t_type.
3916 static struct mbuf *
3917 key_setsadbxtype(u_int16_t type)
3921 struct sadb_x_nat_t_type *p;
3923 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3925 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3930 p = mtod(m, struct sadb_x_nat_t_type *);
3933 p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3934 p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3935 p->sadb_x_nat_t_type_type = type;
3940 * Set a port in sadb_x_nat_t_port.
3941 * In contrast to default RFC 2367 behaviour, port is in network byte order.
3943 static struct mbuf *
3944 key_setsadbxport(u_int16_t port, u_int16_t type)
3948 struct sadb_x_nat_t_port *p;
3950 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3952 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3957 p = mtod(m, struct sadb_x_nat_t_port *);
3960 p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3961 p->sadb_x_nat_t_port_exttype = type;
3962 p->sadb_x_nat_t_port_port = port;
3968 * Get port from sockaddr. Port is in network byte order.
3971 key_portfromsaddr(struct sockaddr *sa)
3974 switch (sa->sa_family) {
3977 return ((struct sockaddr_in *)sa)->sin_port;
3981 return ((struct sockaddr_in6 *)sa)->sin6_port;
3988 * Set port in struct sockaddr. Port is in network byte order.
3991 key_porttosaddr(struct sockaddr *sa, uint16_t port)
3994 switch (sa->sa_family) {
3997 ((struct sockaddr_in *)sa)->sin_port = port;
4002 ((struct sockaddr_in6 *)sa)->sin6_port = port;
4006 ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
4007 __func__, sa->sa_family));
4013 * set data into sadb_x_policy
4015 static struct mbuf *
4016 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id, u_int32_t priority)
4019 struct sadb_x_policy *p;
4022 len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
4023 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
4028 p = mtod(m, struct sadb_x_policy *);
4031 p->sadb_x_policy_len = PFKEY_UNIT64(len);
4032 p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
4033 p->sadb_x_policy_type = type;
4034 p->sadb_x_policy_dir = dir;
4035 p->sadb_x_policy_id = id;
4036 p->sadb_x_policy_priority = priority;
4042 /* Take a key message (sadb_key) from the socket and turn it into one
4043 * of the kernel's key structures (seckey).
4045 * IN: pointer to the src
4046 * OUT: NULL no more memory
4049 key_dup_keymsg(const struct sadb_key *src, size_t len,
4050 struct malloc_type *type)
4054 dst = malloc(sizeof(*dst), type, M_NOWAIT);
4056 dst->bits = src->sadb_key_bits;
4057 dst->key_data = malloc(len, type, M_NOWAIT);
4058 if (dst->key_data != NULL) {
4059 bcopy((const char *)(src + 1), dst->key_data, len);
4061 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
4067 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
4074 /* Take a lifetime message (sadb_lifetime) passed in on a socket and
4075 * turn it into one of the kernel's lifetime structures (seclifetime).
4077 * IN: pointer to the destination, source and malloc type
4078 * OUT: NULL, no more memory
4081 static struct seclifetime *
4082 key_dup_lifemsg(const struct sadb_lifetime *src, struct malloc_type *type)
4084 struct seclifetime *dst;
4086 dst = malloc(sizeof(*dst), type, M_NOWAIT);
4088 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4091 dst->allocations = src->sadb_lifetime_allocations;
4092 dst->bytes = src->sadb_lifetime_bytes;
4093 dst->addtime = src->sadb_lifetime_addtime;
4094 dst->usetime = src->sadb_lifetime_usetime;
4099 * compare two secasindex structure.
4100 * flag can specify to compare 2 saidxes.
4101 * compare two secasindex structure without both mode and reqid.
4102 * don't compare port.
4104 * saidx0: source, it can be in SAD.
4111 key_cmpsaidx(const struct secasindex *saidx0, const struct secasindex *saidx1,
4116 if (saidx0 == NULL && saidx1 == NULL)
4119 if (saidx0 == NULL || saidx1 == NULL)
4122 if (saidx0->proto != saidx1->proto)
4125 if (flag == CMP_EXACTLY) {
4126 if (saidx0->mode != saidx1->mode)
4128 if (saidx0->reqid != saidx1->reqid)
4130 if (bcmp(&saidx0->src, &saidx1->src,
4131 saidx0->src.sa.sa_len) != 0 ||
4132 bcmp(&saidx0->dst, &saidx1->dst,
4133 saidx0->dst.sa.sa_len) != 0)
4137 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4138 if (flag == CMP_MODE_REQID || flag == CMP_REQID) {
4140 * If reqid of SPD is non-zero, unique SA is required.
4141 * The result must be of same reqid in this case.
4143 if (saidx1->reqid != 0 &&
4144 saidx0->reqid != saidx1->reqid)
4148 if (flag == CMP_MODE_REQID) {
4149 if (saidx0->mode != IPSEC_MODE_ANY
4150 && saidx0->mode != saidx1->mode)
4154 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0)
4156 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0)
4164 * compare two secindex structure exactly.
4166 * spidx0: source, it is often in SPD.
4167 * spidx1: object, it is often from PFKEY message.
4173 key_cmpspidx_exactly(struct secpolicyindex *spidx0,
4174 struct secpolicyindex *spidx1)
4177 if (spidx0 == NULL && spidx1 == NULL)
4180 if (spidx0 == NULL || spidx1 == NULL)
4183 if (spidx0->prefs != spidx1->prefs
4184 || spidx0->prefd != spidx1->prefd
4185 || spidx0->ul_proto != spidx1->ul_proto
4186 || spidx0->dir != spidx1->dir)
4189 return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4190 key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4194 * compare two secindex structure with mask.
4196 * spidx0: source, it is often in SPD.
4197 * spidx1: object, it is often from IP header.
4203 key_cmpspidx_withmask(struct secpolicyindex *spidx0,
4204 struct secpolicyindex *spidx1)
4207 if (spidx0 == NULL && spidx1 == NULL)
4210 if (spidx0 == NULL || spidx1 == NULL)
4213 if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4214 spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4215 spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4216 spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4219 /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4220 if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4221 && spidx0->ul_proto != spidx1->ul_proto)
4224 switch (spidx0->src.sa.sa_family) {
4226 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4227 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4229 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4230 &spidx1->src.sin.sin_addr, spidx0->prefs))
4234 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4235 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4238 * scope_id check. if sin6_scope_id is 0, we regard it
4239 * as a wildcard scope, which matches any scope zone ID.
4241 if (spidx0->src.sin6.sin6_scope_id &&
4242 spidx1->src.sin6.sin6_scope_id &&
4243 spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4245 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4246 &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4251 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4256 switch (spidx0->dst.sa.sa_family) {
4258 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4259 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4261 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4262 &spidx1->dst.sin.sin_addr, spidx0->prefd))
4266 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4267 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4270 * scope_id check. if sin6_scope_id is 0, we regard it
4271 * as a wildcard scope, which matches any scope zone ID.
4273 if (spidx0->dst.sin6.sin6_scope_id &&
4274 spidx1->dst.sin6.sin6_scope_id &&
4275 spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4277 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4278 &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4283 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4288 /* XXX Do we check other field ? e.g. flowinfo */
4296 #define satosin(s) ((const struct sockaddr_in *)s)
4300 #define satosin6(s) ((const struct sockaddr_in6 *)s)
4301 /* returns 0 on match */
4303 key_sockaddrcmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
4306 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4309 switch (sa1->sa_family) {
4312 if (sa1->sa_len != sizeof(struct sockaddr_in))
4314 if (satosin(sa1)->sin_addr.s_addr !=
4315 satosin(sa2)->sin_addr.s_addr) {
4318 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4324 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4325 return 1; /*EINVAL*/
4326 if (satosin6(sa1)->sin6_scope_id !=
4327 satosin6(sa2)->sin6_scope_id) {
4330 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4331 &satosin6(sa2)->sin6_addr)) {
4335 satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4341 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4349 /* returns 0 on match */
4351 key_sockaddrcmp_withmask(const struct sockaddr *sa1,
4352 const struct sockaddr *sa2, size_t mask)
4354 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4357 switch (sa1->sa_family) {
4360 return (!key_bbcmp(&satosin(sa1)->sin_addr,
4361 &satosin(sa2)->sin_addr, mask));
4365 if (satosin6(sa1)->sin6_scope_id !=
4366 satosin6(sa2)->sin6_scope_id)
4368 return (!key_bbcmp(&satosin6(sa1)->sin6_addr,
4369 &satosin6(sa2)->sin6_addr, mask));
4378 * compare two buffers with mask.
4382 * bits: Number of bits to compare
4388 key_bbcmp(const void *a1, const void *a2, u_int bits)
4390 const unsigned char *p1 = a1;
4391 const unsigned char *p2 = a2;
4393 /* XXX: This could be considerably faster if we compare a word
4394 * at a time, but it is complicated on LSB Endian machines */
4396 /* Handle null pointers */
4397 if (p1 == NULL || p2 == NULL)
4407 u_int8_t mask = ~((1<<(8-bits))-1);
4408 if ((*p1 & mask) != (*p2 & mask))
4411 return 1; /* Match! */
4415 key_flush_spd(time_t now)
4417 SPTREE_RLOCK_TRACKER;
4418 struct secpolicy_list drainq;
4419 struct secpolicy *sp, *nextsp;
4424 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4425 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
4426 if (sp->lifetime == 0 && sp->validtime == 0)
4428 if ((sp->lifetime &&
4429 now - sp->created > sp->lifetime) ||
4431 now - sp->lastused > sp->validtime)) {
4432 /* Hold extra reference to send SPDEXPIRE */
4434 LIST_INSERT_HEAD(&drainq, sp, drainq);
4439 if (LIST_EMPTY(&drainq))
4443 sp = LIST_FIRST(&drainq);
4444 while (sp != NULL) {
4445 nextsp = LIST_NEXT(sp, drainq);
4446 /* Check that SP is still linked */
4447 if (sp->state != IPSEC_SPSTATE_ALIVE) {
4448 LIST_REMOVE(sp, drainq);
4449 key_freesp(&sp); /* release extra reference */
4453 TAILQ_REMOVE(&V_sptree[sp->spidx.dir], sp, chain);
4455 LIST_REMOVE(sp, idhash);
4456 sp->state = IPSEC_SPSTATE_DEAD;
4461 if (SPDCACHE_ENABLED())
4464 sp = LIST_FIRST(&drainq);
4465 while (sp != NULL) {
4466 nextsp = LIST_NEXT(sp, drainq);
4468 key_freesp(&sp); /* release extra reference */
4469 key_freesp(&sp); /* release last reference */
4475 key_flush_sad(time_t now)
4477 SAHTREE_RLOCK_TRACKER;
4478 struct secashead_list emptyq;
4479 struct secasvar_list drainq, hexpireq, sexpireq, freeq;
4480 struct secashead *sah, *nextsah;
4481 struct secasvar *sav, *nextsav;
4484 LIST_INIT(&hexpireq);
4485 LIST_INIT(&sexpireq);
4489 TAILQ_FOREACH(sah, &V_sahtree, chain) {
4490 /* Check for empty SAH */
4491 if (TAILQ_EMPTY(&sah->savtree_larval) &&
4492 TAILQ_EMPTY(&sah->savtree_alive)) {
4494 LIST_INSERT_HEAD(&emptyq, sah, drainq);
4497 /* Add all stale LARVAL SAs into drainq */
4498 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
4499 if (now - sav->created < V_key_larval_lifetime)
4502 LIST_INSERT_HEAD(&drainq, sav, drainq);
4504 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
4505 /* lifetimes aren't specified */
4506 if (sav->lft_h == NULL)
4510 * Check again with lock held, because it may
4511 * be updated by SADB_UPDATE.
4513 if (sav->lft_h == NULL) {
4514 SECASVAR_UNLOCK(sav);
4519 * HARD lifetimes MUST take precedence over SOFT
4520 * lifetimes, meaning if the HARD and SOFT lifetimes
4521 * are the same, the HARD lifetime will appear on the
4524 /* check HARD lifetime */
4525 if ((sav->lft_h->addtime != 0 &&
4526 now - sav->created > sav->lft_h->addtime) ||
4527 (sav->lft_h->usetime != 0 && sav->firstused &&
4528 now - sav->firstused > sav->lft_h->usetime) ||
4529 (sav->lft_h->bytes != 0 && counter_u64_fetch(
4530 sav->lft_c_bytes) > sav->lft_h->bytes)) {
4531 SECASVAR_UNLOCK(sav);
4533 LIST_INSERT_HEAD(&hexpireq, sav, drainq);
4536 /* check SOFT lifetime (only for MATURE SAs) */
4537 if (sav->state == SADB_SASTATE_MATURE && (
4538 (sav->lft_s->addtime != 0 &&
4539 now - sav->created > sav->lft_s->addtime) ||
4540 (sav->lft_s->usetime != 0 && sav->firstused &&
4541 now - sav->firstused > sav->lft_s->usetime) ||
4542 (sav->lft_s->bytes != 0 && counter_u64_fetch(
4543 sav->lft_c_bytes) > sav->lft_s->bytes))) {
4544 SECASVAR_UNLOCK(sav);
4546 LIST_INSERT_HEAD(&sexpireq, sav, drainq);
4549 SECASVAR_UNLOCK(sav);
4554 if (LIST_EMPTY(&emptyq) && LIST_EMPTY(&drainq) &&
4555 LIST_EMPTY(&hexpireq) && LIST_EMPTY(&sexpireq))
4560 /* Unlink stale LARVAL SAs */
4561 sav = LIST_FIRST(&drainq);
4562 while (sav != NULL) {
4563 nextsav = LIST_NEXT(sav, drainq);
4564 /* Check that SA is still LARVAL */
4565 if (sav->state != SADB_SASTATE_LARVAL) {
4566 LIST_REMOVE(sav, drainq);
4567 LIST_INSERT_HEAD(&freeq, sav, drainq);
4571 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
4572 LIST_REMOVE(sav, spihash);
4573 sav->state = SADB_SASTATE_DEAD;
4576 /* Unlink all SAs with expired HARD lifetime */
4577 sav = LIST_FIRST(&hexpireq);
4578 while (sav != NULL) {
4579 nextsav = LIST_NEXT(sav, drainq);
4580 /* Check that SA is not unlinked */
4581 if (sav->state == SADB_SASTATE_DEAD) {
4582 LIST_REMOVE(sav, drainq);
4583 LIST_INSERT_HEAD(&freeq, sav, drainq);
4587 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
4588 LIST_REMOVE(sav, spihash);
4589 sav->state = SADB_SASTATE_DEAD;
4592 /* Mark all SAs with expired SOFT lifetime as DYING */
4593 sav = LIST_FIRST(&sexpireq);
4594 while (sav != NULL) {
4595 nextsav = LIST_NEXT(sav, drainq);
4596 /* Check that SA is not unlinked */
4597 if (sav->state == SADB_SASTATE_DEAD) {
4598 LIST_REMOVE(sav, drainq);
4599 LIST_INSERT_HEAD(&freeq, sav, drainq);
4604 * NOTE: this doesn't change SA order in the chain.
4606 sav->state = SADB_SASTATE_DYING;
4609 /* Unlink empty SAHs */
4610 sah = LIST_FIRST(&emptyq);
4611 while (sah != NULL) {
4612 nextsah = LIST_NEXT(sah, drainq);
4613 /* Check that SAH is still empty and not unlinked */
4614 if (sah->state == SADB_SASTATE_DEAD ||
4615 !TAILQ_EMPTY(&sah->savtree_larval) ||
4616 !TAILQ_EMPTY(&sah->savtree_alive)) {
4617 LIST_REMOVE(sah, drainq);
4618 key_freesah(&sah); /* release extra reference */
4622 TAILQ_REMOVE(&V_sahtree, sah, chain);
4623 LIST_REMOVE(sah, addrhash);
4624 sah->state = SADB_SASTATE_DEAD;
4629 /* Send SPDEXPIRE messages */
4630 sav = LIST_FIRST(&hexpireq);
4631 while (sav != NULL) {
4632 nextsav = LIST_NEXT(sav, drainq);
4634 key_freesah(&sav->sah); /* release reference from SAV */
4635 key_freesav(&sav); /* release extra reference */
4636 key_freesav(&sav); /* release last reference */
4639 sav = LIST_FIRST(&sexpireq);
4640 while (sav != NULL) {
4641 nextsav = LIST_NEXT(sav, drainq);
4643 key_freesav(&sav); /* release extra reference */
4646 /* Free stale LARVAL SAs */
4647 sav = LIST_FIRST(&drainq);
4648 while (sav != NULL) {
4649 nextsav = LIST_NEXT(sav, drainq);
4650 key_freesah(&sav->sah); /* release reference from SAV */
4651 key_freesav(&sav); /* release extra reference */
4652 key_freesav(&sav); /* release last reference */
4655 /* Free SAs that were unlinked/changed by someone else */
4656 sav = LIST_FIRST(&freeq);
4657 while (sav != NULL) {
4658 nextsav = LIST_NEXT(sav, drainq);
4659 key_freesav(&sav); /* release extra reference */
4662 /* Free empty SAH */
4663 sah = LIST_FIRST(&emptyq);
4664 while (sah != NULL) {
4665 nextsah = LIST_NEXT(sah, drainq);
4666 key_freesah(&sah); /* release extra reference */
4667 key_freesah(&sah); /* release last reference */
4673 key_flush_acq(time_t now)
4675 struct secacq *acq, *nextacq;
4679 acq = LIST_FIRST(&V_acqtree);
4680 while (acq != NULL) {
4681 nextacq = LIST_NEXT(acq, chain);
4682 if (now - acq->created > V_key_blockacq_lifetime) {
4683 LIST_REMOVE(acq, chain);
4684 LIST_REMOVE(acq, addrhash);
4685 LIST_REMOVE(acq, seqhash);
4686 free(acq, M_IPSEC_SAQ);
4694 key_flush_spacq(time_t now)
4696 struct secspacq *acq, *nextacq;
4700 for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4701 nextacq = LIST_NEXT(acq, chain);
4702 if (now - acq->created > V_key_blockacq_lifetime
4703 && __LIST_CHAINED(acq)) {
4704 LIST_REMOVE(acq, chain);
4705 free(acq, M_IPSEC_SAQ);
4713 * scanning SPD and SAD to check status for each entries,
4714 * and do to remove or to expire.
4715 * XXX: year 2038 problem may remain.
4718 key_timehandler(void *arg)
4720 VNET_ITERATOR_DECL(vnet_iter);
4721 time_t now = time_second;
4723 VNET_LIST_RLOCK_NOSLEEP();
4724 VNET_FOREACH(vnet_iter) {
4725 CURVNET_SET(vnet_iter);
4729 key_flush_spacq(now);
4732 VNET_LIST_RUNLOCK_NOSLEEP();
4734 #ifndef IPSEC_DEBUG2
4735 /* do exchange to tick time !! */
4736 callout_schedule(&key_timer, hz);
4737 #endif /* IPSEC_DEBUG2 */
4745 arc4random_buf(&value, sizeof(value));
4750 * map SADB_SATYPE_* to IPPROTO_*.
4751 * if satype == SADB_SATYPE then satype is mapped to ~0.
4753 * 0: invalid satype.
4756 key_satype2proto(uint8_t satype)
4759 case SADB_SATYPE_UNSPEC:
4760 return IPSEC_PROTO_ANY;
4761 case SADB_SATYPE_AH:
4763 case SADB_SATYPE_ESP:
4765 case SADB_X_SATYPE_IPCOMP:
4766 return IPPROTO_IPCOMP;
4767 case SADB_X_SATYPE_TCPSIGNATURE:
4776 * map IPPROTO_* to SADB_SATYPE_*
4778 * 0: invalid protocol type.
4781 key_proto2satype(uint8_t proto)
4785 return SADB_SATYPE_AH;
4787 return SADB_SATYPE_ESP;
4788 case IPPROTO_IPCOMP:
4789 return SADB_X_SATYPE_IPCOMP;
4791 return SADB_X_SATYPE_TCPSIGNATURE;
4800 * SADB_GETSPI processing is to receive
4801 * <base, (SA2), src address, dst address, (SPI range)>
4802 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4803 * tree with the status of LARVAL, and send
4804 * <base, SA(*), address(SD)>
4807 * IN: mhp: pointer to the pointer to each header.
4808 * OUT: NULL if fail.
4809 * other if success, return pointer to the message to send.
4812 key_getspi(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4814 struct secasindex saidx;
4815 struct sadb_address *src0, *dst0;
4816 struct secasvar *sav;
4817 uint32_t reqid, spi;
4819 uint8_t mode, proto;
4821 IPSEC_ASSERT(so != NULL, ("null socket"));
4822 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4823 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4824 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4826 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
4827 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST)
4828 #ifdef PFKEY_STRICT_CHECKS
4829 || SADB_CHECKHDR(mhp, SADB_EXT_SPIRANGE)
4832 ipseclog((LOG_DEBUG,
4833 "%s: invalid message: missing required header.\n",
4838 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
4839 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)
4840 #ifdef PFKEY_STRICT_CHECKS
4841 || SADB_CHECKLEN(mhp, SADB_EXT_SPIRANGE)
4844 ipseclog((LOG_DEBUG,
4845 "%s: invalid message: wrong header size.\n", __func__));
4849 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
4850 mode = IPSEC_MODE_ANY;
4853 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
4854 ipseclog((LOG_DEBUG,
4855 "%s: invalid message: wrong header size.\n",
4860 mode = ((struct sadb_x_sa2 *)
4861 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4862 reqid = ((struct sadb_x_sa2 *)
4863 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4866 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4867 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4869 /* map satype to proto */
4870 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4871 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4876 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
4877 (struct sockaddr *)(dst0 + 1));
4879 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
4883 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4885 /* SPI allocation */
4886 spi = key_do_getnewspi(
4887 (struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE], &saidx);
4890 * Requested SPI or SPI range is not available or
4896 sav = key_newsav(mhp, &saidx, spi, &error);
4900 if (sav->seq != 0) {
4903 * If the SADB_GETSPI message is in response to a
4904 * kernel-generated SADB_ACQUIRE, the sadb_msg_seq
4905 * MUST be the same as the SADB_ACQUIRE message.
4907 * XXXAE: However it doesn't definethe behaviour how to
4908 * check this and what to do if it doesn't match.
4909 * Also what we should do if it matches?
4911 * We can compare saidx used in SADB_ACQUIRE with saidx
4912 * used in SADB_GETSPI, but this probably can break
4913 * existing software. For now just warn if it doesn't match.
4915 * XXXAE: anyway it looks useless.
4917 key_acqdone(&saidx, sav->seq);
4920 printf("%s: SA(%p)\n", __func__, sav));
4921 KEYDBG(KEY_DATA, kdebug_secasv(sav));
4924 struct mbuf *n, *nn;
4925 struct sadb_sa *m_sa;
4926 struct sadb_msg *newmsg;
4929 /* create new sadb_msg to reply. */
4930 len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4931 PFKEY_ALIGN8(sizeof(struct sadb_sa));
4933 MGETHDR(n, M_NOWAIT, MT_DATA);
4935 if (!(MCLGET(n, M_NOWAIT))) {
4949 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4950 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4952 m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4953 m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4954 m_sa->sadb_sa_exttype = SADB_EXT_SA;
4955 m_sa->sadb_sa_spi = spi; /* SPI is already in network byte order */
4956 off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4958 IPSEC_ASSERT(off == len,
4959 ("length inconsistency (off %u len %u)", off, len));
4961 n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4962 SADB_EXT_ADDRESS_DST);
4969 if (n->m_len < sizeof(struct sadb_msg)) {
4970 n = m_pullup(n, sizeof(struct sadb_msg));
4972 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4975 n->m_pkthdr.len = 0;
4976 for (nn = n; nn; nn = nn->m_next)
4977 n->m_pkthdr.len += nn->m_len;
4979 newmsg = mtod(n, struct sadb_msg *);
4980 newmsg->sadb_msg_seq = sav->seq;
4981 newmsg->sadb_msg_errno = 0;
4982 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4985 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4989 return (key_senderror(so, m, error));
4993 * allocating new SPI
4994 * called by key_getspi().
4997 * others: success, SPI in network byte order.
5000 key_do_getnewspi(struct sadb_spirange *spirange, struct secasindex *saidx)
5002 uint32_t min, max, newspi, t;
5003 int count = V_key_spi_trycnt;
5005 /* set spi range to allocate */
5006 if (spirange != NULL) {
5007 min = spirange->sadb_spirange_min;
5008 max = spirange->sadb_spirange_max;
5010 min = V_key_spi_minval;
5011 max = V_key_spi_maxval;
5013 /* IPCOMP needs 2-byte SPI */
5014 if (saidx->proto == IPPROTO_IPCOMP) {
5020 t = min; min = max; max = t;
5025 if (!key_checkspidup(htonl(min))) {
5026 ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
5031 count--; /* taking one cost. */
5038 /* when requesting to allocate spi ranged */
5040 /* generate pseudo-random SPI value ranged. */
5041 newspi = min + (key_random() % (max - min + 1));
5042 if (!key_checkspidup(htonl(newspi)))
5046 if (count == 0 || newspi == 0) {
5047 ipseclog((LOG_DEBUG,
5048 "%s: failed to allocate SPI.\n", __func__));
5054 keystat.getspi_count =
5055 (keystat.getspi_count + V_key_spi_trycnt - count) / 2;
5057 return (htonl(newspi));
5061 * Find TCP-MD5 SA with corresponding secasindex.
5062 * If not found, return NULL and fill SPI with usable value if needed.
5064 static struct secasvar *
5065 key_getsav_tcpmd5(struct secasindex *saidx, uint32_t *spi)
5067 SAHTREE_RLOCK_TRACKER;
5068 struct secashead *sah;
5069 struct secasvar *sav;
5071 IPSEC_ASSERT(saidx->proto == IPPROTO_TCP, ("wrong proto"));
5073 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
5074 if (sah->saidx.proto != IPPROTO_TCP)
5076 if (!key_sockaddrcmp(&saidx->dst.sa, &sah->saidx.dst.sa, 0) &&
5077 !key_sockaddrcmp(&saidx->src.sa, &sah->saidx.src.sa, 0))
5081 if (V_key_preferred_oldsa)
5082 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
5084 sav = TAILQ_FIRST(&sah->savtree_alive);
5092 /* No SPI required */
5096 /* Check that SPI is unique */
5097 LIST_FOREACH(sav, SAVHASH_HASH(*spi), spihash) {
5098 if (sav->spi == *spi)
5103 /* SPI is already unique */
5107 /* XXX: not optimal */
5108 *spi = key_do_getnewspi(NULL, saidx);
5113 key_updateaddresses(struct socket *so, struct mbuf *m,
5114 const struct sadb_msghdr *mhp, struct secasvar *sav,
5115 struct secasindex *saidx)
5117 struct sockaddr *newaddr;
5118 struct secashead *sah;
5119 struct secasvar *newsav, *tmp;
5123 /* Check that we need to change SAH */
5124 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC)) {
5125 newaddr = (struct sockaddr *)(
5126 ((struct sadb_address *)
5127 mhp->ext[SADB_X_EXT_NEW_ADDRESS_SRC]) + 1);
5128 bcopy(newaddr, &saidx->src, newaddr->sa_len);
5129 key_porttosaddr(&saidx->src.sa, 0);
5131 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST)) {
5132 newaddr = (struct sockaddr *)(
5133 ((struct sadb_address *)
5134 mhp->ext[SADB_X_EXT_NEW_ADDRESS_DST]) + 1);
5135 bcopy(newaddr, &saidx->dst, newaddr->sa_len);
5136 key_porttosaddr(&saidx->dst.sa, 0);
5138 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC) ||
5139 !SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST)) {
5140 error = key_checksockaddrs(&saidx->src.sa, &saidx->dst.sa);
5142 ipseclog((LOG_DEBUG, "%s: invalid new sockaddr.\n",
5147 sah = key_getsah(saidx);
5149 /* create a new SA index */
5150 sah = key_newsah(saidx);
5152 ipseclog((LOG_DEBUG,
5153 "%s: No more memory.\n", __func__));
5156 isnew = 2; /* SAH is new */
5158 isnew = 1; /* existing SAH is referenced */
5161 * src and dst addresses are still the same.
5162 * Do we want to change NAT-T config?
5164 if (sav->sah->saidx.proto != IPPROTO_ESP ||
5165 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5166 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_SPORT) ||
5167 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5168 ipseclog((LOG_DEBUG,
5169 "%s: invalid message: missing required header.\n",
5173 /* We hold reference to SA, thus SAH will be referenced too. */
5178 newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA,
5180 if (newsav == NULL) {
5181 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5186 /* Clone SA's content into newsav */
5187 SAV_INITREF(newsav);
5188 bcopy(sav, newsav, offsetof(struct secasvar, chain));
5190 * We create new NAT-T config if it is needed.
5191 * Old NAT-T config will be freed by key_cleansav() when
5192 * last reference to SA will be released.
5194 newsav->natt = NULL;
5196 newsav->state = SADB_SASTATE_MATURE;
5197 error = key_setnatt(newsav, mhp);
5202 /* Check that SA is still alive */
5203 if (sav->state == SADB_SASTATE_DEAD) {
5204 /* SA was unlinked */
5210 /* Unlink SA from SAH and SPI hash */
5211 IPSEC_ASSERT((sav->flags & SADB_X_EXT_F_CLONED) == 0,
5212 ("SA is already cloned"));
5213 IPSEC_ASSERT(sav->state == SADB_SASTATE_MATURE ||
5214 sav->state == SADB_SASTATE_DYING,
5215 ("Wrong SA state %u\n", sav->state));
5216 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
5217 LIST_REMOVE(sav, spihash);
5218 sav->state = SADB_SASTATE_DEAD;
5221 * Link new SA with SAH. Keep SAs ordered by
5222 * create time (newer are first).
5224 TAILQ_FOREACH(tmp, &sah->savtree_alive, chain) {
5225 if (newsav->created > tmp->created) {
5226 TAILQ_INSERT_BEFORE(tmp, newsav, chain);
5231 TAILQ_INSERT_TAIL(&sah->savtree_alive, newsav, chain);
5233 /* Add new SA into SPI hash. */
5234 LIST_INSERT_HEAD(SAVHASH_HASH(newsav->spi), newsav, spihash);
5236 /* Add new SAH into SADB. */
5238 TAILQ_INSERT_HEAD(&V_sahtree, sah, chain);
5239 LIST_INSERT_HEAD(SAHADDRHASH_HASH(saidx), sah, addrhash);
5240 sah->state = SADB_SASTATE_MATURE;
5241 SAH_ADDREF(sah); /* newsav references new SAH */
5244 * isnew == 1 -> @sah was referenced by key_getsah().
5245 * isnew == 0 -> we use the same @sah, that was used by @sav,
5246 * and we use its reference for @newsav.
5249 /* XXX: replace cntr with pointer? */
5250 newsav->cntr = sav->cntr;
5251 sav->flags |= SADB_X_EXT_F_CLONED;
5252 SECASVAR_UNLOCK(sav);
5257 printf("%s: SA(%p) cloned into SA(%p)\n",
5258 __func__, sav, newsav));
5259 KEYDBG(KEY_DATA, kdebug_secasv(newsav));
5261 key_freesav(&sav); /* release last reference */
5263 /* set msg buf from mhp */
5264 n = key_getmsgbuf_x1(m, mhp);
5266 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5270 key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5275 if (newsav != NULL) {
5276 if (newsav->natt != NULL)
5277 free(newsav->natt, M_IPSEC_MISC);
5278 free(newsav, M_IPSEC_SA);
5284 * SADB_UPDATE processing
5286 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5287 * key(AE), (identity(SD),) (sensitivity)>
5288 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
5290 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5291 * (identity(SD),) (sensitivity)>
5294 * m will always be freed.
5297 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5299 struct secasindex saidx;
5300 struct sadb_address *src0, *dst0;
5301 struct sadb_sa *sa0;
5302 struct secasvar *sav;
5305 uint8_t mode, proto;
5307 IPSEC_ASSERT(so != NULL, ("null socket"));
5308 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5309 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5310 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5312 /* map satype to proto */
5313 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5314 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5316 return key_senderror(so, m, EINVAL);
5319 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
5320 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5321 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5322 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
5323 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
5324 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
5325 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
5326 ipseclog((LOG_DEBUG,
5327 "%s: invalid message: missing required header.\n",
5329 return key_senderror(so, m, EINVAL);
5331 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
5332 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5333 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5334 ipseclog((LOG_DEBUG,
5335 "%s: invalid message: wrong header size.\n", __func__));
5336 return key_senderror(so, m, EINVAL);
5338 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
5339 mode = IPSEC_MODE_ANY;
5342 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
5343 ipseclog((LOG_DEBUG,
5344 "%s: invalid message: wrong header size.\n",
5346 return key_senderror(so, m, EINVAL);
5348 mode = ((struct sadb_x_sa2 *)
5349 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5350 reqid = ((struct sadb_x_sa2 *)
5351 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5354 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5355 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5356 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5359 * Only SADB_SASTATE_MATURE SAs may be submitted in an
5360 * SADB_UPDATE message.
5362 if (sa0->sadb_sa_state != SADB_SASTATE_MATURE) {
5363 ipseclog((LOG_DEBUG, "%s: invalid state.\n", __func__));
5364 #ifdef PFKEY_STRICT_CHECKS
5365 return key_senderror(so, m, EINVAL);
5368 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
5369 (struct sockaddr *)(dst0 + 1));
5371 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5372 return key_senderror(so, m, error);
5374 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5375 sav = key_getsavbyspi(sa0->sadb_sa_spi);
5377 ipseclog((LOG_DEBUG, "%s: no SA found for SPI %u\n",
5378 __func__, ntohl(sa0->sadb_sa_spi)));
5379 return key_senderror(so, m, EINVAL);
5382 * Check that SADB_UPDATE issued by the same process that did
5383 * SADB_GETSPI or SADB_ADD.
5385 if (sav->pid != mhp->msg->sadb_msg_pid) {
5386 ipseclog((LOG_DEBUG,
5387 "%s: pid mismatched (SPI %u, pid %u vs. %u)\n", __func__,
5388 ntohl(sav->spi), sav->pid, mhp->msg->sadb_msg_pid));
5390 return key_senderror(so, m, EINVAL);
5392 /* saidx should match with SA. */
5393 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_MODE_REQID) == 0) {
5394 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u\n",
5395 __func__, ntohl(sav->spi)));
5397 return key_senderror(so, m, ESRCH);
5400 if (sav->state == SADB_SASTATE_LARVAL) {
5401 if ((mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5402 SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT)) ||
5403 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5404 SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH))) {
5405 ipseclog((LOG_DEBUG,
5406 "%s: invalid message: missing required header.\n",
5409 return key_senderror(so, m, EINVAL);
5412 * We can set any values except src, dst and SPI.
5414 error = key_setsaval(sav, mhp);
5417 return (key_senderror(so, m, error));
5419 /* Change SA state to MATURE */
5421 if (sav->state != SADB_SASTATE_LARVAL) {
5422 /* SA was deleted or another thread made it MATURE. */
5425 return (key_senderror(so, m, ESRCH));
5428 * NOTE: we keep SAs in savtree_alive ordered by created
5429 * time. When SA's state changed from LARVAL to MATURE,
5430 * we update its created time in key_setsaval() and move
5431 * it into head of savtree_alive.
5433 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
5434 TAILQ_INSERT_HEAD(&sav->sah->savtree_alive, sav, chain);
5435 sav->state = SADB_SASTATE_MATURE;
5439 * For DYING and MATURE SA we can change only state
5440 * and lifetimes. Report EINVAL if something else attempted
5443 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT) ||
5444 !SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH)) {
5446 return (key_senderror(so, m, EINVAL));
5448 error = key_updatelifetimes(sav, mhp);
5451 return (key_senderror(so, m, error));
5454 * This is FreeBSD extension to RFC2367.
5455 * IKEd can specify SADB_X_EXT_NEW_ADDRESS_SRC and/or
5456 * SADB_X_EXT_NEW_ADDRESS_DST when it wants to change
5457 * SA addresses (for example to implement MOBIKE protocol
5458 * as described in RFC4555). Also we allow to change
5461 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC) ||
5462 !SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST) ||
5463 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5464 sav->natt != NULL) {
5465 error = key_updateaddresses(so, m, mhp, sav, &saidx);
5468 return (key_senderror(so, m, error));
5471 /* Check that SA is still alive */
5473 if (sav->state == SADB_SASTATE_DEAD) {
5474 /* SA was unlinked */
5477 return (key_senderror(so, m, ESRCH));
5480 * NOTE: there is possible state moving from DYING to MATURE,
5481 * but this doesn't change created time, so we won't reorder
5484 sav->state = SADB_SASTATE_MATURE;
5488 printf("%s: SA(%p)\n", __func__, sav));
5489 KEYDBG(KEY_DATA, kdebug_secasv(sav));
5495 /* set msg buf from mhp */
5496 n = key_getmsgbuf_x1(m, mhp);
5498 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5499 return key_senderror(so, m, ENOBUFS);
5503 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5508 * SADB_ADD processing
5509 * add an entry to SA database, when received
5510 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5511 * key(AE), (identity(SD),) (sensitivity)>
5514 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5515 * (identity(SD),) (sensitivity)>
5518 * IGNORE identity and sensitivity messages.
5520 * m will always be freed.
5523 key_add(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5525 struct secasindex saidx;
5526 struct sadb_address *src0, *dst0;
5527 struct sadb_sa *sa0;
5528 struct secasvar *sav;
5529 uint32_t reqid, spi;
5530 uint8_t mode, proto;
5533 IPSEC_ASSERT(so != NULL, ("null socket"));
5534 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5535 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5536 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5538 /* map satype to proto */
5539 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5540 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5542 return key_senderror(so, m, EINVAL);
5545 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
5546 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5547 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5548 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP && (
5549 SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT) ||
5550 SADB_CHECKLEN(mhp, SADB_EXT_KEY_ENCRYPT))) ||
5551 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH && (
5552 SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH) ||
5553 SADB_CHECKLEN(mhp, SADB_EXT_KEY_AUTH))) ||
5554 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
5555 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
5556 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
5557 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
5558 ipseclog((LOG_DEBUG,
5559 "%s: invalid message: missing required header.\n",
5561 return key_senderror(so, m, EINVAL);
5563 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
5564 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5565 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5566 ipseclog((LOG_DEBUG,
5567 "%s: invalid message: wrong header size.\n", __func__));
5568 return key_senderror(so, m, EINVAL);
5570 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
5571 mode = IPSEC_MODE_ANY;
5574 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
5575 ipseclog((LOG_DEBUG,
5576 "%s: invalid message: wrong header size.\n",
5578 return key_senderror(so, m, EINVAL);
5580 mode = ((struct sadb_x_sa2 *)
5581 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5582 reqid = ((struct sadb_x_sa2 *)
5583 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5586 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5587 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5588 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5591 * Only SADB_SASTATE_MATURE SAs may be submitted in an
5594 if (sa0->sadb_sa_state != SADB_SASTATE_MATURE) {
5595 ipseclog((LOG_DEBUG, "%s: invalid state.\n", __func__));
5596 #ifdef PFKEY_STRICT_CHECKS
5597 return key_senderror(so, m, EINVAL);
5600 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
5601 (struct sockaddr *)(dst0 + 1));
5603 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5604 return key_senderror(so, m, error);
5606 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5607 spi = sa0->sadb_sa_spi;
5609 * For TCP-MD5 SAs we don't use SPI. Check the uniqueness using
5611 * XXXAE: IPComp seems also doesn't use SPI.
5613 if (proto == IPPROTO_TCP) {
5614 sav = key_getsav_tcpmd5(&saidx, &spi);
5615 if (sav == NULL && spi == 0) {
5616 /* Failed to allocate SPI */
5617 ipseclog((LOG_DEBUG, "%s: SA already exists.\n",
5619 return key_senderror(so, m, EEXIST);
5621 /* XXX: SPI that we report back can have another value */
5623 /* We can create new SA only if SPI is different. */
5624 sav = key_getsavbyspi(spi);
5628 ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5629 return key_senderror(so, m, EEXIST);
5632 sav = key_newsav(mhp, &saidx, spi, &error);
5634 return key_senderror(so, m, error);
5636 printf("%s: return SA(%p)\n", __func__, sav));
5637 KEYDBG(KEY_DATA, kdebug_secasv(sav));
5639 * If SADB_ADD was in response to SADB_ACQUIRE, we need to schedule
5643 key_acqdone(&saidx, sav->seq);
5647 * Don't call key_freesav() on error here, as we would like to
5648 * keep the SA in the database.
5652 /* set msg buf from mhp */
5653 n = key_getmsgbuf_x1(m, mhp);
5655 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5656 return key_senderror(so, m, ENOBUFS);
5660 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5666 * IKEd may request the use ESP in UDP encapsulation when it detects the
5667 * presence of NAT. It uses NAT-T extension headers for such SAs to specify
5668 * parameters needed for encapsulation and decapsulation. These PF_KEY
5669 * extension headers are not standardized, so this comment addresses our
5671 * SADB_X_EXT_NAT_T_TYPE specifies type of encapsulation, we support only
5672 * UDP_ENCAP_ESPINUDP as described in RFC3948.
5673 * SADB_X_EXT_NAT_T_SPORT/DPORT specifies source and destination ports for
5674 * UDP header. We use these ports in UDP encapsulation procedure, also we
5675 * can check them in UDP decapsulation procedure.
5676 * SADB_X_EXT_NAT_T_OA[IR] specifies original address of initiator or
5677 * responder. These addresses can be used for transport mode to adjust
5678 * checksum after decapsulation and decryption. Since original IP addresses
5679 * used by peer usually different (we detected presence of NAT), TCP/UDP
5680 * pseudo header checksum and IP header checksum was calculated using original
5681 * addresses. After decapsulation and decryption we need to adjust checksum
5682 * to have correct datagram.
5684 * We expect presence of NAT-T extension headers only in SADB_ADD and
5685 * SADB_UPDATE messages. We report NAT-T extension headers in replies
5686 * to SADB_ADD, SADB_UPDATE, SADB_GET, and SADB_DUMP messages.
5689 key_setnatt(struct secasvar *sav, const struct sadb_msghdr *mhp)
5691 struct sadb_x_nat_t_port *port;
5692 struct sadb_x_nat_t_type *type;
5693 struct sadb_address *oai, *oar;
5694 struct sockaddr *sa;
5698 IPSEC_ASSERT(sav->natt == NULL, ("natt is already initialized"));
5700 * Ignore NAT-T headers if sproto isn't ESP.
5702 if (sav->sah->saidx.proto != IPPROTO_ESP)
5705 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) &&
5706 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_SPORT) &&
5707 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5708 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5709 SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_SPORT) ||
5710 SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5711 ipseclog((LOG_DEBUG,
5712 "%s: invalid message: wrong header size.\n",
5719 type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5720 if (type->sadb_x_nat_t_type_type != UDP_ENCAP_ESPINUDP) {
5721 ipseclog((LOG_DEBUG, "%s: unsupported NAT-T type %u.\n",
5722 __func__, type->sadb_x_nat_t_type_type));
5726 * Allocate storage for NAT-T config.
5727 * On error it will be released by key_cleansav().
5729 sav->natt = malloc(sizeof(struct secnatt), M_IPSEC_MISC,
5731 if (sav->natt == NULL) {
5732 PFKEYSTAT_INC(in_nomem);
5733 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5736 port = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5737 if (port->sadb_x_nat_t_port_port == 0) {
5738 ipseclog((LOG_DEBUG, "%s: invalid NAT-T sport specified.\n",
5742 sav->natt->sport = port->sadb_x_nat_t_port_port;
5743 port = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5744 if (port->sadb_x_nat_t_port_port == 0) {
5745 ipseclog((LOG_DEBUG, "%s: invalid NAT-T dport specified.\n",
5749 sav->natt->dport = port->sadb_x_nat_t_port_port;
5752 * SADB_X_EXT_NAT_T_OAI and SADB_X_EXT_NAT_T_OAR are optional
5753 * and needed only for transport mode IPsec.
5754 * Usually NAT translates only one address, but it is possible,
5755 * that both addresses could be translated.
5756 * NOTE: Value of SADB_X_EXT_NAT_T_OAI is equal to SADB_X_EXT_NAT_T_OA.
5758 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_OAI)) {
5759 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_OAI)) {
5760 ipseclog((LOG_DEBUG,
5761 "%s: invalid message: wrong header size.\n",
5765 oai = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5768 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_OAR)) {
5769 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_OAR)) {
5770 ipseclog((LOG_DEBUG,
5771 "%s: invalid message: wrong header size.\n",
5775 oar = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5779 /* Initialize addresses only for transport mode */
5780 if (sav->sah->saidx.mode != IPSEC_MODE_TUNNEL) {
5783 /* Currently we support only AF_INET */
5784 sa = (struct sockaddr *)(oai + 1);
5785 if (sa->sa_family != AF_INET ||
5786 sa->sa_len != sizeof(struct sockaddr_in)) {
5787 ipseclog((LOG_DEBUG,
5788 "%s: wrong NAT-OAi header.\n",
5792 /* Ignore address if it the same */
5793 if (((struct sockaddr_in *)sa)->sin_addr.s_addr !=
5794 sav->sah->saidx.src.sin.sin_addr.s_addr) {
5795 bcopy(sa, &sav->natt->oai.sa, sa->sa_len);
5796 sav->natt->flags |= IPSEC_NATT_F_OAI;
5797 /* Calculate checksum delta */
5798 addr = sav->sah->saidx.src.sin.sin_addr.s_addr;
5799 cksum = in_addword(cksum, ~addr >> 16);
5800 cksum = in_addword(cksum, ~addr & 0xffff);
5801 addr = sav->natt->oai.sin.sin_addr.s_addr;
5802 cksum = in_addword(cksum, addr >> 16);
5803 cksum = in_addword(cksum, addr & 0xffff);
5807 /* Currently we support only AF_INET */
5808 sa = (struct sockaddr *)(oar + 1);
5809 if (sa->sa_family != AF_INET ||
5810 sa->sa_len != sizeof(struct sockaddr_in)) {
5811 ipseclog((LOG_DEBUG,
5812 "%s: wrong NAT-OAr header.\n",
5816 /* Ignore address if it the same */
5817 if (((struct sockaddr_in *)sa)->sin_addr.s_addr !=
5818 sav->sah->saidx.dst.sin.sin_addr.s_addr) {
5819 bcopy(sa, &sav->natt->oar.sa, sa->sa_len);
5820 sav->natt->flags |= IPSEC_NATT_F_OAR;
5821 /* Calculate checksum delta */
5822 addr = sav->sah->saidx.dst.sin.sin_addr.s_addr;
5823 cksum = in_addword(cksum, ~addr >> 16);
5824 cksum = in_addword(cksum, ~addr & 0xffff);
5825 addr = sav->natt->oar.sin.sin_addr.s_addr;
5826 cksum = in_addword(cksum, addr >> 16);
5827 cksum = in_addword(cksum, addr & 0xffff);
5830 sav->natt->cksum = cksum;
5836 key_setident(struct secashead *sah, const struct sadb_msghdr *mhp)
5838 const struct sadb_ident *idsrc, *iddst;
5840 IPSEC_ASSERT(sah != NULL, ("null secashead"));
5841 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5842 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5844 /* don't make buffer if not there */
5845 if (SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_SRC) &&
5846 SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_DST)) {
5852 if (SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_SRC) ||
5853 SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_DST)) {
5854 ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5858 idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5859 iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5861 /* validity check */
5862 if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5863 ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5867 switch (idsrc->sadb_ident_type) {
5868 case SADB_IDENTTYPE_PREFIX:
5869 case SADB_IDENTTYPE_FQDN:
5870 case SADB_IDENTTYPE_USERFQDN:
5872 /* XXX do nothing */
5878 /* make structure */
5879 sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5880 if (sah->idents == NULL) {
5881 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5884 sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5885 if (sah->identd == NULL) {
5886 free(sah->idents, M_IPSEC_MISC);
5888 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5891 sah->idents->type = idsrc->sadb_ident_type;
5892 sah->idents->id = idsrc->sadb_ident_id;
5894 sah->identd->type = iddst->sadb_ident_type;
5895 sah->identd->id = iddst->sadb_ident_id;
5901 * m will not be freed on return.
5902 * it is caller's responsibility to free the result.
5904 * Called from SADB_ADD and SADB_UPDATE. Reply will contain headers
5905 * from the request in defined order.
5907 static struct mbuf *
5908 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
5912 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5913 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5914 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5916 /* create new sadb_msg to reply. */
5917 n = key_gather_mbuf(m, mhp, 1, 16, SADB_EXT_RESERVED,
5918 SADB_EXT_SA, SADB_X_EXT_SA2,
5919 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5920 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5921 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
5922 SADB_X_EXT_NAT_T_TYPE, SADB_X_EXT_NAT_T_SPORT,
5923 SADB_X_EXT_NAT_T_DPORT, SADB_X_EXT_NAT_T_OAI,
5924 SADB_X_EXT_NAT_T_OAR, SADB_X_EXT_NEW_ADDRESS_SRC,
5925 SADB_X_EXT_NEW_ADDRESS_DST);
5929 if (n->m_len < sizeof(struct sadb_msg)) {
5930 n = m_pullup(n, sizeof(struct sadb_msg));
5934 mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5935 mtod(n, struct sadb_msg *)->sadb_msg_len =
5936 PFKEY_UNIT64(n->m_pkthdr.len);
5942 * SADB_DELETE processing
5944 * <base, SA(*), address(SD)>
5945 * from the ikmpd, and set SADB_SASTATE_DEAD,
5947 * <base, SA(*), address(SD)>
5950 * m will always be freed.
5953 key_delete(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5955 struct secasindex saidx;
5956 struct sadb_address *src0, *dst0;
5957 struct secasvar *sav;
5958 struct sadb_sa *sa0;
5961 IPSEC_ASSERT(so != NULL, ("null socket"));
5962 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5963 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5964 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5966 /* map satype to proto */
5967 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5968 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5970 return key_senderror(so, m, EINVAL);
5973 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5974 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5975 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5976 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5977 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5979 return key_senderror(so, m, EINVAL);
5982 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5983 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5985 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
5986 (struct sockaddr *)(dst0 + 1)) != 0) {
5987 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5988 return (key_senderror(so, m, EINVAL));
5990 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5991 if (SADB_CHECKHDR(mhp, SADB_EXT_SA)) {
5993 * Caller wants us to delete all non-LARVAL SAs
5994 * that match the src/dst. This is used during
5995 * IKE INITIAL-CONTACT.
5996 * XXXAE: this looks like some extension to RFC2367.
5998 ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5999 return (key_delete_all(so, m, mhp, &saidx));
6001 if (SADB_CHECKLEN(mhp, SADB_EXT_SA)) {
6002 ipseclog((LOG_DEBUG,
6003 "%s: invalid message: wrong header size.\n", __func__));
6004 return (key_senderror(so, m, EINVAL));
6006 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
6007 if (proto == IPPROTO_TCP)
6008 sav = key_getsav_tcpmd5(&saidx, NULL);
6010 sav = key_getsavbyspi(sa0->sadb_sa_spi);
6012 ipseclog((LOG_DEBUG, "%s: no SA found for SPI %u.\n",
6013 __func__, ntohl(sa0->sadb_sa_spi)));
6014 return (key_senderror(so, m, ESRCH));
6016 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_HEAD) == 0) {
6017 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u.\n",
6018 __func__, ntohl(sav->spi)));
6020 return (key_senderror(so, m, ESRCH));
6023 printf("%s: SA(%p)\n", __func__, sav));
6024 KEYDBG(KEY_DATA, kdebug_secasv(sav));
6030 struct sadb_msg *newmsg;
6032 /* create new sadb_msg to reply. */
6033 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
6034 SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
6036 return key_senderror(so, m, ENOBUFS);
6038 if (n->m_len < sizeof(struct sadb_msg)) {
6039 n = m_pullup(n, sizeof(struct sadb_msg));
6041 return key_senderror(so, m, ENOBUFS);
6043 newmsg = mtod(n, struct sadb_msg *);
6044 newmsg->sadb_msg_errno = 0;
6045 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
6048 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
6053 * delete all SAs for src/dst. Called from key_delete().
6056 key_delete_all(struct socket *so, struct mbuf *m,
6057 const struct sadb_msghdr *mhp, struct secasindex *saidx)
6059 struct secasvar_queue drainq;
6060 struct secashead *sah;
6061 struct secasvar *sav, *nextsav;
6063 TAILQ_INIT(&drainq);
6065 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
6066 if (key_cmpsaidx(&sah->saidx, saidx, CMP_HEAD) == 0)
6068 /* Move all ALIVE SAs into drainq */
6069 TAILQ_CONCAT(&drainq, &sah->savtree_alive, chain);
6071 /* Unlink all queued SAs from SPI hash */
6072 TAILQ_FOREACH(sav, &drainq, chain) {
6073 sav->state = SADB_SASTATE_DEAD;
6074 LIST_REMOVE(sav, spihash);
6077 /* Now we can release reference for all SAs in drainq */
6078 sav = TAILQ_FIRST(&drainq);
6079 while (sav != NULL) {
6081 printf("%s: SA(%p)\n", __func__, sav));
6082 KEYDBG(KEY_DATA, kdebug_secasv(sav));
6083 nextsav = TAILQ_NEXT(sav, chain);
6084 key_freesah(&sav->sah); /* release reference from SAV */
6085 key_freesav(&sav); /* release last reference */
6091 struct sadb_msg *newmsg;
6093 /* create new sadb_msg to reply. */
6094 n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
6095 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
6097 return key_senderror(so, m, ENOBUFS);
6099 if (n->m_len < sizeof(struct sadb_msg)) {
6100 n = m_pullup(n, sizeof(struct sadb_msg));
6102 return key_senderror(so, m, ENOBUFS);
6104 newmsg = mtod(n, struct sadb_msg *);
6105 newmsg->sadb_msg_errno = 0;
6106 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
6109 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
6114 * Delete all alive SAs for corresponding xform.
6115 * Larval SAs have not initialized tdb_xform, so it is safe to leave them
6116 * here when xform disappears.
6119 key_delete_xform(const struct xformsw *xsp)
6121 struct secasvar_queue drainq;
6122 struct secashead *sah;
6123 struct secasvar *sav, *nextsav;
6125 TAILQ_INIT(&drainq);
6127 TAILQ_FOREACH(sah, &V_sahtree, chain) {
6128 sav = TAILQ_FIRST(&sah->savtree_alive);
6131 if (sav->tdb_xform != xsp)
6134 * It is supposed that all SAs in the chain are related to
6137 TAILQ_CONCAT(&drainq, &sah->savtree_alive, chain);
6139 /* Unlink all queued SAs from SPI hash */
6140 TAILQ_FOREACH(sav, &drainq, chain) {
6141 sav->state = SADB_SASTATE_DEAD;
6142 LIST_REMOVE(sav, spihash);
6146 /* Now we can release reference for all SAs in drainq */
6147 sav = TAILQ_FIRST(&drainq);
6148 while (sav != NULL) {
6150 printf("%s: SA(%p)\n", __func__, sav));
6151 KEYDBG(KEY_DATA, kdebug_secasv(sav));
6152 nextsav = TAILQ_NEXT(sav, chain);
6153 key_freesah(&sav->sah); /* release reference from SAV */
6154 key_freesav(&sav); /* release last reference */
6160 * SADB_GET processing
6162 * <base, SA(*), address(SD)>
6163 * from the ikmpd, and get a SP and a SA to respond,
6165 * <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
6166 * (identity(SD),) (sensitivity)>
6169 * m will always be freed.
6172 key_get(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6174 struct secasindex saidx;
6175 struct sadb_address *src0, *dst0;
6176 struct sadb_sa *sa0;
6177 struct secasvar *sav;
6180 IPSEC_ASSERT(so != NULL, ("null socket"));
6181 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6182 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6183 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6185 /* map satype to proto */
6186 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6187 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6189 return key_senderror(so, m, EINVAL);
6192 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
6193 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
6194 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST)) {
6195 ipseclog((LOG_DEBUG,
6196 "%s: invalid message: missing required header.\n",
6198 return key_senderror(so, m, EINVAL);
6200 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
6201 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
6202 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
6203 ipseclog((LOG_DEBUG,
6204 "%s: invalid message: wrong header size.\n", __func__));
6205 return key_senderror(so, m, EINVAL);
6208 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
6209 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6210 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6212 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
6213 (struct sockaddr *)(dst0 + 1)) != 0) {
6214 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
6215 return key_senderror(so, m, EINVAL);
6217 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6219 if (proto == IPPROTO_TCP)
6220 sav = key_getsav_tcpmd5(&saidx, NULL);
6222 sav = key_getsavbyspi(sa0->sadb_sa_spi);
6224 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
6225 return key_senderror(so, m, ESRCH);
6227 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_HEAD) == 0) {
6228 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u.\n",
6229 __func__, ntohl(sa0->sadb_sa_spi)));
6231 return (key_senderror(so, m, ESRCH));
6238 /* map proto to satype */
6239 if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0) {
6240 ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
6243 return key_senderror(so, m, EINVAL);
6246 /* create new sadb_msg to reply. */
6247 n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
6248 mhp->msg->sadb_msg_pid);
6252 return key_senderror(so, m, ENOBUFS);
6255 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6259 /* XXX make it sysctl-configurable? */
6261 key_getcomb_setlifetime(struct sadb_comb *comb)
6264 comb->sadb_comb_soft_allocations = 1;
6265 comb->sadb_comb_hard_allocations = 1;
6266 comb->sadb_comb_soft_bytes = 0;
6267 comb->sadb_comb_hard_bytes = 0;
6268 comb->sadb_comb_hard_addtime = 86400; /* 1 day */
6269 comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
6270 comb->sadb_comb_soft_usetime = 28800; /* 8 hours */
6271 comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
6275 * XXX reorder combinations by preference
6276 * XXX no idea if the user wants ESP authentication or not
6278 static struct mbuf *
6279 key_getcomb_ealg(void)
6281 struct sadb_comb *comb;
6282 const struct enc_xform *algo;
6283 struct mbuf *result = NULL, *m, *n;
6287 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6290 for (i = 1; i <= SADB_EALG_MAX; i++) {
6291 algo = enc_algorithm_lookup(i);
6295 /* discard algorithms with key size smaller than system min */
6296 if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6298 if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6299 encmin = V_ipsec_esp_keymin;
6301 encmin = _BITS(algo->minkey);
6303 if (V_ipsec_esp_auth)
6304 m = key_getcomb_ah();
6306 IPSEC_ASSERT(l <= MLEN,
6307 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6308 MGET(m, M_NOWAIT, MT_DATA);
6313 bzero(mtod(m, caddr_t), m->m_len);
6320 for (n = m; n; n = n->m_next)
6322 IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6324 for (off = 0; off < totlen; off += l) {
6325 n = m_pulldown(m, off, l, &o);
6327 /* m is already freed */
6330 comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6331 bzero(comb, sizeof(*comb));
6332 key_getcomb_setlifetime(comb);
6333 comb->sadb_comb_encrypt = i;
6334 comb->sadb_comb_encrypt_minbits = encmin;
6335 comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6353 key_getsizes_ah(const struct auth_hash *ah, int alg, u_int16_t* min,
6357 *min = *max = ah->hashsize;
6358 if (ah->keysize == 0) {
6360 * Transform takes arbitrary key size but algorithm
6361 * key size is restricted. Enforce this here.
6364 case SADB_X_AALG_NULL: *min = 1; *max = 256; break;
6365 case SADB_X_AALG_SHA2_256: *min = *max = 32; break;
6366 case SADB_X_AALG_SHA2_384: *min = *max = 48; break;
6367 case SADB_X_AALG_SHA2_512: *min = *max = 64; break;
6369 DPRINTF(("%s: unknown AH algorithm %u\n",
6377 * XXX reorder combinations by preference
6379 static struct mbuf *
6382 const struct auth_hash *algo;
6383 struct sadb_comb *comb;
6385 u_int16_t minkeysize, maxkeysize;
6387 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6390 for (i = 1; i <= SADB_AALG_MAX; i++) {
6392 /* we prefer HMAC algorithms, not old algorithms */
6393 if (i != SADB_AALG_SHA1HMAC &&
6394 i != SADB_X_AALG_SHA2_256 &&
6395 i != SADB_X_AALG_SHA2_384 &&
6396 i != SADB_X_AALG_SHA2_512)
6399 algo = auth_algorithm_lookup(i);
6402 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6403 /* discard algorithms with key size smaller than system min */
6404 if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6408 IPSEC_ASSERT(l <= MLEN,
6409 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6410 MGET(m, M_NOWAIT, MT_DATA);
6417 M_PREPEND(m, l, M_NOWAIT);
6421 comb = mtod(m, struct sadb_comb *);
6422 bzero(comb, sizeof(*comb));
6423 key_getcomb_setlifetime(comb);
6424 comb->sadb_comb_auth = i;
6425 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6426 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6433 * not really an official behavior. discussed in pf_key@inner.net in Sep2000.
6434 * XXX reorder combinations by preference
6436 static struct mbuf *
6437 key_getcomb_ipcomp()
6439 const struct comp_algo *algo;
6440 struct sadb_comb *comb;
6443 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6446 for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6447 algo = comp_algorithm_lookup(i);
6452 IPSEC_ASSERT(l <= MLEN,
6453 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6454 MGET(m, M_NOWAIT, MT_DATA);
6461 M_PREPEND(m, l, M_NOWAIT);
6465 comb = mtod(m, struct sadb_comb *);
6466 bzero(comb, sizeof(*comb));
6467 key_getcomb_setlifetime(comb);
6468 comb->sadb_comb_encrypt = i;
6469 /* what should we set into sadb_comb_*_{min,max}bits? */
6476 * XXX no way to pass mode (transport/tunnel) to userland
6477 * XXX replay checking?
6478 * XXX sysctl interface to ipsec_{ah,esp}_keymin
6480 static struct mbuf *
6481 key_getprop(const struct secasindex *saidx)
6483 struct sadb_prop *prop;
6485 const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6488 switch (saidx->proto) {
6490 m = key_getcomb_ealg();
6493 m = key_getcomb_ah();
6495 case IPPROTO_IPCOMP:
6496 m = key_getcomb_ipcomp();
6504 M_PREPEND(m, l, M_NOWAIT);
6509 for (n = m; n; n = n->m_next)
6512 prop = mtod(m, struct sadb_prop *);
6513 bzero(prop, sizeof(*prop));
6514 prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6515 prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6516 prop->sadb_prop_replay = 32; /* XXX */
6522 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6524 * <base, SA, address(SD), (address(P)), x_policy,
6525 * (identity(SD),) (sensitivity,) proposal>
6526 * to KMD, and expect to receive
6527 * <base> with SADB_ACQUIRE if error occurred,
6529 * <base, src address, dst address, (SPI range)> with SADB_GETSPI
6530 * from KMD by PF_KEY.
6532 * XXX x_policy is outside of RFC2367 (KAME extension).
6533 * XXX sensitivity is not supported.
6534 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6535 * see comment for key_getcomb_ipcomp().
6539 * others: error number
6542 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6544 union sockaddr_union addr;
6545 struct mbuf *result, *m;
6549 uint8_t mask, satype;
6551 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6552 satype = key_proto2satype(saidx->proto);
6553 IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6557 ul_proto = IPSEC_ULPROTO_ANY;
6559 /* Get seq number to check whether sending message or not. */
6560 seq = key_getacq(saidx, &error);
6564 m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6572 * set sadb_address for saidx's.
6574 * Note that if sp is supplied, then we're being called from
6575 * key_allocsa_policy() and should supply port and protocol
6577 * XXXAE: why only TCP and UDP? ICMP and SCTP looks applicable too.
6578 * XXXAE: probably we can handle this in the ipsec[46]_allocsa().
6579 * XXXAE: it looks like we should save this info in the ACQ entry.
6581 if (sp != NULL && (sp->spidx.ul_proto == IPPROTO_TCP ||
6582 sp->spidx.ul_proto == IPPROTO_UDP))
6583 ul_proto = sp->spidx.ul_proto;
6587 if (ul_proto != IPSEC_ULPROTO_ANY) {
6588 switch (sp->spidx.src.sa.sa_family) {
6590 if (sp->spidx.src.sin.sin_port != IPSEC_PORT_ANY) {
6591 addr.sin.sin_port = sp->spidx.src.sin.sin_port;
6592 mask = sp->spidx.prefs;
6596 if (sp->spidx.src.sin6.sin6_port != IPSEC_PORT_ANY) {
6597 addr.sin6.sin6_port =
6598 sp->spidx.src.sin6.sin6_port;
6599 mask = sp->spidx.prefs;
6606 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &addr.sa, mask, ul_proto);
6615 if (ul_proto != IPSEC_ULPROTO_ANY) {
6616 switch (sp->spidx.dst.sa.sa_family) {
6618 if (sp->spidx.dst.sin.sin_port != IPSEC_PORT_ANY) {
6619 addr.sin.sin_port = sp->spidx.dst.sin.sin_port;
6620 mask = sp->spidx.prefd;
6624 if (sp->spidx.dst.sin6.sin6_port != IPSEC_PORT_ANY) {
6625 addr.sin6.sin6_port =
6626 sp->spidx.dst.sin6.sin6_port;
6627 mask = sp->spidx.prefd;
6634 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &addr.sa, mask, ul_proto);
6641 /* XXX proxy address (optional) */
6644 * Set sadb_x_policy. This is KAME extension to RFC2367.
6647 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id,
6657 * Set sadb_x_sa2 extension if saidx->reqid is not zero.
6658 * This is FreeBSD extension to RFC2367.
6660 if (saidx->reqid != 0) {
6661 m = key_setsadbxsa2(saidx->mode, 0, saidx->reqid);
6668 /* XXX identity (optional) */
6670 if (idexttype && fqdn) {
6671 /* create identity extension (FQDN) */
6672 struct sadb_ident *id;
6675 fqdnlen = strlen(fqdn) + 1; /* +1 for terminating-NUL */
6676 id = (struct sadb_ident *)p;
6677 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6678 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6679 id->sadb_ident_exttype = idexttype;
6680 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6681 bcopy(fqdn, id + 1, fqdnlen);
6682 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6686 /* create identity extension (USERFQDN) */
6687 struct sadb_ident *id;
6691 /* +1 for terminating-NUL */
6692 userfqdnlen = strlen(userfqdn) + 1;
6695 id = (struct sadb_ident *)p;
6696 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6697 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6698 id->sadb_ident_exttype = idexttype;
6699 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6700 /* XXX is it correct? */
6701 if (curproc && curproc->p_cred)
6702 id->sadb_ident_id = curproc->p_cred->p_ruid;
6703 if (userfqdn && userfqdnlen)
6704 bcopy(userfqdn, id + 1, userfqdnlen);
6705 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6709 /* XXX sensitivity (optional) */
6711 /* create proposal/combination extension */
6712 m = key_getprop(saidx);
6715 * spec conformant: always attach proposal/combination extension,
6716 * the problem is that we have no way to attach it for ipcomp,
6717 * due to the way sadb_comb is declared in RFC2367.
6726 * outside of spec; make proposal/combination extension optional.
6732 if ((result->m_flags & M_PKTHDR) == 0) {
6737 if (result->m_len < sizeof(struct sadb_msg)) {
6738 result = m_pullup(result, sizeof(struct sadb_msg));
6739 if (result == NULL) {
6745 result->m_pkthdr.len = 0;
6746 for (m = result; m; m = m->m_next)
6747 result->m_pkthdr.len += m->m_len;
6749 mtod(result, struct sadb_msg *)->sadb_msg_len =
6750 PFKEY_UNIT64(result->m_pkthdr.len);
6753 printf("%s: SP(%p)\n", __func__, sp));
6754 KEYDBG(KEY_DATA, kdebug_secasindex(saidx, NULL));
6756 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6765 key_newacq(const struct secasindex *saidx, int *perror)
6770 acq = malloc(sizeof(*acq), M_IPSEC_SAQ, M_NOWAIT | M_ZERO);
6772 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6778 bcopy(saidx, &acq->saidx, sizeof(acq->saidx));
6779 acq->created = time_second;
6782 /* add to acqtree */
6784 seq = acq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6785 LIST_INSERT_HEAD(&V_acqtree, acq, chain);
6786 LIST_INSERT_HEAD(ACQADDRHASH_HASH(saidx), acq, addrhash);
6787 LIST_INSERT_HEAD(ACQSEQHASH_HASH(seq), acq, seqhash);
6794 key_getacq(const struct secasindex *saidx, int *perror)
6800 LIST_FOREACH(acq, ACQADDRHASH_HASH(saidx), addrhash) {
6801 if (key_cmpsaidx(&acq->saidx, saidx, CMP_EXACTLY)) {
6802 if (acq->count > V_key_blockacq_count) {
6804 * Reset counter and send message.
6805 * Also reset created time to keep ACQ for
6808 acq->created = time_second;
6813 * Increment counter and do nothing.
6814 * We send SADB_ACQUIRE message only
6815 * for each V_key_blockacq_count packet.
6828 /* allocate new entry */
6829 return (key_newacq(saidx, perror));
6833 key_acqreset(uint32_t seq)
6838 LIST_FOREACH(acq, ACQSEQHASH_HASH(seq), seqhash) {
6839 if (acq->seq == seq) {
6841 acq->created = time_second;
6851 * Mark ACQ entry as stale to remove it in key_flush_acq().
6852 * Called after successful SADB_GETSPI message.
6855 key_acqdone(const struct secasindex *saidx, uint32_t seq)
6860 LIST_FOREACH(acq, ACQSEQHASH_HASH(seq), seqhash) {
6861 if (acq->seq == seq)
6865 if (key_cmpsaidx(&acq->saidx, saidx, CMP_EXACTLY) == 0) {
6866 ipseclog((LOG_DEBUG,
6867 "%s: Mismatched saidx for ACQ %u\n", __func__, seq));
6873 ipseclog((LOG_DEBUG,
6874 "%s: ACQ %u is not found.\n", __func__, seq));
6882 static struct secspacq *
6883 key_newspacq(struct secpolicyindex *spidx)
6885 struct secspacq *acq;
6888 acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6890 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6895 bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6896 acq->created = time_second;
6899 /* add to spacqtree */
6901 LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6907 static struct secspacq *
6908 key_getspacq(struct secpolicyindex *spidx)
6910 struct secspacq *acq;
6913 LIST_FOREACH(acq, &V_spacqtree, chain) {
6914 if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6915 /* NB: return holding spacq_lock */
6925 * SADB_ACQUIRE processing,
6926 * in first situation, is receiving
6928 * from the ikmpd, and clear sequence of its secasvar entry.
6930 * In second situation, is receiving
6931 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6932 * from a user land process, and return
6933 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6936 * m will always be freed.
6939 key_acquire2(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6941 SAHTREE_RLOCK_TRACKER;
6942 struct sadb_address *src0, *dst0;
6943 struct secasindex saidx;
6944 struct secashead *sah;
6947 uint8_t mode, proto;
6949 IPSEC_ASSERT(so != NULL, ("null socket"));
6950 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6951 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6952 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6955 * Error message from KMd.
6956 * We assume that if error was occurred in IKEd, the length of PFKEY
6957 * message is equal to the size of sadb_msg structure.
6958 * We do not raise error even if error occurred in this function.
6960 if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6961 /* check sequence number */
6962 if (mhp->msg->sadb_msg_seq == 0 ||
6963 mhp->msg->sadb_msg_errno == 0) {
6964 ipseclog((LOG_DEBUG, "%s: must specify sequence "
6965 "number and errno.\n", __func__));
6968 * IKEd reported that error occurred.
6969 * XXXAE: what it expects from the kernel?
6970 * Probably we should send SADB_ACQUIRE again?
6971 * If so, reset ACQ's state.
6972 * XXXAE: it looks useless.
6974 key_acqreset(mhp->msg->sadb_msg_seq);
6981 * This message is from user land.
6984 /* map satype to proto */
6985 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6986 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6988 return key_senderror(so, m, EINVAL);
6991 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
6992 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
6993 SADB_CHECKHDR(mhp, SADB_EXT_PROPOSAL)) {
6994 ipseclog((LOG_DEBUG,
6995 "%s: invalid message: missing required header.\n",
6997 return key_senderror(so, m, EINVAL);
6999 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
7000 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
7001 SADB_CHECKLEN(mhp, SADB_EXT_PROPOSAL)) {
7002 ipseclog((LOG_DEBUG,
7003 "%s: invalid message: wrong header size.\n", __func__));
7004 return key_senderror(so, m, EINVAL);
7007 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
7008 mode = IPSEC_MODE_ANY;
7011 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
7012 ipseclog((LOG_DEBUG,
7013 "%s: invalid message: wrong header size.\n",
7015 return key_senderror(so, m, EINVAL);
7017 mode = ((struct sadb_x_sa2 *)
7018 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
7019 reqid = ((struct sadb_x_sa2 *)
7020 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
7023 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
7024 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
7026 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
7027 (struct sockaddr *)(dst0 + 1));
7029 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
7030 return key_senderror(so, m, EINVAL);
7032 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
7034 /* get a SA index */
7036 LIST_FOREACH(sah, SAHADDRHASH_HASH(&saidx), addrhash) {
7037 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
7042 ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
7043 return key_senderror(so, m, EEXIST);
7046 error = key_acquire(&saidx, NULL);
7048 ipseclog((LOG_DEBUG,
7049 "%s: error %d returned from key_acquire()\n",
7051 return key_senderror(so, m, error);
7058 * SADB_REGISTER processing.
7059 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
7062 * from the ikmpd, and register a socket to send PF_KEY messages,
7066 * If socket is detached, must free from regnode.
7068 * m will always be freed.
7071 key_register(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7073 struct secreg *reg, *newreg = NULL;
7075 IPSEC_ASSERT(so != NULL, ("null socket"));
7076 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7077 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7078 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7080 /* check for invalid register message */
7081 if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
7082 return key_senderror(so, m, EINVAL);
7084 /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
7085 if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
7088 /* check whether existing or not */
7090 LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
7091 if (reg->so == so) {
7093 ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
7095 return key_senderror(so, m, EEXIST);
7099 /* create regnode */
7100 newreg = malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
7101 if (newreg == NULL) {
7103 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7104 return key_senderror(so, m, ENOBUFS);
7108 ((struct keycb *)sotorawcb(so))->kp_registered++;
7110 /* add regnode to regtree. */
7111 LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
7117 struct sadb_msg *newmsg;
7118 struct sadb_supported *sup;
7119 u_int len, alen, elen;
7122 struct sadb_alg *alg;
7124 /* create new sadb_msg to reply. */
7126 for (i = 1; i <= SADB_AALG_MAX; i++) {
7127 if (auth_algorithm_lookup(i))
7128 alen += sizeof(struct sadb_alg);
7131 alen += sizeof(struct sadb_supported);
7133 for (i = 1; i <= SADB_EALG_MAX; i++) {
7134 if (enc_algorithm_lookup(i))
7135 elen += sizeof(struct sadb_alg);
7138 elen += sizeof(struct sadb_supported);
7140 len = sizeof(struct sadb_msg) + alen + elen;
7143 return key_senderror(so, m, ENOBUFS);
7145 MGETHDR(n, M_NOWAIT, MT_DATA);
7146 if (n != NULL && len > MHLEN) {
7147 if (!(MCLGET(n, M_NOWAIT))) {
7153 return key_senderror(so, m, ENOBUFS);
7155 n->m_pkthdr.len = n->m_len = len;
7159 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
7160 newmsg = mtod(n, struct sadb_msg *);
7161 newmsg->sadb_msg_errno = 0;
7162 newmsg->sadb_msg_len = PFKEY_UNIT64(len);
7163 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
7165 /* for authentication algorithm */
7167 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
7168 sup->sadb_supported_len = PFKEY_UNIT64(alen);
7169 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
7170 off += PFKEY_ALIGN8(sizeof(*sup));
7172 for (i = 1; i <= SADB_AALG_MAX; i++) {
7173 const struct auth_hash *aalgo;
7174 u_int16_t minkeysize, maxkeysize;
7176 aalgo = auth_algorithm_lookup(i);
7179 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
7180 alg->sadb_alg_id = i;
7181 alg->sadb_alg_ivlen = 0;
7182 key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
7183 alg->sadb_alg_minbits = _BITS(minkeysize);
7184 alg->sadb_alg_maxbits = _BITS(maxkeysize);
7185 off += PFKEY_ALIGN8(sizeof(*alg));
7189 /* for encryption algorithm */
7191 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
7192 sup->sadb_supported_len = PFKEY_UNIT64(elen);
7193 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
7194 off += PFKEY_ALIGN8(sizeof(*sup));
7196 for (i = 1; i <= SADB_EALG_MAX; i++) {
7197 const struct enc_xform *ealgo;
7199 ealgo = enc_algorithm_lookup(i);
7202 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
7203 alg->sadb_alg_id = i;
7204 alg->sadb_alg_ivlen = ealgo->ivsize;
7205 alg->sadb_alg_minbits = _BITS(ealgo->minkey);
7206 alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
7207 off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
7211 IPSEC_ASSERT(off == len,
7212 ("length assumption failed (off %u len %u)", off, len));
7215 return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
7220 * free secreg entry registered.
7221 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
7224 key_freereg(struct socket *so)
7229 IPSEC_ASSERT(so != NULL, ("NULL so"));
7232 * check whether existing or not.
7233 * check all type of SA, because there is a potential that
7234 * one socket is registered to multiple type of SA.
7237 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7238 LIST_FOREACH(reg, &V_regtree[i], chain) {
7239 if (reg->so == so && __LIST_CHAINED(reg)) {
7240 LIST_REMOVE(reg, chain);
7241 free(reg, M_IPSEC_SAR);
7250 * SADB_EXPIRE processing
7252 * <base, SA, SA2, lifetime(C and one of HS), address(SD)>
7254 * NOTE: We send only soft lifetime extension.
7257 * others : error number
7260 key_expire(struct secasvar *sav, int hard)
7262 struct mbuf *result = NULL, *m;
7263 struct sadb_lifetime *lt;
7264 uint32_t replay_count;
7268 IPSEC_ASSERT (sav != NULL, ("null sav"));
7269 IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
7272 printf("%s: SA(%p) expired %s lifetime\n", __func__,
7273 sav, hard ? "hard": "soft"));
7274 KEYDBG(KEY_DATA, kdebug_secasv(sav));
7275 /* set msg header */
7276 satype = key_proto2satype(sav->sah->saidx.proto);
7277 IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
7278 m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
7285 /* create SA extension */
7286 m = key_setsadbsa(sav);
7293 /* create SA extension */
7295 replay_count = sav->replay ? sav->replay->count : 0;
7296 SECASVAR_UNLOCK(sav);
7298 m = key_setsadbxsa2(sav->sah->saidx.mode, replay_count,
7299 sav->sah->saidx.reqid);
7306 if (sav->replay && sav->replay->wsize > UINT8_MAX) {
7307 m = key_setsadbxsareplay(sav->replay->wsize);
7315 /* create lifetime extension (current and soft) */
7316 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
7317 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
7324 bzero(mtod(m, caddr_t), len);
7325 lt = mtod(m, struct sadb_lifetime *);
7326 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7327 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
7328 lt->sadb_lifetime_allocations =
7329 (uint32_t)counter_u64_fetch(sav->lft_c_allocations);
7330 lt->sadb_lifetime_bytes =
7331 counter_u64_fetch(sav->lft_c_bytes);
7332 lt->sadb_lifetime_addtime = sav->created;
7333 lt->sadb_lifetime_usetime = sav->firstused;
7334 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
7335 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7337 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
7338 lt->sadb_lifetime_allocations = sav->lft_h->allocations;
7339 lt->sadb_lifetime_bytes = sav->lft_h->bytes;
7340 lt->sadb_lifetime_addtime = sav->lft_h->addtime;
7341 lt->sadb_lifetime_usetime = sav->lft_h->usetime;
7343 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
7344 lt->sadb_lifetime_allocations = sav->lft_s->allocations;
7345 lt->sadb_lifetime_bytes = sav->lft_s->bytes;
7346 lt->sadb_lifetime_addtime = sav->lft_s->addtime;
7347 lt->sadb_lifetime_usetime = sav->lft_s->usetime;
7351 /* set sadb_address for source */
7352 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
7353 &sav->sah->saidx.src.sa,
7354 FULLMASK, IPSEC_ULPROTO_ANY);
7361 /* set sadb_address for destination */
7362 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
7363 &sav->sah->saidx.dst.sa,
7364 FULLMASK, IPSEC_ULPROTO_ANY);
7372 * XXX-BZ Handle NAT-T extensions here.
7373 * XXXAE: it doesn't seem quite useful. IKEs should not depend on
7374 * this information, we report only significant SA fields.
7377 if ((result->m_flags & M_PKTHDR) == 0) {
7382 if (result->m_len < sizeof(struct sadb_msg)) {
7383 result = m_pullup(result, sizeof(struct sadb_msg));
7384 if (result == NULL) {
7390 result->m_pkthdr.len = 0;
7391 for (m = result; m; m = m->m_next)
7392 result->m_pkthdr.len += m->m_len;
7394 mtod(result, struct sadb_msg *)->sadb_msg_len =
7395 PFKEY_UNIT64(result->m_pkthdr.len);
7397 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7406 key_freesah_flushed(struct secashead_queue *flushq)
7408 struct secashead *sah, *nextsah;
7409 struct secasvar *sav, *nextsav;
7411 sah = TAILQ_FIRST(flushq);
7412 while (sah != NULL) {
7413 sav = TAILQ_FIRST(&sah->savtree_larval);
7414 while (sav != NULL) {
7415 nextsav = TAILQ_NEXT(sav, chain);
7416 TAILQ_REMOVE(&sah->savtree_larval, sav, chain);
7417 key_freesav(&sav); /* release last reference */
7418 key_freesah(&sah); /* release reference from SAV */
7421 sav = TAILQ_FIRST(&sah->savtree_alive);
7422 while (sav != NULL) {
7423 nextsav = TAILQ_NEXT(sav, chain);
7424 TAILQ_REMOVE(&sah->savtree_alive, sav, chain);
7425 key_freesav(&sav); /* release last reference */
7426 key_freesah(&sah); /* release reference from SAV */
7429 nextsah = TAILQ_NEXT(sah, chain);
7430 key_freesah(&sah); /* release last reference */
7436 * SADB_FLUSH processing
7439 * from the ikmpd, and free all entries in secastree.
7443 * NOTE: to do is only marking SADB_SASTATE_DEAD.
7445 * m will always be freed.
7448 key_flush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7450 struct secashead_queue flushq;
7451 struct sadb_msg *newmsg;
7452 struct secashead *sah, *nextsah;
7453 struct secasvar *sav;
7457 IPSEC_ASSERT(so != NULL, ("null socket"));
7458 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7459 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7461 /* map satype to proto */
7462 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7463 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7465 return key_senderror(so, m, EINVAL);
7468 printf("%s: proto %u\n", __func__, proto));
7470 TAILQ_INIT(&flushq);
7471 if (proto == IPSEC_PROTO_ANY) {
7472 /* no SATYPE specified, i.e. flushing all SA. */
7474 /* Move all SAHs into flushq */
7475 TAILQ_CONCAT(&flushq, &V_sahtree, chain);
7476 /* Flush all buckets in SPI hash */
7477 for (i = 0; i < V_savhash_mask + 1; i++)
7478 LIST_INIT(&V_savhashtbl[i]);
7479 /* Flush all buckets in SAHADDRHASH */
7480 for (i = 0; i < V_sahaddrhash_mask + 1; i++)
7481 LIST_INIT(&V_sahaddrhashtbl[i]);
7482 /* Mark all SAHs as unlinked */
7483 TAILQ_FOREACH(sah, &flushq, chain) {
7484 sah->state = SADB_SASTATE_DEAD;
7486 * Callout handler makes its job using
7487 * RLOCK and drain queues. In case, when this
7488 * function will be called just before it
7489 * acquires WLOCK, we need to mark SAs as
7490 * unlinked to prevent second unlink.
7492 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7493 sav->state = SADB_SASTATE_DEAD;
7495 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7496 sav->state = SADB_SASTATE_DEAD;
7502 sah = TAILQ_FIRST(&V_sahtree);
7503 while (sah != NULL) {
7504 IPSEC_ASSERT(sah->state != SADB_SASTATE_DEAD,
7505 ("DEAD SAH %p in SADB_FLUSH", sah));
7506 nextsah = TAILQ_NEXT(sah, chain);
7507 if (sah->saidx.proto != proto) {
7511 sah->state = SADB_SASTATE_DEAD;
7512 TAILQ_REMOVE(&V_sahtree, sah, chain);
7513 LIST_REMOVE(sah, addrhash);
7514 /* Unlink all SAs from SPI hash */
7515 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7516 LIST_REMOVE(sav, spihash);
7517 sav->state = SADB_SASTATE_DEAD;
7519 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7520 LIST_REMOVE(sav, spihash);
7521 sav->state = SADB_SASTATE_DEAD;
7523 /* Add SAH into flushq */
7524 TAILQ_INSERT_HEAD(&flushq, sah, chain);
7530 key_freesah_flushed(&flushq);
7531 /* Free all queued SAs and SAHs */
7532 if (m->m_len < sizeof(struct sadb_msg) ||
7533 sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7534 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7535 return key_senderror(so, m, ENOBUFS);
7541 m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7542 newmsg = mtod(m, struct sadb_msg *);
7543 newmsg->sadb_msg_errno = 0;
7544 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7546 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7550 * SADB_DUMP processing
7551 * dump all entries including status of DEAD in SAD.
7554 * from the ikmpd, and dump all secasvar leaves
7559 * m will always be freed.
7562 key_dump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7564 SAHTREE_RLOCK_TRACKER;
7565 struct secashead *sah;
7566 struct secasvar *sav;
7569 uint8_t proto, satype;
7571 IPSEC_ASSERT(so != NULL, ("null socket"));
7572 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7573 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7574 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7576 /* map satype to proto */
7577 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7578 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7580 return key_senderror(so, m, EINVAL);
7583 /* count sav entries to be sent to the userland. */
7586 TAILQ_FOREACH(sah, &V_sahtree, chain) {
7587 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
7588 proto != sah->saidx.proto)
7591 TAILQ_FOREACH(sav, &sah->savtree_larval, chain)
7593 TAILQ_FOREACH(sav, &sah->savtree_alive, chain)
7599 return key_senderror(so, m, ENOENT);
7602 /* send this to the userland, one at a time. */
7603 TAILQ_FOREACH(sah, &V_sahtree, chain) {
7604 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
7605 proto != sah->saidx.proto)
7608 /* map proto to satype */
7609 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7611 ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7612 "SAD.\n", __func__));
7613 return key_senderror(so, m, EINVAL);
7615 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7616 n = key_setdumpsa(sav, SADB_DUMP, satype,
7617 --cnt, mhp->msg->sadb_msg_pid);
7620 return key_senderror(so, m, ENOBUFS);
7622 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7624 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7625 n = key_setdumpsa(sav, SADB_DUMP, satype,
7626 --cnt, mhp->msg->sadb_msg_pid);
7629 return key_senderror(so, m, ENOBUFS);
7631 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7639 * SADB_X_PROMISC processing
7641 * m will always be freed.
7644 key_promisc(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7648 IPSEC_ASSERT(so != NULL, ("null socket"));
7649 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7650 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7651 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7653 olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7655 if (olen < sizeof(struct sadb_msg)) {
7657 return key_senderror(so, m, EINVAL);
7662 } else if (olen == sizeof(struct sadb_msg)) {
7663 /* enable/disable promisc mode */
7666 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7667 return key_senderror(so, m, EINVAL);
7668 mhp->msg->sadb_msg_errno = 0;
7669 switch (mhp->msg->sadb_msg_satype) {
7672 kp->kp_promisc = mhp->msg->sadb_msg_satype;
7675 return key_senderror(so, m, EINVAL);
7678 /* send the original message back to everyone */
7679 mhp->msg->sadb_msg_errno = 0;
7680 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7682 /* send packet as is */
7684 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7686 /* TODO: if sadb_msg_seq is specified, send to specific pid */
7687 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7691 static int (*key_typesw[])(struct socket *, struct mbuf *,
7692 const struct sadb_msghdr *) = {
7693 NULL, /* SADB_RESERVED */
7694 key_getspi, /* SADB_GETSPI */
7695 key_update, /* SADB_UPDATE */
7696 key_add, /* SADB_ADD */
7697 key_delete, /* SADB_DELETE */
7698 key_get, /* SADB_GET */
7699 key_acquire2, /* SADB_ACQUIRE */
7700 key_register, /* SADB_REGISTER */
7701 NULL, /* SADB_EXPIRE */
7702 key_flush, /* SADB_FLUSH */
7703 key_dump, /* SADB_DUMP */
7704 key_promisc, /* SADB_X_PROMISC */
7705 NULL, /* SADB_X_PCHANGE */
7706 key_spdadd, /* SADB_X_SPDUPDATE */
7707 key_spdadd, /* SADB_X_SPDADD */
7708 key_spddelete, /* SADB_X_SPDDELETE */
7709 key_spdget, /* SADB_X_SPDGET */
7710 NULL, /* SADB_X_SPDACQUIRE */
7711 key_spddump, /* SADB_X_SPDDUMP */
7712 key_spdflush, /* SADB_X_SPDFLUSH */
7713 key_spdadd, /* SADB_X_SPDSETIDX */
7714 NULL, /* SADB_X_SPDEXPIRE */
7715 key_spddelete2, /* SADB_X_SPDDELETE2 */
7719 * parse sadb_msg buffer to process PFKEYv2,
7720 * and create a data to response if needed.
7721 * I think to be dealed with mbuf directly.
7723 * msgp : pointer to pointer to a received buffer pulluped.
7724 * This is rewrited to response.
7725 * so : pointer to socket.
7727 * length for buffer to send to user process.
7730 key_parse(struct mbuf *m, struct socket *so)
7732 struct sadb_msg *msg;
7733 struct sadb_msghdr mh;
7738 IPSEC_ASSERT(so != NULL, ("null socket"));
7739 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7741 if (m->m_len < sizeof(struct sadb_msg)) {
7742 m = m_pullup(m, sizeof(struct sadb_msg));
7746 msg = mtod(m, struct sadb_msg *);
7747 orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7748 target = KEY_SENDUP_ONE;
7750 if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len != orglen) {
7751 ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7752 PFKEYSTAT_INC(out_invlen);
7757 if (msg->sadb_msg_version != PF_KEY_V2) {
7758 ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7759 __func__, msg->sadb_msg_version));
7760 PFKEYSTAT_INC(out_invver);
7765 if (msg->sadb_msg_type > SADB_MAX) {
7766 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7767 __func__, msg->sadb_msg_type));
7768 PFKEYSTAT_INC(out_invmsgtype);
7773 /* for old-fashioned code - should be nuked */
7774 if (m->m_pkthdr.len > MCLBYTES) {
7781 MGETHDR(n, M_NOWAIT, MT_DATA);
7782 if (n && m->m_pkthdr.len > MHLEN) {
7783 if (!(MCLGET(n, M_NOWAIT))) {
7792 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7793 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7799 /* align the mbuf chain so that extensions are in contiguous region. */
7800 error = key_align(m, &mh);
7806 /* We use satype as scope mask for spddump */
7807 if (msg->sadb_msg_type == SADB_X_SPDDUMP) {
7808 switch (msg->sadb_msg_satype) {
7809 case IPSEC_POLICYSCOPE_ANY:
7810 case IPSEC_POLICYSCOPE_GLOBAL:
7811 case IPSEC_POLICYSCOPE_IFNET:
7812 case IPSEC_POLICYSCOPE_PCB:
7815 ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7816 __func__, msg->sadb_msg_type));
7817 PFKEYSTAT_INC(out_invsatype);
7822 switch (msg->sadb_msg_satype) { /* check SA type */
7823 case SADB_SATYPE_UNSPEC:
7824 switch (msg->sadb_msg_type) {
7832 ipseclog((LOG_DEBUG, "%s: must specify satype "
7833 "when msg type=%u.\n", __func__,
7834 msg->sadb_msg_type));
7835 PFKEYSTAT_INC(out_invsatype);
7840 case SADB_SATYPE_AH:
7841 case SADB_SATYPE_ESP:
7842 case SADB_X_SATYPE_IPCOMP:
7843 case SADB_X_SATYPE_TCPSIGNATURE:
7844 switch (msg->sadb_msg_type) {
7846 case SADB_X_SPDDELETE:
7848 case SADB_X_SPDFLUSH:
7849 case SADB_X_SPDSETIDX:
7850 case SADB_X_SPDUPDATE:
7851 case SADB_X_SPDDELETE2:
7852 ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7853 __func__, msg->sadb_msg_type));
7854 PFKEYSTAT_INC(out_invsatype);
7859 case SADB_SATYPE_RSVP:
7860 case SADB_SATYPE_OSPFV2:
7861 case SADB_SATYPE_RIPV2:
7862 case SADB_SATYPE_MIP:
7863 ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7864 __func__, msg->sadb_msg_satype));
7865 PFKEYSTAT_INC(out_invsatype);
7868 case 1: /* XXX: What does it do? */
7869 if (msg->sadb_msg_type == SADB_X_PROMISC)
7873 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7874 __func__, msg->sadb_msg_satype));
7875 PFKEYSTAT_INC(out_invsatype);
7881 /* check field of upper layer protocol and address family */
7882 if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7883 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7884 struct sadb_address *src0, *dst0;
7887 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7888 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7890 /* check upper layer protocol */
7891 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7892 ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7893 "mismatched.\n", __func__));
7894 PFKEYSTAT_INC(out_invaddr);
7900 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7901 PFKEY_ADDR_SADDR(dst0)->sa_family) {
7902 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7904 PFKEYSTAT_INC(out_invaddr);
7908 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7909 PFKEY_ADDR_SADDR(dst0)->sa_len) {
7910 ipseclog((LOG_DEBUG, "%s: address struct size "
7911 "mismatched.\n", __func__));
7912 PFKEYSTAT_INC(out_invaddr);
7917 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7919 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7920 sizeof(struct sockaddr_in)) {
7921 PFKEYSTAT_INC(out_invaddr);
7927 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7928 sizeof(struct sockaddr_in6)) {
7929 PFKEYSTAT_INC(out_invaddr);
7935 ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7937 PFKEYSTAT_INC(out_invaddr);
7938 error = EAFNOSUPPORT;
7942 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7944 plen = sizeof(struct in_addr) << 3;
7947 plen = sizeof(struct in6_addr) << 3;
7950 plen = 0; /*fool gcc*/
7954 /* check max prefix length */
7955 if (src0->sadb_address_prefixlen > plen ||
7956 dst0->sadb_address_prefixlen > plen) {
7957 ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7959 PFKEYSTAT_INC(out_invaddr);
7965 * prefixlen == 0 is valid because there can be a case when
7966 * all addresses are matched.
7970 if (msg->sadb_msg_type >= nitems(key_typesw) ||
7971 key_typesw[msg->sadb_msg_type] == NULL) {
7972 PFKEYSTAT_INC(out_invmsgtype);
7977 return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7980 msg->sadb_msg_errno = error;
7981 return key_sendup_mbuf(so, m, target);
7985 key_senderror(struct socket *so, struct mbuf *m, int code)
7987 struct sadb_msg *msg;
7989 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7990 ("mbuf too small, len %u", m->m_len));
7992 msg = mtod(m, struct sadb_msg *);
7993 msg->sadb_msg_errno = code;
7994 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7998 * set the pointer to each header into message buffer.
7999 * m will be freed on error.
8000 * XXX larger-than-MCLBYTES extension?
8003 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
8006 struct sadb_ext *ext;
8011 IPSEC_ASSERT(m != NULL, ("null mbuf"));
8012 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
8013 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
8014 ("mbuf too small, len %u", m->m_len));
8017 bzero(mhp, sizeof(*mhp));
8019 mhp->msg = mtod(m, struct sadb_msg *);
8020 mhp->ext[0] = (struct sadb_ext *)mhp->msg; /*XXX backward compat */
8022 end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
8023 extlen = end; /*just in case extlen is not updated*/
8024 for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
8025 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
8027 /* m is already freed */
8030 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
8033 switch (ext->sadb_ext_type) {
8035 case SADB_EXT_ADDRESS_SRC:
8036 case SADB_EXT_ADDRESS_DST:
8037 case SADB_EXT_ADDRESS_PROXY:
8038 case SADB_EXT_LIFETIME_CURRENT:
8039 case SADB_EXT_LIFETIME_HARD:
8040 case SADB_EXT_LIFETIME_SOFT:
8041 case SADB_EXT_KEY_AUTH:
8042 case SADB_EXT_KEY_ENCRYPT:
8043 case SADB_EXT_IDENTITY_SRC:
8044 case SADB_EXT_IDENTITY_DST:
8045 case SADB_EXT_SENSITIVITY:
8046 case SADB_EXT_PROPOSAL:
8047 case SADB_EXT_SUPPORTED_AUTH:
8048 case SADB_EXT_SUPPORTED_ENCRYPT:
8049 case SADB_EXT_SPIRANGE:
8050 case SADB_X_EXT_POLICY:
8051 case SADB_X_EXT_SA2:
8052 case SADB_X_EXT_NAT_T_TYPE:
8053 case SADB_X_EXT_NAT_T_SPORT:
8054 case SADB_X_EXT_NAT_T_DPORT:
8055 case SADB_X_EXT_NAT_T_OAI:
8056 case SADB_X_EXT_NAT_T_OAR:
8057 case SADB_X_EXT_NAT_T_FRAG:
8058 case SADB_X_EXT_SA_REPLAY:
8059 case SADB_X_EXT_NEW_ADDRESS_SRC:
8060 case SADB_X_EXT_NEW_ADDRESS_DST:
8061 /* duplicate check */
8063 * XXX Are there duplication payloads of either
8064 * KEY_AUTH or KEY_ENCRYPT ?
8066 if (mhp->ext[ext->sadb_ext_type] != NULL) {
8067 ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
8068 "%u\n", __func__, ext->sadb_ext_type));
8070 PFKEYSTAT_INC(out_dupext);
8075 ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
8076 __func__, ext->sadb_ext_type));
8078 PFKEYSTAT_INC(out_invexttype);
8082 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
8084 if (key_validate_ext(ext, extlen)) {
8086 PFKEYSTAT_INC(out_invlen);
8090 n = m_pulldown(m, off, extlen, &toff);
8092 /* m is already freed */
8095 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
8097 mhp->ext[ext->sadb_ext_type] = ext;
8098 mhp->extoff[ext->sadb_ext_type] = off;
8099 mhp->extlen[ext->sadb_ext_type] = extlen;
8104 PFKEYSTAT_INC(out_invlen);
8112 key_validate_ext(const struct sadb_ext *ext, int len)
8114 const struct sockaddr *sa;
8115 enum { NONE, ADDR } checktype = NONE;
8117 const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
8119 if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
8122 /* if it does not match minimum/maximum length, bail */
8123 if (ext->sadb_ext_type >= nitems(minsize) ||
8124 ext->sadb_ext_type >= nitems(maxsize))
8126 if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
8128 if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
8131 /* more checks based on sadb_ext_type XXX need more */
8132 switch (ext->sadb_ext_type) {
8133 case SADB_EXT_ADDRESS_SRC:
8134 case SADB_EXT_ADDRESS_DST:
8135 case SADB_EXT_ADDRESS_PROXY:
8136 case SADB_X_EXT_NAT_T_OAI:
8137 case SADB_X_EXT_NAT_T_OAR:
8138 case SADB_X_EXT_NEW_ADDRESS_SRC:
8139 case SADB_X_EXT_NEW_ADDRESS_DST:
8140 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
8143 case SADB_EXT_IDENTITY_SRC:
8144 case SADB_EXT_IDENTITY_DST:
8145 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
8146 SADB_X_IDENTTYPE_ADDR) {
8147 baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
8157 switch (checktype) {
8161 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
8162 if (len < baselen + sal)
8164 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
8177 TUNABLE_INT_FETCH("net.key.spdcache.maxentries",
8178 &V_key_spdcache_maxentries);
8179 TUNABLE_INT_FETCH("net.key.spdcache.threshold",
8180 &V_key_spdcache_threshold);
8182 if (V_key_spdcache_maxentries) {
8183 V_key_spdcache_maxentries = MAX(V_key_spdcache_maxentries,
8184 SPDCACHE_MAX_ENTRIES_PER_HASH);
8185 V_spdcachehashtbl = hashinit(V_key_spdcache_maxentries /
8186 SPDCACHE_MAX_ENTRIES_PER_HASH,
8187 M_IPSEC_SPDCACHE, &V_spdcachehash_mask);
8188 V_key_spdcache_maxentries = (V_spdcachehash_mask + 1)
8189 * SPDCACHE_MAX_ENTRIES_PER_HASH;
8191 V_spdcache_lock = malloc(sizeof(struct mtx) *
8192 (V_spdcachehash_mask + 1),
8193 M_IPSEC_SPDCACHE, M_WAITOK|M_ZERO);
8195 for (i = 0; i < V_spdcachehash_mask + 1; ++i)
8196 SPDCACHE_LOCK_INIT(i);
8200 struct spdcache_entry *
8201 spdcache_entry_alloc(const struct secpolicyindex *spidx, struct secpolicy *sp)
8203 struct spdcache_entry *entry;
8205 entry = malloc(sizeof(struct spdcache_entry),
8206 M_IPSEC_SPDCACHE, M_NOWAIT|M_ZERO);
8213 entry->spidx = *spidx;
8220 spdcache_entry_free(struct spdcache_entry *entry)
8223 if (entry->sp != NULL)
8224 key_freesp(&entry->sp);
8225 free(entry, M_IPSEC_SPDCACHE);
8229 spdcache_clear(void)
8231 struct spdcache_entry *entry;
8234 for (i = 0; i < V_spdcachehash_mask + 1; ++i) {
8236 while (!LIST_EMPTY(&V_spdcachehashtbl[i])) {
8237 entry = LIST_FIRST(&V_spdcachehashtbl[i]);
8238 LIST_REMOVE(entry, chain);
8239 spdcache_entry_free(entry);
8247 spdcache_destroy(void)
8251 if (SPDCACHE_ENABLED()) {
8253 hashdestroy(V_spdcachehashtbl, M_IPSEC_SPDCACHE, V_spdcachehash_mask);
8255 for (i = 0; i < V_spdcachehash_mask + 1; ++i)
8256 SPDCACHE_LOCK_DESTROY(i);
8258 free(V_spdcache_lock, M_IPSEC_SPDCACHE);
8267 for (i = 0; i < IPSEC_DIR_MAX; i++) {
8268 TAILQ_INIT(&V_sptree[i]);
8269 TAILQ_INIT(&V_sptree_ifnet[i]);
8272 V_key_lft_zone = uma_zcreate("IPsec SA lft_c",
8273 sizeof(uint64_t) * 2, NULL, NULL, NULL, NULL,
8274 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
8276 TAILQ_INIT(&V_sahtree);
8277 V_sphashtbl = hashinit(SPHASH_NHASH, M_IPSEC_SP, &V_sphash_mask);
8278 V_savhashtbl = hashinit(SAVHASH_NHASH, M_IPSEC_SA, &V_savhash_mask);
8279 V_sahaddrhashtbl = hashinit(SAHHASH_NHASH, M_IPSEC_SAH,
8280 &V_sahaddrhash_mask);
8281 V_acqaddrhashtbl = hashinit(ACQHASH_NHASH, M_IPSEC_SAQ,
8282 &V_acqaddrhash_mask);
8283 V_acqseqhashtbl = hashinit(ACQHASH_NHASH, M_IPSEC_SAQ,
8284 &V_acqseqhash_mask);
8288 for (i = 0; i <= SADB_SATYPE_MAX; i++)
8289 LIST_INIT(&V_regtree[i]);
8291 LIST_INIT(&V_acqtree);
8292 LIST_INIT(&V_spacqtree);
8294 if (!IS_DEFAULT_VNET(curvnet))
8298 REGTREE_LOCK_INIT();
8299 SAHTREE_LOCK_INIT();
8303 #ifndef IPSEC_DEBUG2
8304 callout_init(&key_timer, 1);
8305 callout_reset(&key_timer, hz, key_timehandler, NULL);
8306 #endif /*IPSEC_DEBUG2*/
8308 /* initialize key statistics */
8309 keystat.getspi_count = 1;
8312 printf("IPsec: Initialized Security Association Processing.\n");
8319 struct secashead_queue sahdrainq;
8320 struct secpolicy_queue drainq;
8321 struct secpolicy *sp, *nextsp;
8322 struct secacq *acq, *nextacq;
8323 struct secspacq *spacq, *nextspacq;
8324 struct secashead *sah;
8325 struct secasvar *sav;
8330 * XXX: can we just call free() for each object without
8331 * walking through safe way with releasing references?
8333 TAILQ_INIT(&drainq);
8335 for (i = 0; i < IPSEC_DIR_MAX; i++) {
8336 TAILQ_CONCAT(&drainq, &V_sptree[i], chain);
8337 TAILQ_CONCAT(&drainq, &V_sptree_ifnet[i], chain);
8339 for (i = 0; i < V_sphash_mask + 1; i++)
8340 LIST_INIT(&V_sphashtbl[i]);
8344 sp = TAILQ_FIRST(&drainq);
8345 while (sp != NULL) {
8346 nextsp = TAILQ_NEXT(sp, chain);
8351 TAILQ_INIT(&sahdrainq);
8353 TAILQ_CONCAT(&sahdrainq, &V_sahtree, chain);
8354 for (i = 0; i < V_savhash_mask + 1; i++)
8355 LIST_INIT(&V_savhashtbl[i]);
8356 for (i = 0; i < V_sahaddrhash_mask + 1; i++)
8357 LIST_INIT(&V_sahaddrhashtbl[i]);
8358 TAILQ_FOREACH(sah, &sahdrainq, chain) {
8359 sah->state = SADB_SASTATE_DEAD;
8360 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
8361 sav->state = SADB_SASTATE_DEAD;
8363 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
8364 sav->state = SADB_SASTATE_DEAD;
8369 key_freesah_flushed(&sahdrainq);
8370 hashdestroy(V_sphashtbl, M_IPSEC_SP, V_sphash_mask);
8371 hashdestroy(V_savhashtbl, M_IPSEC_SA, V_savhash_mask);
8372 hashdestroy(V_sahaddrhashtbl, M_IPSEC_SAH, V_sahaddrhash_mask);
8375 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
8376 LIST_FOREACH(reg, &V_regtree[i], chain) {
8377 if (__LIST_CHAINED(reg)) {
8378 LIST_REMOVE(reg, chain);
8379 free(reg, M_IPSEC_SAR);
8387 acq = LIST_FIRST(&V_acqtree);
8388 while (acq != NULL) {
8389 nextacq = LIST_NEXT(acq, chain);
8390 LIST_REMOVE(acq, chain);
8391 free(acq, M_IPSEC_SAQ);
8394 for (i = 0; i < V_acqaddrhash_mask + 1; i++)
8395 LIST_INIT(&V_acqaddrhashtbl[i]);
8396 for (i = 0; i < V_acqseqhash_mask + 1; i++)
8397 LIST_INIT(&V_acqseqhashtbl[i]);
8401 for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
8402 spacq = nextspacq) {
8403 nextspacq = LIST_NEXT(spacq, chain);
8404 if (__LIST_CHAINED(spacq)) {
8405 LIST_REMOVE(spacq, chain);
8406 free(spacq, M_IPSEC_SAQ);
8410 hashdestroy(V_acqaddrhashtbl, M_IPSEC_SAQ, V_acqaddrhash_mask);
8411 hashdestroy(V_acqseqhashtbl, M_IPSEC_SAQ, V_acqseqhash_mask);
8412 uma_zdestroy(V_key_lft_zone);
8414 if (!IS_DEFAULT_VNET(curvnet))
8416 #ifndef IPSEC_DEBUG2
8417 callout_drain(&key_timer);
8419 SPTREE_LOCK_DESTROY();
8420 REGTREE_LOCK_DESTROY();
8421 SAHTREE_LOCK_DESTROY();
8423 SPACQ_LOCK_DESTROY();
8427 /* record data transfer on SA, and update timestamps */
8429 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
8431 IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
8432 IPSEC_ASSERT(m != NULL, ("Null mbuf"));
8435 * XXX Currently, there is a difference of bytes size
8436 * between inbound and outbound processing.
8438 counter_u64_add(sav->lft_c_bytes, m->m_pkthdr.len);
8441 * We use the number of packets as the unit of
8442 * allocations. We increment the variable
8443 * whenever {esp,ah}_{in,out}put is called.
8445 counter_u64_add(sav->lft_c_allocations, 1);
8448 * NOTE: We record CURRENT usetime by using wall clock,
8449 * in seconds. HARD and SOFT lifetime are measured by the time
8450 * difference (again in seconds) from usetime.
8454 * -----+-----+--------+---> t
8455 * <--------------> HARD
8458 if (sav->firstused == 0)
8459 sav->firstused = time_second;
8463 * Take one of the kernel's security keys and convert it into a PF_KEY
8464 * structure within an mbuf, suitable for sending up to a waiting
8465 * application in user land.
8468 * src: A pointer to a kernel security key.
8469 * exttype: Which type of key this is. Refer to the PF_KEY data structures.
8471 * a valid mbuf or NULL indicating an error
8475 static struct mbuf *
8476 key_setkey(struct seckey *src, uint16_t exttype)
8485 len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8486 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
8491 p = mtod(m, struct sadb_key *);
8493 p->sadb_key_len = PFKEY_UNIT64(len);
8494 p->sadb_key_exttype = exttype;
8495 p->sadb_key_bits = src->bits;
8496 bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8502 * Take one of the kernel's lifetime data structures and convert it
8503 * into a PF_KEY structure within an mbuf, suitable for sending up to
8504 * a waiting application in user land.
8507 * src: A pointer to a kernel lifetime structure.
8508 * exttype: Which type of lifetime this is. Refer to the PF_KEY
8509 * data structures for more information.
8511 * a valid mbuf or NULL indicating an error
8515 static struct mbuf *
8516 key_setlifetime(struct seclifetime *src, uint16_t exttype)
8518 struct mbuf *m = NULL;
8519 struct sadb_lifetime *p;
8520 int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8525 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
8530 p = mtod(m, struct sadb_lifetime *);
8533 p->sadb_lifetime_len = PFKEY_UNIT64(len);
8534 p->sadb_lifetime_exttype = exttype;
8535 p->sadb_lifetime_allocations = src->allocations;
8536 p->sadb_lifetime_bytes = src->bytes;
8537 p->sadb_lifetime_addtime = src->addtime;
8538 p->sadb_lifetime_usetime = src->usetime;
8544 const struct enc_xform *
8545 enc_algorithm_lookup(int alg)
8549 for (i = 0; i < nitems(supported_ealgs); i++)
8550 if (alg == supported_ealgs[i].sadb_alg)
8551 return (supported_ealgs[i].xform);
8555 const struct auth_hash *
8556 auth_algorithm_lookup(int alg)
8560 for (i = 0; i < nitems(supported_aalgs); i++)
8561 if (alg == supported_aalgs[i].sadb_alg)
8562 return (supported_aalgs[i].xform);
8566 const struct comp_algo *
8567 comp_algorithm_lookup(int alg)
8571 for (i = 0; i < nitems(supported_calgs); i++)
8572 if (alg == supported_calgs[i].sadb_alg)
8573 return (supported_calgs[i].xform);