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)) {
875 * allocating a SP for OUTBOUND or INBOUND packet.
876 * Must call key_freesp() later.
877 * OUT: NULL: not found
878 * others: found and return the pointer.
881 key_allocsp(struct secpolicyindex *spidx, u_int dir)
883 struct spdcache_entry *entry, *lastentry, *tmpentry;
884 struct secpolicy *sp;
888 if (!SPDCACHE_ACTIVE()) {
889 sp = key_do_allocsp(spidx, dir);
893 hashv = SPDCACHE_HASHVAL(spidx);
894 SPDCACHE_LOCK(hashv);
896 LIST_FOREACH_SAFE(entry, &V_spdcachehashtbl[hashv], chain, tmpentry) {
897 /* Removed outdated entries */
898 if (entry->sp != NULL &&
899 entry->sp->state == IPSEC_SPSTATE_DEAD) {
900 LIST_REMOVE(entry, chain);
901 spdcache_entry_free(entry);
906 if (!key_cmpspidx_exactly(&entry->spidx, spidx)) {
912 if (entry->sp != NULL)
915 /* IPSECSTAT_INC(ips_spdcache_hits); */
917 SPDCACHE_UNLOCK(hashv);
921 /* IPSECSTAT_INC(ips_spdcache_misses); */
923 sp = key_do_allocsp(spidx, dir);
924 entry = spdcache_entry_alloc(spidx, sp);
926 if (nb_entries >= SPDCACHE_MAX_ENTRIES_PER_HASH) {
927 LIST_REMOVE(lastentry, chain);
928 spdcache_entry_free(lastentry);
931 LIST_INSERT_HEAD(&V_spdcachehashtbl[hashv], entry, chain);
934 SPDCACHE_UNLOCK(hashv);
937 if (sp != NULL) { /* found a SPD entry */
938 sp->lastused = time_second;
940 printf("%s: return SP(%p)\n", __func__, sp));
941 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
944 printf("%s: lookup failed for ", __func__);
945 kdebug_secpolicyindex(spidx, NULL));
951 * Allocating an SA entry for an *INBOUND* or *OUTBOUND* TCP packet, signed
952 * or should be signed by MD5 signature.
953 * We don't use key_allocsa() for such lookups, because we don't know SPI.
954 * Unlike ESP and AH protocols, SPI isn't transmitted in the TCP header with
955 * signed packet. We use SADB only as storage for password.
956 * OUT: positive: corresponding SA for given saidx found.
960 key_allocsa_tcpmd5(struct secasindex *saidx)
962 SAHTREE_RLOCK_TRACKER;
963 struct secashead *sah;
964 struct secasvar *sav;
966 IPSEC_ASSERT(saidx->proto == IPPROTO_TCP,
967 ("unexpected security protocol %u", saidx->proto));
968 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TCPMD5,
969 ("unexpected mode %u", saidx->mode));
972 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
974 printf("%s: checking SAH\n", __func__);
975 kdebug_secash(sah, " "));
976 if (sah->saidx.proto != IPPROTO_TCP)
978 if (!key_sockaddrcmp(&saidx->dst.sa, &sah->saidx.dst.sa, 0) &&
979 !key_sockaddrcmp(&saidx->src.sa, &sah->saidx.src.sa, 0))
983 if (V_key_preferred_oldsa)
984 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
986 sav = TAILQ_FIRST(&sah->savtree_alive);
995 printf("%s: return SA(%p)\n", __func__, sav));
996 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
999 printf("%s: SA not found\n", __func__));
1000 KEYDBG(IPSEC_DATA, kdebug_secasindex(saidx, NULL));
1006 * Allocating an SA entry for an *OUTBOUND* packet.
1007 * OUT: positive: corresponding SA for given saidx found.
1008 * NULL: SA not found, but will be acquired, check *error
1009 * for acquiring status.
1012 key_allocsa_policy(struct secpolicy *sp, const struct secasindex *saidx,
1015 SAHTREE_RLOCK_TRACKER;
1016 struct secashead *sah;
1017 struct secasvar *sav;
1019 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
1020 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
1021 saidx->mode == IPSEC_MODE_TUNNEL,
1022 ("unexpected policy %u", saidx->mode));
1025 * We check new SA in the IPsec request because a different
1026 * SA may be involved each time this request is checked, either
1027 * because new SAs are being configured, or this request is
1028 * associated with an unconnected datagram socket, or this request
1029 * is associated with a system default policy.
1032 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
1034 printf("%s: checking SAH\n", __func__);
1035 kdebug_secash(sah, " "));
1036 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID))
1041 * Allocate the oldest SA available according to
1042 * draft-jenkins-ipsec-rekeying-03.
1044 if (V_key_preferred_oldsa)
1045 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
1047 sav = TAILQ_FIRST(&sah->savtree_alive);
1057 printf("%s: chosen SA(%p) for SP(%p)\n", __func__,
1059 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1060 return (sav); /* return referenced SA */
1063 /* there is no SA */
1064 *error = key_acquire(saidx, sp);
1066 ipseclog((LOG_DEBUG,
1067 "%s: error %d returned from key_acquire()\n",
1070 printf("%s: acquire SA for SP(%p), error %d\n",
1071 __func__, sp, *error));
1072 KEYDBG(IPSEC_DATA, kdebug_secasindex(saidx, NULL));
1077 * allocating a usable SA entry for a *INBOUND* packet.
1078 * Must call key_freesav() later.
1079 * OUT: positive: pointer to a usable sav (i.e. MATURE or DYING state).
1080 * NULL: not found, or error occurred.
1082 * According to RFC 2401 SA is uniquely identified by a triple SPI,
1083 * destination address, and security protocol. But according to RFC 4301,
1084 * SPI by itself suffices to specify an SA.
1086 * Note that, however, we do need to keep source address in IPsec SA.
1087 * IKE specification and PF_KEY specification do assume that we
1088 * keep source address in IPsec SA. We see a tricky situation here.
1091 key_allocsa(union sockaddr_union *dst, uint8_t proto, uint32_t spi)
1093 SAHTREE_RLOCK_TRACKER;
1094 struct secasvar *sav;
1096 IPSEC_ASSERT(proto == IPPROTO_ESP || proto == IPPROTO_AH ||
1097 proto == IPPROTO_IPCOMP, ("unexpected security protocol %u",
1101 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
1102 if (sav->spi == spi)
1106 * We use single SPI namespace for all protocols, so it is
1107 * impossible to have SPI duplicates in the SAVHASH.
1110 if (sav->state != SADB_SASTATE_LARVAL &&
1111 sav->sah->saidx.proto == proto &&
1112 key_sockaddrcmp(&dst->sa,
1113 &sav->sah->saidx.dst.sa, 0) == 0)
1122 char buf[IPSEC_ADDRSTRLEN];
1123 printf("%s: SA not found for spi %u proto %u dst %s\n",
1124 __func__, ntohl(spi), proto, ipsec_address(dst, buf,
1128 printf("%s: return SA(%p)\n", __func__, sav));
1129 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1135 key_allocsa_tunnel(union sockaddr_union *src, union sockaddr_union *dst,
1138 SAHTREE_RLOCK_TRACKER;
1139 struct secasindex saidx;
1140 struct secashead *sah;
1141 struct secasvar *sav;
1143 IPSEC_ASSERT(src != NULL, ("null src address"));
1144 IPSEC_ASSERT(dst != NULL, ("null dst address"));
1146 KEY_SETSECASIDX(proto, IPSEC_MODE_TUNNEL, 0, &src->sa,
1151 LIST_FOREACH(sah, SAHADDRHASH_HASH(&saidx), addrhash) {
1152 if (IPSEC_MODE_TUNNEL != sah->saidx.mode)
1154 if (proto != sah->saidx.proto)
1156 if (key_sockaddrcmp(&src->sa, &sah->saidx.src.sa, 0) != 0)
1158 if (key_sockaddrcmp(&dst->sa, &sah->saidx.dst.sa, 0) != 0)
1160 /* XXXAE: is key_preferred_oldsa reasonably?*/
1161 if (V_key_preferred_oldsa)
1162 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
1164 sav = TAILQ_FIRST(&sah->savtree_alive);
1172 printf("%s: return SA(%p)\n", __func__, sav));
1174 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1179 * Must be called after calling key_allocsp().
1182 key_freesp(struct secpolicy **spp)
1184 struct secpolicy *sp = *spp;
1186 IPSEC_ASSERT(sp != NULL, ("null sp"));
1187 if (SP_DELREF(sp) == 0)
1191 printf("%s: last reference to SP(%p)\n", __func__, sp));
1192 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1195 while (sp->tcount > 0)
1196 ipsec_delisr(sp->req[--sp->tcount]);
1197 free(sp, M_IPSEC_SP);
1201 key_unlink(struct secpolicy *sp)
1204 IPSEC_ASSERT(sp->spidx.dir == IPSEC_DIR_INBOUND ||
1205 sp->spidx.dir == IPSEC_DIR_OUTBOUND,
1206 ("invalid direction %u", sp->spidx.dir));
1207 SPTREE_UNLOCK_ASSERT();
1210 printf("%s: SP(%p)\n", __func__, sp));
1212 if (sp->state != IPSEC_SPSTATE_ALIVE) {
1213 /* SP is already unlinked */
1217 sp->state = IPSEC_SPSTATE_DEAD;
1218 TAILQ_REMOVE(&V_sptree[sp->spidx.dir], sp, chain);
1220 LIST_REMOVE(sp, idhash);
1223 if (SPDCACHE_ENABLED())
1229 * insert a secpolicy into the SP database. Lower priorities first
1232 key_insertsp(struct secpolicy *newsp)
1234 struct secpolicy *sp;
1236 SPTREE_WLOCK_ASSERT();
1237 TAILQ_FOREACH(sp, &V_sptree[newsp->spidx.dir], chain) {
1238 if (newsp->priority < sp->priority) {
1239 TAILQ_INSERT_BEFORE(sp, newsp, chain);
1243 TAILQ_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, chain);
1245 LIST_INSERT_HEAD(SPHASH_HASH(newsp->id), newsp, idhash);
1246 newsp->state = IPSEC_SPSTATE_ALIVE;
1252 * Insert a bunch of VTI secpolicies into the SPDB.
1253 * We keep VTI policies in the separate list due to following reasons:
1254 * 1) they should be immutable to user's or some deamon's attempts to
1255 * delete. The only way delete such policies - destroy or unconfigure
1256 * corresponding virtual inteface.
1257 * 2) such policies have traffic selector that matches all traffic per
1259 * Since all VTI policies have the same priority, we don't care about
1263 key_register_ifnet(struct secpolicy **spp, u_int count)
1270 * First of try to acquire id for each SP.
1272 for (i = 0; i < count; i++) {
1273 IPSEC_ASSERT(spp[i]->spidx.dir == IPSEC_DIR_INBOUND ||
1274 spp[i]->spidx.dir == IPSEC_DIR_OUTBOUND,
1275 ("invalid direction %u", spp[i]->spidx.dir));
1277 if ((spp[i]->id = key_getnewspid()) == 0) {
1282 for (i = 0; i < count; i++) {
1283 TAILQ_INSERT_TAIL(&V_sptree_ifnet[spp[i]->spidx.dir],
1286 * NOTE: despite the fact that we keep VTI SP in the
1287 * separate list, SPHASH contains policies from both
1288 * sources. Thus SADB_X_SPDGET will correctly return
1289 * SP by id, because it uses SPHASH for lookups.
1291 LIST_INSERT_HEAD(SPHASH_HASH(spp[i]->id), spp[i], idhash);
1292 spp[i]->state = IPSEC_SPSTATE_IFNET;
1296 * Notify user processes about new SP.
1298 for (i = 0; i < count; i++) {
1299 m = key_setdumpsp(spp[i], SADB_X_SPDADD, 0, 0);
1301 key_sendup_mbuf(NULL, m, KEY_SENDUP_ALL);
1307 key_unregister_ifnet(struct secpolicy **spp, u_int count)
1313 for (i = 0; i < count; i++) {
1314 IPSEC_ASSERT(spp[i]->spidx.dir == IPSEC_DIR_INBOUND ||
1315 spp[i]->spidx.dir == IPSEC_DIR_OUTBOUND,
1316 ("invalid direction %u", spp[i]->spidx.dir));
1318 if (spp[i]->state != IPSEC_SPSTATE_IFNET)
1320 spp[i]->state = IPSEC_SPSTATE_DEAD;
1321 TAILQ_REMOVE(&V_sptree_ifnet[spp[i]->spidx.dir],
1324 LIST_REMOVE(spp[i], idhash);
1327 if (SPDCACHE_ENABLED())
1330 for (i = 0; i < count; i++) {
1331 m = key_setdumpsp(spp[i], SADB_X_SPDDELETE, 0, 0);
1333 key_sendup_mbuf(NULL, m, KEY_SENDUP_ALL);
1338 * Must be called after calling key_allocsa().
1339 * This function is called by key_freesp() to free some SA allocated
1343 key_freesav(struct secasvar **psav)
1345 struct secasvar *sav = *psav;
1347 IPSEC_ASSERT(sav != NULL, ("null sav"));
1348 if (SAV_DELREF(sav) == 0)
1352 printf("%s: last reference to SA(%p)\n", __func__, sav));
1359 * Unlink SA from SAH and SPI hash under SAHTREE_WLOCK.
1360 * Expect that SA has extra reference due to lookup.
1361 * Release this references, also release SAH reference after unlink.
1364 key_unlinksav(struct secasvar *sav)
1366 struct secashead *sah;
1369 printf("%s: SA(%p)\n", __func__, sav));
1371 SAHTREE_UNLOCK_ASSERT();
1373 if (sav->state == SADB_SASTATE_DEAD) {
1374 /* SA is already unlinked */
1378 /* Unlink from SAH */
1379 if (sav->state == SADB_SASTATE_LARVAL)
1380 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
1382 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
1383 /* Unlink from SPI hash */
1384 LIST_REMOVE(sav, spihash);
1385 sav->state = SADB_SASTATE_DEAD;
1389 /* Since we are unlinked, release reference to SAH */
1393 /* %%% SPD management */
1396 * OUT: NULL : not found
1397 * others : found, pointer to a SP.
1399 static struct secpolicy *
1400 key_getsp(struct secpolicyindex *spidx)
1402 SPTREE_RLOCK_TRACKER;
1403 struct secpolicy *sp;
1405 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1408 TAILQ_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1409 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1421 * OUT: NULL : not found
1422 * others : found, pointer to referenced SP.
1424 static struct secpolicy *
1425 key_getspbyid(uint32_t id)
1427 SPTREE_RLOCK_TRACKER;
1428 struct secpolicy *sp;
1431 LIST_FOREACH(sp, SPHASH_HASH(id), idhash) {
1444 struct secpolicy *sp;
1446 sp = malloc(sizeof(*sp), M_IPSEC_SP, M_NOWAIT | M_ZERO);
1452 struct ipsecrequest *
1456 return (malloc(sizeof(struct ipsecrequest), M_IPSEC_SR,
1457 M_NOWAIT | M_ZERO));
1461 ipsec_delisr(struct ipsecrequest *p)
1464 free(p, M_IPSEC_SR);
1468 * create secpolicy structure from sadb_x_policy structure.
1469 * NOTE: `state', `secpolicyindex' and 'id' in secpolicy structure
1470 * are not set, so must be set properly later.
1473 key_msg2sp(struct sadb_x_policy *xpl0, size_t len, int *error)
1475 struct secpolicy *newsp;
1477 IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1478 IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1480 if (len != PFKEY_EXTLEN(xpl0)) {
1481 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1486 if ((newsp = key_newsp()) == NULL) {
1491 newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1492 newsp->policy = xpl0->sadb_x_policy_type;
1493 newsp->priority = xpl0->sadb_x_policy_priority;
1497 switch (xpl0->sadb_x_policy_type) {
1498 case IPSEC_POLICY_DISCARD:
1499 case IPSEC_POLICY_NONE:
1500 case IPSEC_POLICY_ENTRUST:
1501 case IPSEC_POLICY_BYPASS:
1504 case IPSEC_POLICY_IPSEC:
1506 struct sadb_x_ipsecrequest *xisr;
1507 struct ipsecrequest *isr;
1510 /* validity check */
1511 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1512 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1519 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1520 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1524 if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr) ||
1525 xisr->sadb_x_ipsecrequest_len > tlen) {
1526 ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1527 "length.\n", __func__));
1533 if (newsp->tcount >= IPSEC_MAXREQ) {
1534 ipseclog((LOG_DEBUG,
1535 "%s: too many ipsecrequests.\n",
1542 /* allocate request buffer */
1543 /* NB: data structure is zero'd */
1544 isr = ipsec_newisr();
1546 ipseclog((LOG_DEBUG,
1547 "%s: No more memory.\n", __func__));
1553 newsp->req[newsp->tcount++] = isr;
1556 switch (xisr->sadb_x_ipsecrequest_proto) {
1559 case IPPROTO_IPCOMP:
1562 ipseclog((LOG_DEBUG,
1563 "%s: invalid proto type=%u\n", __func__,
1564 xisr->sadb_x_ipsecrequest_proto));
1566 *error = EPROTONOSUPPORT;
1570 (uint8_t)xisr->sadb_x_ipsecrequest_proto;
1572 switch (xisr->sadb_x_ipsecrequest_mode) {
1573 case IPSEC_MODE_TRANSPORT:
1574 case IPSEC_MODE_TUNNEL:
1576 case IPSEC_MODE_ANY:
1578 ipseclog((LOG_DEBUG,
1579 "%s: invalid mode=%u\n", __func__,
1580 xisr->sadb_x_ipsecrequest_mode));
1585 isr->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1587 switch (xisr->sadb_x_ipsecrequest_level) {
1588 case IPSEC_LEVEL_DEFAULT:
1589 case IPSEC_LEVEL_USE:
1590 case IPSEC_LEVEL_REQUIRE:
1592 case IPSEC_LEVEL_UNIQUE:
1593 /* validity check */
1595 * If range violation of reqid, kernel will
1596 * update it, don't refuse it.
1598 if (xisr->sadb_x_ipsecrequest_reqid
1599 > IPSEC_MANUAL_REQID_MAX) {
1600 ipseclog((LOG_DEBUG,
1601 "%s: reqid=%d range "
1602 "violation, updated by kernel.\n",
1604 xisr->sadb_x_ipsecrequest_reqid));
1605 xisr->sadb_x_ipsecrequest_reqid = 0;
1608 /* allocate new reqid id if reqid is zero. */
1609 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1611 if ((reqid = key_newreqid()) == 0) {
1616 isr->saidx.reqid = reqid;
1617 xisr->sadb_x_ipsecrequest_reqid = reqid;
1619 /* set it for manual keying. */
1621 xisr->sadb_x_ipsecrequest_reqid;
1626 ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1628 xisr->sadb_x_ipsecrequest_level));
1633 isr->level = xisr->sadb_x_ipsecrequest_level;
1635 /* set IP addresses if there */
1636 if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1637 struct sockaddr *paddr;
1639 len = tlen - sizeof(*xisr);
1640 paddr = (struct sockaddr *)(xisr + 1);
1641 /* validity check */
1642 if (len < sizeof(struct sockaddr) ||
1643 len < 2 * paddr->sa_len ||
1644 paddr->sa_len > sizeof(isr->saidx.src)) {
1645 ipseclog((LOG_DEBUG, "%s: invalid "
1646 "request address length.\n",
1653 * Request length should be enough to keep
1654 * source and destination addresses.
1656 if (xisr->sadb_x_ipsecrequest_len <
1657 sizeof(*xisr) + 2 * paddr->sa_len) {
1658 ipseclog((LOG_DEBUG, "%s: invalid "
1659 "ipsecrequest length.\n",
1665 bcopy(paddr, &isr->saidx.src, paddr->sa_len);
1666 paddr = (struct sockaddr *)((caddr_t)paddr +
1669 /* validity check */
1670 if (paddr->sa_len !=
1671 isr->saidx.src.sa.sa_len) {
1672 ipseclog((LOG_DEBUG, "%s: invalid "
1673 "request address length.\n",
1679 /* AF family should match */
1680 if (paddr->sa_family !=
1681 isr->saidx.src.sa.sa_family) {
1682 ipseclog((LOG_DEBUG, "%s: address "
1683 "family doesn't match.\n",
1689 bcopy(paddr, &isr->saidx.dst, paddr->sa_len);
1692 * Addresses for TUNNEL mode requests are
1695 if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
1696 ipseclog((LOG_DEBUG, "%s: missing "
1697 "request addresses.\n", __func__));
1703 tlen -= xisr->sadb_x_ipsecrequest_len;
1705 /* validity check */
1707 ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1714 xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1715 + xisr->sadb_x_ipsecrequest_len);
1717 /* XXXAE: LARVAL SP */
1718 if (newsp->tcount < 1) {
1719 ipseclog((LOG_DEBUG, "%s: valid IPSEC transforms "
1720 "not found.\n", __func__));
1728 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1741 static uint32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1743 if (auto_reqid == ~0)
1744 auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1748 /* XXX should be unique check */
1749 return (auto_reqid);
1753 * copy secpolicy struct to sadb_x_policy structure indicated.
1755 static struct mbuf *
1756 key_sp2mbuf(struct secpolicy *sp)
1761 tlen = key_getspreqmsglen(sp);
1762 m = m_get2(tlen, M_NOWAIT, MT_DATA, 0);
1767 if (key_sp2msg(sp, m->m_data, &tlen) != 0) {
1775 key_sp2msg(struct secpolicy *sp, void *request, size_t *len)
1777 struct sadb_x_ipsecrequest *xisr;
1778 struct sadb_x_policy *xpl;
1779 struct ipsecrequest *isr;
1784 IPSEC_ASSERT(sp != NULL, ("null policy"));
1786 xlen = sizeof(*xpl);
1791 bzero(request, *len);
1792 xpl = (struct sadb_x_policy *)request;
1793 xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1794 xpl->sadb_x_policy_type = sp->policy;
1795 xpl->sadb_x_policy_dir = sp->spidx.dir;
1796 xpl->sadb_x_policy_id = sp->id;
1797 xpl->sadb_x_policy_priority = sp->priority;
1798 switch (sp->state) {
1799 case IPSEC_SPSTATE_IFNET:
1800 xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_IFNET;
1802 case IPSEC_SPSTATE_PCB:
1803 xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_PCB;
1806 xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_GLOBAL;
1809 /* if is the policy for ipsec ? */
1810 if (sp->policy == IPSEC_POLICY_IPSEC) {
1811 p = (caddr_t)xpl + sizeof(*xpl);
1812 for (i = 0; i < sp->tcount; i++) {
1814 ilen = PFKEY_ALIGN8(sizeof(*xisr) +
1815 isr->saidx.src.sa.sa_len +
1816 isr->saidx.dst.sa.sa_len);
1820 /* Calculate needed size */
1823 xisr = (struct sadb_x_ipsecrequest *)p;
1824 xisr->sadb_x_ipsecrequest_len = ilen;
1825 xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1826 xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1827 xisr->sadb_x_ipsecrequest_level = isr->level;
1828 xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1831 bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1832 p += isr->saidx.src.sa.sa_len;
1833 bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1834 p += isr->saidx.dst.sa.sa_len;
1837 xpl->sadb_x_policy_len = PFKEY_UNIT64(xlen);
1841 *len = sizeof(*xpl);
1845 /* m will not be freed nor modified */
1846 static struct mbuf *
1847 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1848 int ndeep, int nitem, ...)
1853 struct mbuf *result = NULL, *n;
1856 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1857 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1859 va_start(ap, nitem);
1860 for (i = 0; i < nitem; i++) {
1861 idx = va_arg(ap, int);
1862 if (idx < 0 || idx > SADB_EXT_MAX)
1864 /* don't attempt to pull empty extension */
1865 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1867 if (idx != SADB_EXT_RESERVED &&
1868 (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1871 if (idx == SADB_EXT_RESERVED) {
1872 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1874 IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1876 MGETHDR(n, M_NOWAIT, MT_DATA);
1881 m_copydata(m, 0, sizeof(struct sadb_msg),
1883 } else if (i < ndeep) {
1884 len = mhp->extlen[idx];
1885 n = m_get2(len, M_NOWAIT, MT_DATA, 0);
1890 m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1893 n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1906 if ((result->m_flags & M_PKTHDR) != 0) {
1907 result->m_pkthdr.len = 0;
1908 for (n = result; n; n = n->m_next)
1909 result->m_pkthdr.len += n->m_len;
1921 * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1922 * add an entry to SP database, when received
1923 * <base, address(SD), (lifetime(H),) policy>
1925 * Adding to SP database,
1927 * <base, address(SD), (lifetime(H),) policy>
1928 * to the socket which was send.
1930 * SPDADD set a unique policy entry.
1931 * SPDSETIDX like SPDADD without a part of policy requests.
1932 * SPDUPDATE replace a unique policy entry.
1934 * XXXAE: serialize this in PF_KEY to avoid races.
1935 * m will always be freed.
1938 key_spdadd(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
1940 struct secpolicyindex spidx;
1941 struct sadb_address *src0, *dst0;
1942 struct sadb_x_policy *xpl0, *xpl;
1943 struct sadb_lifetime *lft = NULL;
1944 struct secpolicy *newsp;
1947 IPSEC_ASSERT(so != NULL, ("null socket"));
1948 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1949 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1950 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1952 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
1953 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
1954 SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY)) {
1955 ipseclog((LOG_DEBUG,
1956 "%s: invalid message: missing required header.\n",
1958 return key_senderror(so, m, EINVAL);
1960 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
1961 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
1962 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
1963 ipseclog((LOG_DEBUG,
1964 "%s: invalid message: wrong header size.\n", __func__));
1965 return key_senderror(so, m, EINVAL);
1967 if (!SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD)) {
1968 if (SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_HARD)) {
1969 ipseclog((LOG_DEBUG,
1970 "%s: invalid message: wrong header size.\n",
1972 return key_senderror(so, m, EINVAL);
1974 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1977 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1978 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1979 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1981 /* check the direciton */
1982 switch (xpl0->sadb_x_policy_dir) {
1983 case IPSEC_DIR_INBOUND:
1984 case IPSEC_DIR_OUTBOUND:
1987 ipseclog((LOG_DEBUG, "%s: invalid SP direction.\n", __func__));
1988 return key_senderror(so, m, EINVAL);
1990 /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1991 if (xpl0->sadb_x_policy_type != IPSEC_POLICY_DISCARD &&
1992 xpl0->sadb_x_policy_type != IPSEC_POLICY_NONE &&
1993 xpl0->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
1994 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1995 return key_senderror(so, m, EINVAL);
1998 /* policy requests are mandatory when action is ipsec. */
1999 if (xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
2000 mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
2001 ipseclog((LOG_DEBUG,
2002 "%s: policy requests required.\n", __func__));
2003 return key_senderror(so, m, EINVAL);
2006 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
2007 (struct sockaddr *)(dst0 + 1));
2009 src0->sadb_address_proto != dst0->sadb_address_proto) {
2010 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
2011 return key_senderror(so, m, error);
2014 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2017 src0->sadb_address_prefixlen,
2018 dst0->sadb_address_prefixlen,
2019 src0->sadb_address_proto,
2021 /* Checking there is SP already or not. */
2022 newsp = key_getsp(&spidx);
2023 if (newsp != NULL) {
2024 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
2026 printf("%s: unlink SP(%p) for SPDUPDATE\n",
2028 KEYDBG(KEY_DATA, kdebug_secpolicy(newsp));
2033 ipseclog((LOG_DEBUG,
2034 "%s: a SP entry exists already.\n", __func__));
2035 return (key_senderror(so, m, EEXIST));
2039 /* allocate new SP entry */
2040 if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
2041 return key_senderror(so, m, error);
2044 newsp->lastused = newsp->created = time_second;
2045 newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
2046 newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
2047 bcopy(&spidx, &newsp->spidx, sizeof(spidx));
2049 /* XXXAE: there is race between key_getsp() and key_insertsp() */
2051 if ((newsp->id = key_getnewspid()) == 0) {
2054 return key_senderror(so, m, ENOBUFS);
2056 key_insertsp(newsp);
2058 if (SPDCACHE_ENABLED())
2062 printf("%s: SP(%p)\n", __func__, newsp));
2063 KEYDBG(KEY_DATA, kdebug_secpolicy(newsp));
2066 struct mbuf *n, *mpolicy;
2067 struct sadb_msg *newmsg;
2070 /* create new sadb_msg to reply. */
2072 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
2073 SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
2074 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2076 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
2078 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2081 return key_senderror(so, m, ENOBUFS);
2083 if (n->m_len < sizeof(*newmsg)) {
2084 n = m_pullup(n, sizeof(*newmsg));
2086 return key_senderror(so, m, ENOBUFS);
2088 newmsg = mtod(n, struct sadb_msg *);
2089 newmsg->sadb_msg_errno = 0;
2090 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2093 mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
2094 sizeof(*xpl), &off);
2095 if (mpolicy == NULL) {
2096 /* n is already freed */
2097 return key_senderror(so, m, ENOBUFS);
2099 xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
2100 if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
2102 return key_senderror(so, m, EINVAL);
2104 xpl->sadb_x_policy_id = newsp->id;
2107 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2112 * get new policy id.
2118 key_getnewspid(void)
2120 struct secpolicy *sp;
2122 int count = V_key_spi_trycnt; /* XXX */
2124 SPTREE_WLOCK_ASSERT();
2126 if (V_policy_id == ~0) /* overflowed */
2127 newid = V_policy_id = 1;
2129 newid = ++V_policy_id;
2130 LIST_FOREACH(sp, SPHASH_HASH(newid), idhash) {
2131 if (sp->id == newid)
2137 if (count == 0 || newid == 0) {
2138 ipseclog((LOG_DEBUG, "%s: failed to allocate policy id.\n",
2146 * SADB_SPDDELETE processing
2148 * <base, address(SD), policy(*)>
2149 * from the user(?), and set SADB_SASTATE_DEAD,
2151 * <base, address(SD), policy(*)>
2153 * policy(*) including direction of policy.
2155 * m will always be freed.
2158 key_spddelete(struct socket *so, struct mbuf *m,
2159 const struct sadb_msghdr *mhp)
2161 struct secpolicyindex spidx;
2162 struct sadb_address *src0, *dst0;
2163 struct sadb_x_policy *xpl0;
2164 struct secpolicy *sp;
2166 IPSEC_ASSERT(so != NULL, ("null so"));
2167 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2168 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2169 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2171 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
2172 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
2173 SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY)) {
2174 ipseclog((LOG_DEBUG,
2175 "%s: invalid message: missing required header.\n",
2177 return key_senderror(so, m, EINVAL);
2179 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
2180 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
2181 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2182 ipseclog((LOG_DEBUG,
2183 "%s: invalid message: wrong header size.\n", __func__));
2184 return key_senderror(so, m, EINVAL);
2187 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2188 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2189 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2191 /* check the direciton */
2192 switch (xpl0->sadb_x_policy_dir) {
2193 case IPSEC_DIR_INBOUND:
2194 case IPSEC_DIR_OUTBOUND:
2197 ipseclog((LOG_DEBUG, "%s: invalid SP direction.\n", __func__));
2198 return key_senderror(so, m, EINVAL);
2200 /* Only DISCARD, NONE and IPSEC are allowed */
2201 if (xpl0->sadb_x_policy_type != IPSEC_POLICY_DISCARD &&
2202 xpl0->sadb_x_policy_type != IPSEC_POLICY_NONE &&
2203 xpl0->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
2204 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
2205 return key_senderror(so, m, EINVAL);
2207 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
2208 (struct sockaddr *)(dst0 + 1)) != 0 ||
2209 src0->sadb_address_proto != dst0->sadb_address_proto) {
2210 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
2211 return key_senderror(so, m, EINVAL);
2214 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2217 src0->sadb_address_prefixlen,
2218 dst0->sadb_address_prefixlen,
2219 src0->sadb_address_proto,
2222 /* Is there SP in SPD ? */
2223 if ((sp = key_getsp(&spidx)) == NULL) {
2224 ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2225 return key_senderror(so, m, EINVAL);
2228 /* save policy id to buffer to be returned. */
2229 xpl0->sadb_x_policy_id = sp->id;
2232 printf("%s: SP(%p)\n", __func__, sp));
2233 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2239 struct sadb_msg *newmsg;
2241 /* create new sadb_msg to reply. */
2242 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2243 SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2245 return key_senderror(so, m, ENOBUFS);
2247 newmsg = mtod(n, struct sadb_msg *);
2248 newmsg->sadb_msg_errno = 0;
2249 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2252 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2257 * SADB_SPDDELETE2 processing
2260 * from the user(?), and set SADB_SASTATE_DEAD,
2264 * policy(*) including direction of policy.
2266 * m will always be freed.
2269 key_spddelete2(struct socket *so, struct mbuf *m,
2270 const struct sadb_msghdr *mhp)
2272 struct secpolicy *sp;
2275 IPSEC_ASSERT(so != NULL, ("null socket"));
2276 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2277 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2278 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2280 if (SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY) ||
2281 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2282 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2284 return key_senderror(so, m, EINVAL);
2287 id = ((struct sadb_x_policy *)
2288 mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2290 /* Is there SP in SPD ? */
2291 if ((sp = key_getspbyid(id)) == NULL) {
2292 ipseclog((LOG_DEBUG, "%s: no SP found for id %u.\n",
2294 return key_senderror(so, m, EINVAL);
2298 printf("%s: SP(%p)\n", __func__, sp));
2299 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2301 if (sp->state != IPSEC_SPSTATE_DEAD) {
2302 ipseclog((LOG_DEBUG, "%s: failed to delete SP with id %u.\n",
2305 return (key_senderror(so, m, EACCES));
2310 struct mbuf *n, *nn;
2311 struct sadb_msg *newmsg;
2314 /* create new sadb_msg to reply. */
2315 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2317 MGETHDR(n, M_NOWAIT, MT_DATA);
2318 if (n && len > MHLEN) {
2319 if (!(MCLGET(n, M_NOWAIT))) {
2325 return key_senderror(so, m, ENOBUFS);
2331 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2332 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2334 IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2337 n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2338 mhp->extlen[SADB_X_EXT_POLICY], M_NOWAIT);
2341 return key_senderror(so, m, ENOBUFS);
2344 n->m_pkthdr.len = 0;
2345 for (nn = n; nn; nn = nn->m_next)
2346 n->m_pkthdr.len += nn->m_len;
2348 newmsg = mtod(n, struct sadb_msg *);
2349 newmsg->sadb_msg_errno = 0;
2350 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2353 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2358 * SADB_X_SPDGET processing
2363 * <base, address(SD), policy>
2365 * policy(*) including direction of policy.
2367 * m will always be freed.
2370 key_spdget(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2372 struct secpolicy *sp;
2376 IPSEC_ASSERT(so != NULL, ("null socket"));
2377 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2378 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2379 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2381 if (SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY) ||
2382 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2383 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2385 return key_senderror(so, m, EINVAL);
2388 id = ((struct sadb_x_policy *)
2389 mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2391 /* Is there SP in SPD ? */
2392 if ((sp = key_getspbyid(id)) == NULL) {
2393 ipseclog((LOG_DEBUG, "%s: no SP found for id %u.\n",
2395 return key_senderror(so, m, ENOENT);
2398 n = key_setdumpsp(sp, SADB_X_SPDGET, mhp->msg->sadb_msg_seq,
2399 mhp->msg->sadb_msg_pid);
2403 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2405 return key_senderror(so, m, ENOBUFS);
2409 * SADB_X_SPDACQUIRE processing.
2410 * Acquire policy and SA(s) for a *OUTBOUND* packet.
2413 * to KMD, and expect to receive
2414 * <base> with SADB_X_SPDACQUIRE if error occurred,
2417 * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2418 * policy(*) is without policy requests.
2421 * others: error number
2424 key_spdacquire(struct secpolicy *sp)
2426 struct mbuf *result = NULL, *m;
2427 struct secspacq *newspacq;
2429 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2430 IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2431 IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2432 ("policy not IPSEC %u", sp->policy));
2434 /* Get an entry to check whether sent message or not. */
2435 newspacq = key_getspacq(&sp->spidx);
2436 if (newspacq != NULL) {
2437 if (V_key_blockacq_count < newspacq->count) {
2438 /* reset counter and do send message. */
2439 newspacq->count = 0;
2441 /* increment counter and do nothing. */
2448 /* make new entry for blocking to send SADB_ACQUIRE. */
2449 newspacq = key_newspacq(&sp->spidx);
2450 if (newspacq == NULL)
2454 /* create new sadb_msg to reply. */
2455 m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2461 result->m_pkthdr.len = 0;
2462 for (m = result; m; m = m->m_next)
2463 result->m_pkthdr.len += m->m_len;
2465 mtod(result, struct sadb_msg *)->sadb_msg_len =
2466 PFKEY_UNIT64(result->m_pkthdr.len);
2468 return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2472 * SADB_SPDFLUSH processing
2475 * from the user, and free all entries in secpctree.
2479 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2481 * m will always be freed.
2484 key_spdflush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2486 struct secpolicy_queue drainq;
2487 struct sadb_msg *newmsg;
2488 struct secpolicy *sp, *nextsp;
2491 IPSEC_ASSERT(so != NULL, ("null socket"));
2492 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2493 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2494 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2496 if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2497 return key_senderror(so, m, EINVAL);
2499 TAILQ_INIT(&drainq);
2501 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2502 TAILQ_CONCAT(&drainq, &V_sptree[dir], chain);
2505 * We need to set state to DEAD for each policy to be sure,
2506 * that another thread won't try to unlink it.
2507 * Also remove SP from sphash.
2509 TAILQ_FOREACH(sp, &drainq, chain) {
2510 sp->state = IPSEC_SPSTATE_DEAD;
2511 LIST_REMOVE(sp, idhash);
2516 if (SPDCACHE_ENABLED())
2518 sp = TAILQ_FIRST(&drainq);
2519 while (sp != NULL) {
2520 nextsp = TAILQ_NEXT(sp, chain);
2525 if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2526 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2527 return key_senderror(so, m, ENOBUFS);
2533 m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2534 newmsg = mtod(m, struct sadb_msg *);
2535 newmsg->sadb_msg_errno = 0;
2536 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2538 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2542 key_satype2scopemask(uint8_t satype)
2545 if (satype == IPSEC_POLICYSCOPE_ANY)
2550 * SADB_SPDDUMP processing
2553 * from the user, and dump all SP leaves and send,
2558 * sadb_msg_satype is considered as mask of policy scopes.
2559 * m will always be freed.
2562 key_spddump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2564 SPTREE_RLOCK_TRACKER;
2565 struct secpolicy *sp;
2570 IPSEC_ASSERT(so != NULL, ("null socket"));
2571 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2572 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2573 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2575 /* search SPD entry and get buffer size. */
2577 scope = key_satype2scopemask(mhp->msg->sadb_msg_satype);
2579 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2580 if (scope & IPSEC_POLICYSCOPE_GLOBAL) {
2581 TAILQ_FOREACH(sp, &V_sptree[dir], chain)
2584 if (scope & IPSEC_POLICYSCOPE_IFNET) {
2585 TAILQ_FOREACH(sp, &V_sptree_ifnet[dir], chain)
2592 return key_senderror(so, m, ENOENT);
2595 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2596 if (scope & IPSEC_POLICYSCOPE_GLOBAL) {
2597 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
2599 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2600 mhp->msg->sadb_msg_pid);
2603 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2606 if (scope & IPSEC_POLICYSCOPE_IFNET) {
2607 TAILQ_FOREACH(sp, &V_sptree_ifnet[dir], chain) {
2609 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2610 mhp->msg->sadb_msg_pid);
2613 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2623 static struct mbuf *
2624 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq,
2627 struct mbuf *result = NULL, *m;
2628 struct seclifetime lt;
2630 m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2635 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2636 &sp->spidx.src.sa, sp->spidx.prefs,
2637 sp->spidx.ul_proto);
2642 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2643 &sp->spidx.dst.sa, sp->spidx.prefd,
2644 sp->spidx.ul_proto);
2649 m = key_sp2mbuf(sp);
2655 lt.addtime=sp->created;
2656 lt.usetime= sp->lastused;
2657 m = key_setlifetime(<, SADB_EXT_LIFETIME_CURRENT);
2662 lt.addtime=sp->lifetime;
2663 lt.usetime= sp->validtime;
2664 m = key_setlifetime(<, SADB_EXT_LIFETIME_HARD);
2670 if ((result->m_flags & M_PKTHDR) == 0)
2673 if (result->m_len < sizeof(struct sadb_msg)) {
2674 result = m_pullup(result, sizeof(struct sadb_msg));
2679 result->m_pkthdr.len = 0;
2680 for (m = result; m; m = m->m_next)
2681 result->m_pkthdr.len += m->m_len;
2683 mtod(result, struct sadb_msg *)->sadb_msg_len =
2684 PFKEY_UNIT64(result->m_pkthdr.len);
2693 * get PFKEY message length for security policy and request.
2696 key_getspreqmsglen(struct secpolicy *sp)
2701 tlen = sizeof(struct sadb_x_policy);
2702 /* if is the policy for ipsec ? */
2703 if (sp->policy != IPSEC_POLICY_IPSEC)
2706 /* get length of ipsec requests */
2707 for (i = 0; i < sp->tcount; i++) {
2708 len = sizeof(struct sadb_x_ipsecrequest)
2709 + sp->req[i]->saidx.src.sa.sa_len
2710 + sp->req[i]->saidx.dst.sa.sa_len;
2712 tlen += PFKEY_ALIGN8(len);
2718 * SADB_SPDEXPIRE processing
2720 * <base, address(SD), lifetime(CH), policy>
2724 * others : error number
2727 key_spdexpire(struct secpolicy *sp)
2729 struct sadb_lifetime *lt;
2730 struct mbuf *result = NULL, *m;
2731 int len, error = -1;
2733 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2736 printf("%s: SP(%p)\n", __func__, sp));
2737 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2739 /* set msg header */
2740 m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2747 /* create lifetime extension (current and hard) */
2748 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2749 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
2756 bzero(mtod(m, caddr_t), len);
2757 lt = mtod(m, struct sadb_lifetime *);
2758 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2759 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2760 lt->sadb_lifetime_allocations = 0;
2761 lt->sadb_lifetime_bytes = 0;
2762 lt->sadb_lifetime_addtime = sp->created;
2763 lt->sadb_lifetime_usetime = sp->lastused;
2764 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2765 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2766 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2767 lt->sadb_lifetime_allocations = 0;
2768 lt->sadb_lifetime_bytes = 0;
2769 lt->sadb_lifetime_addtime = sp->lifetime;
2770 lt->sadb_lifetime_usetime = sp->validtime;
2773 /* set sadb_address for source */
2774 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2776 sp->spidx.prefs, sp->spidx.ul_proto);
2783 /* set sadb_address for destination */
2784 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2786 sp->spidx.prefd, sp->spidx.ul_proto);
2794 m = key_sp2mbuf(sp);
2801 if ((result->m_flags & M_PKTHDR) == 0) {
2806 if (result->m_len < sizeof(struct sadb_msg)) {
2807 result = m_pullup(result, sizeof(struct sadb_msg));
2808 if (result == NULL) {
2814 result->m_pkthdr.len = 0;
2815 for (m = result; m; m = m->m_next)
2816 result->m_pkthdr.len += m->m_len;
2818 mtod(result, struct sadb_msg *)->sadb_msg_len =
2819 PFKEY_UNIT64(result->m_pkthdr.len);
2821 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2829 /* %%% SAD management */
2831 * allocating and initialize new SA head.
2832 * OUT: NULL : failure due to the lack of memory.
2833 * others : pointer to new SA head.
2835 static struct secashead *
2836 key_newsah(struct secasindex *saidx)
2838 struct secashead *sah;
2840 sah = malloc(sizeof(struct secashead), M_IPSEC_SAH,
2843 PFKEYSTAT_INC(in_nomem);
2846 TAILQ_INIT(&sah->savtree_larval);
2847 TAILQ_INIT(&sah->savtree_alive);
2848 sah->saidx = *saidx;
2849 sah->state = SADB_SASTATE_DEAD;
2853 printf("%s: SAH(%p)\n", __func__, sah));
2854 KEYDBG(KEY_DATA, kdebug_secash(sah, NULL));
2859 key_freesah(struct secashead **psah)
2861 struct secashead *sah = *psah;
2863 if (SAH_DELREF(sah) == 0)
2867 printf("%s: last reference to SAH(%p)\n", __func__, sah));
2868 KEYDBG(KEY_DATA, kdebug_secash(sah, NULL));
2875 key_delsah(struct secashead *sah)
2877 IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2878 IPSEC_ASSERT(sah->state == SADB_SASTATE_DEAD,
2879 ("Attempt to free non DEAD SAH %p", sah));
2880 IPSEC_ASSERT(TAILQ_EMPTY(&sah->savtree_larval),
2881 ("Attempt to free SAH %p with LARVAL SA", sah));
2882 IPSEC_ASSERT(TAILQ_EMPTY(&sah->savtree_alive),
2883 ("Attempt to free SAH %p with ALIVE SA", sah));
2885 free(sah, M_IPSEC_SAH);
2889 * allocating a new SA for key_add() and key_getspi() call,
2890 * and copy the values of mhp into new buffer.
2891 * When SAD message type is SADB_GETSPI set SA state to LARVAL.
2892 * For SADB_ADD create and initialize SA with MATURE state.
2894 * others : pointer to new secasvar.
2896 static struct secasvar *
2897 key_newsav(const struct sadb_msghdr *mhp, struct secasindex *saidx,
2898 uint32_t spi, int *errp)
2900 struct secashead *sah;
2901 struct secasvar *sav;
2904 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2905 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2906 IPSEC_ASSERT(mhp->msg->sadb_msg_type == SADB_GETSPI ||
2907 mhp->msg->sadb_msg_type == SADB_ADD, ("wrong message type"));
2911 /* check SPI value */
2912 switch (saidx->proto) {
2916 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
2917 * 1-255 reserved by IANA for future use,
2918 * 0 for implementation specific, local use.
2920 if (ntohl(spi) <= 255) {
2921 ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
2922 __func__, ntohl(spi)));
2929 sav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT | M_ZERO);
2934 sav->lock = malloc(sizeof(struct mtx), M_IPSEC_MISC,
2936 if (sav->lock == NULL) {
2940 mtx_init(sav->lock, "ipsec association", NULL, MTX_DEF);
2941 sav->lft_c = uma_zalloc_pcpu(V_key_lft_zone, M_NOWAIT);
2942 if (sav->lft_c == NULL) {
2946 counter_u64_zero(sav->lft_c_allocations);
2947 counter_u64_zero(sav->lft_c_bytes);
2950 sav->seq = mhp->msg->sadb_msg_seq;
2951 sav->state = SADB_SASTATE_LARVAL;
2952 sav->pid = (pid_t)mhp->msg->sadb_msg_pid;
2955 sah = key_getsah(saidx);
2957 /* create a new SA index */
2958 sah = key_newsah(saidx);
2960 ipseclog((LOG_DEBUG,
2961 "%s: No more memory.\n", __func__));
2970 if (mhp->msg->sadb_msg_type == SADB_GETSPI) {
2971 sav->created = time_second;
2972 } else if (sav->state == SADB_SASTATE_LARVAL) {
2974 * Do not call key_setsaval() second time in case
2975 * of `goto again`. We will have MATURE state.
2977 *errp = key_setsaval(sav, mhp);
2980 sav->state = SADB_SASTATE_MATURE;
2985 * Check that existing SAH wasn't unlinked.
2986 * Since we didn't hold the SAHTREE lock, it is possible,
2987 * that callout handler or key_flush() or key_delete() could
2990 if (isnew == 0 && sah->state == SADB_SASTATE_DEAD) {
2992 key_freesah(&sah); /* reference from key_getsah() */
2997 * Add new SAH into SADB.
2999 * XXXAE: we can serialize key_add and key_getspi calls, so
3000 * several threads will not fight in the race.
3001 * Otherwise we should check under SAHTREE lock, that this
3002 * SAH would not added twice.
3004 TAILQ_INSERT_HEAD(&V_sahtree, sah, chain);
3005 /* Add new SAH into hash by addresses */
3006 LIST_INSERT_HEAD(SAHADDRHASH_HASH(saidx), sah, addrhash);
3007 /* Now we are linked in the chain */
3008 sah->state = SADB_SASTATE_MATURE;
3010 * SAV references this new SAH.
3011 * In case of existing SAH we reuse reference
3012 * from key_getsah().
3016 /* Link SAV with SAH */
3017 if (sav->state == SADB_SASTATE_MATURE)
3018 TAILQ_INSERT_HEAD(&sah->savtree_alive, sav, chain);
3020 TAILQ_INSERT_HEAD(&sah->savtree_larval, sav, chain);
3021 /* Add SAV into SPI hash */
3022 LIST_INSERT_HEAD(SAVHASH_HASH(sav->spi), sav, spihash);
3024 *errp = 0; /* success */
3028 if (sav->lock != NULL) {
3029 mtx_destroy(sav->lock);
3030 free(sav->lock, M_IPSEC_MISC);
3032 if (sav->lft_c != NULL)
3033 uma_zfree_pcpu(V_key_lft_zone, sav->lft_c);
3034 free(sav, M_IPSEC_SA), sav = NULL;
3038 if (*errp == ENOBUFS) {
3039 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3041 PFKEYSTAT_INC(in_nomem);
3048 * free() SA variable entry.
3051 key_cleansav(struct secasvar *sav)
3054 if (sav->natt != NULL) {
3055 free(sav->natt, M_IPSEC_MISC);
3058 if (sav->flags & SADB_X_EXT_F_CLONED)
3060 if (sav->tdb_xform != NULL) {
3061 sav->tdb_xform->xf_cleanup(sav);
3062 sav->tdb_xform = NULL;
3064 if (sav->key_auth != NULL) {
3065 zfree(sav->key_auth->key_data, M_IPSEC_MISC);
3066 free(sav->key_auth, M_IPSEC_MISC);
3067 sav->key_auth = NULL;
3069 if (sav->key_enc != NULL) {
3070 zfree(sav->key_enc->key_data, M_IPSEC_MISC);
3071 free(sav->key_enc, M_IPSEC_MISC);
3072 sav->key_enc = NULL;
3074 if (sav->replay != NULL) {
3075 if (sav->replay->bitmap != NULL)
3076 free(sav->replay->bitmap, M_IPSEC_MISC);
3077 free(sav->replay, M_IPSEC_MISC);
3080 if (sav->lft_h != NULL) {
3081 free(sav->lft_h, M_IPSEC_MISC);
3084 if (sav->lft_s != NULL) {
3085 free(sav->lft_s, M_IPSEC_MISC);
3091 * free() SA variable entry.
3094 key_delsav(struct secasvar *sav)
3096 IPSEC_ASSERT(sav != NULL, ("null sav"));
3097 IPSEC_ASSERT(sav->state == SADB_SASTATE_DEAD,
3098 ("attempt to free non DEAD SA %p", sav));
3099 IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0",
3103 * SA must be unlinked from the chain and hashtbl.
3104 * If SA was cloned, we leave all fields untouched,
3105 * except NAT-T config.
3108 if ((sav->flags & SADB_X_EXT_F_CLONED) == 0) {
3109 mtx_destroy(sav->lock);
3110 free(sav->lock, M_IPSEC_MISC);
3111 uma_zfree_pcpu(V_key_lft_zone, sav->lft_c);
3113 free(sav, M_IPSEC_SA);
3120 * others : found, referenced pointer to a SAH.
3122 static struct secashead *
3123 key_getsah(struct secasindex *saidx)
3125 SAHTREE_RLOCK_TRACKER;
3126 struct secashead *sah;
3129 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
3130 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID) != 0) {
3140 * Check not to be duplicated SPI.
3143 * 1 : found SA with given SPI.
3146 key_checkspidup(uint32_t spi)
3148 SAHTREE_RLOCK_TRACKER;
3149 struct secasvar *sav;
3151 /* Assume SPI is in network byte order */
3153 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
3154 if (sav->spi == spi)
3158 return (sav != NULL);
3165 * others : found, referenced pointer to a SA.
3167 static struct secasvar *
3168 key_getsavbyspi(uint32_t spi)
3170 SAHTREE_RLOCK_TRACKER;
3171 struct secasvar *sav;
3173 /* Assume SPI is in network byte order */
3175 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
3176 if (sav->spi != spi)
3186 key_updatelifetimes(struct secasvar *sav, const struct sadb_msghdr *mhp)
3188 struct seclifetime *lft_h, *lft_s, *tmp;
3190 /* Lifetime extension is optional, check that it is present. */
3191 if (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
3192 SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) {
3194 * In case of SADB_UPDATE we may need to change
3195 * existing lifetimes.
3197 if (sav->state == SADB_SASTATE_MATURE) {
3198 lft_h = lft_s = NULL;
3203 /* Both HARD and SOFT extensions must present */
3204 if ((SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
3205 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
3206 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
3207 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
3208 ipseclog((LOG_DEBUG,
3209 "%s: invalid message: missing required header.\n",
3213 if (SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_HARD) ||
3214 SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_SOFT)) {
3215 ipseclog((LOG_DEBUG,
3216 "%s: invalid message: wrong header size.\n", __func__));
3219 lft_h = key_dup_lifemsg((const struct sadb_lifetime *)
3220 mhp->ext[SADB_EXT_LIFETIME_HARD], M_IPSEC_MISC);
3221 if (lft_h == NULL) {
3222 PFKEYSTAT_INC(in_nomem);
3223 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3226 lft_s = key_dup_lifemsg((const struct sadb_lifetime *)
3227 mhp->ext[SADB_EXT_LIFETIME_SOFT], M_IPSEC_MISC);
3228 if (lft_s == NULL) {
3229 PFKEYSTAT_INC(in_nomem);
3230 free(lft_h, M_IPSEC_MISC);
3231 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3235 if (sav->state != SADB_SASTATE_LARVAL) {
3237 * key_update() holds reference to this SA,
3238 * so it won't be deleted in meanwhile.
3248 SECASVAR_UNLOCK(sav);
3250 free(lft_h, M_IPSEC_MISC);
3252 free(lft_s, M_IPSEC_MISC);
3255 /* We can update lifetime without holding a lock */
3256 IPSEC_ASSERT(sav->lft_h == NULL, ("lft_h is already initialized\n"));
3257 IPSEC_ASSERT(sav->lft_s == NULL, ("lft_s is already initialized\n"));
3264 * copy SA values from PF_KEY message except *SPI, SEQ, PID and TYPE*.
3265 * You must update these if need. Expects only LARVAL SAs.
3270 key_setsaval(struct secasvar *sav, const struct sadb_msghdr *mhp)
3272 const struct sadb_sa *sa0;
3273 const struct sadb_key *key0;
3278 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3279 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3280 IPSEC_ASSERT(sav->state == SADB_SASTATE_LARVAL,
3281 ("Attempt to update non LARVAL SA"));
3284 error = key_setident(sav->sah, mhp);
3289 if (!SADB_CHECKHDR(mhp, SADB_EXT_SA)) {
3290 if (SADB_CHECKLEN(mhp, SADB_EXT_SA)) {
3294 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3295 sav->alg_auth = sa0->sadb_sa_auth;
3296 sav->alg_enc = sa0->sadb_sa_encrypt;
3297 sav->flags = sa0->sadb_sa_flags;
3298 if ((sav->flags & SADB_KEY_FLAGS_MAX) != sav->flags) {
3299 ipseclog((LOG_DEBUG,
3300 "%s: invalid sa_flags 0x%08x.\n", __func__,
3306 /* Optional replay window */
3308 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0)
3309 replay = sa0->sadb_sa_replay;
3310 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_SA_REPLAY)) {
3311 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA_REPLAY)) {
3315 replay = ((const struct sadb_x_sa_replay *)
3316 mhp->ext[SADB_X_EXT_SA_REPLAY])->sadb_x_sa_replay_replay;
3318 if (replay > UINT32_MAX - 32) {
3319 ipseclog((LOG_DEBUG,
3320 "%s: replay window too big.\n", __func__));
3325 replay = (replay + 7) >> 3;
3328 sav->replay = malloc(sizeof(struct secreplay), M_IPSEC_MISC,
3330 if (sav->replay == NULL) {
3331 PFKEYSTAT_INC(in_nomem);
3332 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3339 /* number of 32b blocks to be allocated */
3340 uint32_t bitmap_size;
3343 * - the allocated replay window size must be
3345 * - use an extra 32b block as a redundant window.
3348 while (replay + 4 > bitmap_size)
3350 bitmap_size = bitmap_size / 4;
3352 sav->replay->bitmap = malloc(
3353 bitmap_size * sizeof(uint32_t), M_IPSEC_MISC,
3355 if (sav->replay->bitmap == NULL) {
3356 PFKEYSTAT_INC(in_nomem);
3357 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3362 sav->replay->bitmap_size = bitmap_size;
3363 sav->replay->wsize = replay;
3367 /* Authentication keys */
3368 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH)) {
3369 if (SADB_CHECKLEN(mhp, SADB_EXT_KEY_AUTH)) {
3374 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3375 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3376 switch (mhp->msg->sadb_msg_satype) {
3377 case SADB_SATYPE_AH:
3378 case SADB_SATYPE_ESP:
3379 case SADB_X_SATYPE_TCPSIGNATURE:
3380 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3381 sav->alg_auth != SADB_X_AALG_NULL)
3384 case SADB_X_SATYPE_IPCOMP:
3390 ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3395 sav->key_auth = key_dup_keymsg(key0, len, M_IPSEC_MISC);
3396 if (sav->key_auth == NULL ) {
3397 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3399 PFKEYSTAT_INC(in_nomem);
3405 /* Encryption key */
3406 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT)) {
3407 if (SADB_CHECKLEN(mhp, SADB_EXT_KEY_ENCRYPT)) {
3412 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3413 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3414 switch (mhp->msg->sadb_msg_satype) {
3415 case SADB_SATYPE_ESP:
3416 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3417 sav->alg_enc != SADB_EALG_NULL) {
3421 sav->key_enc = key_dup_keymsg(key0, len, M_IPSEC_MISC);
3422 if (sav->key_enc == NULL) {
3423 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3425 PFKEYSTAT_INC(in_nomem);
3430 case SADB_X_SATYPE_IPCOMP:
3431 if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3433 sav->key_enc = NULL; /*just in case*/
3435 case SADB_SATYPE_AH:
3436 case SADB_X_SATYPE_TCPSIGNATURE:
3442 ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3450 switch (mhp->msg->sadb_msg_satype) {
3451 case SADB_SATYPE_AH:
3452 if (sav->flags & SADB_X_EXT_DERIV) {
3453 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3454 "given to AH SA.\n", __func__));
3458 if (sav->alg_enc != SADB_EALG_NONE) {
3459 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3460 "mismated.\n", __func__));
3464 error = xform_init(sav, XF_AH);
3466 case SADB_SATYPE_ESP:
3467 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_DERIV)) ==
3468 (SADB_X_EXT_OLD | SADB_X_EXT_DERIV)) {
3469 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3470 "given to old-esp.\n", __func__));
3474 error = xform_init(sav, XF_ESP);
3476 case SADB_X_SATYPE_IPCOMP:
3477 if (sav->alg_auth != SADB_AALG_NONE) {
3478 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3479 "mismated.\n", __func__));
3483 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0 &&
3484 ntohl(sav->spi) >= 0x10000) {
3485 ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3490 error = xform_init(sav, XF_IPCOMP);
3492 case SADB_X_SATYPE_TCPSIGNATURE:
3493 if (sav->alg_enc != SADB_EALG_NONE) {
3494 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3495 "mismated.\n", __func__));
3499 error = xform_init(sav, XF_TCPSIGNATURE);
3502 ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3503 error = EPROTONOSUPPORT;
3507 ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3508 __func__, mhp->msg->sadb_msg_satype));
3512 /* Handle NAT-T headers */
3513 error = key_setnatt(sav, mhp);
3517 /* Initialize lifetime for CURRENT */
3519 sav->created = time_second;
3521 /* lifetimes for HARD and SOFT */
3522 error = key_updatelifetimes(sav, mhp);
3531 * subroutine for SADB_GET and SADB_DUMP.
3533 static struct mbuf *
3534 key_setdumpsa(struct secasvar *sav, uint8_t type, uint8_t satype,
3535 uint32_t seq, uint32_t pid)
3537 struct seclifetime lft_c;
3538 struct mbuf *result = NULL, *tres = NULL, *m;
3539 int i, dumporder[] = {
3540 SADB_EXT_SA, SADB_X_EXT_SA2, SADB_X_EXT_SA_REPLAY,
3541 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3542 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3543 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY,
3544 SADB_EXT_KEY_AUTH, SADB_EXT_KEY_ENCRYPT,
3545 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
3546 SADB_EXT_SENSITIVITY,
3547 SADB_X_EXT_NAT_T_TYPE,
3548 SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3549 SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3550 SADB_X_EXT_NAT_T_FRAG,
3552 uint32_t replay_count;
3554 m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3559 for (i = nitems(dumporder) - 1; i >= 0; i--) {
3561 switch (dumporder[i]) {
3563 m = key_setsadbsa(sav);
3568 case SADB_X_EXT_SA2:
3570 replay_count = sav->replay ? sav->replay->count : 0;
3571 SECASVAR_UNLOCK(sav);
3572 m = key_setsadbxsa2(sav->sah->saidx.mode, replay_count,
3573 sav->sah->saidx.reqid);
3578 case SADB_X_EXT_SA_REPLAY:
3579 if (sav->replay == NULL ||
3580 sav->replay->wsize <= UINT8_MAX)
3583 m = key_setsadbxsareplay(sav->replay->wsize);
3588 case SADB_EXT_ADDRESS_SRC:
3589 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3590 &sav->sah->saidx.src.sa,
3591 FULLMASK, IPSEC_ULPROTO_ANY);
3596 case SADB_EXT_ADDRESS_DST:
3597 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3598 &sav->sah->saidx.dst.sa,
3599 FULLMASK, IPSEC_ULPROTO_ANY);
3604 case SADB_EXT_KEY_AUTH:
3607 m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3612 case SADB_EXT_KEY_ENCRYPT:
3615 m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3620 case SADB_EXT_LIFETIME_CURRENT:
3621 lft_c.addtime = sav->created;
3622 lft_c.allocations = (uint32_t)counter_u64_fetch(
3623 sav->lft_c_allocations);
3624 lft_c.bytes = counter_u64_fetch(sav->lft_c_bytes);
3625 lft_c.usetime = sav->firstused;
3626 m = key_setlifetime(&lft_c, SADB_EXT_LIFETIME_CURRENT);
3631 case SADB_EXT_LIFETIME_HARD:
3634 m = key_setlifetime(sav->lft_h,
3635 SADB_EXT_LIFETIME_HARD);
3640 case SADB_EXT_LIFETIME_SOFT:
3643 m = key_setlifetime(sav->lft_s,
3644 SADB_EXT_LIFETIME_SOFT);
3650 case SADB_X_EXT_NAT_T_TYPE:
3651 if (sav->natt == NULL)
3653 m = key_setsadbxtype(UDP_ENCAP_ESPINUDP);
3658 case SADB_X_EXT_NAT_T_DPORT:
3659 if (sav->natt == NULL)
3661 m = key_setsadbxport(sav->natt->dport,
3662 SADB_X_EXT_NAT_T_DPORT);
3667 case SADB_X_EXT_NAT_T_SPORT:
3668 if (sav->natt == NULL)
3670 m = key_setsadbxport(sav->natt->sport,
3671 SADB_X_EXT_NAT_T_SPORT);
3676 case SADB_X_EXT_NAT_T_OAI:
3677 if (sav->natt == NULL ||
3678 (sav->natt->flags & IPSEC_NATT_F_OAI) == 0)
3680 m = key_setsadbaddr(SADB_X_EXT_NAT_T_OAI,
3681 &sav->natt->oai.sa, FULLMASK, IPSEC_ULPROTO_ANY);
3685 case SADB_X_EXT_NAT_T_OAR:
3686 if (sav->natt == NULL ||
3687 (sav->natt->flags & IPSEC_NATT_F_OAR) == 0)
3689 m = key_setsadbaddr(SADB_X_EXT_NAT_T_OAR,
3690 &sav->natt->oar.sa, FULLMASK, IPSEC_ULPROTO_ANY);
3694 case SADB_X_EXT_NAT_T_FRAG:
3695 /* We do not (yet) support those. */
3698 case SADB_EXT_ADDRESS_PROXY:
3699 case SADB_EXT_IDENTITY_SRC:
3700 case SADB_EXT_IDENTITY_DST:
3701 /* XXX: should we brought from SPD ? */
3702 case SADB_EXT_SENSITIVITY:
3714 m_cat(result, tres);
3716 if (result->m_len < sizeof(struct sadb_msg)) {
3717 result = m_pullup(result, sizeof(struct sadb_msg));
3722 result->m_pkthdr.len = 0;
3723 for (m = result; m; m = m->m_next)
3724 result->m_pkthdr.len += m->m_len;
3726 mtod(result, struct sadb_msg *)->sadb_msg_len =
3727 PFKEY_UNIT64(result->m_pkthdr.len);
3738 * set data into sadb_msg.
3740 static struct mbuf *
3741 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3742 pid_t pid, u_int16_t reserved)
3748 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3751 MGETHDR(m, M_NOWAIT, MT_DATA);
3752 if (m && len > MHLEN) {
3753 if (!(MCLGET(m, M_NOWAIT))) {
3760 m->m_pkthdr.len = m->m_len = len;
3763 p = mtod(m, struct sadb_msg *);
3766 p->sadb_msg_version = PF_KEY_V2;
3767 p->sadb_msg_type = type;
3768 p->sadb_msg_errno = 0;
3769 p->sadb_msg_satype = satype;
3770 p->sadb_msg_len = PFKEY_UNIT64(tlen);
3771 p->sadb_msg_reserved = reserved;
3772 p->sadb_msg_seq = seq;
3773 p->sadb_msg_pid = (u_int32_t)pid;
3779 * copy secasvar data into sadb_address.
3781 static struct mbuf *
3782 key_setsadbsa(struct secasvar *sav)
3788 len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3789 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3794 p = mtod(m, struct sadb_sa *);
3796 p->sadb_sa_len = PFKEY_UNIT64(len);
3797 p->sadb_sa_exttype = SADB_EXT_SA;
3798 p->sadb_sa_spi = sav->spi;
3799 p->sadb_sa_replay = sav->replay ?
3800 (sav->replay->wsize > UINT8_MAX ? UINT8_MAX :
3801 sav->replay->wsize): 0;
3802 p->sadb_sa_state = sav->state;
3803 p->sadb_sa_auth = sav->alg_auth;
3804 p->sadb_sa_encrypt = sav->alg_enc;
3805 p->sadb_sa_flags = sav->flags & SADB_KEY_FLAGS_MAX;
3810 * set data into sadb_address.
3812 static struct mbuf *
3813 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
3814 u_int8_t prefixlen, u_int16_t ul_proto)
3817 struct sadb_address *p;
3820 len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3821 PFKEY_ALIGN8(saddr->sa_len);
3822 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3827 p = mtod(m, struct sadb_address *);
3830 p->sadb_address_len = PFKEY_UNIT64(len);
3831 p->sadb_address_exttype = exttype;
3832 p->sadb_address_proto = ul_proto;
3833 if (prefixlen == FULLMASK) {
3834 switch (saddr->sa_family) {
3836 prefixlen = sizeof(struct in_addr) << 3;
3839 prefixlen = sizeof(struct in6_addr) << 3;
3845 p->sadb_address_prefixlen = prefixlen;
3846 p->sadb_address_reserved = 0;
3849 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3856 * set data into sadb_x_sa2.
3858 static struct mbuf *
3859 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3862 struct sadb_x_sa2 *p;
3865 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3866 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3871 p = mtod(m, struct sadb_x_sa2 *);
3874 p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3875 p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3876 p->sadb_x_sa2_mode = mode;
3877 p->sadb_x_sa2_reserved1 = 0;
3878 p->sadb_x_sa2_reserved2 = 0;
3879 p->sadb_x_sa2_sequence = seq;
3880 p->sadb_x_sa2_reqid = reqid;
3886 * Set data into sadb_x_sa_replay.
3888 static struct mbuf *
3889 key_setsadbxsareplay(u_int32_t replay)
3892 struct sadb_x_sa_replay *p;
3895 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa_replay));
3896 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3901 p = mtod(m, struct sadb_x_sa_replay *);
3904 p->sadb_x_sa_replay_len = PFKEY_UNIT64(len);
3905 p->sadb_x_sa_replay_exttype = SADB_X_EXT_SA_REPLAY;
3906 p->sadb_x_sa_replay_replay = (replay << 3);
3912 * Set a type in sadb_x_nat_t_type.
3914 static struct mbuf *
3915 key_setsadbxtype(u_int16_t type)
3919 struct sadb_x_nat_t_type *p;
3921 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3923 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3928 p = mtod(m, struct sadb_x_nat_t_type *);
3931 p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3932 p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3933 p->sadb_x_nat_t_type_type = type;
3938 * Set a port in sadb_x_nat_t_port.
3939 * In contrast to default RFC 2367 behaviour, port is in network byte order.
3941 static struct mbuf *
3942 key_setsadbxport(u_int16_t port, u_int16_t type)
3946 struct sadb_x_nat_t_port *p;
3948 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3950 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3955 p = mtod(m, struct sadb_x_nat_t_port *);
3958 p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3959 p->sadb_x_nat_t_port_exttype = type;
3960 p->sadb_x_nat_t_port_port = port;
3966 * Get port from sockaddr. Port is in network byte order.
3969 key_portfromsaddr(struct sockaddr *sa)
3972 switch (sa->sa_family) {
3975 return ((struct sockaddr_in *)sa)->sin_port;
3979 return ((struct sockaddr_in6 *)sa)->sin6_port;
3986 * Set port in struct sockaddr. Port is in network byte order.
3989 key_porttosaddr(struct sockaddr *sa, uint16_t port)
3992 switch (sa->sa_family) {
3995 ((struct sockaddr_in *)sa)->sin_port = port;
4000 ((struct sockaddr_in6 *)sa)->sin6_port = port;
4004 ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
4005 __func__, sa->sa_family));
4011 * set data into sadb_x_policy
4013 static struct mbuf *
4014 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id, u_int32_t priority)
4017 struct sadb_x_policy *p;
4020 len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
4021 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
4026 p = mtod(m, struct sadb_x_policy *);
4029 p->sadb_x_policy_len = PFKEY_UNIT64(len);
4030 p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
4031 p->sadb_x_policy_type = type;
4032 p->sadb_x_policy_dir = dir;
4033 p->sadb_x_policy_id = id;
4034 p->sadb_x_policy_priority = priority;
4040 /* Take a key message (sadb_key) from the socket and turn it into one
4041 * of the kernel's key structures (seckey).
4043 * IN: pointer to the src
4044 * OUT: NULL no more memory
4047 key_dup_keymsg(const struct sadb_key *src, size_t len,
4048 struct malloc_type *type)
4052 dst = malloc(sizeof(*dst), type, M_NOWAIT);
4054 dst->bits = src->sadb_key_bits;
4055 dst->key_data = malloc(len, type, M_NOWAIT);
4056 if (dst->key_data != NULL) {
4057 bcopy((const char *)(src + 1), dst->key_data, len);
4059 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
4065 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
4071 /* Take a lifetime message (sadb_lifetime) passed in on a socket and
4072 * turn it into one of the kernel's lifetime structures (seclifetime).
4074 * IN: pointer to the destination, source and malloc type
4075 * OUT: NULL, no more memory
4078 static struct seclifetime *
4079 key_dup_lifemsg(const struct sadb_lifetime *src, struct malloc_type *type)
4081 struct seclifetime *dst;
4083 dst = malloc(sizeof(*dst), type, M_NOWAIT);
4085 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4088 dst->allocations = src->sadb_lifetime_allocations;
4089 dst->bytes = src->sadb_lifetime_bytes;
4090 dst->addtime = src->sadb_lifetime_addtime;
4091 dst->usetime = src->sadb_lifetime_usetime;
4096 * compare two secasindex structure.
4097 * flag can specify to compare 2 saidxes.
4098 * compare two secasindex structure without both mode and reqid.
4099 * don't compare port.
4101 * saidx0: source, it can be in SAD.
4108 key_cmpsaidx(const struct secasindex *saidx0, const struct secasindex *saidx1,
4113 if (saidx0 == NULL && saidx1 == NULL)
4116 if (saidx0 == NULL || saidx1 == NULL)
4119 if (saidx0->proto != saidx1->proto)
4122 if (flag == CMP_EXACTLY) {
4123 if (saidx0->mode != saidx1->mode)
4125 if (saidx0->reqid != saidx1->reqid)
4127 if (bcmp(&saidx0->src, &saidx1->src,
4128 saidx0->src.sa.sa_len) != 0 ||
4129 bcmp(&saidx0->dst, &saidx1->dst,
4130 saidx0->dst.sa.sa_len) != 0)
4133 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4134 if (flag == CMP_MODE_REQID || flag == CMP_REQID) {
4136 * If reqid of SPD is non-zero, unique SA is required.
4137 * The result must be of same reqid in this case.
4139 if (saidx1->reqid != 0 &&
4140 saidx0->reqid != saidx1->reqid)
4144 if (flag == CMP_MODE_REQID) {
4145 if (saidx0->mode != IPSEC_MODE_ANY
4146 && saidx0->mode != saidx1->mode)
4150 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0)
4152 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0)
4160 * compare two secindex structure exactly.
4162 * spidx0: source, it is often in SPD.
4163 * spidx1: object, it is often from PFKEY message.
4169 key_cmpspidx_exactly(struct secpolicyindex *spidx0,
4170 struct secpolicyindex *spidx1)
4173 if (spidx0 == NULL && spidx1 == NULL)
4176 if (spidx0 == NULL || spidx1 == NULL)
4179 if (spidx0->prefs != spidx1->prefs
4180 || spidx0->prefd != spidx1->prefd
4181 || spidx0->ul_proto != spidx1->ul_proto
4182 || spidx0->dir != spidx1->dir)
4185 return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4186 key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4190 * compare two secindex structure with mask.
4192 * spidx0: source, it is often in SPD.
4193 * spidx1: object, it is often from IP header.
4199 key_cmpspidx_withmask(struct secpolicyindex *spidx0,
4200 struct secpolicyindex *spidx1)
4203 if (spidx0 == NULL && spidx1 == NULL)
4206 if (spidx0 == NULL || spidx1 == NULL)
4209 if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4210 spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4211 spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4212 spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4215 /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4216 if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4217 && spidx0->ul_proto != spidx1->ul_proto)
4220 switch (spidx0->src.sa.sa_family) {
4222 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4223 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4225 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4226 &spidx1->src.sin.sin_addr, spidx0->prefs))
4230 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4231 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4234 * scope_id check. if sin6_scope_id is 0, we regard it
4235 * as a wildcard scope, which matches any scope zone ID.
4237 if (spidx0->src.sin6.sin6_scope_id &&
4238 spidx1->src.sin6.sin6_scope_id &&
4239 spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4241 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4242 &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4247 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4252 switch (spidx0->dst.sa.sa_family) {
4254 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4255 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4257 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4258 &spidx1->dst.sin.sin_addr, spidx0->prefd))
4262 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4263 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4266 * scope_id check. if sin6_scope_id is 0, we regard it
4267 * as a wildcard scope, which matches any scope zone ID.
4269 if (spidx0->dst.sin6.sin6_scope_id &&
4270 spidx1->dst.sin6.sin6_scope_id &&
4271 spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4273 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4274 &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4279 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4284 /* XXX Do we check other field ? e.g. flowinfo */
4292 #define satosin(s) ((const struct sockaddr_in *)s)
4296 #define satosin6(s) ((const struct sockaddr_in6 *)s)
4297 /* returns 0 on match */
4299 key_sockaddrcmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
4302 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4305 switch (sa1->sa_family) {
4308 if (sa1->sa_len != sizeof(struct sockaddr_in))
4310 if (satosin(sa1)->sin_addr.s_addr !=
4311 satosin(sa2)->sin_addr.s_addr) {
4314 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4320 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4321 return 1; /*EINVAL*/
4322 if (satosin6(sa1)->sin6_scope_id !=
4323 satosin6(sa2)->sin6_scope_id) {
4326 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4327 &satosin6(sa2)->sin6_addr)) {
4331 satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4337 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4345 /* returns 0 on match */
4347 key_sockaddrcmp_withmask(const struct sockaddr *sa1,
4348 const struct sockaddr *sa2, size_t mask)
4350 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4353 switch (sa1->sa_family) {
4356 return (!key_bbcmp(&satosin(sa1)->sin_addr,
4357 &satosin(sa2)->sin_addr, mask));
4361 if (satosin6(sa1)->sin6_scope_id !=
4362 satosin6(sa2)->sin6_scope_id)
4364 return (!key_bbcmp(&satosin6(sa1)->sin6_addr,
4365 &satosin6(sa2)->sin6_addr, mask));
4374 * compare two buffers with mask.
4378 * bits: Number of bits to compare
4384 key_bbcmp(const void *a1, const void *a2, u_int bits)
4386 const unsigned char *p1 = a1;
4387 const unsigned char *p2 = a2;
4389 /* XXX: This could be considerably faster if we compare a word
4390 * at a time, but it is complicated on LSB Endian machines */
4392 /* Handle null pointers */
4393 if (p1 == NULL || p2 == NULL)
4403 u_int8_t mask = ~((1<<(8-bits))-1);
4404 if ((*p1 & mask) != (*p2 & mask))
4407 return 1; /* Match! */
4411 key_flush_spd(time_t now)
4413 SPTREE_RLOCK_TRACKER;
4414 struct secpolicy_list drainq;
4415 struct secpolicy *sp, *nextsp;
4420 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4421 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
4422 if (sp->lifetime == 0 && sp->validtime == 0)
4424 if ((sp->lifetime &&
4425 now - sp->created > sp->lifetime) ||
4427 now - sp->lastused > sp->validtime)) {
4428 /* Hold extra reference to send SPDEXPIRE */
4430 LIST_INSERT_HEAD(&drainq, sp, drainq);
4435 if (LIST_EMPTY(&drainq))
4439 sp = LIST_FIRST(&drainq);
4440 while (sp != NULL) {
4441 nextsp = LIST_NEXT(sp, drainq);
4442 /* Check that SP is still linked */
4443 if (sp->state != IPSEC_SPSTATE_ALIVE) {
4444 LIST_REMOVE(sp, drainq);
4445 key_freesp(&sp); /* release extra reference */
4449 TAILQ_REMOVE(&V_sptree[sp->spidx.dir], sp, chain);
4451 LIST_REMOVE(sp, idhash);
4452 sp->state = IPSEC_SPSTATE_DEAD;
4457 if (SPDCACHE_ENABLED())
4460 sp = LIST_FIRST(&drainq);
4461 while (sp != NULL) {
4462 nextsp = LIST_NEXT(sp, drainq);
4464 key_freesp(&sp); /* release extra reference */
4465 key_freesp(&sp); /* release last reference */
4471 key_flush_sad(time_t now)
4473 SAHTREE_RLOCK_TRACKER;
4474 struct secashead_list emptyq;
4475 struct secasvar_list drainq, hexpireq, sexpireq, freeq;
4476 struct secashead *sah, *nextsah;
4477 struct secasvar *sav, *nextsav;
4480 LIST_INIT(&hexpireq);
4481 LIST_INIT(&sexpireq);
4485 TAILQ_FOREACH(sah, &V_sahtree, chain) {
4486 /* Check for empty SAH */
4487 if (TAILQ_EMPTY(&sah->savtree_larval) &&
4488 TAILQ_EMPTY(&sah->savtree_alive)) {
4490 LIST_INSERT_HEAD(&emptyq, sah, drainq);
4493 /* Add all stale LARVAL SAs into drainq */
4494 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
4495 if (now - sav->created < V_key_larval_lifetime)
4498 LIST_INSERT_HEAD(&drainq, sav, drainq);
4500 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
4501 /* lifetimes aren't specified */
4502 if (sav->lft_h == NULL)
4506 * Check again with lock held, because it may
4507 * be updated by SADB_UPDATE.
4509 if (sav->lft_h == NULL) {
4510 SECASVAR_UNLOCK(sav);
4515 * HARD lifetimes MUST take precedence over SOFT
4516 * lifetimes, meaning if the HARD and SOFT lifetimes
4517 * are the same, the HARD lifetime will appear on the
4520 /* check HARD lifetime */
4521 if ((sav->lft_h->addtime != 0 &&
4522 now - sav->created > sav->lft_h->addtime) ||
4523 (sav->lft_h->usetime != 0 && sav->firstused &&
4524 now - sav->firstused > sav->lft_h->usetime) ||
4525 (sav->lft_h->bytes != 0 && counter_u64_fetch(
4526 sav->lft_c_bytes) > sav->lft_h->bytes)) {
4527 SECASVAR_UNLOCK(sav);
4529 LIST_INSERT_HEAD(&hexpireq, sav, drainq);
4532 /* check SOFT lifetime (only for MATURE SAs) */
4533 if (sav->state == SADB_SASTATE_MATURE && (
4534 (sav->lft_s->addtime != 0 &&
4535 now - sav->created > sav->lft_s->addtime) ||
4536 (sav->lft_s->usetime != 0 && sav->firstused &&
4537 now - sav->firstused > sav->lft_s->usetime) ||
4538 (sav->lft_s->bytes != 0 && counter_u64_fetch(
4539 sav->lft_c_bytes) > sav->lft_s->bytes))) {
4540 SECASVAR_UNLOCK(sav);
4542 LIST_INSERT_HEAD(&sexpireq, sav, drainq);
4545 SECASVAR_UNLOCK(sav);
4550 if (LIST_EMPTY(&emptyq) && LIST_EMPTY(&drainq) &&
4551 LIST_EMPTY(&hexpireq) && LIST_EMPTY(&sexpireq))
4556 /* Unlink stale LARVAL SAs */
4557 sav = LIST_FIRST(&drainq);
4558 while (sav != NULL) {
4559 nextsav = LIST_NEXT(sav, drainq);
4560 /* Check that SA is still LARVAL */
4561 if (sav->state != SADB_SASTATE_LARVAL) {
4562 LIST_REMOVE(sav, drainq);
4563 LIST_INSERT_HEAD(&freeq, sav, drainq);
4567 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
4568 LIST_REMOVE(sav, spihash);
4569 sav->state = SADB_SASTATE_DEAD;
4572 /* Unlink all SAs with expired HARD lifetime */
4573 sav = LIST_FIRST(&hexpireq);
4574 while (sav != NULL) {
4575 nextsav = LIST_NEXT(sav, drainq);
4576 /* Check that SA is not unlinked */
4577 if (sav->state == SADB_SASTATE_DEAD) {
4578 LIST_REMOVE(sav, drainq);
4579 LIST_INSERT_HEAD(&freeq, sav, drainq);
4583 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
4584 LIST_REMOVE(sav, spihash);
4585 sav->state = SADB_SASTATE_DEAD;
4588 /* Mark all SAs with expired SOFT lifetime as DYING */
4589 sav = LIST_FIRST(&sexpireq);
4590 while (sav != NULL) {
4591 nextsav = LIST_NEXT(sav, drainq);
4592 /* Check that SA is not unlinked */
4593 if (sav->state == SADB_SASTATE_DEAD) {
4594 LIST_REMOVE(sav, drainq);
4595 LIST_INSERT_HEAD(&freeq, sav, drainq);
4600 * NOTE: this doesn't change SA order in the chain.
4602 sav->state = SADB_SASTATE_DYING;
4605 /* Unlink empty SAHs */
4606 sah = LIST_FIRST(&emptyq);
4607 while (sah != NULL) {
4608 nextsah = LIST_NEXT(sah, drainq);
4609 /* Check that SAH is still empty and not unlinked */
4610 if (sah->state == SADB_SASTATE_DEAD ||
4611 !TAILQ_EMPTY(&sah->savtree_larval) ||
4612 !TAILQ_EMPTY(&sah->savtree_alive)) {
4613 LIST_REMOVE(sah, drainq);
4614 key_freesah(&sah); /* release extra reference */
4618 TAILQ_REMOVE(&V_sahtree, sah, chain);
4619 LIST_REMOVE(sah, addrhash);
4620 sah->state = SADB_SASTATE_DEAD;
4625 /* Send SPDEXPIRE messages */
4626 sav = LIST_FIRST(&hexpireq);
4627 while (sav != NULL) {
4628 nextsav = LIST_NEXT(sav, drainq);
4630 key_freesah(&sav->sah); /* release reference from SAV */
4631 key_freesav(&sav); /* release extra reference */
4632 key_freesav(&sav); /* release last reference */
4635 sav = LIST_FIRST(&sexpireq);
4636 while (sav != NULL) {
4637 nextsav = LIST_NEXT(sav, drainq);
4639 key_freesav(&sav); /* release extra reference */
4642 /* Free stale LARVAL SAs */
4643 sav = LIST_FIRST(&drainq);
4644 while (sav != NULL) {
4645 nextsav = LIST_NEXT(sav, drainq);
4646 key_freesah(&sav->sah); /* release reference from SAV */
4647 key_freesav(&sav); /* release extra reference */
4648 key_freesav(&sav); /* release last reference */
4651 /* Free SAs that were unlinked/changed by someone else */
4652 sav = LIST_FIRST(&freeq);
4653 while (sav != NULL) {
4654 nextsav = LIST_NEXT(sav, drainq);
4655 key_freesav(&sav); /* release extra reference */
4658 /* Free empty SAH */
4659 sah = LIST_FIRST(&emptyq);
4660 while (sah != NULL) {
4661 nextsah = LIST_NEXT(sah, drainq);
4662 key_freesah(&sah); /* release extra reference */
4663 key_freesah(&sah); /* release last reference */
4669 key_flush_acq(time_t now)
4671 struct secacq *acq, *nextacq;
4675 acq = LIST_FIRST(&V_acqtree);
4676 while (acq != NULL) {
4677 nextacq = LIST_NEXT(acq, chain);
4678 if (now - acq->created > V_key_blockacq_lifetime) {
4679 LIST_REMOVE(acq, chain);
4680 LIST_REMOVE(acq, addrhash);
4681 LIST_REMOVE(acq, seqhash);
4682 free(acq, M_IPSEC_SAQ);
4690 key_flush_spacq(time_t now)
4692 struct secspacq *acq, *nextacq;
4696 for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4697 nextacq = LIST_NEXT(acq, chain);
4698 if (now - acq->created > V_key_blockacq_lifetime
4699 && __LIST_CHAINED(acq)) {
4700 LIST_REMOVE(acq, chain);
4701 free(acq, M_IPSEC_SAQ);
4709 * scanning SPD and SAD to check status for each entries,
4710 * and do to remove or to expire.
4711 * XXX: year 2038 problem may remain.
4714 key_timehandler(void *arg)
4716 VNET_ITERATOR_DECL(vnet_iter);
4717 time_t now = time_second;
4719 VNET_LIST_RLOCK_NOSLEEP();
4720 VNET_FOREACH(vnet_iter) {
4721 CURVNET_SET(vnet_iter);
4725 key_flush_spacq(now);
4728 VNET_LIST_RUNLOCK_NOSLEEP();
4730 #ifndef IPSEC_DEBUG2
4731 /* do exchange to tick time !! */
4732 callout_schedule(&key_timer, hz);
4733 #endif /* IPSEC_DEBUG2 */
4741 arc4random_buf(&value, sizeof(value));
4746 * map SADB_SATYPE_* to IPPROTO_*.
4747 * if satype == SADB_SATYPE then satype is mapped to ~0.
4749 * 0: invalid satype.
4752 key_satype2proto(uint8_t satype)
4755 case SADB_SATYPE_UNSPEC:
4756 return IPSEC_PROTO_ANY;
4757 case SADB_SATYPE_AH:
4759 case SADB_SATYPE_ESP:
4761 case SADB_X_SATYPE_IPCOMP:
4762 return IPPROTO_IPCOMP;
4763 case SADB_X_SATYPE_TCPSIGNATURE:
4772 * map IPPROTO_* to SADB_SATYPE_*
4774 * 0: invalid protocol type.
4777 key_proto2satype(uint8_t proto)
4781 return SADB_SATYPE_AH;
4783 return SADB_SATYPE_ESP;
4784 case IPPROTO_IPCOMP:
4785 return SADB_X_SATYPE_IPCOMP;
4787 return SADB_X_SATYPE_TCPSIGNATURE;
4796 * SADB_GETSPI processing is to receive
4797 * <base, (SA2), src address, dst address, (SPI range)>
4798 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4799 * tree with the status of LARVAL, and send
4800 * <base, SA(*), address(SD)>
4803 * IN: mhp: pointer to the pointer to each header.
4804 * OUT: NULL if fail.
4805 * other if success, return pointer to the message to send.
4808 key_getspi(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4810 struct secasindex saidx;
4811 struct sadb_address *src0, *dst0;
4812 struct secasvar *sav;
4813 uint32_t reqid, spi;
4815 uint8_t mode, proto;
4817 IPSEC_ASSERT(so != NULL, ("null socket"));
4818 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4819 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4820 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4822 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
4823 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST)
4824 #ifdef PFKEY_STRICT_CHECKS
4825 || SADB_CHECKHDR(mhp, SADB_EXT_SPIRANGE)
4828 ipseclog((LOG_DEBUG,
4829 "%s: invalid message: missing required header.\n",
4834 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
4835 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)
4836 #ifdef PFKEY_STRICT_CHECKS
4837 || SADB_CHECKLEN(mhp, SADB_EXT_SPIRANGE)
4840 ipseclog((LOG_DEBUG,
4841 "%s: invalid message: wrong header size.\n", __func__));
4845 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
4846 mode = IPSEC_MODE_ANY;
4849 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
4850 ipseclog((LOG_DEBUG,
4851 "%s: invalid message: wrong header size.\n",
4856 mode = ((struct sadb_x_sa2 *)
4857 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4858 reqid = ((struct sadb_x_sa2 *)
4859 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4862 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4863 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4865 /* map satype to proto */
4866 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4867 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4872 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
4873 (struct sockaddr *)(dst0 + 1));
4875 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
4879 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4881 /* SPI allocation */
4882 spi = key_do_getnewspi(
4883 (struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE], &saidx);
4886 * Requested SPI or SPI range is not available or
4892 sav = key_newsav(mhp, &saidx, spi, &error);
4896 if (sav->seq != 0) {
4899 * If the SADB_GETSPI message is in response to a
4900 * kernel-generated SADB_ACQUIRE, the sadb_msg_seq
4901 * MUST be the same as the SADB_ACQUIRE message.
4903 * XXXAE: However it doesn't definethe behaviour how to
4904 * check this and what to do if it doesn't match.
4905 * Also what we should do if it matches?
4907 * We can compare saidx used in SADB_ACQUIRE with saidx
4908 * used in SADB_GETSPI, but this probably can break
4909 * existing software. For now just warn if it doesn't match.
4911 * XXXAE: anyway it looks useless.
4913 key_acqdone(&saidx, sav->seq);
4916 printf("%s: SA(%p)\n", __func__, sav));
4917 KEYDBG(KEY_DATA, kdebug_secasv(sav));
4920 struct mbuf *n, *nn;
4921 struct sadb_sa *m_sa;
4922 struct sadb_msg *newmsg;
4925 /* create new sadb_msg to reply. */
4926 len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4927 PFKEY_ALIGN8(sizeof(struct sadb_sa));
4929 MGETHDR(n, M_NOWAIT, MT_DATA);
4931 if (!(MCLGET(n, M_NOWAIT))) {
4945 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4946 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4948 m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4949 m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4950 m_sa->sadb_sa_exttype = SADB_EXT_SA;
4951 m_sa->sadb_sa_spi = spi; /* SPI is already in network byte order */
4952 off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4954 IPSEC_ASSERT(off == len,
4955 ("length inconsistency (off %u len %u)", off, len));
4957 n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4958 SADB_EXT_ADDRESS_DST);
4965 if (n->m_len < sizeof(struct sadb_msg)) {
4966 n = m_pullup(n, sizeof(struct sadb_msg));
4968 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4971 n->m_pkthdr.len = 0;
4972 for (nn = n; nn; nn = nn->m_next)
4973 n->m_pkthdr.len += nn->m_len;
4975 newmsg = mtod(n, struct sadb_msg *);
4976 newmsg->sadb_msg_seq = sav->seq;
4977 newmsg->sadb_msg_errno = 0;
4978 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4981 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4985 return (key_senderror(so, m, error));
4989 * allocating new SPI
4990 * called by key_getspi().
4993 * others: success, SPI in network byte order.
4996 key_do_getnewspi(struct sadb_spirange *spirange, struct secasindex *saidx)
4998 uint32_t min, max, newspi, t;
4999 int count = V_key_spi_trycnt;
5001 /* set spi range to allocate */
5002 if (spirange != NULL) {
5003 min = spirange->sadb_spirange_min;
5004 max = spirange->sadb_spirange_max;
5006 min = V_key_spi_minval;
5007 max = V_key_spi_maxval;
5009 /* IPCOMP needs 2-byte SPI */
5010 if (saidx->proto == IPPROTO_IPCOMP) {
5016 t = min; min = max; max = t;
5021 if (!key_checkspidup(htonl(min))) {
5022 ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
5027 count--; /* taking one cost. */
5033 /* when requesting to allocate spi ranged */
5035 /* generate pseudo-random SPI value ranged. */
5036 newspi = min + (key_random() % (max - min + 1));
5037 if (!key_checkspidup(htonl(newspi)))
5041 if (count == 0 || newspi == 0) {
5042 ipseclog((LOG_DEBUG,
5043 "%s: failed to allocate SPI.\n", __func__));
5049 keystat.getspi_count =
5050 (keystat.getspi_count + V_key_spi_trycnt - count) / 2;
5052 return (htonl(newspi));
5056 * Find TCP-MD5 SA with corresponding secasindex.
5057 * If not found, return NULL and fill SPI with usable value if needed.
5059 static struct secasvar *
5060 key_getsav_tcpmd5(struct secasindex *saidx, uint32_t *spi)
5062 SAHTREE_RLOCK_TRACKER;
5063 struct secashead *sah;
5064 struct secasvar *sav;
5066 IPSEC_ASSERT(saidx->proto == IPPROTO_TCP, ("wrong proto"));
5068 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
5069 if (sah->saidx.proto != IPPROTO_TCP)
5071 if (!key_sockaddrcmp(&saidx->dst.sa, &sah->saidx.dst.sa, 0) &&
5072 !key_sockaddrcmp(&saidx->src.sa, &sah->saidx.src.sa, 0))
5076 if (V_key_preferred_oldsa)
5077 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
5079 sav = TAILQ_FIRST(&sah->savtree_alive);
5087 /* No SPI required */
5091 /* Check that SPI is unique */
5092 LIST_FOREACH(sav, SAVHASH_HASH(*spi), spihash) {
5093 if (sav->spi == *spi)
5098 /* SPI is already unique */
5102 /* XXX: not optimal */
5103 *spi = key_do_getnewspi(NULL, saidx);
5108 key_updateaddresses(struct socket *so, struct mbuf *m,
5109 const struct sadb_msghdr *mhp, struct secasvar *sav,
5110 struct secasindex *saidx)
5112 struct sockaddr *newaddr;
5113 struct secashead *sah;
5114 struct secasvar *newsav, *tmp;
5118 /* Check that we need to change SAH */
5119 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC)) {
5120 newaddr = (struct sockaddr *)(
5121 ((struct sadb_address *)
5122 mhp->ext[SADB_X_EXT_NEW_ADDRESS_SRC]) + 1);
5123 bcopy(newaddr, &saidx->src, newaddr->sa_len);
5124 key_porttosaddr(&saidx->src.sa, 0);
5126 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST)) {
5127 newaddr = (struct sockaddr *)(
5128 ((struct sadb_address *)
5129 mhp->ext[SADB_X_EXT_NEW_ADDRESS_DST]) + 1);
5130 bcopy(newaddr, &saidx->dst, newaddr->sa_len);
5131 key_porttosaddr(&saidx->dst.sa, 0);
5133 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC) ||
5134 !SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST)) {
5135 error = key_checksockaddrs(&saidx->src.sa, &saidx->dst.sa);
5137 ipseclog((LOG_DEBUG, "%s: invalid new sockaddr.\n",
5142 sah = key_getsah(saidx);
5144 /* create a new SA index */
5145 sah = key_newsah(saidx);
5147 ipseclog((LOG_DEBUG,
5148 "%s: No more memory.\n", __func__));
5151 isnew = 2; /* SAH is new */
5153 isnew = 1; /* existing SAH is referenced */
5156 * src and dst addresses are still the same.
5157 * Do we want to change NAT-T config?
5159 if (sav->sah->saidx.proto != IPPROTO_ESP ||
5160 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5161 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_SPORT) ||
5162 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5163 ipseclog((LOG_DEBUG,
5164 "%s: invalid message: missing required header.\n",
5168 /* We hold reference to SA, thus SAH will be referenced too. */
5173 newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA,
5175 if (newsav == NULL) {
5176 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5181 /* Clone SA's content into newsav */
5182 SAV_INITREF(newsav);
5183 bcopy(sav, newsav, offsetof(struct secasvar, chain));
5185 * We create new NAT-T config if it is needed.
5186 * Old NAT-T config will be freed by key_cleansav() when
5187 * last reference to SA will be released.
5189 newsav->natt = NULL;
5191 newsav->state = SADB_SASTATE_MATURE;
5192 error = key_setnatt(newsav, mhp);
5197 /* Check that SA is still alive */
5198 if (sav->state == SADB_SASTATE_DEAD) {
5199 /* SA was unlinked */
5205 /* Unlink SA from SAH and SPI hash */
5206 IPSEC_ASSERT((sav->flags & SADB_X_EXT_F_CLONED) == 0,
5207 ("SA is already cloned"));
5208 IPSEC_ASSERT(sav->state == SADB_SASTATE_MATURE ||
5209 sav->state == SADB_SASTATE_DYING,
5210 ("Wrong SA state %u\n", sav->state));
5211 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
5212 LIST_REMOVE(sav, spihash);
5213 sav->state = SADB_SASTATE_DEAD;
5216 * Link new SA with SAH. Keep SAs ordered by
5217 * create time (newer are first).
5219 TAILQ_FOREACH(tmp, &sah->savtree_alive, chain) {
5220 if (newsav->created > tmp->created) {
5221 TAILQ_INSERT_BEFORE(tmp, newsav, chain);
5226 TAILQ_INSERT_TAIL(&sah->savtree_alive, newsav, chain);
5228 /* Add new SA into SPI hash. */
5229 LIST_INSERT_HEAD(SAVHASH_HASH(newsav->spi), newsav, spihash);
5231 /* Add new SAH into SADB. */
5233 TAILQ_INSERT_HEAD(&V_sahtree, sah, chain);
5234 LIST_INSERT_HEAD(SAHADDRHASH_HASH(saidx), sah, addrhash);
5235 sah->state = SADB_SASTATE_MATURE;
5236 SAH_ADDREF(sah); /* newsav references new SAH */
5239 * isnew == 1 -> @sah was referenced by key_getsah().
5240 * isnew == 0 -> we use the same @sah, that was used by @sav,
5241 * and we use its reference for @newsav.
5244 /* XXX: replace cntr with pointer? */
5245 newsav->cntr = sav->cntr;
5246 sav->flags |= SADB_X_EXT_F_CLONED;
5247 SECASVAR_UNLOCK(sav);
5252 printf("%s: SA(%p) cloned into SA(%p)\n",
5253 __func__, sav, newsav));
5254 KEYDBG(KEY_DATA, kdebug_secasv(newsav));
5256 key_freesav(&sav); /* release last reference */
5258 /* set msg buf from mhp */
5259 n = key_getmsgbuf_x1(m, mhp);
5261 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5265 key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5270 if (newsav != NULL) {
5271 if (newsav->natt != NULL)
5272 free(newsav->natt, M_IPSEC_MISC);
5273 free(newsav, M_IPSEC_SA);
5279 * SADB_UPDATE processing
5281 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5282 * key(AE), (identity(SD),) (sensitivity)>
5283 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
5285 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5286 * (identity(SD),) (sensitivity)>
5289 * m will always be freed.
5292 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5294 struct secasindex saidx;
5295 struct sadb_address *src0, *dst0;
5296 struct sadb_sa *sa0;
5297 struct secasvar *sav;
5300 uint8_t mode, proto;
5302 IPSEC_ASSERT(so != NULL, ("null socket"));
5303 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5304 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5305 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5307 /* map satype to proto */
5308 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5309 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5311 return key_senderror(so, m, EINVAL);
5314 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
5315 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5316 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5317 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
5318 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
5319 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
5320 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
5321 ipseclog((LOG_DEBUG,
5322 "%s: invalid message: missing required header.\n",
5324 return key_senderror(so, m, EINVAL);
5326 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
5327 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5328 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5329 ipseclog((LOG_DEBUG,
5330 "%s: invalid message: wrong header size.\n", __func__));
5331 return key_senderror(so, m, EINVAL);
5333 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
5334 mode = IPSEC_MODE_ANY;
5337 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
5338 ipseclog((LOG_DEBUG,
5339 "%s: invalid message: wrong header size.\n",
5341 return key_senderror(so, m, EINVAL);
5343 mode = ((struct sadb_x_sa2 *)
5344 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5345 reqid = ((struct sadb_x_sa2 *)
5346 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5349 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5350 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5351 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5354 * Only SADB_SASTATE_MATURE SAs may be submitted in an
5355 * SADB_UPDATE message.
5357 if (sa0->sadb_sa_state != SADB_SASTATE_MATURE) {
5358 ipseclog((LOG_DEBUG, "%s: invalid state.\n", __func__));
5359 #ifdef PFKEY_STRICT_CHECKS
5360 return key_senderror(so, m, EINVAL);
5363 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
5364 (struct sockaddr *)(dst0 + 1));
5366 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5367 return key_senderror(so, m, error);
5369 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5370 sav = key_getsavbyspi(sa0->sadb_sa_spi);
5372 ipseclog((LOG_DEBUG, "%s: no SA found for SPI %u\n",
5373 __func__, ntohl(sa0->sadb_sa_spi)));
5374 return key_senderror(so, m, EINVAL);
5377 * Check that SADB_UPDATE issued by the same process that did
5378 * SADB_GETSPI or SADB_ADD.
5380 if (sav->pid != mhp->msg->sadb_msg_pid) {
5381 ipseclog((LOG_DEBUG,
5382 "%s: pid mismatched (SPI %u, pid %u vs. %u)\n", __func__,
5383 ntohl(sav->spi), sav->pid, mhp->msg->sadb_msg_pid));
5385 return key_senderror(so, m, EINVAL);
5387 /* saidx should match with SA. */
5388 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_MODE_REQID) == 0) {
5389 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u\n",
5390 __func__, ntohl(sav->spi)));
5392 return key_senderror(so, m, ESRCH);
5395 if (sav->state == SADB_SASTATE_LARVAL) {
5396 if ((mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5397 SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT)) ||
5398 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5399 SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH))) {
5400 ipseclog((LOG_DEBUG,
5401 "%s: invalid message: missing required header.\n",
5404 return key_senderror(so, m, EINVAL);
5407 * We can set any values except src, dst and SPI.
5409 error = key_setsaval(sav, mhp);
5412 return (key_senderror(so, m, error));
5414 /* Change SA state to MATURE */
5416 if (sav->state != SADB_SASTATE_LARVAL) {
5417 /* SA was deleted or another thread made it MATURE. */
5420 return (key_senderror(so, m, ESRCH));
5423 * NOTE: we keep SAs in savtree_alive ordered by created
5424 * time. When SA's state changed from LARVAL to MATURE,
5425 * we update its created time in key_setsaval() and move
5426 * it into head of savtree_alive.
5428 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
5429 TAILQ_INSERT_HEAD(&sav->sah->savtree_alive, sav, chain);
5430 sav->state = SADB_SASTATE_MATURE;
5434 * For DYING and MATURE SA we can change only state
5435 * and lifetimes. Report EINVAL if something else attempted
5438 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT) ||
5439 !SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH)) {
5441 return (key_senderror(so, m, EINVAL));
5443 error = key_updatelifetimes(sav, mhp);
5446 return (key_senderror(so, m, error));
5449 * This is FreeBSD extension to RFC2367.
5450 * IKEd can specify SADB_X_EXT_NEW_ADDRESS_SRC and/or
5451 * SADB_X_EXT_NEW_ADDRESS_DST when it wants to change
5452 * SA addresses (for example to implement MOBIKE protocol
5453 * as described in RFC4555). Also we allow to change
5456 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC) ||
5457 !SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST) ||
5458 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5459 sav->natt != NULL) {
5460 error = key_updateaddresses(so, m, mhp, sav, &saidx);
5463 return (key_senderror(so, m, error));
5466 /* Check that SA is still alive */
5468 if (sav->state == SADB_SASTATE_DEAD) {
5469 /* SA was unlinked */
5472 return (key_senderror(so, m, ESRCH));
5475 * NOTE: there is possible state moving from DYING to MATURE,
5476 * but this doesn't change created time, so we won't reorder
5479 sav->state = SADB_SASTATE_MATURE;
5483 printf("%s: SA(%p)\n", __func__, sav));
5484 KEYDBG(KEY_DATA, kdebug_secasv(sav));
5490 /* set msg buf from mhp */
5491 n = key_getmsgbuf_x1(m, mhp);
5493 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5494 return key_senderror(so, m, ENOBUFS);
5498 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5503 * SADB_ADD processing
5504 * add an entry to SA database, when received
5505 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5506 * key(AE), (identity(SD),) (sensitivity)>
5509 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5510 * (identity(SD),) (sensitivity)>
5513 * IGNORE identity and sensitivity messages.
5515 * m will always be freed.
5518 key_add(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5520 struct secasindex saidx;
5521 struct sadb_address *src0, *dst0;
5522 struct sadb_sa *sa0;
5523 struct secasvar *sav;
5524 uint32_t reqid, spi;
5525 uint8_t mode, proto;
5528 IPSEC_ASSERT(so != NULL, ("null socket"));
5529 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5530 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5531 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5533 /* map satype to proto */
5534 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5535 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5537 return key_senderror(so, m, EINVAL);
5540 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
5541 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5542 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5543 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP && (
5544 SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT) ||
5545 SADB_CHECKLEN(mhp, SADB_EXT_KEY_ENCRYPT))) ||
5546 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH && (
5547 SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH) ||
5548 SADB_CHECKLEN(mhp, SADB_EXT_KEY_AUTH))) ||
5549 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
5550 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
5551 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
5552 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
5553 ipseclog((LOG_DEBUG,
5554 "%s: invalid message: missing required header.\n",
5556 return key_senderror(so, m, EINVAL);
5558 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
5559 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5560 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5561 ipseclog((LOG_DEBUG,
5562 "%s: invalid message: wrong header size.\n", __func__));
5563 return key_senderror(so, m, EINVAL);
5565 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
5566 mode = IPSEC_MODE_ANY;
5569 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
5570 ipseclog((LOG_DEBUG,
5571 "%s: invalid message: wrong header size.\n",
5573 return key_senderror(so, m, EINVAL);
5575 mode = ((struct sadb_x_sa2 *)
5576 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5577 reqid = ((struct sadb_x_sa2 *)
5578 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5581 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5582 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5583 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5586 * Only SADB_SASTATE_MATURE SAs may be submitted in an
5589 if (sa0->sadb_sa_state != SADB_SASTATE_MATURE) {
5590 ipseclog((LOG_DEBUG, "%s: invalid state.\n", __func__));
5591 #ifdef PFKEY_STRICT_CHECKS
5592 return key_senderror(so, m, EINVAL);
5595 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
5596 (struct sockaddr *)(dst0 + 1));
5598 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5599 return key_senderror(so, m, error);
5601 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5602 spi = sa0->sadb_sa_spi;
5604 * For TCP-MD5 SAs we don't use SPI. Check the uniqueness using
5606 * XXXAE: IPComp seems also doesn't use SPI.
5608 if (proto == IPPROTO_TCP) {
5609 sav = key_getsav_tcpmd5(&saidx, &spi);
5610 if (sav == NULL && spi == 0) {
5611 /* Failed to allocate SPI */
5612 ipseclog((LOG_DEBUG, "%s: SA already exists.\n",
5614 return key_senderror(so, m, EEXIST);
5616 /* XXX: SPI that we report back can have another value */
5618 /* We can create new SA only if SPI is different. */
5619 sav = key_getsavbyspi(spi);
5623 ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5624 return key_senderror(so, m, EEXIST);
5627 sav = key_newsav(mhp, &saidx, spi, &error);
5629 return key_senderror(so, m, error);
5631 printf("%s: return SA(%p)\n", __func__, sav));
5632 KEYDBG(KEY_DATA, kdebug_secasv(sav));
5634 * If SADB_ADD was in response to SADB_ACQUIRE, we need to schedule
5638 key_acqdone(&saidx, sav->seq);
5642 * Don't call key_freesav() on error here, as we would like to
5643 * keep the SA in the database.
5647 /* set msg buf from mhp */
5648 n = key_getmsgbuf_x1(m, mhp);
5650 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5651 return key_senderror(so, m, ENOBUFS);
5655 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5661 * IKEd may request the use ESP in UDP encapsulation when it detects the
5662 * presence of NAT. It uses NAT-T extension headers for such SAs to specify
5663 * parameters needed for encapsulation and decapsulation. These PF_KEY
5664 * extension headers are not standardized, so this comment addresses our
5666 * SADB_X_EXT_NAT_T_TYPE specifies type of encapsulation, we support only
5667 * UDP_ENCAP_ESPINUDP as described in RFC3948.
5668 * SADB_X_EXT_NAT_T_SPORT/DPORT specifies source and destination ports for
5669 * UDP header. We use these ports in UDP encapsulation procedure, also we
5670 * can check them in UDP decapsulation procedure.
5671 * SADB_X_EXT_NAT_T_OA[IR] specifies original address of initiator or
5672 * responder. These addresses can be used for transport mode to adjust
5673 * checksum after decapsulation and decryption. Since original IP addresses
5674 * used by peer usually different (we detected presence of NAT), TCP/UDP
5675 * pseudo header checksum and IP header checksum was calculated using original
5676 * addresses. After decapsulation and decryption we need to adjust checksum
5677 * to have correct datagram.
5679 * We expect presence of NAT-T extension headers only in SADB_ADD and
5680 * SADB_UPDATE messages. We report NAT-T extension headers in replies
5681 * to SADB_ADD, SADB_UPDATE, SADB_GET, and SADB_DUMP messages.
5684 key_setnatt(struct secasvar *sav, const struct sadb_msghdr *mhp)
5686 struct sadb_x_nat_t_port *port;
5687 struct sadb_x_nat_t_type *type;
5688 struct sadb_address *oai, *oar;
5689 struct sockaddr *sa;
5693 IPSEC_ASSERT(sav->natt == NULL, ("natt is already initialized"));
5695 * Ignore NAT-T headers if sproto isn't ESP.
5697 if (sav->sah->saidx.proto != IPPROTO_ESP)
5700 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) &&
5701 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_SPORT) &&
5702 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5703 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5704 SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_SPORT) ||
5705 SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5706 ipseclog((LOG_DEBUG,
5707 "%s: invalid message: wrong header size.\n",
5714 type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5715 if (type->sadb_x_nat_t_type_type != UDP_ENCAP_ESPINUDP) {
5716 ipseclog((LOG_DEBUG, "%s: unsupported NAT-T type %u.\n",
5717 __func__, type->sadb_x_nat_t_type_type));
5721 * Allocate storage for NAT-T config.
5722 * On error it will be released by key_cleansav().
5724 sav->natt = malloc(sizeof(struct secnatt), M_IPSEC_MISC,
5726 if (sav->natt == NULL) {
5727 PFKEYSTAT_INC(in_nomem);
5728 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5731 port = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5732 if (port->sadb_x_nat_t_port_port == 0) {
5733 ipseclog((LOG_DEBUG, "%s: invalid NAT-T sport specified.\n",
5737 sav->natt->sport = port->sadb_x_nat_t_port_port;
5738 port = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5739 if (port->sadb_x_nat_t_port_port == 0) {
5740 ipseclog((LOG_DEBUG, "%s: invalid NAT-T dport specified.\n",
5744 sav->natt->dport = port->sadb_x_nat_t_port_port;
5747 * SADB_X_EXT_NAT_T_OAI and SADB_X_EXT_NAT_T_OAR are optional
5748 * and needed only for transport mode IPsec.
5749 * Usually NAT translates only one address, but it is possible,
5750 * that both addresses could be translated.
5751 * NOTE: Value of SADB_X_EXT_NAT_T_OAI is equal to SADB_X_EXT_NAT_T_OA.
5753 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_OAI)) {
5754 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_OAI)) {
5755 ipseclog((LOG_DEBUG,
5756 "%s: invalid message: wrong header size.\n",
5760 oai = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5763 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_OAR)) {
5764 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_OAR)) {
5765 ipseclog((LOG_DEBUG,
5766 "%s: invalid message: wrong header size.\n",
5770 oar = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5774 /* Initialize addresses only for transport mode */
5775 if (sav->sah->saidx.mode != IPSEC_MODE_TUNNEL) {
5778 /* Currently we support only AF_INET */
5779 sa = (struct sockaddr *)(oai + 1);
5780 if (sa->sa_family != AF_INET ||
5781 sa->sa_len != sizeof(struct sockaddr_in)) {
5782 ipseclog((LOG_DEBUG,
5783 "%s: wrong NAT-OAi header.\n",
5787 /* Ignore address if it the same */
5788 if (((struct sockaddr_in *)sa)->sin_addr.s_addr !=
5789 sav->sah->saidx.src.sin.sin_addr.s_addr) {
5790 bcopy(sa, &sav->natt->oai.sa, sa->sa_len);
5791 sav->natt->flags |= IPSEC_NATT_F_OAI;
5792 /* Calculate checksum delta */
5793 addr = sav->sah->saidx.src.sin.sin_addr.s_addr;
5794 cksum = in_addword(cksum, ~addr >> 16);
5795 cksum = in_addword(cksum, ~addr & 0xffff);
5796 addr = sav->natt->oai.sin.sin_addr.s_addr;
5797 cksum = in_addword(cksum, addr >> 16);
5798 cksum = in_addword(cksum, addr & 0xffff);
5802 /* Currently we support only AF_INET */
5803 sa = (struct sockaddr *)(oar + 1);
5804 if (sa->sa_family != AF_INET ||
5805 sa->sa_len != sizeof(struct sockaddr_in)) {
5806 ipseclog((LOG_DEBUG,
5807 "%s: wrong NAT-OAr header.\n",
5811 /* Ignore address if it the same */
5812 if (((struct sockaddr_in *)sa)->sin_addr.s_addr !=
5813 sav->sah->saidx.dst.sin.sin_addr.s_addr) {
5814 bcopy(sa, &sav->natt->oar.sa, sa->sa_len);
5815 sav->natt->flags |= IPSEC_NATT_F_OAR;
5816 /* Calculate checksum delta */
5817 addr = sav->sah->saidx.dst.sin.sin_addr.s_addr;
5818 cksum = in_addword(cksum, ~addr >> 16);
5819 cksum = in_addword(cksum, ~addr & 0xffff);
5820 addr = sav->natt->oar.sin.sin_addr.s_addr;
5821 cksum = in_addword(cksum, addr >> 16);
5822 cksum = in_addword(cksum, addr & 0xffff);
5825 sav->natt->cksum = cksum;
5831 key_setident(struct secashead *sah, const struct sadb_msghdr *mhp)
5833 const struct sadb_ident *idsrc, *iddst;
5835 IPSEC_ASSERT(sah != NULL, ("null secashead"));
5836 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5837 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5839 /* don't make buffer if not there */
5840 if (SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_SRC) &&
5841 SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_DST)) {
5847 if (SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_SRC) ||
5848 SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_DST)) {
5849 ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5853 idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5854 iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5856 /* validity check */
5857 if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5858 ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5862 switch (idsrc->sadb_ident_type) {
5863 case SADB_IDENTTYPE_PREFIX:
5864 case SADB_IDENTTYPE_FQDN:
5865 case SADB_IDENTTYPE_USERFQDN:
5867 /* XXX do nothing */
5873 /* make structure */
5874 sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5875 if (sah->idents == NULL) {
5876 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5879 sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5880 if (sah->identd == NULL) {
5881 free(sah->idents, M_IPSEC_MISC);
5883 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5886 sah->idents->type = idsrc->sadb_ident_type;
5887 sah->idents->id = idsrc->sadb_ident_id;
5889 sah->identd->type = iddst->sadb_ident_type;
5890 sah->identd->id = iddst->sadb_ident_id;
5896 * m will not be freed on return.
5897 * it is caller's responsibility to free the result.
5899 * Called from SADB_ADD and SADB_UPDATE. Reply will contain headers
5900 * from the request in defined order.
5902 static struct mbuf *
5903 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
5907 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5908 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5909 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5911 /* create new sadb_msg to reply. */
5912 n = key_gather_mbuf(m, mhp, 1, 16, SADB_EXT_RESERVED,
5913 SADB_EXT_SA, SADB_X_EXT_SA2,
5914 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5915 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5916 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
5917 SADB_X_EXT_NAT_T_TYPE, SADB_X_EXT_NAT_T_SPORT,
5918 SADB_X_EXT_NAT_T_DPORT, SADB_X_EXT_NAT_T_OAI,
5919 SADB_X_EXT_NAT_T_OAR, SADB_X_EXT_NEW_ADDRESS_SRC,
5920 SADB_X_EXT_NEW_ADDRESS_DST);
5924 if (n->m_len < sizeof(struct sadb_msg)) {
5925 n = m_pullup(n, sizeof(struct sadb_msg));
5929 mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5930 mtod(n, struct sadb_msg *)->sadb_msg_len =
5931 PFKEY_UNIT64(n->m_pkthdr.len);
5937 * SADB_DELETE processing
5939 * <base, SA(*), address(SD)>
5940 * from the ikmpd, and set SADB_SASTATE_DEAD,
5942 * <base, SA(*), address(SD)>
5945 * m will always be freed.
5948 key_delete(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5950 struct secasindex saidx;
5951 struct sadb_address *src0, *dst0;
5952 struct secasvar *sav;
5953 struct sadb_sa *sa0;
5956 IPSEC_ASSERT(so != NULL, ("null socket"));
5957 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5958 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5959 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5961 /* map satype to proto */
5962 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5963 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5965 return key_senderror(so, m, EINVAL);
5968 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5969 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5970 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5971 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5972 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5974 return key_senderror(so, m, EINVAL);
5977 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5978 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5980 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
5981 (struct sockaddr *)(dst0 + 1)) != 0) {
5982 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5983 return (key_senderror(so, m, EINVAL));
5985 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5986 if (SADB_CHECKHDR(mhp, SADB_EXT_SA)) {
5988 * Caller wants us to delete all non-LARVAL SAs
5989 * that match the src/dst. This is used during
5990 * IKE INITIAL-CONTACT.
5991 * XXXAE: this looks like some extension to RFC2367.
5993 ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5994 return (key_delete_all(so, m, mhp, &saidx));
5996 if (SADB_CHECKLEN(mhp, SADB_EXT_SA)) {
5997 ipseclog((LOG_DEBUG,
5998 "%s: invalid message: wrong header size.\n", __func__));
5999 return (key_senderror(so, m, EINVAL));
6001 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
6002 if (proto == IPPROTO_TCP)
6003 sav = key_getsav_tcpmd5(&saidx, NULL);
6005 sav = key_getsavbyspi(sa0->sadb_sa_spi);
6007 ipseclog((LOG_DEBUG, "%s: no SA found for SPI %u.\n",
6008 __func__, ntohl(sa0->sadb_sa_spi)));
6009 return (key_senderror(so, m, ESRCH));
6011 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_HEAD) == 0) {
6012 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u.\n",
6013 __func__, ntohl(sav->spi)));
6015 return (key_senderror(so, m, ESRCH));
6018 printf("%s: SA(%p)\n", __func__, sav));
6019 KEYDBG(KEY_DATA, kdebug_secasv(sav));
6025 struct sadb_msg *newmsg;
6027 /* create new sadb_msg to reply. */
6028 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
6029 SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
6031 return key_senderror(so, m, ENOBUFS);
6033 if (n->m_len < sizeof(struct sadb_msg)) {
6034 n = m_pullup(n, sizeof(struct sadb_msg));
6036 return key_senderror(so, m, ENOBUFS);
6038 newmsg = mtod(n, struct sadb_msg *);
6039 newmsg->sadb_msg_errno = 0;
6040 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
6043 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
6048 * delete all SAs for src/dst. Called from key_delete().
6051 key_delete_all(struct socket *so, struct mbuf *m,
6052 const struct sadb_msghdr *mhp, struct secasindex *saidx)
6054 struct secasvar_queue drainq;
6055 struct secashead *sah;
6056 struct secasvar *sav, *nextsav;
6058 TAILQ_INIT(&drainq);
6060 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
6061 if (key_cmpsaidx(&sah->saidx, saidx, CMP_HEAD) == 0)
6063 /* Move all ALIVE SAs into drainq */
6064 TAILQ_CONCAT(&drainq, &sah->savtree_alive, chain);
6066 /* Unlink all queued SAs from SPI hash */
6067 TAILQ_FOREACH(sav, &drainq, chain) {
6068 sav->state = SADB_SASTATE_DEAD;
6069 LIST_REMOVE(sav, spihash);
6072 /* Now we can release reference for all SAs in drainq */
6073 sav = TAILQ_FIRST(&drainq);
6074 while (sav != NULL) {
6076 printf("%s: SA(%p)\n", __func__, sav));
6077 KEYDBG(KEY_DATA, kdebug_secasv(sav));
6078 nextsav = TAILQ_NEXT(sav, chain);
6079 key_freesah(&sav->sah); /* release reference from SAV */
6080 key_freesav(&sav); /* release last reference */
6086 struct sadb_msg *newmsg;
6088 /* create new sadb_msg to reply. */
6089 n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
6090 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
6092 return key_senderror(so, m, ENOBUFS);
6094 if (n->m_len < sizeof(struct sadb_msg)) {
6095 n = m_pullup(n, sizeof(struct sadb_msg));
6097 return key_senderror(so, m, ENOBUFS);
6099 newmsg = mtod(n, struct sadb_msg *);
6100 newmsg->sadb_msg_errno = 0;
6101 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
6104 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
6109 * Delete all alive SAs for corresponding xform.
6110 * Larval SAs have not initialized tdb_xform, so it is safe to leave them
6111 * here when xform disappears.
6114 key_delete_xform(const struct xformsw *xsp)
6116 struct secasvar_queue drainq;
6117 struct secashead *sah;
6118 struct secasvar *sav, *nextsav;
6120 TAILQ_INIT(&drainq);
6122 TAILQ_FOREACH(sah, &V_sahtree, chain) {
6123 sav = TAILQ_FIRST(&sah->savtree_alive);
6126 if (sav->tdb_xform != xsp)
6129 * It is supposed that all SAs in the chain are related to
6132 TAILQ_CONCAT(&drainq, &sah->savtree_alive, chain);
6134 /* Unlink all queued SAs from SPI hash */
6135 TAILQ_FOREACH(sav, &drainq, chain) {
6136 sav->state = SADB_SASTATE_DEAD;
6137 LIST_REMOVE(sav, spihash);
6141 /* Now we can release reference for all SAs in drainq */
6142 sav = TAILQ_FIRST(&drainq);
6143 while (sav != NULL) {
6145 printf("%s: SA(%p)\n", __func__, sav));
6146 KEYDBG(KEY_DATA, kdebug_secasv(sav));
6147 nextsav = TAILQ_NEXT(sav, chain);
6148 key_freesah(&sav->sah); /* release reference from SAV */
6149 key_freesav(&sav); /* release last reference */
6155 * SADB_GET processing
6157 * <base, SA(*), address(SD)>
6158 * from the ikmpd, and get a SP and a SA to respond,
6160 * <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
6161 * (identity(SD),) (sensitivity)>
6164 * m will always be freed.
6167 key_get(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6169 struct secasindex saidx;
6170 struct sadb_address *src0, *dst0;
6171 struct sadb_sa *sa0;
6172 struct secasvar *sav;
6175 IPSEC_ASSERT(so != NULL, ("null socket"));
6176 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6177 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6178 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6180 /* map satype to proto */
6181 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6182 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6184 return key_senderror(so, m, EINVAL);
6187 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
6188 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
6189 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST)) {
6190 ipseclog((LOG_DEBUG,
6191 "%s: invalid message: missing required header.\n",
6193 return key_senderror(so, m, EINVAL);
6195 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
6196 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
6197 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
6198 ipseclog((LOG_DEBUG,
6199 "%s: invalid message: wrong header size.\n", __func__));
6200 return key_senderror(so, m, EINVAL);
6203 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
6204 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6205 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6207 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
6208 (struct sockaddr *)(dst0 + 1)) != 0) {
6209 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
6210 return key_senderror(so, m, EINVAL);
6212 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6214 if (proto == IPPROTO_TCP)
6215 sav = key_getsav_tcpmd5(&saidx, NULL);
6217 sav = key_getsavbyspi(sa0->sadb_sa_spi);
6219 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
6220 return key_senderror(so, m, ESRCH);
6222 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_HEAD) == 0) {
6223 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u.\n",
6224 __func__, ntohl(sa0->sadb_sa_spi)));
6226 return (key_senderror(so, m, ESRCH));
6233 /* map proto to satype */
6234 if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0) {
6235 ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
6238 return key_senderror(so, m, EINVAL);
6241 /* create new sadb_msg to reply. */
6242 n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
6243 mhp->msg->sadb_msg_pid);
6247 return key_senderror(so, m, ENOBUFS);
6250 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6254 /* XXX make it sysctl-configurable? */
6256 key_getcomb_setlifetime(struct sadb_comb *comb)
6259 comb->sadb_comb_soft_allocations = 1;
6260 comb->sadb_comb_hard_allocations = 1;
6261 comb->sadb_comb_soft_bytes = 0;
6262 comb->sadb_comb_hard_bytes = 0;
6263 comb->sadb_comb_hard_addtime = 86400; /* 1 day */
6264 comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
6265 comb->sadb_comb_soft_usetime = 28800; /* 8 hours */
6266 comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
6270 * XXX reorder combinations by preference
6271 * XXX no idea if the user wants ESP authentication or not
6273 static struct mbuf *
6274 key_getcomb_ealg(void)
6276 struct sadb_comb *comb;
6277 const struct enc_xform *algo;
6278 struct mbuf *result = NULL, *m, *n;
6282 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6285 for (i = 1; i <= SADB_EALG_MAX; i++) {
6286 algo = enc_algorithm_lookup(i);
6290 /* discard algorithms with key size smaller than system min */
6291 if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6293 if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6294 encmin = V_ipsec_esp_keymin;
6296 encmin = _BITS(algo->minkey);
6298 if (V_ipsec_esp_auth)
6299 m = key_getcomb_ah();
6301 IPSEC_ASSERT(l <= MLEN,
6302 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6303 MGET(m, M_NOWAIT, MT_DATA);
6308 bzero(mtod(m, caddr_t), m->m_len);
6315 for (n = m; n; n = n->m_next)
6317 IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6319 for (off = 0; off < totlen; off += l) {
6320 n = m_pulldown(m, off, l, &o);
6322 /* m is already freed */
6325 comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6326 bzero(comb, sizeof(*comb));
6327 key_getcomb_setlifetime(comb);
6328 comb->sadb_comb_encrypt = i;
6329 comb->sadb_comb_encrypt_minbits = encmin;
6330 comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6348 key_getsizes_ah(const struct auth_hash *ah, int alg, u_int16_t* min,
6352 *min = *max = ah->hashsize;
6353 if (ah->keysize == 0) {
6355 * Transform takes arbitrary key size but algorithm
6356 * key size is restricted. Enforce this here.
6359 case SADB_X_AALG_NULL: *min = 1; *max = 256; break;
6360 case SADB_X_AALG_SHA2_256: *min = *max = 32; break;
6361 case SADB_X_AALG_SHA2_384: *min = *max = 48; break;
6362 case SADB_X_AALG_SHA2_512: *min = *max = 64; break;
6364 DPRINTF(("%s: unknown AH algorithm %u\n",
6372 * XXX reorder combinations by preference
6374 static struct mbuf *
6377 const struct auth_hash *algo;
6378 struct sadb_comb *comb;
6380 u_int16_t minkeysize, maxkeysize;
6382 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6385 for (i = 1; i <= SADB_AALG_MAX; i++) {
6387 /* we prefer HMAC algorithms, not old algorithms */
6388 if (i != SADB_AALG_SHA1HMAC &&
6389 i != SADB_X_AALG_SHA2_256 &&
6390 i != SADB_X_AALG_SHA2_384 &&
6391 i != SADB_X_AALG_SHA2_512)
6394 algo = auth_algorithm_lookup(i);
6397 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6398 /* discard algorithms with key size smaller than system min */
6399 if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6403 IPSEC_ASSERT(l <= MLEN,
6404 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6405 MGET(m, M_NOWAIT, MT_DATA);
6412 M_PREPEND(m, l, M_NOWAIT);
6416 comb = mtod(m, struct sadb_comb *);
6417 bzero(comb, sizeof(*comb));
6418 key_getcomb_setlifetime(comb);
6419 comb->sadb_comb_auth = i;
6420 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6421 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6428 * not really an official behavior. discussed in pf_key@inner.net in Sep2000.
6429 * XXX reorder combinations by preference
6431 static struct mbuf *
6432 key_getcomb_ipcomp()
6434 const struct comp_algo *algo;
6435 struct sadb_comb *comb;
6438 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6441 for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6442 algo = comp_algorithm_lookup(i);
6447 IPSEC_ASSERT(l <= MLEN,
6448 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6449 MGET(m, M_NOWAIT, MT_DATA);
6456 M_PREPEND(m, l, M_NOWAIT);
6460 comb = mtod(m, struct sadb_comb *);
6461 bzero(comb, sizeof(*comb));
6462 key_getcomb_setlifetime(comb);
6463 comb->sadb_comb_encrypt = i;
6464 /* what should we set into sadb_comb_*_{min,max}bits? */
6471 * XXX no way to pass mode (transport/tunnel) to userland
6472 * XXX replay checking?
6473 * XXX sysctl interface to ipsec_{ah,esp}_keymin
6475 static struct mbuf *
6476 key_getprop(const struct secasindex *saidx)
6478 struct sadb_prop *prop;
6480 const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6483 switch (saidx->proto) {
6485 m = key_getcomb_ealg();
6488 m = key_getcomb_ah();
6490 case IPPROTO_IPCOMP:
6491 m = key_getcomb_ipcomp();
6499 M_PREPEND(m, l, M_NOWAIT);
6504 for (n = m; n; n = n->m_next)
6507 prop = mtod(m, struct sadb_prop *);
6508 bzero(prop, sizeof(*prop));
6509 prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6510 prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6511 prop->sadb_prop_replay = 32; /* XXX */
6517 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6519 * <base, SA, address(SD), (address(P)), x_policy,
6520 * (identity(SD),) (sensitivity,) proposal>
6521 * to KMD, and expect to receive
6522 * <base> with SADB_ACQUIRE if error occurred,
6524 * <base, src address, dst address, (SPI range)> with SADB_GETSPI
6525 * from KMD by PF_KEY.
6527 * XXX x_policy is outside of RFC2367 (KAME extension).
6528 * XXX sensitivity is not supported.
6529 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6530 * see comment for key_getcomb_ipcomp().
6534 * others: error number
6537 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6539 union sockaddr_union addr;
6540 struct mbuf *result, *m;
6544 uint8_t mask, satype;
6546 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6547 satype = key_proto2satype(saidx->proto);
6548 IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6552 ul_proto = IPSEC_ULPROTO_ANY;
6554 /* Get seq number to check whether sending message or not. */
6555 seq = key_getacq(saidx, &error);
6559 m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6567 * set sadb_address for saidx's.
6569 * Note that if sp is supplied, then we're being called from
6570 * key_allocsa_policy() and should supply port and protocol
6572 * XXXAE: why only TCP and UDP? ICMP and SCTP looks applicable too.
6573 * XXXAE: probably we can handle this in the ipsec[46]_allocsa().
6574 * XXXAE: it looks like we should save this info in the ACQ entry.
6576 if (sp != NULL && (sp->spidx.ul_proto == IPPROTO_TCP ||
6577 sp->spidx.ul_proto == IPPROTO_UDP))
6578 ul_proto = sp->spidx.ul_proto;
6582 if (ul_proto != IPSEC_ULPROTO_ANY) {
6583 switch (sp->spidx.src.sa.sa_family) {
6585 if (sp->spidx.src.sin.sin_port != IPSEC_PORT_ANY) {
6586 addr.sin.sin_port = sp->spidx.src.sin.sin_port;
6587 mask = sp->spidx.prefs;
6591 if (sp->spidx.src.sin6.sin6_port != IPSEC_PORT_ANY) {
6592 addr.sin6.sin6_port =
6593 sp->spidx.src.sin6.sin6_port;
6594 mask = sp->spidx.prefs;
6601 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &addr.sa, mask, ul_proto);
6610 if (ul_proto != IPSEC_ULPROTO_ANY) {
6611 switch (sp->spidx.dst.sa.sa_family) {
6613 if (sp->spidx.dst.sin.sin_port != IPSEC_PORT_ANY) {
6614 addr.sin.sin_port = sp->spidx.dst.sin.sin_port;
6615 mask = sp->spidx.prefd;
6619 if (sp->spidx.dst.sin6.sin6_port != IPSEC_PORT_ANY) {
6620 addr.sin6.sin6_port =
6621 sp->spidx.dst.sin6.sin6_port;
6622 mask = sp->spidx.prefd;
6629 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &addr.sa, mask, ul_proto);
6636 /* XXX proxy address (optional) */
6639 * Set sadb_x_policy. This is KAME extension to RFC2367.
6642 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id,
6652 * Set sadb_x_sa2 extension if saidx->reqid is not zero.
6653 * This is FreeBSD extension to RFC2367.
6655 if (saidx->reqid != 0) {
6656 m = key_setsadbxsa2(saidx->mode, 0, saidx->reqid);
6663 /* XXX identity (optional) */
6665 if (idexttype && fqdn) {
6666 /* create identity extension (FQDN) */
6667 struct sadb_ident *id;
6670 fqdnlen = strlen(fqdn) + 1; /* +1 for terminating-NUL */
6671 id = (struct sadb_ident *)p;
6672 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6673 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6674 id->sadb_ident_exttype = idexttype;
6675 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6676 bcopy(fqdn, id + 1, fqdnlen);
6677 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6681 /* create identity extension (USERFQDN) */
6682 struct sadb_ident *id;
6686 /* +1 for terminating-NUL */
6687 userfqdnlen = strlen(userfqdn) + 1;
6690 id = (struct sadb_ident *)p;
6691 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6692 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6693 id->sadb_ident_exttype = idexttype;
6694 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6695 /* XXX is it correct? */
6696 if (curproc && curproc->p_cred)
6697 id->sadb_ident_id = curproc->p_cred->p_ruid;
6698 if (userfqdn && userfqdnlen)
6699 bcopy(userfqdn, id + 1, userfqdnlen);
6700 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6704 /* XXX sensitivity (optional) */
6706 /* create proposal/combination extension */
6707 m = key_getprop(saidx);
6710 * spec conformant: always attach proposal/combination extension,
6711 * the problem is that we have no way to attach it for ipcomp,
6712 * due to the way sadb_comb is declared in RFC2367.
6721 * outside of spec; make proposal/combination extension optional.
6727 if ((result->m_flags & M_PKTHDR) == 0) {
6732 if (result->m_len < sizeof(struct sadb_msg)) {
6733 result = m_pullup(result, sizeof(struct sadb_msg));
6734 if (result == NULL) {
6740 result->m_pkthdr.len = 0;
6741 for (m = result; m; m = m->m_next)
6742 result->m_pkthdr.len += m->m_len;
6744 mtod(result, struct sadb_msg *)->sadb_msg_len =
6745 PFKEY_UNIT64(result->m_pkthdr.len);
6748 printf("%s: SP(%p)\n", __func__, sp));
6749 KEYDBG(KEY_DATA, kdebug_secasindex(saidx, NULL));
6751 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6760 key_newacq(const struct secasindex *saidx, int *perror)
6765 acq = malloc(sizeof(*acq), M_IPSEC_SAQ, M_NOWAIT | M_ZERO);
6767 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6773 bcopy(saidx, &acq->saidx, sizeof(acq->saidx));
6774 acq->created = time_second;
6777 /* add to acqtree */
6779 seq = acq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6780 LIST_INSERT_HEAD(&V_acqtree, acq, chain);
6781 LIST_INSERT_HEAD(ACQADDRHASH_HASH(saidx), acq, addrhash);
6782 LIST_INSERT_HEAD(ACQSEQHASH_HASH(seq), acq, seqhash);
6789 key_getacq(const struct secasindex *saidx, int *perror)
6795 LIST_FOREACH(acq, ACQADDRHASH_HASH(saidx), addrhash) {
6796 if (key_cmpsaidx(&acq->saidx, saidx, CMP_EXACTLY)) {
6797 if (acq->count > V_key_blockacq_count) {
6799 * Reset counter and send message.
6800 * Also reset created time to keep ACQ for
6803 acq->created = time_second;
6808 * Increment counter and do nothing.
6809 * We send SADB_ACQUIRE message only
6810 * for each V_key_blockacq_count packet.
6823 /* allocate new entry */
6824 return (key_newacq(saidx, perror));
6828 key_acqreset(uint32_t seq)
6833 LIST_FOREACH(acq, ACQSEQHASH_HASH(seq), seqhash) {
6834 if (acq->seq == seq) {
6836 acq->created = time_second;
6846 * Mark ACQ entry as stale to remove it in key_flush_acq().
6847 * Called after successful SADB_GETSPI message.
6850 key_acqdone(const struct secasindex *saidx, uint32_t seq)
6855 LIST_FOREACH(acq, ACQSEQHASH_HASH(seq), seqhash) {
6856 if (acq->seq == seq)
6860 if (key_cmpsaidx(&acq->saidx, saidx, CMP_EXACTLY) == 0) {
6861 ipseclog((LOG_DEBUG,
6862 "%s: Mismatched saidx for ACQ %u\n", __func__, seq));
6868 ipseclog((LOG_DEBUG,
6869 "%s: ACQ %u is not found.\n", __func__, seq));
6877 static struct secspacq *
6878 key_newspacq(struct secpolicyindex *spidx)
6880 struct secspacq *acq;
6883 acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6885 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6890 bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6891 acq->created = time_second;
6894 /* add to spacqtree */
6896 LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6902 static struct secspacq *
6903 key_getspacq(struct secpolicyindex *spidx)
6905 struct secspacq *acq;
6908 LIST_FOREACH(acq, &V_spacqtree, chain) {
6909 if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6910 /* NB: return holding spacq_lock */
6920 * SADB_ACQUIRE processing,
6921 * in first situation, is receiving
6923 * from the ikmpd, and clear sequence of its secasvar entry.
6925 * In second situation, is receiving
6926 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6927 * from a user land process, and return
6928 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6931 * m will always be freed.
6934 key_acquire2(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6936 SAHTREE_RLOCK_TRACKER;
6937 struct sadb_address *src0, *dst0;
6938 struct secasindex saidx;
6939 struct secashead *sah;
6942 uint8_t mode, proto;
6944 IPSEC_ASSERT(so != NULL, ("null socket"));
6945 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6946 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6947 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6950 * Error message from KMd.
6951 * We assume that if error was occurred in IKEd, the length of PFKEY
6952 * message is equal to the size of sadb_msg structure.
6953 * We do not raise error even if error occurred in this function.
6955 if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6956 /* check sequence number */
6957 if (mhp->msg->sadb_msg_seq == 0 ||
6958 mhp->msg->sadb_msg_errno == 0) {
6959 ipseclog((LOG_DEBUG, "%s: must specify sequence "
6960 "number and errno.\n", __func__));
6963 * IKEd reported that error occurred.
6964 * XXXAE: what it expects from the kernel?
6965 * Probably we should send SADB_ACQUIRE again?
6966 * If so, reset ACQ's state.
6967 * XXXAE: it looks useless.
6969 key_acqreset(mhp->msg->sadb_msg_seq);
6976 * This message is from user land.
6979 /* map satype to proto */
6980 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6981 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6983 return key_senderror(so, m, EINVAL);
6986 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
6987 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
6988 SADB_CHECKHDR(mhp, SADB_EXT_PROPOSAL)) {
6989 ipseclog((LOG_DEBUG,
6990 "%s: invalid message: missing required header.\n",
6992 return key_senderror(so, m, EINVAL);
6994 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
6995 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
6996 SADB_CHECKLEN(mhp, SADB_EXT_PROPOSAL)) {
6997 ipseclog((LOG_DEBUG,
6998 "%s: invalid message: wrong header size.\n", __func__));
6999 return key_senderror(so, m, EINVAL);
7002 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
7003 mode = IPSEC_MODE_ANY;
7006 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
7007 ipseclog((LOG_DEBUG,
7008 "%s: invalid message: wrong header size.\n",
7010 return key_senderror(so, m, EINVAL);
7012 mode = ((struct sadb_x_sa2 *)
7013 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
7014 reqid = ((struct sadb_x_sa2 *)
7015 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
7018 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
7019 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
7021 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
7022 (struct sockaddr *)(dst0 + 1));
7024 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
7025 return key_senderror(so, m, EINVAL);
7027 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
7029 /* get a SA index */
7031 LIST_FOREACH(sah, SAHADDRHASH_HASH(&saidx), addrhash) {
7032 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
7037 ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
7038 return key_senderror(so, m, EEXIST);
7041 error = key_acquire(&saidx, NULL);
7043 ipseclog((LOG_DEBUG,
7044 "%s: error %d returned from key_acquire()\n",
7046 return key_senderror(so, m, error);
7053 * SADB_REGISTER processing.
7054 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
7057 * from the ikmpd, and register a socket to send PF_KEY messages,
7061 * If socket is detached, must free from regnode.
7063 * m will always be freed.
7066 key_register(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7068 struct secreg *reg, *newreg = NULL;
7070 IPSEC_ASSERT(so != NULL, ("null socket"));
7071 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7072 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7073 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7075 /* check for invalid register message */
7076 if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
7077 return key_senderror(so, m, EINVAL);
7079 /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
7080 if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
7083 /* check whether existing or not */
7085 LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
7086 if (reg->so == so) {
7088 ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
7090 return key_senderror(so, m, EEXIST);
7094 /* create regnode */
7095 newreg = malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
7096 if (newreg == NULL) {
7098 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7099 return key_senderror(so, m, ENOBUFS);
7103 ((struct keycb *)sotorawcb(so))->kp_registered++;
7105 /* add regnode to regtree. */
7106 LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
7112 struct sadb_msg *newmsg;
7113 struct sadb_supported *sup;
7114 u_int len, alen, elen;
7117 struct sadb_alg *alg;
7119 /* create new sadb_msg to reply. */
7121 for (i = 1; i <= SADB_AALG_MAX; i++) {
7122 if (auth_algorithm_lookup(i))
7123 alen += sizeof(struct sadb_alg);
7126 alen += sizeof(struct sadb_supported);
7128 for (i = 1; i <= SADB_EALG_MAX; i++) {
7129 if (enc_algorithm_lookup(i))
7130 elen += sizeof(struct sadb_alg);
7133 elen += sizeof(struct sadb_supported);
7135 len = sizeof(struct sadb_msg) + alen + elen;
7138 return key_senderror(so, m, ENOBUFS);
7140 MGETHDR(n, M_NOWAIT, MT_DATA);
7141 if (n != NULL && len > MHLEN) {
7142 if (!(MCLGET(n, M_NOWAIT))) {
7148 return key_senderror(so, m, ENOBUFS);
7150 n->m_pkthdr.len = n->m_len = len;
7154 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
7155 newmsg = mtod(n, struct sadb_msg *);
7156 newmsg->sadb_msg_errno = 0;
7157 newmsg->sadb_msg_len = PFKEY_UNIT64(len);
7158 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
7160 /* for authentication algorithm */
7162 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
7163 sup->sadb_supported_len = PFKEY_UNIT64(alen);
7164 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
7165 off += PFKEY_ALIGN8(sizeof(*sup));
7167 for (i = 1; i <= SADB_AALG_MAX; i++) {
7168 const struct auth_hash *aalgo;
7169 u_int16_t minkeysize, maxkeysize;
7171 aalgo = auth_algorithm_lookup(i);
7174 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
7175 alg->sadb_alg_id = i;
7176 alg->sadb_alg_ivlen = 0;
7177 key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
7178 alg->sadb_alg_minbits = _BITS(minkeysize);
7179 alg->sadb_alg_maxbits = _BITS(maxkeysize);
7180 off += PFKEY_ALIGN8(sizeof(*alg));
7184 /* for encryption algorithm */
7186 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
7187 sup->sadb_supported_len = PFKEY_UNIT64(elen);
7188 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
7189 off += PFKEY_ALIGN8(sizeof(*sup));
7191 for (i = 1; i <= SADB_EALG_MAX; i++) {
7192 const struct enc_xform *ealgo;
7194 ealgo = enc_algorithm_lookup(i);
7197 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
7198 alg->sadb_alg_id = i;
7199 alg->sadb_alg_ivlen = ealgo->ivsize;
7200 alg->sadb_alg_minbits = _BITS(ealgo->minkey);
7201 alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
7202 off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
7206 IPSEC_ASSERT(off == len,
7207 ("length assumption failed (off %u len %u)", off, len));
7210 return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
7215 * free secreg entry registered.
7216 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
7219 key_freereg(struct socket *so)
7224 IPSEC_ASSERT(so != NULL, ("NULL so"));
7227 * check whether existing or not.
7228 * check all type of SA, because there is a potential that
7229 * one socket is registered to multiple type of SA.
7232 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7233 LIST_FOREACH(reg, &V_regtree[i], chain) {
7234 if (reg->so == so && __LIST_CHAINED(reg)) {
7235 LIST_REMOVE(reg, chain);
7236 free(reg, M_IPSEC_SAR);
7245 * SADB_EXPIRE processing
7247 * <base, SA, SA2, lifetime(C and one of HS), address(SD)>
7249 * NOTE: We send only soft lifetime extension.
7252 * others : error number
7255 key_expire(struct secasvar *sav, int hard)
7257 struct mbuf *result = NULL, *m;
7258 struct sadb_lifetime *lt;
7259 uint32_t replay_count;
7263 IPSEC_ASSERT (sav != NULL, ("null sav"));
7264 IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
7267 printf("%s: SA(%p) expired %s lifetime\n", __func__,
7268 sav, hard ? "hard": "soft"));
7269 KEYDBG(KEY_DATA, kdebug_secasv(sav));
7270 /* set msg header */
7271 satype = key_proto2satype(sav->sah->saidx.proto);
7272 IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
7273 m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
7280 /* create SA extension */
7281 m = key_setsadbsa(sav);
7288 /* create SA extension */
7290 replay_count = sav->replay ? sav->replay->count : 0;
7291 SECASVAR_UNLOCK(sav);
7293 m = key_setsadbxsa2(sav->sah->saidx.mode, replay_count,
7294 sav->sah->saidx.reqid);
7301 if (sav->replay && sav->replay->wsize > UINT8_MAX) {
7302 m = key_setsadbxsareplay(sav->replay->wsize);
7310 /* create lifetime extension (current and soft) */
7311 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
7312 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
7319 bzero(mtod(m, caddr_t), len);
7320 lt = mtod(m, struct sadb_lifetime *);
7321 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7322 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
7323 lt->sadb_lifetime_allocations =
7324 (uint32_t)counter_u64_fetch(sav->lft_c_allocations);
7325 lt->sadb_lifetime_bytes =
7326 counter_u64_fetch(sav->lft_c_bytes);
7327 lt->sadb_lifetime_addtime = sav->created;
7328 lt->sadb_lifetime_usetime = sav->firstused;
7329 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
7330 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7332 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
7333 lt->sadb_lifetime_allocations = sav->lft_h->allocations;
7334 lt->sadb_lifetime_bytes = sav->lft_h->bytes;
7335 lt->sadb_lifetime_addtime = sav->lft_h->addtime;
7336 lt->sadb_lifetime_usetime = sav->lft_h->usetime;
7338 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
7339 lt->sadb_lifetime_allocations = sav->lft_s->allocations;
7340 lt->sadb_lifetime_bytes = sav->lft_s->bytes;
7341 lt->sadb_lifetime_addtime = sav->lft_s->addtime;
7342 lt->sadb_lifetime_usetime = sav->lft_s->usetime;
7346 /* set sadb_address for source */
7347 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
7348 &sav->sah->saidx.src.sa,
7349 FULLMASK, IPSEC_ULPROTO_ANY);
7356 /* set sadb_address for destination */
7357 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
7358 &sav->sah->saidx.dst.sa,
7359 FULLMASK, IPSEC_ULPROTO_ANY);
7367 * XXX-BZ Handle NAT-T extensions here.
7368 * XXXAE: it doesn't seem quite useful. IKEs should not depend on
7369 * this information, we report only significant SA fields.
7372 if ((result->m_flags & M_PKTHDR) == 0) {
7377 if (result->m_len < sizeof(struct sadb_msg)) {
7378 result = m_pullup(result, sizeof(struct sadb_msg));
7379 if (result == NULL) {
7385 result->m_pkthdr.len = 0;
7386 for (m = result; m; m = m->m_next)
7387 result->m_pkthdr.len += m->m_len;
7389 mtod(result, struct sadb_msg *)->sadb_msg_len =
7390 PFKEY_UNIT64(result->m_pkthdr.len);
7392 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7401 key_freesah_flushed(struct secashead_queue *flushq)
7403 struct secashead *sah, *nextsah;
7404 struct secasvar *sav, *nextsav;
7406 sah = TAILQ_FIRST(flushq);
7407 while (sah != NULL) {
7408 sav = TAILQ_FIRST(&sah->savtree_larval);
7409 while (sav != NULL) {
7410 nextsav = TAILQ_NEXT(sav, chain);
7411 TAILQ_REMOVE(&sah->savtree_larval, sav, chain);
7412 key_freesav(&sav); /* release last reference */
7413 key_freesah(&sah); /* release reference from SAV */
7416 sav = TAILQ_FIRST(&sah->savtree_alive);
7417 while (sav != NULL) {
7418 nextsav = TAILQ_NEXT(sav, chain);
7419 TAILQ_REMOVE(&sah->savtree_alive, sav, chain);
7420 key_freesav(&sav); /* release last reference */
7421 key_freesah(&sah); /* release reference from SAV */
7424 nextsah = TAILQ_NEXT(sah, chain);
7425 key_freesah(&sah); /* release last reference */
7431 * SADB_FLUSH processing
7434 * from the ikmpd, and free all entries in secastree.
7438 * NOTE: to do is only marking SADB_SASTATE_DEAD.
7440 * m will always be freed.
7443 key_flush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7445 struct secashead_queue flushq;
7446 struct sadb_msg *newmsg;
7447 struct secashead *sah, *nextsah;
7448 struct secasvar *sav;
7452 IPSEC_ASSERT(so != NULL, ("null socket"));
7453 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7454 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7456 /* map satype to proto */
7457 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7458 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7460 return key_senderror(so, m, EINVAL);
7463 printf("%s: proto %u\n", __func__, proto));
7465 TAILQ_INIT(&flushq);
7466 if (proto == IPSEC_PROTO_ANY) {
7467 /* no SATYPE specified, i.e. flushing all SA. */
7469 /* Move all SAHs into flushq */
7470 TAILQ_CONCAT(&flushq, &V_sahtree, chain);
7471 /* Flush all buckets in SPI hash */
7472 for (i = 0; i < V_savhash_mask + 1; i++)
7473 LIST_INIT(&V_savhashtbl[i]);
7474 /* Flush all buckets in SAHADDRHASH */
7475 for (i = 0; i < V_sahaddrhash_mask + 1; i++)
7476 LIST_INIT(&V_sahaddrhashtbl[i]);
7477 /* Mark all SAHs as unlinked */
7478 TAILQ_FOREACH(sah, &flushq, chain) {
7479 sah->state = SADB_SASTATE_DEAD;
7481 * Callout handler makes its job using
7482 * RLOCK and drain queues. In case, when this
7483 * function will be called just before it
7484 * acquires WLOCK, we need to mark SAs as
7485 * unlinked to prevent second unlink.
7487 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7488 sav->state = SADB_SASTATE_DEAD;
7490 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7491 sav->state = SADB_SASTATE_DEAD;
7497 sah = TAILQ_FIRST(&V_sahtree);
7498 while (sah != NULL) {
7499 IPSEC_ASSERT(sah->state != SADB_SASTATE_DEAD,
7500 ("DEAD SAH %p in SADB_FLUSH", sah));
7501 nextsah = TAILQ_NEXT(sah, chain);
7502 if (sah->saidx.proto != proto) {
7506 sah->state = SADB_SASTATE_DEAD;
7507 TAILQ_REMOVE(&V_sahtree, sah, chain);
7508 LIST_REMOVE(sah, addrhash);
7509 /* Unlink all SAs from SPI hash */
7510 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7511 LIST_REMOVE(sav, spihash);
7512 sav->state = SADB_SASTATE_DEAD;
7514 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7515 LIST_REMOVE(sav, spihash);
7516 sav->state = SADB_SASTATE_DEAD;
7518 /* Add SAH into flushq */
7519 TAILQ_INSERT_HEAD(&flushq, sah, chain);
7525 key_freesah_flushed(&flushq);
7526 /* Free all queued SAs and SAHs */
7527 if (m->m_len < sizeof(struct sadb_msg) ||
7528 sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7529 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7530 return key_senderror(so, m, ENOBUFS);
7536 m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7537 newmsg = mtod(m, struct sadb_msg *);
7538 newmsg->sadb_msg_errno = 0;
7539 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7541 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7545 * SADB_DUMP processing
7546 * dump all entries including status of DEAD in SAD.
7549 * from the ikmpd, and dump all secasvar leaves
7554 * m will always be freed.
7557 key_dump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7559 SAHTREE_RLOCK_TRACKER;
7560 struct secashead *sah;
7561 struct secasvar *sav;
7564 uint8_t proto, satype;
7566 IPSEC_ASSERT(so != NULL, ("null socket"));
7567 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7568 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7569 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7571 /* map satype to proto */
7572 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7573 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7575 return key_senderror(so, m, EINVAL);
7578 /* count sav entries to be sent to the userland. */
7581 TAILQ_FOREACH(sah, &V_sahtree, chain) {
7582 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
7583 proto != sah->saidx.proto)
7586 TAILQ_FOREACH(sav, &sah->savtree_larval, chain)
7588 TAILQ_FOREACH(sav, &sah->savtree_alive, chain)
7594 return key_senderror(so, m, ENOENT);
7597 /* send this to the userland, one at a time. */
7598 TAILQ_FOREACH(sah, &V_sahtree, chain) {
7599 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
7600 proto != sah->saidx.proto)
7603 /* map proto to satype */
7604 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7606 ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7607 "SAD.\n", __func__));
7608 return key_senderror(so, m, EINVAL);
7610 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7611 n = key_setdumpsa(sav, SADB_DUMP, satype,
7612 --cnt, mhp->msg->sadb_msg_pid);
7615 return key_senderror(so, m, ENOBUFS);
7617 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7619 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7620 n = key_setdumpsa(sav, SADB_DUMP, satype,
7621 --cnt, mhp->msg->sadb_msg_pid);
7624 return key_senderror(so, m, ENOBUFS);
7626 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7634 * SADB_X_PROMISC processing
7636 * m will always be freed.
7639 key_promisc(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7643 IPSEC_ASSERT(so != NULL, ("null socket"));
7644 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7645 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7646 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7648 olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7650 if (olen < sizeof(struct sadb_msg)) {
7652 return key_senderror(so, m, EINVAL);
7657 } else if (olen == sizeof(struct sadb_msg)) {
7658 /* enable/disable promisc mode */
7661 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7662 return key_senderror(so, m, EINVAL);
7663 mhp->msg->sadb_msg_errno = 0;
7664 switch (mhp->msg->sadb_msg_satype) {
7667 kp->kp_promisc = mhp->msg->sadb_msg_satype;
7670 return key_senderror(so, m, EINVAL);
7673 /* send the original message back to everyone */
7674 mhp->msg->sadb_msg_errno = 0;
7675 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7677 /* send packet as is */
7679 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7681 /* TODO: if sadb_msg_seq is specified, send to specific pid */
7682 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7686 static int (*key_typesw[])(struct socket *, struct mbuf *,
7687 const struct sadb_msghdr *) = {
7688 NULL, /* SADB_RESERVED */
7689 key_getspi, /* SADB_GETSPI */
7690 key_update, /* SADB_UPDATE */
7691 key_add, /* SADB_ADD */
7692 key_delete, /* SADB_DELETE */
7693 key_get, /* SADB_GET */
7694 key_acquire2, /* SADB_ACQUIRE */
7695 key_register, /* SADB_REGISTER */
7696 NULL, /* SADB_EXPIRE */
7697 key_flush, /* SADB_FLUSH */
7698 key_dump, /* SADB_DUMP */
7699 key_promisc, /* SADB_X_PROMISC */
7700 NULL, /* SADB_X_PCHANGE */
7701 key_spdadd, /* SADB_X_SPDUPDATE */
7702 key_spdadd, /* SADB_X_SPDADD */
7703 key_spddelete, /* SADB_X_SPDDELETE */
7704 key_spdget, /* SADB_X_SPDGET */
7705 NULL, /* SADB_X_SPDACQUIRE */
7706 key_spddump, /* SADB_X_SPDDUMP */
7707 key_spdflush, /* SADB_X_SPDFLUSH */
7708 key_spdadd, /* SADB_X_SPDSETIDX */
7709 NULL, /* SADB_X_SPDEXPIRE */
7710 key_spddelete2, /* SADB_X_SPDDELETE2 */
7714 * parse sadb_msg buffer to process PFKEYv2,
7715 * and create a data to response if needed.
7716 * I think to be dealed with mbuf directly.
7718 * msgp : pointer to pointer to a received buffer pulluped.
7719 * This is rewrited to response.
7720 * so : pointer to socket.
7722 * length for buffer to send to user process.
7725 key_parse(struct mbuf *m, struct socket *so)
7727 struct sadb_msg *msg;
7728 struct sadb_msghdr mh;
7733 IPSEC_ASSERT(so != NULL, ("null socket"));
7734 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7736 if (m->m_len < sizeof(struct sadb_msg)) {
7737 m = m_pullup(m, sizeof(struct sadb_msg));
7741 msg = mtod(m, struct sadb_msg *);
7742 orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7743 target = KEY_SENDUP_ONE;
7745 if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len != orglen) {
7746 ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7747 PFKEYSTAT_INC(out_invlen);
7752 if (msg->sadb_msg_version != PF_KEY_V2) {
7753 ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7754 __func__, msg->sadb_msg_version));
7755 PFKEYSTAT_INC(out_invver);
7760 if (msg->sadb_msg_type > SADB_MAX) {
7761 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7762 __func__, msg->sadb_msg_type));
7763 PFKEYSTAT_INC(out_invmsgtype);
7768 /* for old-fashioned code - should be nuked */
7769 if (m->m_pkthdr.len > MCLBYTES) {
7776 MGETHDR(n, M_NOWAIT, MT_DATA);
7777 if (n && m->m_pkthdr.len > MHLEN) {
7778 if (!(MCLGET(n, M_NOWAIT))) {
7787 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7788 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7794 /* align the mbuf chain so that extensions are in contiguous region. */
7795 error = key_align(m, &mh);
7801 /* We use satype as scope mask for spddump */
7802 if (msg->sadb_msg_type == SADB_X_SPDDUMP) {
7803 switch (msg->sadb_msg_satype) {
7804 case IPSEC_POLICYSCOPE_ANY:
7805 case IPSEC_POLICYSCOPE_GLOBAL:
7806 case IPSEC_POLICYSCOPE_IFNET:
7807 case IPSEC_POLICYSCOPE_PCB:
7810 ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7811 __func__, msg->sadb_msg_type));
7812 PFKEYSTAT_INC(out_invsatype);
7817 switch (msg->sadb_msg_satype) { /* check SA type */
7818 case SADB_SATYPE_UNSPEC:
7819 switch (msg->sadb_msg_type) {
7827 ipseclog((LOG_DEBUG, "%s: must specify satype "
7828 "when msg type=%u.\n", __func__,
7829 msg->sadb_msg_type));
7830 PFKEYSTAT_INC(out_invsatype);
7835 case SADB_SATYPE_AH:
7836 case SADB_SATYPE_ESP:
7837 case SADB_X_SATYPE_IPCOMP:
7838 case SADB_X_SATYPE_TCPSIGNATURE:
7839 switch (msg->sadb_msg_type) {
7841 case SADB_X_SPDDELETE:
7843 case SADB_X_SPDFLUSH:
7844 case SADB_X_SPDSETIDX:
7845 case SADB_X_SPDUPDATE:
7846 case SADB_X_SPDDELETE2:
7847 ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7848 __func__, msg->sadb_msg_type));
7849 PFKEYSTAT_INC(out_invsatype);
7854 case SADB_SATYPE_RSVP:
7855 case SADB_SATYPE_OSPFV2:
7856 case SADB_SATYPE_RIPV2:
7857 case SADB_SATYPE_MIP:
7858 ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7859 __func__, msg->sadb_msg_satype));
7860 PFKEYSTAT_INC(out_invsatype);
7863 case 1: /* XXX: What does it do? */
7864 if (msg->sadb_msg_type == SADB_X_PROMISC)
7868 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7869 __func__, msg->sadb_msg_satype));
7870 PFKEYSTAT_INC(out_invsatype);
7876 /* check field of upper layer protocol and address family */
7877 if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7878 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7879 struct sadb_address *src0, *dst0;
7882 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7883 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7885 /* check upper layer protocol */
7886 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7887 ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7888 "mismatched.\n", __func__));
7889 PFKEYSTAT_INC(out_invaddr);
7895 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7896 PFKEY_ADDR_SADDR(dst0)->sa_family) {
7897 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7899 PFKEYSTAT_INC(out_invaddr);
7903 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7904 PFKEY_ADDR_SADDR(dst0)->sa_len) {
7905 ipseclog((LOG_DEBUG, "%s: address struct size "
7906 "mismatched.\n", __func__));
7907 PFKEYSTAT_INC(out_invaddr);
7912 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7914 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7915 sizeof(struct sockaddr_in)) {
7916 PFKEYSTAT_INC(out_invaddr);
7922 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7923 sizeof(struct sockaddr_in6)) {
7924 PFKEYSTAT_INC(out_invaddr);
7930 ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7932 PFKEYSTAT_INC(out_invaddr);
7933 error = EAFNOSUPPORT;
7937 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7939 plen = sizeof(struct in_addr) << 3;
7942 plen = sizeof(struct in6_addr) << 3;
7945 plen = 0; /*fool gcc*/
7949 /* check max prefix length */
7950 if (src0->sadb_address_prefixlen > plen ||
7951 dst0->sadb_address_prefixlen > plen) {
7952 ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7954 PFKEYSTAT_INC(out_invaddr);
7960 * prefixlen == 0 is valid because there can be a case when
7961 * all addresses are matched.
7965 if (msg->sadb_msg_type >= nitems(key_typesw) ||
7966 key_typesw[msg->sadb_msg_type] == NULL) {
7967 PFKEYSTAT_INC(out_invmsgtype);
7972 return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7975 msg->sadb_msg_errno = error;
7976 return key_sendup_mbuf(so, m, target);
7980 key_senderror(struct socket *so, struct mbuf *m, int code)
7982 struct sadb_msg *msg;
7984 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7985 ("mbuf too small, len %u", m->m_len));
7987 msg = mtod(m, struct sadb_msg *);
7988 msg->sadb_msg_errno = code;
7989 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7993 * set the pointer to each header into message buffer.
7994 * m will be freed on error.
7995 * XXX larger-than-MCLBYTES extension?
7998 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
8001 struct sadb_ext *ext;
8006 IPSEC_ASSERT(m != NULL, ("null mbuf"));
8007 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
8008 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
8009 ("mbuf too small, len %u", m->m_len));
8012 bzero(mhp, sizeof(*mhp));
8014 mhp->msg = mtod(m, struct sadb_msg *);
8015 mhp->ext[0] = (struct sadb_ext *)mhp->msg; /*XXX backward compat */
8017 end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
8018 extlen = end; /*just in case extlen is not updated*/
8019 for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
8020 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
8022 /* m is already freed */
8025 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
8028 switch (ext->sadb_ext_type) {
8030 case SADB_EXT_ADDRESS_SRC:
8031 case SADB_EXT_ADDRESS_DST:
8032 case SADB_EXT_ADDRESS_PROXY:
8033 case SADB_EXT_LIFETIME_CURRENT:
8034 case SADB_EXT_LIFETIME_HARD:
8035 case SADB_EXT_LIFETIME_SOFT:
8036 case SADB_EXT_KEY_AUTH:
8037 case SADB_EXT_KEY_ENCRYPT:
8038 case SADB_EXT_IDENTITY_SRC:
8039 case SADB_EXT_IDENTITY_DST:
8040 case SADB_EXT_SENSITIVITY:
8041 case SADB_EXT_PROPOSAL:
8042 case SADB_EXT_SUPPORTED_AUTH:
8043 case SADB_EXT_SUPPORTED_ENCRYPT:
8044 case SADB_EXT_SPIRANGE:
8045 case SADB_X_EXT_POLICY:
8046 case SADB_X_EXT_SA2:
8047 case SADB_X_EXT_NAT_T_TYPE:
8048 case SADB_X_EXT_NAT_T_SPORT:
8049 case SADB_X_EXT_NAT_T_DPORT:
8050 case SADB_X_EXT_NAT_T_OAI:
8051 case SADB_X_EXT_NAT_T_OAR:
8052 case SADB_X_EXT_NAT_T_FRAG:
8053 case SADB_X_EXT_SA_REPLAY:
8054 case SADB_X_EXT_NEW_ADDRESS_SRC:
8055 case SADB_X_EXT_NEW_ADDRESS_DST:
8056 /* duplicate check */
8058 * XXX Are there duplication payloads of either
8059 * KEY_AUTH or KEY_ENCRYPT ?
8061 if (mhp->ext[ext->sadb_ext_type] != NULL) {
8062 ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
8063 "%u\n", __func__, ext->sadb_ext_type));
8065 PFKEYSTAT_INC(out_dupext);
8070 ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
8071 __func__, ext->sadb_ext_type));
8073 PFKEYSTAT_INC(out_invexttype);
8077 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
8079 if (key_validate_ext(ext, extlen)) {
8081 PFKEYSTAT_INC(out_invlen);
8085 n = m_pulldown(m, off, extlen, &toff);
8087 /* m is already freed */
8090 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
8092 mhp->ext[ext->sadb_ext_type] = ext;
8093 mhp->extoff[ext->sadb_ext_type] = off;
8094 mhp->extlen[ext->sadb_ext_type] = extlen;
8099 PFKEYSTAT_INC(out_invlen);
8107 key_validate_ext(const struct sadb_ext *ext, int len)
8109 const struct sockaddr *sa;
8110 enum { NONE, ADDR } checktype = NONE;
8112 const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
8114 if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
8117 /* if it does not match minimum/maximum length, bail */
8118 if (ext->sadb_ext_type >= nitems(minsize) ||
8119 ext->sadb_ext_type >= nitems(maxsize))
8121 if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
8123 if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
8126 /* more checks based on sadb_ext_type XXX need more */
8127 switch (ext->sadb_ext_type) {
8128 case SADB_EXT_ADDRESS_SRC:
8129 case SADB_EXT_ADDRESS_DST:
8130 case SADB_EXT_ADDRESS_PROXY:
8131 case SADB_X_EXT_NAT_T_OAI:
8132 case SADB_X_EXT_NAT_T_OAR:
8133 case SADB_X_EXT_NEW_ADDRESS_SRC:
8134 case SADB_X_EXT_NEW_ADDRESS_DST:
8135 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
8138 case SADB_EXT_IDENTITY_SRC:
8139 case SADB_EXT_IDENTITY_DST:
8140 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
8141 SADB_X_IDENTTYPE_ADDR) {
8142 baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
8152 switch (checktype) {
8156 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
8157 if (len < baselen + sal)
8159 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
8172 TUNABLE_INT_FETCH("net.key.spdcache.maxentries",
8173 &V_key_spdcache_maxentries);
8174 TUNABLE_INT_FETCH("net.key.spdcache.threshold",
8175 &V_key_spdcache_threshold);
8177 if (V_key_spdcache_maxentries) {
8178 V_key_spdcache_maxentries = MAX(V_key_spdcache_maxentries,
8179 SPDCACHE_MAX_ENTRIES_PER_HASH);
8180 V_spdcachehashtbl = hashinit(V_key_spdcache_maxentries /
8181 SPDCACHE_MAX_ENTRIES_PER_HASH,
8182 M_IPSEC_SPDCACHE, &V_spdcachehash_mask);
8183 V_key_spdcache_maxentries = (V_spdcachehash_mask + 1)
8184 * SPDCACHE_MAX_ENTRIES_PER_HASH;
8186 V_spdcache_lock = malloc(sizeof(struct mtx) *
8187 (V_spdcachehash_mask + 1),
8188 M_IPSEC_SPDCACHE, M_WAITOK|M_ZERO);
8190 for (i = 0; i < V_spdcachehash_mask + 1; ++i)
8191 SPDCACHE_LOCK_INIT(i);
8195 struct spdcache_entry *
8196 spdcache_entry_alloc(const struct secpolicyindex *spidx, struct secpolicy *sp)
8198 struct spdcache_entry *entry;
8200 entry = malloc(sizeof(struct spdcache_entry),
8201 M_IPSEC_SPDCACHE, M_NOWAIT|M_ZERO);
8208 entry->spidx = *spidx;
8215 spdcache_entry_free(struct spdcache_entry *entry)
8218 if (entry->sp != NULL)
8219 key_freesp(&entry->sp);
8220 free(entry, M_IPSEC_SPDCACHE);
8224 spdcache_clear(void)
8226 struct spdcache_entry *entry;
8229 for (i = 0; i < V_spdcachehash_mask + 1; ++i) {
8231 while (!LIST_EMPTY(&V_spdcachehashtbl[i])) {
8232 entry = LIST_FIRST(&V_spdcachehashtbl[i]);
8233 LIST_REMOVE(entry, chain);
8234 spdcache_entry_free(entry);
8242 spdcache_destroy(void)
8246 if (SPDCACHE_ENABLED()) {
8248 hashdestroy(V_spdcachehashtbl, M_IPSEC_SPDCACHE, V_spdcachehash_mask);
8250 for (i = 0; i < V_spdcachehash_mask + 1; ++i)
8251 SPDCACHE_LOCK_DESTROY(i);
8253 free(V_spdcache_lock, M_IPSEC_SPDCACHE);
8262 for (i = 0; i < IPSEC_DIR_MAX; i++) {
8263 TAILQ_INIT(&V_sptree[i]);
8264 TAILQ_INIT(&V_sptree_ifnet[i]);
8267 V_key_lft_zone = uma_zcreate("IPsec SA lft_c",
8268 sizeof(uint64_t) * 2, NULL, NULL, NULL, NULL,
8269 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
8271 TAILQ_INIT(&V_sahtree);
8272 V_sphashtbl = hashinit(SPHASH_NHASH, M_IPSEC_SP, &V_sphash_mask);
8273 V_savhashtbl = hashinit(SAVHASH_NHASH, M_IPSEC_SA, &V_savhash_mask);
8274 V_sahaddrhashtbl = hashinit(SAHHASH_NHASH, M_IPSEC_SAH,
8275 &V_sahaddrhash_mask);
8276 V_acqaddrhashtbl = hashinit(ACQHASH_NHASH, M_IPSEC_SAQ,
8277 &V_acqaddrhash_mask);
8278 V_acqseqhashtbl = hashinit(ACQHASH_NHASH, M_IPSEC_SAQ,
8279 &V_acqseqhash_mask);
8283 for (i = 0; i <= SADB_SATYPE_MAX; i++)
8284 LIST_INIT(&V_regtree[i]);
8286 LIST_INIT(&V_acqtree);
8287 LIST_INIT(&V_spacqtree);
8289 if (!IS_DEFAULT_VNET(curvnet))
8293 REGTREE_LOCK_INIT();
8294 SAHTREE_LOCK_INIT();
8298 #ifndef IPSEC_DEBUG2
8299 callout_init(&key_timer, 1);
8300 callout_reset(&key_timer, hz, key_timehandler, NULL);
8301 #endif /*IPSEC_DEBUG2*/
8303 /* initialize key statistics */
8304 keystat.getspi_count = 1;
8307 printf("IPsec: Initialized Security Association Processing.\n");
8314 struct secashead_queue sahdrainq;
8315 struct secpolicy_queue drainq;
8316 struct secpolicy *sp, *nextsp;
8317 struct secacq *acq, *nextacq;
8318 struct secspacq *spacq, *nextspacq;
8319 struct secashead *sah;
8320 struct secasvar *sav;
8325 * XXX: can we just call free() for each object without
8326 * walking through safe way with releasing references?
8328 TAILQ_INIT(&drainq);
8330 for (i = 0; i < IPSEC_DIR_MAX; i++) {
8331 TAILQ_CONCAT(&drainq, &V_sptree[i], chain);
8332 TAILQ_CONCAT(&drainq, &V_sptree_ifnet[i], chain);
8334 for (i = 0; i < V_sphash_mask + 1; i++)
8335 LIST_INIT(&V_sphashtbl[i]);
8339 sp = TAILQ_FIRST(&drainq);
8340 while (sp != NULL) {
8341 nextsp = TAILQ_NEXT(sp, chain);
8346 TAILQ_INIT(&sahdrainq);
8348 TAILQ_CONCAT(&sahdrainq, &V_sahtree, chain);
8349 for (i = 0; i < V_savhash_mask + 1; i++)
8350 LIST_INIT(&V_savhashtbl[i]);
8351 for (i = 0; i < V_sahaddrhash_mask + 1; i++)
8352 LIST_INIT(&V_sahaddrhashtbl[i]);
8353 TAILQ_FOREACH(sah, &sahdrainq, chain) {
8354 sah->state = SADB_SASTATE_DEAD;
8355 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
8356 sav->state = SADB_SASTATE_DEAD;
8358 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
8359 sav->state = SADB_SASTATE_DEAD;
8364 key_freesah_flushed(&sahdrainq);
8365 hashdestroy(V_sphashtbl, M_IPSEC_SP, V_sphash_mask);
8366 hashdestroy(V_savhashtbl, M_IPSEC_SA, V_savhash_mask);
8367 hashdestroy(V_sahaddrhashtbl, M_IPSEC_SAH, V_sahaddrhash_mask);
8370 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
8371 LIST_FOREACH(reg, &V_regtree[i], chain) {
8372 if (__LIST_CHAINED(reg)) {
8373 LIST_REMOVE(reg, chain);
8374 free(reg, M_IPSEC_SAR);
8382 acq = LIST_FIRST(&V_acqtree);
8383 while (acq != NULL) {
8384 nextacq = LIST_NEXT(acq, chain);
8385 LIST_REMOVE(acq, chain);
8386 free(acq, M_IPSEC_SAQ);
8389 for (i = 0; i < V_acqaddrhash_mask + 1; i++)
8390 LIST_INIT(&V_acqaddrhashtbl[i]);
8391 for (i = 0; i < V_acqseqhash_mask + 1; i++)
8392 LIST_INIT(&V_acqseqhashtbl[i]);
8396 for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
8397 spacq = nextspacq) {
8398 nextspacq = LIST_NEXT(spacq, chain);
8399 if (__LIST_CHAINED(spacq)) {
8400 LIST_REMOVE(spacq, chain);
8401 free(spacq, M_IPSEC_SAQ);
8405 hashdestroy(V_acqaddrhashtbl, M_IPSEC_SAQ, V_acqaddrhash_mask);
8406 hashdestroy(V_acqseqhashtbl, M_IPSEC_SAQ, V_acqseqhash_mask);
8407 uma_zdestroy(V_key_lft_zone);
8409 if (!IS_DEFAULT_VNET(curvnet))
8411 #ifndef IPSEC_DEBUG2
8412 callout_drain(&key_timer);
8414 SPTREE_LOCK_DESTROY();
8415 REGTREE_LOCK_DESTROY();
8416 SAHTREE_LOCK_DESTROY();
8418 SPACQ_LOCK_DESTROY();
8422 /* record data transfer on SA, and update timestamps */
8424 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
8426 IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
8427 IPSEC_ASSERT(m != NULL, ("Null mbuf"));
8430 * XXX Currently, there is a difference of bytes size
8431 * between inbound and outbound processing.
8433 counter_u64_add(sav->lft_c_bytes, m->m_pkthdr.len);
8436 * We use the number of packets as the unit of
8437 * allocations. We increment the variable
8438 * whenever {esp,ah}_{in,out}put is called.
8440 counter_u64_add(sav->lft_c_allocations, 1);
8443 * NOTE: We record CURRENT usetime by using wall clock,
8444 * in seconds. HARD and SOFT lifetime are measured by the time
8445 * difference (again in seconds) from usetime.
8449 * -----+-----+--------+---> t
8450 * <--------------> HARD
8453 if (sav->firstused == 0)
8454 sav->firstused = time_second;
8458 * Take one of the kernel's security keys and convert it into a PF_KEY
8459 * structure within an mbuf, suitable for sending up to a waiting
8460 * application in user land.
8463 * src: A pointer to a kernel security key.
8464 * exttype: Which type of key this is. Refer to the PF_KEY data structures.
8466 * a valid mbuf or NULL indicating an error
8470 static struct mbuf *
8471 key_setkey(struct seckey *src, uint16_t exttype)
8480 len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8481 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
8486 p = mtod(m, struct sadb_key *);
8488 p->sadb_key_len = PFKEY_UNIT64(len);
8489 p->sadb_key_exttype = exttype;
8490 p->sadb_key_bits = src->bits;
8491 bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8497 * Take one of the kernel's lifetime data structures and convert it
8498 * into a PF_KEY structure within an mbuf, suitable for sending up to
8499 * a waiting application in user land.
8502 * src: A pointer to a kernel lifetime structure.
8503 * exttype: Which type of lifetime this is. Refer to the PF_KEY
8504 * data structures for more information.
8506 * a valid mbuf or NULL indicating an error
8510 static struct mbuf *
8511 key_setlifetime(struct seclifetime *src, uint16_t exttype)
8513 struct mbuf *m = NULL;
8514 struct sadb_lifetime *p;
8515 int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8520 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
8525 p = mtod(m, struct sadb_lifetime *);
8528 p->sadb_lifetime_len = PFKEY_UNIT64(len);
8529 p->sadb_lifetime_exttype = exttype;
8530 p->sadb_lifetime_allocations = src->allocations;
8531 p->sadb_lifetime_bytes = src->bytes;
8532 p->sadb_lifetime_addtime = src->addtime;
8533 p->sadb_lifetime_usetime = src->usetime;
8539 const struct enc_xform *
8540 enc_algorithm_lookup(int alg)
8544 for (i = 0; i < nitems(supported_ealgs); i++)
8545 if (alg == supported_ealgs[i].sadb_alg)
8546 return (supported_ealgs[i].xform);
8550 const struct auth_hash *
8551 auth_algorithm_lookup(int alg)
8555 for (i = 0; i < nitems(supported_aalgs); i++)
8556 if (alg == supported_aalgs[i].sadb_alg)
8557 return (supported_aalgs[i].xform);
8561 const struct comp_algo *
8562 comp_algorithm_lookup(int alg)
8566 for (i = 0; i < nitems(supported_calgs); i++)
8567 if (alg == supported_calgs[i].sadb_alg)
8568 return (supported_calgs[i].xform);