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, CTLFLAG_RW, 0, "SPD cache");
513 SYSCTL_UINT(_net_key_spdcache, OID_AUTO, maxentries,
514 CTLFLAG_VNET | CTLFLAG_RDTUN, &VNET_NAME(key_spdcache_maxentries), 0,
515 "Maximum number of entries in the SPD cache"
516 " (power of 2, 0 to disable)");
518 SYSCTL_UINT(_net_key_spdcache, OID_AUTO, threshold,
519 CTLFLAG_VNET | CTLFLAG_RDTUN, &VNET_NAME(key_spdcache_threshold), 0,
520 "Number of SPs that make the SPD cache active");
522 #define __LIST_CHAINED(elm) \
523 (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
525 MALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
526 MALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
527 MALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
528 MALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
529 MALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
530 MALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
531 MALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
532 MALLOC_DEFINE(M_IPSEC_SPDCACHE, "ipsec-spdcache", "ipsec SPD cache");
534 VNET_DEFINE_STATIC(uma_zone_t, key_lft_zone);
535 #define V_key_lft_zone VNET(key_lft_zone)
538 * set parameters into secpolicyindex buffer.
539 * Must allocate secpolicyindex buffer passed to this function.
541 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
543 bzero((idx), sizeof(struct secpolicyindex)); \
544 (idx)->dir = (_dir); \
545 (idx)->prefs = (ps); \
546 (idx)->prefd = (pd); \
547 (idx)->ul_proto = (ulp); \
548 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
549 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
553 * set parameters into secasindex buffer.
554 * Must allocate secasindex buffer before calling this function.
556 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
558 bzero((idx), sizeof(struct secasindex)); \
559 (idx)->proto = (p); \
561 (idx)->reqid = (r); \
562 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
563 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
564 key_porttosaddr(&(idx)->src.sa, 0); \
565 key_porttosaddr(&(idx)->dst.sa, 0); \
570 u_long getspi_count; /* the avarage of count to try to get new SPI */
574 struct sadb_msg *msg;
575 struct sadb_ext *ext[SADB_EXT_MAX + 1];
576 int extoff[SADB_EXT_MAX + 1];
577 int extlen[SADB_EXT_MAX + 1];
580 static struct supported_ealgs {
582 const struct enc_xform *xform;
583 } supported_ealgs[] = {
584 { SADB_EALG_DESCBC, &enc_xform_des },
585 { SADB_EALG_3DESCBC, &enc_xform_3des },
586 { SADB_X_EALG_AES, &enc_xform_rijndael128 },
587 { SADB_X_EALG_BLOWFISHCBC, &enc_xform_blf },
588 { SADB_X_EALG_CAST128CBC, &enc_xform_cast5 },
589 { SADB_EALG_NULL, &enc_xform_null },
590 { SADB_X_EALG_CAMELLIACBC, &enc_xform_camellia },
591 { SADB_X_EALG_AESCTR, &enc_xform_aes_icm },
592 { SADB_X_EALG_AESGCM16, &enc_xform_aes_nist_gcm },
593 { SADB_X_EALG_AESGMAC, &enc_xform_aes_nist_gmac },
596 static struct supported_aalgs {
598 const struct auth_hash *xform;
599 } supported_aalgs[] = {
600 { SADB_X_AALG_NULL, &auth_hash_null },
601 { SADB_AALG_MD5HMAC, &auth_hash_hmac_md5 },
602 { SADB_AALG_SHA1HMAC, &auth_hash_hmac_sha1 },
603 { SADB_X_AALG_RIPEMD160HMAC, &auth_hash_hmac_ripemd_160 },
604 { SADB_X_AALG_MD5, &auth_hash_key_md5 },
605 { SADB_X_AALG_SHA, &auth_hash_key_sha1 },
606 { SADB_X_AALG_SHA2_256, &auth_hash_hmac_sha2_256 },
607 { SADB_X_AALG_SHA2_384, &auth_hash_hmac_sha2_384 },
608 { SADB_X_AALG_SHA2_512, &auth_hash_hmac_sha2_512 },
609 { SADB_X_AALG_AES128GMAC, &auth_hash_nist_gmac_aes_128 },
610 { SADB_X_AALG_AES192GMAC, &auth_hash_nist_gmac_aes_192 },
611 { SADB_X_AALG_AES256GMAC, &auth_hash_nist_gmac_aes_256 },
614 static struct supported_calgs {
616 const struct comp_algo *xform;
617 } supported_calgs[] = {
618 { SADB_X_CALG_DEFLATE, &comp_algo_deflate },
622 static struct callout key_timer;
625 static void key_unlink(struct secpolicy *);
626 static struct secpolicy *key_do_allocsp(struct secpolicyindex *spidx, u_int dir);
627 static struct secpolicy *key_getsp(struct secpolicyindex *);
628 static struct secpolicy *key_getspbyid(u_int32_t);
629 static struct mbuf *key_gather_mbuf(struct mbuf *,
630 const struct sadb_msghdr *, int, int, ...);
631 static int key_spdadd(struct socket *, struct mbuf *,
632 const struct sadb_msghdr *);
633 static uint32_t key_getnewspid(void);
634 static int key_spddelete(struct socket *, struct mbuf *,
635 const struct sadb_msghdr *);
636 static int key_spddelete2(struct socket *, struct mbuf *,
637 const struct sadb_msghdr *);
638 static int key_spdget(struct socket *, struct mbuf *,
639 const struct sadb_msghdr *);
640 static int key_spdflush(struct socket *, struct mbuf *,
641 const struct sadb_msghdr *);
642 static int key_spddump(struct socket *, struct mbuf *,
643 const struct sadb_msghdr *);
644 static struct mbuf *key_setdumpsp(struct secpolicy *,
645 u_int8_t, u_int32_t, u_int32_t);
646 static struct mbuf *key_sp2mbuf(struct secpolicy *);
647 static size_t key_getspreqmsglen(struct secpolicy *);
648 static int key_spdexpire(struct secpolicy *);
649 static struct secashead *key_newsah(struct secasindex *);
650 static void key_freesah(struct secashead **);
651 static void key_delsah(struct secashead *);
652 static struct secasvar *key_newsav(const struct sadb_msghdr *,
653 struct secasindex *, uint32_t, int *);
654 static void key_delsav(struct secasvar *);
655 static void key_unlinksav(struct secasvar *);
656 static struct secashead *key_getsah(struct secasindex *);
657 static int key_checkspidup(uint32_t);
658 static struct secasvar *key_getsavbyspi(uint32_t);
659 static int key_setnatt(struct secasvar *, const struct sadb_msghdr *);
660 static int key_setsaval(struct secasvar *, const struct sadb_msghdr *);
661 static int key_updatelifetimes(struct secasvar *, const struct sadb_msghdr *);
662 static int key_updateaddresses(struct socket *, struct mbuf *,
663 const struct sadb_msghdr *, struct secasvar *, struct secasindex *);
665 static struct mbuf *key_setdumpsa(struct secasvar *, u_int8_t,
666 u_int8_t, u_int32_t, u_int32_t);
667 static struct mbuf *key_setsadbmsg(u_int8_t, u_int16_t, u_int8_t,
668 u_int32_t, pid_t, u_int16_t);
669 static struct mbuf *key_setsadbsa(struct secasvar *);
670 static struct mbuf *key_setsadbaddr(u_int16_t,
671 const struct sockaddr *, u_int8_t, u_int16_t);
672 static struct mbuf *key_setsadbxport(u_int16_t, u_int16_t);
673 static struct mbuf *key_setsadbxtype(u_int16_t);
674 static struct mbuf *key_setsadbxsa2(u_int8_t, u_int32_t, u_int32_t);
675 static struct mbuf *key_setsadbxsareplay(u_int32_t);
676 static struct mbuf *key_setsadbxpolicy(u_int16_t, u_int8_t,
677 u_int32_t, u_int32_t);
678 static struct seckey *key_dup_keymsg(const struct sadb_key *, size_t,
679 struct malloc_type *);
680 static struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
681 struct malloc_type *);
683 /* flags for key_cmpsaidx() */
684 #define CMP_HEAD 1 /* protocol, addresses. */
685 #define CMP_MODE_REQID 2 /* additionally HEAD, reqid, mode. */
686 #define CMP_REQID 3 /* additionally HEAD, reaid. */
687 #define CMP_EXACTLY 4 /* all elements. */
688 static int key_cmpsaidx(const struct secasindex *,
689 const struct secasindex *, int);
690 static int key_cmpspidx_exactly(struct secpolicyindex *,
691 struct secpolicyindex *);
692 static int key_cmpspidx_withmask(struct secpolicyindex *,
693 struct secpolicyindex *);
694 static int key_bbcmp(const void *, const void *, u_int);
695 static uint8_t key_satype2proto(uint8_t);
696 static uint8_t key_proto2satype(uint8_t);
698 static int key_getspi(struct socket *, struct mbuf *,
699 const struct sadb_msghdr *);
700 static uint32_t key_do_getnewspi(struct sadb_spirange *, struct secasindex *);
701 static int key_update(struct socket *, struct mbuf *,
702 const struct sadb_msghdr *);
703 static int key_add(struct socket *, struct mbuf *,
704 const struct sadb_msghdr *);
705 static int key_setident(struct secashead *, const struct sadb_msghdr *);
706 static struct mbuf *key_getmsgbuf_x1(struct mbuf *,
707 const struct sadb_msghdr *);
708 static int key_delete(struct socket *, struct mbuf *,
709 const struct sadb_msghdr *);
710 static int key_delete_all(struct socket *, struct mbuf *,
711 const struct sadb_msghdr *, struct secasindex *);
712 static int key_get(struct socket *, struct mbuf *,
713 const struct sadb_msghdr *);
715 static void key_getcomb_setlifetime(struct sadb_comb *);
716 static struct mbuf *key_getcomb_ealg(void);
717 static struct mbuf *key_getcomb_ah(void);
718 static struct mbuf *key_getcomb_ipcomp(void);
719 static struct mbuf *key_getprop(const struct secasindex *);
721 static int key_acquire(const struct secasindex *, struct secpolicy *);
722 static uint32_t key_newacq(const struct secasindex *, int *);
723 static uint32_t key_getacq(const struct secasindex *, int *);
724 static int key_acqdone(const struct secasindex *, uint32_t);
725 static int key_acqreset(uint32_t);
726 static struct secspacq *key_newspacq(struct secpolicyindex *);
727 static struct secspacq *key_getspacq(struct secpolicyindex *);
728 static int key_acquire2(struct socket *, struct mbuf *,
729 const struct sadb_msghdr *);
730 static int key_register(struct socket *, struct mbuf *,
731 const struct sadb_msghdr *);
732 static int key_expire(struct secasvar *, int);
733 static int key_flush(struct socket *, struct mbuf *,
734 const struct sadb_msghdr *);
735 static int key_dump(struct socket *, struct mbuf *,
736 const struct sadb_msghdr *);
737 static int key_promisc(struct socket *, struct mbuf *,
738 const struct sadb_msghdr *);
739 static int key_senderror(struct socket *, struct mbuf *, int);
740 static int key_validate_ext(const struct sadb_ext *, int);
741 static int key_align(struct mbuf *, struct sadb_msghdr *);
742 static struct mbuf *key_setlifetime(struct seclifetime *, uint16_t);
743 static struct mbuf *key_setkey(struct seckey *, uint16_t);
745 static void spdcache_init(void);
746 static void spdcache_clear(void);
747 static struct spdcache_entry *spdcache_entry_alloc(
748 const struct secpolicyindex *spidx,
749 struct secpolicy *policy);
750 static void spdcache_entry_free(struct spdcache_entry *entry);
752 static void spdcache_destroy(void);
755 #define DBG_IPSEC_INITREF(t, p) do { \
756 refcount_init(&(p)->refcnt, 1); \
758 printf("%s: Initialize refcnt %s(%p) = %u\n", \
759 __func__, #t, (p), (p)->refcnt)); \
761 #define DBG_IPSEC_ADDREF(t, p) do { \
762 refcount_acquire(&(p)->refcnt); \
764 printf("%s: Acquire refcnt %s(%p) -> %u\n", \
765 __func__, #t, (p), (p)->refcnt)); \
767 #define DBG_IPSEC_DELREF(t, p) do { \
769 printf("%s: Release refcnt %s(%p) -> %u\n", \
770 __func__, #t, (p), (p)->refcnt - 1)); \
771 refcount_release(&(p)->refcnt); \
774 #define IPSEC_INITREF(t, p) refcount_init(&(p)->refcnt, 1)
775 #define IPSEC_ADDREF(t, p) refcount_acquire(&(p)->refcnt)
776 #define IPSEC_DELREF(t, p) refcount_release(&(p)->refcnt)
778 #define SP_INITREF(p) IPSEC_INITREF(SP, p)
779 #define SP_ADDREF(p) IPSEC_ADDREF(SP, p)
780 #define SP_DELREF(p) IPSEC_DELREF(SP, p)
782 #define SAH_INITREF(p) IPSEC_INITREF(SAH, p)
783 #define SAH_ADDREF(p) IPSEC_ADDREF(SAH, p)
784 #define SAH_DELREF(p) IPSEC_DELREF(SAH, p)
786 #define SAV_INITREF(p) IPSEC_INITREF(SAV, p)
787 #define SAV_ADDREF(p) IPSEC_ADDREF(SAV, p)
788 #define SAV_DELREF(p) IPSEC_DELREF(SAV, p)
791 * Update the refcnt while holding the SPTREE lock.
794 key_addref(struct secpolicy *sp)
801 * Return 0 when there are known to be no SP's for the specified
802 * direction. Otherwise return 1. This is used by IPsec code
803 * to optimize performance.
806 key_havesp(u_int dir)
809 return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
810 TAILQ_FIRST(&V_sptree[dir]) != NULL : 1);
813 /* %%% IPsec policy management */
815 * Return current SPDB generation.
832 key_checksockaddrs(struct sockaddr *src, struct sockaddr *dst)
836 if (src->sa_family != dst->sa_family)
839 if (src->sa_len != dst->sa_len)
841 switch (src->sa_family) {
844 if (src->sa_len != sizeof(struct sockaddr_in))
850 if (src->sa_len != sizeof(struct sockaddr_in6))
855 return (EAFNOSUPPORT);
861 key_do_allocsp(struct secpolicyindex *spidx, u_int dir)
863 SPTREE_RLOCK_TRACKER;
864 struct secpolicy *sp;
866 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
867 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
868 ("invalid direction %u", dir));
871 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
872 if (key_cmpspidx_withmask(&sp->spidx, spidx)) {
883 * allocating a SP for OUTBOUND or INBOUND packet.
884 * Must call key_freesp() later.
885 * OUT: NULL: not found
886 * others: found and return the pointer.
889 key_allocsp(struct secpolicyindex *spidx, u_int dir)
891 struct spdcache_entry *entry, *lastentry, *tmpentry;
892 struct secpolicy *sp;
896 if (!SPDCACHE_ACTIVE()) {
897 sp = key_do_allocsp(spidx, dir);
901 hashv = SPDCACHE_HASHVAL(spidx);
902 SPDCACHE_LOCK(hashv);
904 LIST_FOREACH_SAFE(entry, &V_spdcachehashtbl[hashv], chain, tmpentry) {
905 /* Removed outdated entries */
906 if (entry->sp != NULL &&
907 entry->sp->state == IPSEC_SPSTATE_DEAD) {
908 LIST_REMOVE(entry, chain);
909 spdcache_entry_free(entry);
914 if (!key_cmpspidx_exactly(&entry->spidx, spidx)) {
920 if (entry->sp != NULL)
923 /* IPSECSTAT_INC(ips_spdcache_hits); */
925 SPDCACHE_UNLOCK(hashv);
929 /* IPSECSTAT_INC(ips_spdcache_misses); */
931 sp = key_do_allocsp(spidx, dir);
932 entry = spdcache_entry_alloc(spidx, sp);
934 if (nb_entries >= SPDCACHE_MAX_ENTRIES_PER_HASH) {
935 LIST_REMOVE(lastentry, chain);
936 spdcache_entry_free(lastentry);
939 LIST_INSERT_HEAD(&V_spdcachehashtbl[hashv], entry, chain);
942 SPDCACHE_UNLOCK(hashv);
945 if (sp != NULL) { /* found a SPD entry */
946 sp->lastused = time_second;
948 printf("%s: return SP(%p)\n", __func__, sp));
949 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
952 printf("%s: lookup failed for ", __func__);
953 kdebug_secpolicyindex(spidx, NULL));
959 * Allocating an SA entry for an *INBOUND* or *OUTBOUND* TCP packet, signed
960 * or should be signed by MD5 signature.
961 * We don't use key_allocsa() for such lookups, because we don't know SPI.
962 * Unlike ESP and AH protocols, SPI isn't transmitted in the TCP header with
963 * signed packet. We use SADB only as storage for password.
964 * OUT: positive: corresponding SA for given saidx found.
968 key_allocsa_tcpmd5(struct secasindex *saidx)
970 SAHTREE_RLOCK_TRACKER;
971 struct secashead *sah;
972 struct secasvar *sav;
974 IPSEC_ASSERT(saidx->proto == IPPROTO_TCP,
975 ("unexpected security protocol %u", saidx->proto));
976 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TCPMD5,
977 ("unexpected mode %u", saidx->mode));
980 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
982 printf("%s: checking SAH\n", __func__);
983 kdebug_secash(sah, " "));
984 if (sah->saidx.proto != IPPROTO_TCP)
986 if (!key_sockaddrcmp(&saidx->dst.sa, &sah->saidx.dst.sa, 0) &&
987 !key_sockaddrcmp(&saidx->src.sa, &sah->saidx.src.sa, 0))
991 if (V_key_preferred_oldsa)
992 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
994 sav = TAILQ_FIRST(&sah->savtree_alive);
1003 printf("%s: return SA(%p)\n", __func__, sav));
1004 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1007 printf("%s: SA not found\n", __func__));
1008 KEYDBG(IPSEC_DATA, kdebug_secasindex(saidx, NULL));
1014 * Allocating an SA entry for an *OUTBOUND* packet.
1015 * OUT: positive: corresponding SA for given saidx found.
1016 * NULL: SA not found, but will be acquired, check *error
1017 * for acquiring status.
1020 key_allocsa_policy(struct secpolicy *sp, const struct secasindex *saidx,
1023 SAHTREE_RLOCK_TRACKER;
1024 struct secashead *sah;
1025 struct secasvar *sav;
1027 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
1028 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
1029 saidx->mode == IPSEC_MODE_TUNNEL,
1030 ("unexpected policy %u", saidx->mode));
1033 * We check new SA in the IPsec request because a different
1034 * SA may be involved each time this request is checked, either
1035 * because new SAs are being configured, or this request is
1036 * associated with an unconnected datagram socket, or this request
1037 * is associated with a system default policy.
1040 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
1042 printf("%s: checking SAH\n", __func__);
1043 kdebug_secash(sah, " "));
1044 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID))
1050 * Allocate the oldest SA available according to
1051 * draft-jenkins-ipsec-rekeying-03.
1053 if (V_key_preferred_oldsa)
1054 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
1056 sav = TAILQ_FIRST(&sah->savtree_alive);
1066 printf("%s: chosen SA(%p) for SP(%p)\n", __func__,
1068 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1069 return (sav); /* return referenced SA */
1072 /* there is no SA */
1073 *error = key_acquire(saidx, sp);
1075 ipseclog((LOG_DEBUG,
1076 "%s: error %d returned from key_acquire()\n",
1079 printf("%s: acquire SA for SP(%p), error %d\n",
1080 __func__, sp, *error));
1081 KEYDBG(IPSEC_DATA, kdebug_secasindex(saidx, NULL));
1086 * allocating a usable SA entry for a *INBOUND* packet.
1087 * Must call key_freesav() later.
1088 * OUT: positive: pointer to a usable sav (i.e. MATURE or DYING state).
1089 * NULL: not found, or error occurred.
1091 * According to RFC 2401 SA is uniquely identified by a triple SPI,
1092 * destination address, and security protocol. But according to RFC 4301,
1093 * SPI by itself suffices to specify an SA.
1095 * Note that, however, we do need to keep source address in IPsec SA.
1096 * IKE specification and PF_KEY specification do assume that we
1097 * keep source address in IPsec SA. We see a tricky situation here.
1100 key_allocsa(union sockaddr_union *dst, uint8_t proto, uint32_t spi)
1102 SAHTREE_RLOCK_TRACKER;
1103 struct secasvar *sav;
1105 IPSEC_ASSERT(proto == IPPROTO_ESP || proto == IPPROTO_AH ||
1106 proto == IPPROTO_IPCOMP, ("unexpected security protocol %u",
1110 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
1111 if (sav->spi == spi)
1115 * We use single SPI namespace for all protocols, so it is
1116 * impossible to have SPI duplicates in the SAVHASH.
1119 if (sav->state != SADB_SASTATE_LARVAL &&
1120 sav->sah->saidx.proto == proto &&
1121 key_sockaddrcmp(&dst->sa,
1122 &sav->sah->saidx.dst.sa, 0) == 0)
1131 char buf[IPSEC_ADDRSTRLEN];
1132 printf("%s: SA not found for spi %u proto %u dst %s\n",
1133 __func__, ntohl(spi), proto, ipsec_address(dst, buf,
1137 printf("%s: return SA(%p)\n", __func__, sav));
1138 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1144 key_allocsa_tunnel(union sockaddr_union *src, union sockaddr_union *dst,
1147 SAHTREE_RLOCK_TRACKER;
1148 struct secasindex saidx;
1149 struct secashead *sah;
1150 struct secasvar *sav;
1152 IPSEC_ASSERT(src != NULL, ("null src address"));
1153 IPSEC_ASSERT(dst != NULL, ("null dst address"));
1155 KEY_SETSECASIDX(proto, IPSEC_MODE_TUNNEL, 0, &src->sa,
1160 LIST_FOREACH(sah, SAHADDRHASH_HASH(&saidx), addrhash) {
1161 if (IPSEC_MODE_TUNNEL != sah->saidx.mode)
1163 if (proto != sah->saidx.proto)
1165 if (key_sockaddrcmp(&src->sa, &sah->saidx.src.sa, 0) != 0)
1167 if (key_sockaddrcmp(&dst->sa, &sah->saidx.dst.sa, 0) != 0)
1169 /* XXXAE: is key_preferred_oldsa reasonably?*/
1170 if (V_key_preferred_oldsa)
1171 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
1173 sav = TAILQ_FIRST(&sah->savtree_alive);
1181 printf("%s: return SA(%p)\n", __func__, sav));
1183 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1188 * Must be called after calling key_allocsp().
1191 key_freesp(struct secpolicy **spp)
1193 struct secpolicy *sp = *spp;
1195 IPSEC_ASSERT(sp != NULL, ("null sp"));
1196 if (SP_DELREF(sp) == 0)
1200 printf("%s: last reference to SP(%p)\n", __func__, sp));
1201 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1204 while (sp->tcount > 0)
1205 ipsec_delisr(sp->req[--sp->tcount]);
1206 free(sp, M_IPSEC_SP);
1210 key_unlink(struct secpolicy *sp)
1213 IPSEC_ASSERT(sp->spidx.dir == IPSEC_DIR_INBOUND ||
1214 sp->spidx.dir == IPSEC_DIR_OUTBOUND,
1215 ("invalid direction %u", sp->spidx.dir));
1216 SPTREE_UNLOCK_ASSERT();
1219 printf("%s: SP(%p)\n", __func__, sp));
1221 if (sp->state != IPSEC_SPSTATE_ALIVE) {
1222 /* SP is already unlinked */
1226 sp->state = IPSEC_SPSTATE_DEAD;
1227 TAILQ_REMOVE(&V_sptree[sp->spidx.dir], sp, chain);
1229 LIST_REMOVE(sp, idhash);
1232 if (SPDCACHE_ENABLED())
1238 * insert a secpolicy into the SP database. Lower priorities first
1241 key_insertsp(struct secpolicy *newsp)
1243 struct secpolicy *sp;
1245 SPTREE_WLOCK_ASSERT();
1246 TAILQ_FOREACH(sp, &V_sptree[newsp->spidx.dir], chain) {
1247 if (newsp->priority < sp->priority) {
1248 TAILQ_INSERT_BEFORE(sp, newsp, chain);
1252 TAILQ_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, chain);
1254 LIST_INSERT_HEAD(SPHASH_HASH(newsp->id), newsp, idhash);
1255 newsp->state = IPSEC_SPSTATE_ALIVE;
1261 * Insert a bunch of VTI secpolicies into the SPDB.
1262 * We keep VTI policies in the separate list due to following reasons:
1263 * 1) they should be immutable to user's or some deamon's attempts to
1264 * delete. The only way delete such policies - destroy or unconfigure
1265 * corresponding virtual inteface.
1266 * 2) such policies have traffic selector that matches all traffic per
1268 * Since all VTI policies have the same priority, we don't care about
1272 key_register_ifnet(struct secpolicy **spp, u_int count)
1279 * First of try to acquire id for each SP.
1281 for (i = 0; i < count; i++) {
1282 IPSEC_ASSERT(spp[i]->spidx.dir == IPSEC_DIR_INBOUND ||
1283 spp[i]->spidx.dir == IPSEC_DIR_OUTBOUND,
1284 ("invalid direction %u", spp[i]->spidx.dir));
1286 if ((spp[i]->id = key_getnewspid()) == 0) {
1291 for (i = 0; i < count; i++) {
1292 TAILQ_INSERT_TAIL(&V_sptree_ifnet[spp[i]->spidx.dir],
1295 * NOTE: despite the fact that we keep VTI SP in the
1296 * separate list, SPHASH contains policies from both
1297 * sources. Thus SADB_X_SPDGET will correctly return
1298 * SP by id, because it uses SPHASH for lookups.
1300 LIST_INSERT_HEAD(SPHASH_HASH(spp[i]->id), spp[i], idhash);
1301 spp[i]->state = IPSEC_SPSTATE_IFNET;
1305 * Notify user processes about new SP.
1307 for (i = 0; i < count; i++) {
1308 m = key_setdumpsp(spp[i], SADB_X_SPDADD, 0, 0);
1310 key_sendup_mbuf(NULL, m, KEY_SENDUP_ALL);
1316 key_unregister_ifnet(struct secpolicy **spp, u_int count)
1322 for (i = 0; i < count; i++) {
1323 IPSEC_ASSERT(spp[i]->spidx.dir == IPSEC_DIR_INBOUND ||
1324 spp[i]->spidx.dir == IPSEC_DIR_OUTBOUND,
1325 ("invalid direction %u", spp[i]->spidx.dir));
1327 if (spp[i]->state != IPSEC_SPSTATE_IFNET)
1329 spp[i]->state = IPSEC_SPSTATE_DEAD;
1330 TAILQ_REMOVE(&V_sptree_ifnet[spp[i]->spidx.dir],
1333 LIST_REMOVE(spp[i], idhash);
1336 if (SPDCACHE_ENABLED())
1339 for (i = 0; i < count; i++) {
1340 m = key_setdumpsp(spp[i], SADB_X_SPDDELETE, 0, 0);
1342 key_sendup_mbuf(NULL, m, KEY_SENDUP_ALL);
1347 * Must be called after calling key_allocsa().
1348 * This function is called by key_freesp() to free some SA allocated
1352 key_freesav(struct secasvar **psav)
1354 struct secasvar *sav = *psav;
1356 IPSEC_ASSERT(sav != NULL, ("null sav"));
1357 if (SAV_DELREF(sav) == 0)
1361 printf("%s: last reference to SA(%p)\n", __func__, sav));
1368 * Unlink SA from SAH and SPI hash under SAHTREE_WLOCK.
1369 * Expect that SA has extra reference due to lookup.
1370 * Release this references, also release SAH reference after unlink.
1373 key_unlinksav(struct secasvar *sav)
1375 struct secashead *sah;
1378 printf("%s: SA(%p)\n", __func__, sav));
1380 SAHTREE_UNLOCK_ASSERT();
1382 if (sav->state == SADB_SASTATE_DEAD) {
1383 /* SA is already unlinked */
1387 /* Unlink from SAH */
1388 if (sav->state == SADB_SASTATE_LARVAL)
1389 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
1391 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
1392 /* Unlink from SPI hash */
1393 LIST_REMOVE(sav, spihash);
1394 sav->state = SADB_SASTATE_DEAD;
1398 /* Since we are unlinked, release reference to SAH */
1402 /* %%% SPD management */
1405 * OUT: NULL : not found
1406 * others : found, pointer to a SP.
1408 static struct secpolicy *
1409 key_getsp(struct secpolicyindex *spidx)
1411 SPTREE_RLOCK_TRACKER;
1412 struct secpolicy *sp;
1414 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1417 TAILQ_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1418 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1430 * OUT: NULL : not found
1431 * others : found, pointer to referenced SP.
1433 static struct secpolicy *
1434 key_getspbyid(uint32_t id)
1436 SPTREE_RLOCK_TRACKER;
1437 struct secpolicy *sp;
1440 LIST_FOREACH(sp, SPHASH_HASH(id), idhash) {
1453 struct secpolicy *sp;
1455 sp = malloc(sizeof(*sp), M_IPSEC_SP, M_NOWAIT | M_ZERO);
1461 struct ipsecrequest *
1465 return (malloc(sizeof(struct ipsecrequest), M_IPSEC_SR,
1466 M_NOWAIT | M_ZERO));
1470 ipsec_delisr(struct ipsecrequest *p)
1473 free(p, M_IPSEC_SR);
1477 * create secpolicy structure from sadb_x_policy structure.
1478 * NOTE: `state', `secpolicyindex' and 'id' in secpolicy structure
1479 * are not set, so must be set properly later.
1482 key_msg2sp(struct sadb_x_policy *xpl0, size_t len, int *error)
1484 struct secpolicy *newsp;
1486 IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1487 IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1489 if (len != PFKEY_EXTLEN(xpl0)) {
1490 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1495 if ((newsp = key_newsp()) == NULL) {
1500 newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1501 newsp->policy = xpl0->sadb_x_policy_type;
1502 newsp->priority = xpl0->sadb_x_policy_priority;
1506 switch (xpl0->sadb_x_policy_type) {
1507 case IPSEC_POLICY_DISCARD:
1508 case IPSEC_POLICY_NONE:
1509 case IPSEC_POLICY_ENTRUST:
1510 case IPSEC_POLICY_BYPASS:
1513 case IPSEC_POLICY_IPSEC:
1515 struct sadb_x_ipsecrequest *xisr;
1516 struct ipsecrequest *isr;
1519 /* validity check */
1520 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1521 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1528 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1529 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1533 if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr) ||
1534 xisr->sadb_x_ipsecrequest_len > tlen) {
1535 ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1536 "length.\n", __func__));
1542 if (newsp->tcount >= IPSEC_MAXREQ) {
1543 ipseclog((LOG_DEBUG,
1544 "%s: too many ipsecrequests.\n",
1551 /* allocate request buffer */
1552 /* NB: data structure is zero'd */
1553 isr = ipsec_newisr();
1555 ipseclog((LOG_DEBUG,
1556 "%s: No more memory.\n", __func__));
1562 newsp->req[newsp->tcount++] = isr;
1565 switch (xisr->sadb_x_ipsecrequest_proto) {
1568 case IPPROTO_IPCOMP:
1571 ipseclog((LOG_DEBUG,
1572 "%s: invalid proto type=%u\n", __func__,
1573 xisr->sadb_x_ipsecrequest_proto));
1575 *error = EPROTONOSUPPORT;
1579 (uint8_t)xisr->sadb_x_ipsecrequest_proto;
1581 switch (xisr->sadb_x_ipsecrequest_mode) {
1582 case IPSEC_MODE_TRANSPORT:
1583 case IPSEC_MODE_TUNNEL:
1585 case IPSEC_MODE_ANY:
1587 ipseclog((LOG_DEBUG,
1588 "%s: invalid mode=%u\n", __func__,
1589 xisr->sadb_x_ipsecrequest_mode));
1594 isr->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1596 switch (xisr->sadb_x_ipsecrequest_level) {
1597 case IPSEC_LEVEL_DEFAULT:
1598 case IPSEC_LEVEL_USE:
1599 case IPSEC_LEVEL_REQUIRE:
1601 case IPSEC_LEVEL_UNIQUE:
1602 /* validity check */
1604 * If range violation of reqid, kernel will
1605 * update it, don't refuse it.
1607 if (xisr->sadb_x_ipsecrequest_reqid
1608 > IPSEC_MANUAL_REQID_MAX) {
1609 ipseclog((LOG_DEBUG,
1610 "%s: reqid=%d range "
1611 "violation, updated by kernel.\n",
1613 xisr->sadb_x_ipsecrequest_reqid));
1614 xisr->sadb_x_ipsecrequest_reqid = 0;
1617 /* allocate new reqid id if reqid is zero. */
1618 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1620 if ((reqid = key_newreqid()) == 0) {
1625 isr->saidx.reqid = reqid;
1626 xisr->sadb_x_ipsecrequest_reqid = reqid;
1628 /* set it for manual keying. */
1630 xisr->sadb_x_ipsecrequest_reqid;
1635 ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1637 xisr->sadb_x_ipsecrequest_level));
1642 isr->level = xisr->sadb_x_ipsecrequest_level;
1644 /* set IP addresses if there */
1645 if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1646 struct sockaddr *paddr;
1648 len = tlen - sizeof(*xisr);
1649 paddr = (struct sockaddr *)(xisr + 1);
1650 /* validity check */
1651 if (len < sizeof(struct sockaddr) ||
1652 len < 2 * paddr->sa_len ||
1653 paddr->sa_len > sizeof(isr->saidx.src)) {
1654 ipseclog((LOG_DEBUG, "%s: invalid "
1655 "request address length.\n",
1662 * Request length should be enough to keep
1663 * source and destination addresses.
1665 if (xisr->sadb_x_ipsecrequest_len <
1666 sizeof(*xisr) + 2 * paddr->sa_len) {
1667 ipseclog((LOG_DEBUG, "%s: invalid "
1668 "ipsecrequest length.\n",
1674 bcopy(paddr, &isr->saidx.src, paddr->sa_len);
1675 paddr = (struct sockaddr *)((caddr_t)paddr +
1678 /* validity check */
1679 if (paddr->sa_len !=
1680 isr->saidx.src.sa.sa_len) {
1681 ipseclog((LOG_DEBUG, "%s: invalid "
1682 "request address length.\n",
1688 /* AF family should match */
1689 if (paddr->sa_family !=
1690 isr->saidx.src.sa.sa_family) {
1691 ipseclog((LOG_DEBUG, "%s: address "
1692 "family doesn't match.\n",
1698 bcopy(paddr, &isr->saidx.dst, paddr->sa_len);
1701 * Addresses for TUNNEL mode requests are
1704 if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
1705 ipseclog((LOG_DEBUG, "%s: missing "
1706 "request addresses.\n", __func__));
1712 tlen -= xisr->sadb_x_ipsecrequest_len;
1714 /* validity check */
1716 ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1723 xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1724 + xisr->sadb_x_ipsecrequest_len);
1726 /* XXXAE: LARVAL SP */
1727 if (newsp->tcount < 1) {
1728 ipseclog((LOG_DEBUG, "%s: valid IPSEC transforms "
1729 "not found.\n", __func__));
1737 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1750 static uint32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1752 if (auto_reqid == ~0)
1753 auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1757 /* XXX should be unique check */
1758 return (auto_reqid);
1762 * copy secpolicy struct to sadb_x_policy structure indicated.
1764 static struct mbuf *
1765 key_sp2mbuf(struct secpolicy *sp)
1770 tlen = key_getspreqmsglen(sp);
1771 m = m_get2(tlen, M_NOWAIT, MT_DATA, 0);
1776 if (key_sp2msg(sp, m->m_data, &tlen) != 0) {
1784 key_sp2msg(struct secpolicy *sp, void *request, size_t *len)
1786 struct sadb_x_ipsecrequest *xisr;
1787 struct sadb_x_policy *xpl;
1788 struct ipsecrequest *isr;
1793 IPSEC_ASSERT(sp != NULL, ("null policy"));
1795 xlen = sizeof(*xpl);
1800 bzero(request, *len);
1801 xpl = (struct sadb_x_policy *)request;
1802 xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1803 xpl->sadb_x_policy_type = sp->policy;
1804 xpl->sadb_x_policy_dir = sp->spidx.dir;
1805 xpl->sadb_x_policy_id = sp->id;
1806 xpl->sadb_x_policy_priority = sp->priority;
1807 switch (sp->state) {
1808 case IPSEC_SPSTATE_IFNET:
1809 xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_IFNET;
1811 case IPSEC_SPSTATE_PCB:
1812 xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_PCB;
1815 xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_GLOBAL;
1818 /* if is the policy for ipsec ? */
1819 if (sp->policy == IPSEC_POLICY_IPSEC) {
1820 p = (caddr_t)xpl + sizeof(*xpl);
1821 for (i = 0; i < sp->tcount; i++) {
1823 ilen = PFKEY_ALIGN8(sizeof(*xisr) +
1824 isr->saidx.src.sa.sa_len +
1825 isr->saidx.dst.sa.sa_len);
1829 /* Calculate needed size */
1832 xisr = (struct sadb_x_ipsecrequest *)p;
1833 xisr->sadb_x_ipsecrequest_len = ilen;
1834 xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1835 xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1836 xisr->sadb_x_ipsecrequest_level = isr->level;
1837 xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1840 bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1841 p += isr->saidx.src.sa.sa_len;
1842 bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1843 p += isr->saidx.dst.sa.sa_len;
1846 xpl->sadb_x_policy_len = PFKEY_UNIT64(xlen);
1850 *len = sizeof(*xpl);
1854 /* m will not be freed nor modified */
1855 static struct mbuf *
1856 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1857 int ndeep, int nitem, ...)
1862 struct mbuf *result = NULL, *n;
1865 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1866 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1868 va_start(ap, nitem);
1869 for (i = 0; i < nitem; i++) {
1870 idx = va_arg(ap, int);
1871 if (idx < 0 || idx > SADB_EXT_MAX)
1873 /* don't attempt to pull empty extension */
1874 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1876 if (idx != SADB_EXT_RESERVED &&
1877 (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1880 if (idx == SADB_EXT_RESERVED) {
1881 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1883 IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1885 MGETHDR(n, M_NOWAIT, MT_DATA);
1890 m_copydata(m, 0, sizeof(struct sadb_msg),
1892 } else if (i < ndeep) {
1893 len = mhp->extlen[idx];
1894 n = m_get2(len, M_NOWAIT, MT_DATA, 0);
1899 m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1902 n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1915 if ((result->m_flags & M_PKTHDR) != 0) {
1916 result->m_pkthdr.len = 0;
1917 for (n = result; n; n = n->m_next)
1918 result->m_pkthdr.len += n->m_len;
1930 * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1931 * add an entry to SP database, when received
1932 * <base, address(SD), (lifetime(H),) policy>
1934 * Adding to SP database,
1936 * <base, address(SD), (lifetime(H),) policy>
1937 * to the socket which was send.
1939 * SPDADD set a unique policy entry.
1940 * SPDSETIDX like SPDADD without a part of policy requests.
1941 * SPDUPDATE replace a unique policy entry.
1943 * XXXAE: serialize this in PF_KEY to avoid races.
1944 * m will always be freed.
1947 key_spdadd(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
1949 struct secpolicyindex spidx;
1950 struct sadb_address *src0, *dst0;
1951 struct sadb_x_policy *xpl0, *xpl;
1952 struct sadb_lifetime *lft = NULL;
1953 struct secpolicy *newsp;
1956 IPSEC_ASSERT(so != NULL, ("null socket"));
1957 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1958 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1959 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1961 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
1962 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
1963 SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY)) {
1964 ipseclog((LOG_DEBUG,
1965 "%s: invalid message: missing required header.\n",
1967 return key_senderror(so, m, EINVAL);
1969 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
1970 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
1971 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
1972 ipseclog((LOG_DEBUG,
1973 "%s: invalid message: wrong header size.\n", __func__));
1974 return key_senderror(so, m, EINVAL);
1976 if (!SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD)) {
1977 if (SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_HARD)) {
1978 ipseclog((LOG_DEBUG,
1979 "%s: invalid message: wrong header size.\n",
1981 return key_senderror(so, m, EINVAL);
1983 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1986 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1987 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1988 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1990 /* check the direciton */
1991 switch (xpl0->sadb_x_policy_dir) {
1992 case IPSEC_DIR_INBOUND:
1993 case IPSEC_DIR_OUTBOUND:
1996 ipseclog((LOG_DEBUG, "%s: invalid SP direction.\n", __func__));
1997 return key_senderror(so, m, EINVAL);
1999 /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
2000 if (xpl0->sadb_x_policy_type != IPSEC_POLICY_DISCARD &&
2001 xpl0->sadb_x_policy_type != IPSEC_POLICY_NONE &&
2002 xpl0->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
2003 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
2004 return key_senderror(so, m, EINVAL);
2007 /* policy requests are mandatory when action is ipsec. */
2008 if (xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
2009 mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
2010 ipseclog((LOG_DEBUG,
2011 "%s: policy requests required.\n", __func__));
2012 return key_senderror(so, m, EINVAL);
2015 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
2016 (struct sockaddr *)(dst0 + 1));
2018 src0->sadb_address_proto != dst0->sadb_address_proto) {
2019 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
2020 return key_senderror(so, m, error);
2023 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2026 src0->sadb_address_prefixlen,
2027 dst0->sadb_address_prefixlen,
2028 src0->sadb_address_proto,
2030 /* Checking there is SP already or not. */
2031 newsp = key_getsp(&spidx);
2032 if (newsp != NULL) {
2033 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
2035 printf("%s: unlink SP(%p) for SPDUPDATE\n",
2037 KEYDBG(KEY_DATA, kdebug_secpolicy(newsp));
2042 ipseclog((LOG_DEBUG,
2043 "%s: a SP entry exists already.\n", __func__));
2044 return (key_senderror(so, m, EEXIST));
2048 /* allocate new SP entry */
2049 if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
2050 return key_senderror(so, m, error);
2053 newsp->lastused = newsp->created = time_second;
2054 newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
2055 newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
2056 bcopy(&spidx, &newsp->spidx, sizeof(spidx));
2058 /* XXXAE: there is race between key_getsp() and key_insertsp() */
2060 if ((newsp->id = key_getnewspid()) == 0) {
2063 return key_senderror(so, m, ENOBUFS);
2065 key_insertsp(newsp);
2067 if (SPDCACHE_ENABLED())
2071 printf("%s: SP(%p)\n", __func__, newsp));
2072 KEYDBG(KEY_DATA, kdebug_secpolicy(newsp));
2075 struct mbuf *n, *mpolicy;
2076 struct sadb_msg *newmsg;
2079 /* create new sadb_msg to reply. */
2081 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
2082 SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
2083 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2085 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
2087 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2090 return key_senderror(so, m, ENOBUFS);
2092 if (n->m_len < sizeof(*newmsg)) {
2093 n = m_pullup(n, sizeof(*newmsg));
2095 return key_senderror(so, m, ENOBUFS);
2097 newmsg = mtod(n, struct sadb_msg *);
2098 newmsg->sadb_msg_errno = 0;
2099 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2102 mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
2103 sizeof(*xpl), &off);
2104 if (mpolicy == NULL) {
2105 /* n is already freed */
2106 return key_senderror(so, m, ENOBUFS);
2108 xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
2109 if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
2111 return key_senderror(so, m, EINVAL);
2113 xpl->sadb_x_policy_id = newsp->id;
2116 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2121 * get new policy id.
2127 key_getnewspid(void)
2129 struct secpolicy *sp;
2131 int count = V_key_spi_trycnt; /* XXX */
2133 SPTREE_WLOCK_ASSERT();
2135 if (V_policy_id == ~0) /* overflowed */
2136 newid = V_policy_id = 1;
2138 newid = ++V_policy_id;
2139 LIST_FOREACH(sp, SPHASH_HASH(newid), idhash) {
2140 if (sp->id == newid)
2146 if (count == 0 || newid == 0) {
2147 ipseclog((LOG_DEBUG, "%s: failed to allocate policy id.\n",
2155 * SADB_SPDDELETE processing
2157 * <base, address(SD), policy(*)>
2158 * from the user(?), and set SADB_SASTATE_DEAD,
2160 * <base, address(SD), policy(*)>
2162 * policy(*) including direction of policy.
2164 * m will always be freed.
2167 key_spddelete(struct socket *so, struct mbuf *m,
2168 const struct sadb_msghdr *mhp)
2170 struct secpolicyindex spidx;
2171 struct sadb_address *src0, *dst0;
2172 struct sadb_x_policy *xpl0;
2173 struct secpolicy *sp;
2175 IPSEC_ASSERT(so != NULL, ("null so"));
2176 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2177 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2178 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2180 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
2181 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
2182 SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY)) {
2183 ipseclog((LOG_DEBUG,
2184 "%s: invalid message: missing required header.\n",
2186 return key_senderror(so, m, EINVAL);
2188 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
2189 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
2190 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2191 ipseclog((LOG_DEBUG,
2192 "%s: invalid message: wrong header size.\n", __func__));
2193 return key_senderror(so, m, EINVAL);
2196 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2197 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2198 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2200 /* check the direciton */
2201 switch (xpl0->sadb_x_policy_dir) {
2202 case IPSEC_DIR_INBOUND:
2203 case IPSEC_DIR_OUTBOUND:
2206 ipseclog((LOG_DEBUG, "%s: invalid SP direction.\n", __func__));
2207 return key_senderror(so, m, EINVAL);
2209 /* Only DISCARD, NONE and IPSEC are allowed */
2210 if (xpl0->sadb_x_policy_type != IPSEC_POLICY_DISCARD &&
2211 xpl0->sadb_x_policy_type != IPSEC_POLICY_NONE &&
2212 xpl0->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
2213 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
2214 return key_senderror(so, m, EINVAL);
2216 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
2217 (struct sockaddr *)(dst0 + 1)) != 0 ||
2218 src0->sadb_address_proto != dst0->sadb_address_proto) {
2219 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
2220 return key_senderror(so, m, EINVAL);
2223 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2226 src0->sadb_address_prefixlen,
2227 dst0->sadb_address_prefixlen,
2228 src0->sadb_address_proto,
2231 /* Is there SP in SPD ? */
2232 if ((sp = key_getsp(&spidx)) == NULL) {
2233 ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2234 return key_senderror(so, m, EINVAL);
2237 /* save policy id to buffer to be returned. */
2238 xpl0->sadb_x_policy_id = sp->id;
2241 printf("%s: SP(%p)\n", __func__, sp));
2242 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2248 struct sadb_msg *newmsg;
2250 /* create new sadb_msg to reply. */
2251 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2252 SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2254 return key_senderror(so, m, ENOBUFS);
2256 newmsg = mtod(n, struct sadb_msg *);
2257 newmsg->sadb_msg_errno = 0;
2258 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2261 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2266 * SADB_SPDDELETE2 processing
2269 * from the user(?), and set SADB_SASTATE_DEAD,
2273 * policy(*) including direction of policy.
2275 * m will always be freed.
2278 key_spddelete2(struct socket *so, struct mbuf *m,
2279 const struct sadb_msghdr *mhp)
2281 struct secpolicy *sp;
2284 IPSEC_ASSERT(so != NULL, ("null socket"));
2285 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2286 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2287 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2289 if (SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY) ||
2290 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2291 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2293 return key_senderror(so, m, EINVAL);
2296 id = ((struct sadb_x_policy *)
2297 mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2299 /* Is there SP in SPD ? */
2300 if ((sp = key_getspbyid(id)) == NULL) {
2301 ipseclog((LOG_DEBUG, "%s: no SP found for id %u.\n",
2303 return key_senderror(so, m, EINVAL);
2307 printf("%s: SP(%p)\n", __func__, sp));
2308 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2310 if (sp->state != IPSEC_SPSTATE_DEAD) {
2311 ipseclog((LOG_DEBUG, "%s: failed to delete SP with id %u.\n",
2314 return (key_senderror(so, m, EACCES));
2319 struct mbuf *n, *nn;
2320 struct sadb_msg *newmsg;
2323 /* create new sadb_msg to reply. */
2324 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2326 MGETHDR(n, M_NOWAIT, MT_DATA);
2327 if (n && len > MHLEN) {
2328 if (!(MCLGET(n, M_NOWAIT))) {
2334 return key_senderror(so, m, ENOBUFS);
2340 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2341 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2343 IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2346 n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2347 mhp->extlen[SADB_X_EXT_POLICY], M_NOWAIT);
2350 return key_senderror(so, m, ENOBUFS);
2353 n->m_pkthdr.len = 0;
2354 for (nn = n; nn; nn = nn->m_next)
2355 n->m_pkthdr.len += nn->m_len;
2357 newmsg = mtod(n, struct sadb_msg *);
2358 newmsg->sadb_msg_errno = 0;
2359 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2362 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2367 * SADB_X_SPDGET processing
2372 * <base, address(SD), policy>
2374 * policy(*) including direction of policy.
2376 * m will always be freed.
2379 key_spdget(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2381 struct secpolicy *sp;
2385 IPSEC_ASSERT(so != NULL, ("null socket"));
2386 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2387 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2388 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2390 if (SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY) ||
2391 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2392 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2394 return key_senderror(so, m, EINVAL);
2397 id = ((struct sadb_x_policy *)
2398 mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2400 /* Is there SP in SPD ? */
2401 if ((sp = key_getspbyid(id)) == NULL) {
2402 ipseclog((LOG_DEBUG, "%s: no SP found for id %u.\n",
2404 return key_senderror(so, m, ENOENT);
2407 n = key_setdumpsp(sp, SADB_X_SPDGET, mhp->msg->sadb_msg_seq,
2408 mhp->msg->sadb_msg_pid);
2412 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2414 return key_senderror(so, m, ENOBUFS);
2418 * SADB_X_SPDACQUIRE processing.
2419 * Acquire policy and SA(s) for a *OUTBOUND* packet.
2422 * to KMD, and expect to receive
2423 * <base> with SADB_X_SPDACQUIRE if error occurred,
2426 * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2427 * policy(*) is without policy requests.
2430 * others: error number
2433 key_spdacquire(struct secpolicy *sp)
2435 struct mbuf *result = NULL, *m;
2436 struct secspacq *newspacq;
2438 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2439 IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2440 IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2441 ("policy not IPSEC %u", sp->policy));
2443 /* Get an entry to check whether sent message or not. */
2444 newspacq = key_getspacq(&sp->spidx);
2445 if (newspacq != NULL) {
2446 if (V_key_blockacq_count < newspacq->count) {
2447 /* reset counter and do send message. */
2448 newspacq->count = 0;
2450 /* increment counter and do nothing. */
2457 /* make new entry for blocking to send SADB_ACQUIRE. */
2458 newspacq = key_newspacq(&sp->spidx);
2459 if (newspacq == NULL)
2463 /* create new sadb_msg to reply. */
2464 m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2470 result->m_pkthdr.len = 0;
2471 for (m = result; m; m = m->m_next)
2472 result->m_pkthdr.len += m->m_len;
2474 mtod(result, struct sadb_msg *)->sadb_msg_len =
2475 PFKEY_UNIT64(result->m_pkthdr.len);
2477 return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2481 * SADB_SPDFLUSH processing
2484 * from the user, and free all entries in secpctree.
2488 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2490 * m will always be freed.
2493 key_spdflush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2495 struct secpolicy_queue drainq;
2496 struct sadb_msg *newmsg;
2497 struct secpolicy *sp, *nextsp;
2500 IPSEC_ASSERT(so != NULL, ("null socket"));
2501 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2502 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2503 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2505 if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2506 return key_senderror(so, m, EINVAL);
2508 TAILQ_INIT(&drainq);
2510 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2511 TAILQ_CONCAT(&drainq, &V_sptree[dir], chain);
2514 * We need to set state to DEAD for each policy to be sure,
2515 * that another thread won't try to unlink it.
2516 * Also remove SP from sphash.
2518 TAILQ_FOREACH(sp, &drainq, chain) {
2519 sp->state = IPSEC_SPSTATE_DEAD;
2520 LIST_REMOVE(sp, idhash);
2525 if (SPDCACHE_ENABLED())
2527 sp = TAILQ_FIRST(&drainq);
2528 while (sp != NULL) {
2529 nextsp = TAILQ_NEXT(sp, chain);
2534 if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2535 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2536 return key_senderror(so, m, ENOBUFS);
2542 m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2543 newmsg = mtod(m, struct sadb_msg *);
2544 newmsg->sadb_msg_errno = 0;
2545 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2547 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2551 key_satype2scopemask(uint8_t satype)
2554 if (satype == IPSEC_POLICYSCOPE_ANY)
2559 * SADB_SPDDUMP processing
2562 * from the user, and dump all SP leaves and send,
2567 * sadb_msg_satype is considered as mask of policy scopes.
2568 * m will always be freed.
2571 key_spddump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2573 SPTREE_RLOCK_TRACKER;
2574 struct secpolicy *sp;
2579 IPSEC_ASSERT(so != NULL, ("null socket"));
2580 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2581 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2582 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2584 /* search SPD entry and get buffer size. */
2586 scope = key_satype2scopemask(mhp->msg->sadb_msg_satype);
2588 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2589 if (scope & IPSEC_POLICYSCOPE_GLOBAL) {
2590 TAILQ_FOREACH(sp, &V_sptree[dir], chain)
2593 if (scope & IPSEC_POLICYSCOPE_IFNET) {
2594 TAILQ_FOREACH(sp, &V_sptree_ifnet[dir], chain)
2601 return key_senderror(so, m, ENOENT);
2604 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2605 if (scope & IPSEC_POLICYSCOPE_GLOBAL) {
2606 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
2608 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2609 mhp->msg->sadb_msg_pid);
2612 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2615 if (scope & IPSEC_POLICYSCOPE_IFNET) {
2616 TAILQ_FOREACH(sp, &V_sptree_ifnet[dir], chain) {
2618 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2619 mhp->msg->sadb_msg_pid);
2622 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2632 static struct mbuf *
2633 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq,
2636 struct mbuf *result = NULL, *m;
2637 struct seclifetime lt;
2639 m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2644 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2645 &sp->spidx.src.sa, sp->spidx.prefs,
2646 sp->spidx.ul_proto);
2651 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2652 &sp->spidx.dst.sa, sp->spidx.prefd,
2653 sp->spidx.ul_proto);
2658 m = key_sp2mbuf(sp);
2664 lt.addtime=sp->created;
2665 lt.usetime= sp->lastused;
2666 m = key_setlifetime(<, SADB_EXT_LIFETIME_CURRENT);
2671 lt.addtime=sp->lifetime;
2672 lt.usetime= sp->validtime;
2673 m = key_setlifetime(<, SADB_EXT_LIFETIME_HARD);
2679 if ((result->m_flags & M_PKTHDR) == 0)
2682 if (result->m_len < sizeof(struct sadb_msg)) {
2683 result = m_pullup(result, sizeof(struct sadb_msg));
2688 result->m_pkthdr.len = 0;
2689 for (m = result; m; m = m->m_next)
2690 result->m_pkthdr.len += m->m_len;
2692 mtod(result, struct sadb_msg *)->sadb_msg_len =
2693 PFKEY_UNIT64(result->m_pkthdr.len);
2702 * get PFKEY message length for security policy and request.
2705 key_getspreqmsglen(struct secpolicy *sp)
2710 tlen = sizeof(struct sadb_x_policy);
2711 /* if is the policy for ipsec ? */
2712 if (sp->policy != IPSEC_POLICY_IPSEC)
2715 /* get length of ipsec requests */
2716 for (i = 0; i < sp->tcount; i++) {
2717 len = sizeof(struct sadb_x_ipsecrequest)
2718 + sp->req[i]->saidx.src.sa.sa_len
2719 + sp->req[i]->saidx.dst.sa.sa_len;
2721 tlen += PFKEY_ALIGN8(len);
2727 * SADB_SPDEXPIRE processing
2729 * <base, address(SD), lifetime(CH), policy>
2733 * others : error number
2736 key_spdexpire(struct secpolicy *sp)
2738 struct sadb_lifetime *lt;
2739 struct mbuf *result = NULL, *m;
2740 int len, error = -1;
2742 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2745 printf("%s: SP(%p)\n", __func__, sp));
2746 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2748 /* set msg header */
2749 m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2756 /* create lifetime extension (current and hard) */
2757 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2758 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
2765 bzero(mtod(m, caddr_t), len);
2766 lt = mtod(m, struct sadb_lifetime *);
2767 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2768 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2769 lt->sadb_lifetime_allocations = 0;
2770 lt->sadb_lifetime_bytes = 0;
2771 lt->sadb_lifetime_addtime = sp->created;
2772 lt->sadb_lifetime_usetime = sp->lastused;
2773 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2774 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2775 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2776 lt->sadb_lifetime_allocations = 0;
2777 lt->sadb_lifetime_bytes = 0;
2778 lt->sadb_lifetime_addtime = sp->lifetime;
2779 lt->sadb_lifetime_usetime = sp->validtime;
2782 /* set sadb_address for source */
2783 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2785 sp->spidx.prefs, sp->spidx.ul_proto);
2792 /* set sadb_address for destination */
2793 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2795 sp->spidx.prefd, sp->spidx.ul_proto);
2803 m = key_sp2mbuf(sp);
2810 if ((result->m_flags & M_PKTHDR) == 0) {
2815 if (result->m_len < sizeof(struct sadb_msg)) {
2816 result = m_pullup(result, sizeof(struct sadb_msg));
2817 if (result == NULL) {
2823 result->m_pkthdr.len = 0;
2824 for (m = result; m; m = m->m_next)
2825 result->m_pkthdr.len += m->m_len;
2827 mtod(result, struct sadb_msg *)->sadb_msg_len =
2828 PFKEY_UNIT64(result->m_pkthdr.len);
2830 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2838 /* %%% SAD management */
2840 * allocating and initialize new SA head.
2841 * OUT: NULL : failure due to the lack of memory.
2842 * others : pointer to new SA head.
2844 static struct secashead *
2845 key_newsah(struct secasindex *saidx)
2847 struct secashead *sah;
2849 sah = malloc(sizeof(struct secashead), M_IPSEC_SAH,
2852 PFKEYSTAT_INC(in_nomem);
2855 TAILQ_INIT(&sah->savtree_larval);
2856 TAILQ_INIT(&sah->savtree_alive);
2857 sah->saidx = *saidx;
2858 sah->state = SADB_SASTATE_DEAD;
2862 printf("%s: SAH(%p)\n", __func__, sah));
2863 KEYDBG(KEY_DATA, kdebug_secash(sah, NULL));
2868 key_freesah(struct secashead **psah)
2870 struct secashead *sah = *psah;
2872 if (SAH_DELREF(sah) == 0)
2876 printf("%s: last reference to SAH(%p)\n", __func__, sah));
2877 KEYDBG(KEY_DATA, kdebug_secash(sah, NULL));
2884 key_delsah(struct secashead *sah)
2886 IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2887 IPSEC_ASSERT(sah->state == SADB_SASTATE_DEAD,
2888 ("Attempt to free non DEAD SAH %p", sah));
2889 IPSEC_ASSERT(TAILQ_EMPTY(&sah->savtree_larval),
2890 ("Attempt to free SAH %p with LARVAL SA", sah));
2891 IPSEC_ASSERT(TAILQ_EMPTY(&sah->savtree_alive),
2892 ("Attempt to free SAH %p with ALIVE SA", sah));
2894 free(sah, M_IPSEC_SAH);
2898 * allocating a new SA for key_add() and key_getspi() call,
2899 * and copy the values of mhp into new buffer.
2900 * When SAD message type is SADB_GETSPI set SA state to LARVAL.
2901 * For SADB_ADD create and initialize SA with MATURE state.
2903 * others : pointer to new secasvar.
2905 static struct secasvar *
2906 key_newsav(const struct sadb_msghdr *mhp, struct secasindex *saidx,
2907 uint32_t spi, int *errp)
2909 struct secashead *sah;
2910 struct secasvar *sav;
2913 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2914 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2915 IPSEC_ASSERT(mhp->msg->sadb_msg_type == SADB_GETSPI ||
2916 mhp->msg->sadb_msg_type == SADB_ADD, ("wrong message type"));
2920 /* check SPI value */
2921 switch (saidx->proto) {
2925 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
2926 * 1-255 reserved by IANA for future use,
2927 * 0 for implementation specific, local use.
2929 if (ntohl(spi) <= 255) {
2930 ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
2931 __func__, ntohl(spi)));
2938 sav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT | M_ZERO);
2943 sav->lock = malloc(sizeof(struct mtx), M_IPSEC_MISC,
2945 if (sav->lock == NULL) {
2949 mtx_init(sav->lock, "ipsec association", NULL, MTX_DEF);
2950 sav->lft_c = uma_zalloc_pcpu(V_key_lft_zone, M_NOWAIT);
2951 if (sav->lft_c == NULL) {
2955 counter_u64_zero(sav->lft_c_allocations);
2956 counter_u64_zero(sav->lft_c_bytes);
2959 sav->seq = mhp->msg->sadb_msg_seq;
2960 sav->state = SADB_SASTATE_LARVAL;
2961 sav->pid = (pid_t)mhp->msg->sadb_msg_pid;
2964 sah = key_getsah(saidx);
2966 /* create a new SA index */
2967 sah = key_newsah(saidx);
2969 ipseclog((LOG_DEBUG,
2970 "%s: No more memory.\n", __func__));
2979 if (mhp->msg->sadb_msg_type == SADB_GETSPI) {
2980 sav->created = time_second;
2981 } else if (sav->state == SADB_SASTATE_LARVAL) {
2983 * Do not call key_setsaval() second time in case
2984 * of `goto again`. We will have MATURE state.
2986 *errp = key_setsaval(sav, mhp);
2989 sav->state = SADB_SASTATE_MATURE;
2994 * Check that existing SAH wasn't unlinked.
2995 * Since we didn't hold the SAHTREE lock, it is possible,
2996 * that callout handler or key_flush() or key_delete() could
2999 if (isnew == 0 && sah->state == SADB_SASTATE_DEAD) {
3001 key_freesah(&sah); /* reference from key_getsah() */
3006 * Add new SAH into SADB.
3008 * XXXAE: we can serialize key_add and key_getspi calls, so
3009 * several threads will not fight in the race.
3010 * Otherwise we should check under SAHTREE lock, that this
3011 * SAH would not added twice.
3013 TAILQ_INSERT_HEAD(&V_sahtree, sah, chain);
3014 /* Add new SAH into hash by addresses */
3015 LIST_INSERT_HEAD(SAHADDRHASH_HASH(saidx), sah, addrhash);
3016 /* Now we are linked in the chain */
3017 sah->state = SADB_SASTATE_MATURE;
3019 * SAV references this new SAH.
3020 * In case of existing SAH we reuse reference
3021 * from key_getsah().
3025 /* Link SAV with SAH */
3026 if (sav->state == SADB_SASTATE_MATURE)
3027 TAILQ_INSERT_HEAD(&sah->savtree_alive, sav, chain);
3029 TAILQ_INSERT_HEAD(&sah->savtree_larval, sav, chain);
3030 /* Add SAV into SPI hash */
3031 LIST_INSERT_HEAD(SAVHASH_HASH(sav->spi), sav, spihash);
3033 *errp = 0; /* success */
3037 if (sav->lock != NULL) {
3038 mtx_destroy(sav->lock);
3039 free(sav->lock, M_IPSEC_MISC);
3041 if (sav->lft_c != NULL)
3042 uma_zfree_pcpu(V_key_lft_zone, sav->lft_c);
3043 free(sav, M_IPSEC_SA), sav = NULL;
3047 if (*errp == ENOBUFS) {
3048 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3050 PFKEYSTAT_INC(in_nomem);
3057 * free() SA variable entry.
3060 key_cleansav(struct secasvar *sav)
3063 if (sav->natt != NULL) {
3064 free(sav->natt, M_IPSEC_MISC);
3067 if (sav->flags & SADB_X_EXT_F_CLONED)
3070 * Cleanup xform state. Note that zeroize'ing causes the
3071 * keys to be cleared; otherwise we must do it ourself.
3073 if (sav->tdb_xform != NULL) {
3074 sav->tdb_xform->xf_zeroize(sav);
3075 sav->tdb_xform = NULL;
3077 if (sav->key_auth != NULL)
3078 bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
3079 if (sav->key_enc != NULL)
3080 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
3082 if (sav->key_auth != NULL) {
3083 if (sav->key_auth->key_data != NULL)
3084 free(sav->key_auth->key_data, M_IPSEC_MISC);
3085 free(sav->key_auth, M_IPSEC_MISC);
3086 sav->key_auth = NULL;
3088 if (sav->key_enc != NULL) {
3089 if (sav->key_enc->key_data != NULL)
3090 free(sav->key_enc->key_data, M_IPSEC_MISC);
3091 free(sav->key_enc, M_IPSEC_MISC);
3092 sav->key_enc = NULL;
3094 if (sav->replay != NULL) {
3095 if (sav->replay->bitmap != NULL)
3096 free(sav->replay->bitmap, M_IPSEC_MISC);
3097 free(sav->replay, M_IPSEC_MISC);
3100 if (sav->lft_h != NULL) {
3101 free(sav->lft_h, M_IPSEC_MISC);
3104 if (sav->lft_s != NULL) {
3105 free(sav->lft_s, M_IPSEC_MISC);
3111 * free() SA variable entry.
3114 key_delsav(struct secasvar *sav)
3116 IPSEC_ASSERT(sav != NULL, ("null sav"));
3117 IPSEC_ASSERT(sav->state == SADB_SASTATE_DEAD,
3118 ("attempt to free non DEAD SA %p", sav));
3119 IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0",
3123 * SA must be unlinked from the chain and hashtbl.
3124 * If SA was cloned, we leave all fields untouched,
3125 * except NAT-T config.
3128 if ((sav->flags & SADB_X_EXT_F_CLONED) == 0) {
3129 mtx_destroy(sav->lock);
3130 free(sav->lock, M_IPSEC_MISC);
3131 uma_zfree(V_key_lft_zone, sav->lft_c);
3133 free(sav, M_IPSEC_SA);
3140 * others : found, referenced pointer to a SAH.
3142 static struct secashead *
3143 key_getsah(struct secasindex *saidx)
3145 SAHTREE_RLOCK_TRACKER;
3146 struct secashead *sah;
3149 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
3150 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID) != 0) {
3160 * Check not to be duplicated SPI.
3163 * 1 : found SA with given SPI.
3166 key_checkspidup(uint32_t spi)
3168 SAHTREE_RLOCK_TRACKER;
3169 struct secasvar *sav;
3171 /* Assume SPI is in network byte order */
3173 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
3174 if (sav->spi == spi)
3178 return (sav != NULL);
3185 * others : found, referenced pointer to a SA.
3187 static struct secasvar *
3188 key_getsavbyspi(uint32_t spi)
3190 SAHTREE_RLOCK_TRACKER;
3191 struct secasvar *sav;
3193 /* Assume SPI is in network byte order */
3195 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
3196 if (sav->spi != spi)
3206 key_updatelifetimes(struct secasvar *sav, const struct sadb_msghdr *mhp)
3208 struct seclifetime *lft_h, *lft_s, *tmp;
3210 /* Lifetime extension is optional, check that it is present. */
3211 if (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
3212 SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) {
3214 * In case of SADB_UPDATE we may need to change
3215 * existing lifetimes.
3217 if (sav->state == SADB_SASTATE_MATURE) {
3218 lft_h = lft_s = NULL;
3223 /* Both HARD and SOFT extensions must present */
3224 if ((SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
3225 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
3226 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
3227 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
3228 ipseclog((LOG_DEBUG,
3229 "%s: invalid message: missing required header.\n",
3233 if (SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_HARD) ||
3234 SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_SOFT)) {
3235 ipseclog((LOG_DEBUG,
3236 "%s: invalid message: wrong header size.\n", __func__));
3239 lft_h = key_dup_lifemsg((const struct sadb_lifetime *)
3240 mhp->ext[SADB_EXT_LIFETIME_HARD], M_IPSEC_MISC);
3241 if (lft_h == NULL) {
3242 PFKEYSTAT_INC(in_nomem);
3243 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3246 lft_s = key_dup_lifemsg((const struct sadb_lifetime *)
3247 mhp->ext[SADB_EXT_LIFETIME_SOFT], M_IPSEC_MISC);
3248 if (lft_s == NULL) {
3249 PFKEYSTAT_INC(in_nomem);
3250 free(lft_h, M_IPSEC_MISC);
3251 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3255 if (sav->state != SADB_SASTATE_LARVAL) {
3257 * key_update() holds reference to this SA,
3258 * so it won't be deleted in meanwhile.
3268 SECASVAR_UNLOCK(sav);
3270 free(lft_h, M_IPSEC_MISC);
3272 free(lft_s, M_IPSEC_MISC);
3275 /* We can update lifetime without holding a lock */
3276 IPSEC_ASSERT(sav->lft_h == NULL, ("lft_h is already initialized\n"));
3277 IPSEC_ASSERT(sav->lft_s == NULL, ("lft_s is already initialized\n"));
3284 * copy SA values from PF_KEY message except *SPI, SEQ, PID and TYPE*.
3285 * You must update these if need. Expects only LARVAL SAs.
3290 key_setsaval(struct secasvar *sav, const struct sadb_msghdr *mhp)
3292 const struct sadb_sa *sa0;
3293 const struct sadb_key *key0;
3298 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3299 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3300 IPSEC_ASSERT(sav->state == SADB_SASTATE_LARVAL,
3301 ("Attempt to update non LARVAL SA"));
3304 error = key_setident(sav->sah, mhp);
3309 if (!SADB_CHECKHDR(mhp, SADB_EXT_SA)) {
3310 if (SADB_CHECKLEN(mhp, SADB_EXT_SA)) {
3314 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3315 sav->alg_auth = sa0->sadb_sa_auth;
3316 sav->alg_enc = sa0->sadb_sa_encrypt;
3317 sav->flags = sa0->sadb_sa_flags;
3318 if ((sav->flags & SADB_KEY_FLAGS_MAX) != sav->flags) {
3319 ipseclog((LOG_DEBUG,
3320 "%s: invalid sa_flags 0x%08x.\n", __func__,
3326 /* Optional replay window */
3328 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0)
3329 replay = sa0->sadb_sa_replay;
3330 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_SA_REPLAY)) {
3331 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA_REPLAY)) {
3335 replay = ((const struct sadb_x_sa_replay *)
3336 mhp->ext[SADB_X_EXT_SA_REPLAY])->sadb_x_sa_replay_replay;
3338 if (replay > UINT32_MAX - 32) {
3339 ipseclog((LOG_DEBUG,
3340 "%s: replay window too big.\n", __func__));
3345 replay = (replay + 7) >> 3;
3348 sav->replay = malloc(sizeof(struct secreplay), M_IPSEC_MISC,
3350 if (sav->replay == NULL) {
3351 PFKEYSTAT_INC(in_nomem);
3352 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3359 /* number of 32b blocks to be allocated */
3360 uint32_t bitmap_size;
3363 * - the allocated replay window size must be
3365 * - use an extra 32b block as a redundant window.
3368 while (replay + 4 > bitmap_size)
3370 bitmap_size = bitmap_size / 4;
3372 sav->replay->bitmap = malloc(
3373 bitmap_size * sizeof(uint32_t), M_IPSEC_MISC,
3375 if (sav->replay->bitmap == NULL) {
3376 PFKEYSTAT_INC(in_nomem);
3377 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3382 sav->replay->bitmap_size = bitmap_size;
3383 sav->replay->wsize = replay;
3387 /* Authentication keys */
3388 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH)) {
3389 if (SADB_CHECKLEN(mhp, SADB_EXT_KEY_AUTH)) {
3394 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3395 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3396 switch (mhp->msg->sadb_msg_satype) {
3397 case SADB_SATYPE_AH:
3398 case SADB_SATYPE_ESP:
3399 case SADB_X_SATYPE_TCPSIGNATURE:
3400 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3401 sav->alg_auth != SADB_X_AALG_NULL)
3404 case SADB_X_SATYPE_IPCOMP:
3410 ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3415 sav->key_auth = key_dup_keymsg(key0, len, M_IPSEC_MISC);
3416 if (sav->key_auth == NULL ) {
3417 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3419 PFKEYSTAT_INC(in_nomem);
3425 /* Encryption key */
3426 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT)) {
3427 if (SADB_CHECKLEN(mhp, SADB_EXT_KEY_ENCRYPT)) {
3432 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3433 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3434 switch (mhp->msg->sadb_msg_satype) {
3435 case SADB_SATYPE_ESP:
3436 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3437 sav->alg_enc != SADB_EALG_NULL) {
3441 sav->key_enc = key_dup_keymsg(key0, len, M_IPSEC_MISC);
3442 if (sav->key_enc == NULL) {
3443 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3445 PFKEYSTAT_INC(in_nomem);
3450 case SADB_X_SATYPE_IPCOMP:
3451 if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3453 sav->key_enc = NULL; /*just in case*/
3455 case SADB_SATYPE_AH:
3456 case SADB_X_SATYPE_TCPSIGNATURE:
3462 ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3470 switch (mhp->msg->sadb_msg_satype) {
3471 case SADB_SATYPE_AH:
3472 if (sav->flags & SADB_X_EXT_DERIV) {
3473 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3474 "given to AH SA.\n", __func__));
3478 if (sav->alg_enc != SADB_EALG_NONE) {
3479 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3480 "mismated.\n", __func__));
3484 error = xform_init(sav, XF_AH);
3486 case SADB_SATYPE_ESP:
3487 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_DERIV)) ==
3488 (SADB_X_EXT_OLD | SADB_X_EXT_DERIV)) {
3489 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3490 "given to old-esp.\n", __func__));
3494 error = xform_init(sav, XF_ESP);
3496 case SADB_X_SATYPE_IPCOMP:
3497 if (sav->alg_auth != SADB_AALG_NONE) {
3498 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3499 "mismated.\n", __func__));
3503 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0 &&
3504 ntohl(sav->spi) >= 0x10000) {
3505 ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3510 error = xform_init(sav, XF_IPCOMP);
3512 case SADB_X_SATYPE_TCPSIGNATURE:
3513 if (sav->alg_enc != SADB_EALG_NONE) {
3514 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3515 "mismated.\n", __func__));
3519 error = xform_init(sav, XF_TCPSIGNATURE);
3522 ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3523 error = EPROTONOSUPPORT;
3527 ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3528 __func__, mhp->msg->sadb_msg_satype));
3532 /* Handle NAT-T headers */
3533 error = key_setnatt(sav, mhp);
3537 /* Initialize lifetime for CURRENT */
3539 sav->created = time_second;
3541 /* lifetimes for HARD and SOFT */
3542 error = key_updatelifetimes(sav, mhp);
3551 * subroutine for SADB_GET and SADB_DUMP.
3553 static struct mbuf *
3554 key_setdumpsa(struct secasvar *sav, uint8_t type, uint8_t satype,
3555 uint32_t seq, uint32_t pid)
3557 struct seclifetime lft_c;
3558 struct mbuf *result = NULL, *tres = NULL, *m;
3559 int i, dumporder[] = {
3560 SADB_EXT_SA, SADB_X_EXT_SA2, SADB_X_EXT_SA_REPLAY,
3561 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3562 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3563 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY,
3564 SADB_EXT_KEY_AUTH, SADB_EXT_KEY_ENCRYPT,
3565 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
3566 SADB_EXT_SENSITIVITY,
3567 SADB_X_EXT_NAT_T_TYPE,
3568 SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3569 SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3570 SADB_X_EXT_NAT_T_FRAG,
3572 uint32_t replay_count;
3574 m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3579 for (i = nitems(dumporder) - 1; i >= 0; i--) {
3581 switch (dumporder[i]) {
3583 m = key_setsadbsa(sav);
3588 case SADB_X_EXT_SA2:
3590 replay_count = sav->replay ? sav->replay->count : 0;
3591 SECASVAR_UNLOCK(sav);
3592 m = key_setsadbxsa2(sav->sah->saidx.mode, replay_count,
3593 sav->sah->saidx.reqid);
3598 case SADB_X_EXT_SA_REPLAY:
3599 if (sav->replay == NULL ||
3600 sav->replay->wsize <= UINT8_MAX)
3603 m = key_setsadbxsareplay(sav->replay->wsize);
3608 case SADB_EXT_ADDRESS_SRC:
3609 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3610 &sav->sah->saidx.src.sa,
3611 FULLMASK, IPSEC_ULPROTO_ANY);
3616 case SADB_EXT_ADDRESS_DST:
3617 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3618 &sav->sah->saidx.dst.sa,
3619 FULLMASK, IPSEC_ULPROTO_ANY);
3624 case SADB_EXT_KEY_AUTH:
3627 m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3632 case SADB_EXT_KEY_ENCRYPT:
3635 m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3640 case SADB_EXT_LIFETIME_CURRENT:
3641 lft_c.addtime = sav->created;
3642 lft_c.allocations = (uint32_t)counter_u64_fetch(
3643 sav->lft_c_allocations);
3644 lft_c.bytes = counter_u64_fetch(sav->lft_c_bytes);
3645 lft_c.usetime = sav->firstused;
3646 m = key_setlifetime(&lft_c, SADB_EXT_LIFETIME_CURRENT);
3651 case SADB_EXT_LIFETIME_HARD:
3654 m = key_setlifetime(sav->lft_h,
3655 SADB_EXT_LIFETIME_HARD);
3660 case SADB_EXT_LIFETIME_SOFT:
3663 m = key_setlifetime(sav->lft_s,
3664 SADB_EXT_LIFETIME_SOFT);
3670 case SADB_X_EXT_NAT_T_TYPE:
3671 if (sav->natt == NULL)
3673 m = key_setsadbxtype(UDP_ENCAP_ESPINUDP);
3678 case SADB_X_EXT_NAT_T_DPORT:
3679 if (sav->natt == NULL)
3681 m = key_setsadbxport(sav->natt->dport,
3682 SADB_X_EXT_NAT_T_DPORT);
3687 case SADB_X_EXT_NAT_T_SPORT:
3688 if (sav->natt == NULL)
3690 m = key_setsadbxport(sav->natt->sport,
3691 SADB_X_EXT_NAT_T_SPORT);
3696 case SADB_X_EXT_NAT_T_OAI:
3697 if (sav->natt == NULL ||
3698 (sav->natt->flags & IPSEC_NATT_F_OAI) == 0)
3700 m = key_setsadbaddr(SADB_X_EXT_NAT_T_OAI,
3701 &sav->natt->oai.sa, FULLMASK, IPSEC_ULPROTO_ANY);
3705 case SADB_X_EXT_NAT_T_OAR:
3706 if (sav->natt == NULL ||
3707 (sav->natt->flags & IPSEC_NATT_F_OAR) == 0)
3709 m = key_setsadbaddr(SADB_X_EXT_NAT_T_OAR,
3710 &sav->natt->oar.sa, FULLMASK, IPSEC_ULPROTO_ANY);
3714 case SADB_X_EXT_NAT_T_FRAG:
3715 /* We do not (yet) support those. */
3718 case SADB_EXT_ADDRESS_PROXY:
3719 case SADB_EXT_IDENTITY_SRC:
3720 case SADB_EXT_IDENTITY_DST:
3721 /* XXX: should we brought from SPD ? */
3722 case SADB_EXT_SENSITIVITY:
3734 m_cat(result, tres);
3736 if (result->m_len < sizeof(struct sadb_msg)) {
3737 result = m_pullup(result, sizeof(struct sadb_msg));
3742 result->m_pkthdr.len = 0;
3743 for (m = result; m; m = m->m_next)
3744 result->m_pkthdr.len += m->m_len;
3746 mtod(result, struct sadb_msg *)->sadb_msg_len =
3747 PFKEY_UNIT64(result->m_pkthdr.len);
3758 * set data into sadb_msg.
3760 static struct mbuf *
3761 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3762 pid_t pid, u_int16_t reserved)
3768 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3771 MGETHDR(m, M_NOWAIT, MT_DATA);
3772 if (m && len > MHLEN) {
3773 if (!(MCLGET(m, M_NOWAIT))) {
3780 m->m_pkthdr.len = m->m_len = len;
3783 p = mtod(m, struct sadb_msg *);
3786 p->sadb_msg_version = PF_KEY_V2;
3787 p->sadb_msg_type = type;
3788 p->sadb_msg_errno = 0;
3789 p->sadb_msg_satype = satype;
3790 p->sadb_msg_len = PFKEY_UNIT64(tlen);
3791 p->sadb_msg_reserved = reserved;
3792 p->sadb_msg_seq = seq;
3793 p->sadb_msg_pid = (u_int32_t)pid;
3799 * copy secasvar data into sadb_address.
3801 static struct mbuf *
3802 key_setsadbsa(struct secasvar *sav)
3808 len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3809 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3814 p = mtod(m, struct sadb_sa *);
3816 p->sadb_sa_len = PFKEY_UNIT64(len);
3817 p->sadb_sa_exttype = SADB_EXT_SA;
3818 p->sadb_sa_spi = sav->spi;
3819 p->sadb_sa_replay = sav->replay ?
3820 (sav->replay->wsize > UINT8_MAX ? UINT8_MAX :
3821 sav->replay->wsize): 0;
3822 p->sadb_sa_state = sav->state;
3823 p->sadb_sa_auth = sav->alg_auth;
3824 p->sadb_sa_encrypt = sav->alg_enc;
3825 p->sadb_sa_flags = sav->flags & SADB_KEY_FLAGS_MAX;
3830 * set data into sadb_address.
3832 static struct mbuf *
3833 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
3834 u_int8_t prefixlen, u_int16_t ul_proto)
3837 struct sadb_address *p;
3840 len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3841 PFKEY_ALIGN8(saddr->sa_len);
3842 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3847 p = mtod(m, struct sadb_address *);
3850 p->sadb_address_len = PFKEY_UNIT64(len);
3851 p->sadb_address_exttype = exttype;
3852 p->sadb_address_proto = ul_proto;
3853 if (prefixlen == FULLMASK) {
3854 switch (saddr->sa_family) {
3856 prefixlen = sizeof(struct in_addr) << 3;
3859 prefixlen = sizeof(struct in6_addr) << 3;
3865 p->sadb_address_prefixlen = prefixlen;
3866 p->sadb_address_reserved = 0;
3869 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3876 * set data into sadb_x_sa2.
3878 static struct mbuf *
3879 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3882 struct sadb_x_sa2 *p;
3885 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3886 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3891 p = mtod(m, struct sadb_x_sa2 *);
3894 p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3895 p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3896 p->sadb_x_sa2_mode = mode;
3897 p->sadb_x_sa2_reserved1 = 0;
3898 p->sadb_x_sa2_reserved2 = 0;
3899 p->sadb_x_sa2_sequence = seq;
3900 p->sadb_x_sa2_reqid = reqid;
3906 * Set data into sadb_x_sa_replay.
3908 static struct mbuf *
3909 key_setsadbxsareplay(u_int32_t replay)
3912 struct sadb_x_sa_replay *p;
3915 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa_replay));
3916 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3921 p = mtod(m, struct sadb_x_sa_replay *);
3924 p->sadb_x_sa_replay_len = PFKEY_UNIT64(len);
3925 p->sadb_x_sa_replay_exttype = SADB_X_EXT_SA_REPLAY;
3926 p->sadb_x_sa_replay_replay = (replay << 3);
3932 * Set a type in sadb_x_nat_t_type.
3934 static struct mbuf *
3935 key_setsadbxtype(u_int16_t type)
3939 struct sadb_x_nat_t_type *p;
3941 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3943 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3948 p = mtod(m, struct sadb_x_nat_t_type *);
3951 p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3952 p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3953 p->sadb_x_nat_t_type_type = type;
3958 * Set a port in sadb_x_nat_t_port.
3959 * In contrast to default RFC 2367 behaviour, port is in network byte order.
3961 static struct mbuf *
3962 key_setsadbxport(u_int16_t port, u_int16_t type)
3966 struct sadb_x_nat_t_port *p;
3968 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3970 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3975 p = mtod(m, struct sadb_x_nat_t_port *);
3978 p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3979 p->sadb_x_nat_t_port_exttype = type;
3980 p->sadb_x_nat_t_port_port = port;
3986 * Get port from sockaddr. Port is in network byte order.
3989 key_portfromsaddr(struct sockaddr *sa)
3992 switch (sa->sa_family) {
3995 return ((struct sockaddr_in *)sa)->sin_port;
3999 return ((struct sockaddr_in6 *)sa)->sin6_port;
4006 * Set port in struct sockaddr. Port is in network byte order.
4009 key_porttosaddr(struct sockaddr *sa, uint16_t port)
4012 switch (sa->sa_family) {
4015 ((struct sockaddr_in *)sa)->sin_port = port;
4020 ((struct sockaddr_in6 *)sa)->sin6_port = port;
4024 ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
4025 __func__, sa->sa_family));
4031 * set data into sadb_x_policy
4033 static struct mbuf *
4034 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id, u_int32_t priority)
4037 struct sadb_x_policy *p;
4040 len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
4041 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
4046 p = mtod(m, struct sadb_x_policy *);
4049 p->sadb_x_policy_len = PFKEY_UNIT64(len);
4050 p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
4051 p->sadb_x_policy_type = type;
4052 p->sadb_x_policy_dir = dir;
4053 p->sadb_x_policy_id = id;
4054 p->sadb_x_policy_priority = priority;
4060 /* Take a key message (sadb_key) from the socket and turn it into one
4061 * of the kernel's key structures (seckey).
4063 * IN: pointer to the src
4064 * OUT: NULL no more memory
4067 key_dup_keymsg(const struct sadb_key *src, size_t len,
4068 struct malloc_type *type)
4072 dst = malloc(sizeof(*dst), type, M_NOWAIT);
4074 dst->bits = src->sadb_key_bits;
4075 dst->key_data = malloc(len, type, M_NOWAIT);
4076 if (dst->key_data != NULL) {
4077 bcopy((const char *)(src + 1), dst->key_data, len);
4079 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
4085 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
4092 /* Take a lifetime message (sadb_lifetime) passed in on a socket and
4093 * turn it into one of the kernel's lifetime structures (seclifetime).
4095 * IN: pointer to the destination, source and malloc type
4096 * OUT: NULL, no more memory
4099 static struct seclifetime *
4100 key_dup_lifemsg(const struct sadb_lifetime *src, struct malloc_type *type)
4102 struct seclifetime *dst;
4104 dst = malloc(sizeof(*dst), type, M_NOWAIT);
4106 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4109 dst->allocations = src->sadb_lifetime_allocations;
4110 dst->bytes = src->sadb_lifetime_bytes;
4111 dst->addtime = src->sadb_lifetime_addtime;
4112 dst->usetime = src->sadb_lifetime_usetime;
4117 * compare two secasindex structure.
4118 * flag can specify to compare 2 saidxes.
4119 * compare two secasindex structure without both mode and reqid.
4120 * don't compare port.
4122 * saidx0: source, it can be in SAD.
4129 key_cmpsaidx(const struct secasindex *saidx0, const struct secasindex *saidx1,
4134 if (saidx0 == NULL && saidx1 == NULL)
4137 if (saidx0 == NULL || saidx1 == NULL)
4140 if (saidx0->proto != saidx1->proto)
4143 if (flag == CMP_EXACTLY) {
4144 if (saidx0->mode != saidx1->mode)
4146 if (saidx0->reqid != saidx1->reqid)
4148 if (bcmp(&saidx0->src, &saidx1->src,
4149 saidx0->src.sa.sa_len) != 0 ||
4150 bcmp(&saidx0->dst, &saidx1->dst,
4151 saidx0->dst.sa.sa_len) != 0)
4155 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4156 if (flag == CMP_MODE_REQID || flag == CMP_REQID) {
4158 * If reqid of SPD is non-zero, unique SA is required.
4159 * The result must be of same reqid in this case.
4161 if (saidx1->reqid != 0 &&
4162 saidx0->reqid != saidx1->reqid)
4166 if (flag == CMP_MODE_REQID) {
4167 if (saidx0->mode != IPSEC_MODE_ANY
4168 && saidx0->mode != saidx1->mode)
4172 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0)
4174 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0)
4182 * compare two secindex structure exactly.
4184 * spidx0: source, it is often in SPD.
4185 * spidx1: object, it is often from PFKEY message.
4191 key_cmpspidx_exactly(struct secpolicyindex *spidx0,
4192 struct secpolicyindex *spidx1)
4195 if (spidx0 == NULL && spidx1 == NULL)
4198 if (spidx0 == NULL || spidx1 == NULL)
4201 if (spidx0->prefs != spidx1->prefs
4202 || spidx0->prefd != spidx1->prefd
4203 || spidx0->ul_proto != spidx1->ul_proto
4204 || spidx0->dir != spidx1->dir)
4207 return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4208 key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4212 * compare two secindex structure with mask.
4214 * spidx0: source, it is often in SPD.
4215 * spidx1: object, it is often from IP header.
4221 key_cmpspidx_withmask(struct secpolicyindex *spidx0,
4222 struct secpolicyindex *spidx1)
4225 if (spidx0 == NULL && spidx1 == NULL)
4228 if (spidx0 == NULL || spidx1 == NULL)
4231 if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4232 spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4233 spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4234 spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4237 /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4238 if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4239 && spidx0->ul_proto != spidx1->ul_proto)
4242 switch (spidx0->src.sa.sa_family) {
4244 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4245 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4247 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4248 &spidx1->src.sin.sin_addr, spidx0->prefs))
4252 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4253 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4256 * scope_id check. if sin6_scope_id is 0, we regard it
4257 * as a wildcard scope, which matches any scope zone ID.
4259 if (spidx0->src.sin6.sin6_scope_id &&
4260 spidx1->src.sin6.sin6_scope_id &&
4261 spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4263 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4264 &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4269 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4274 switch (spidx0->dst.sa.sa_family) {
4276 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4277 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4279 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4280 &spidx1->dst.sin.sin_addr, spidx0->prefd))
4284 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4285 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4288 * scope_id check. if sin6_scope_id is 0, we regard it
4289 * as a wildcard scope, which matches any scope zone ID.
4291 if (spidx0->dst.sin6.sin6_scope_id &&
4292 spidx1->dst.sin6.sin6_scope_id &&
4293 spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4295 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4296 &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4301 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4306 /* XXX Do we check other field ? e.g. flowinfo */
4314 #define satosin(s) ((const struct sockaddr_in *)s)
4318 #define satosin6(s) ((const struct sockaddr_in6 *)s)
4319 /* returns 0 on match */
4321 key_sockaddrcmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
4324 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4327 switch (sa1->sa_family) {
4330 if (sa1->sa_len != sizeof(struct sockaddr_in))
4332 if (satosin(sa1)->sin_addr.s_addr !=
4333 satosin(sa2)->sin_addr.s_addr) {
4336 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4342 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4343 return 1; /*EINVAL*/
4344 if (satosin6(sa1)->sin6_scope_id !=
4345 satosin6(sa2)->sin6_scope_id) {
4348 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4349 &satosin6(sa2)->sin6_addr)) {
4353 satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4359 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4367 /* returns 0 on match */
4369 key_sockaddrcmp_withmask(const struct sockaddr *sa1,
4370 const struct sockaddr *sa2, size_t mask)
4372 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4375 switch (sa1->sa_family) {
4378 return (!key_bbcmp(&satosin(sa1)->sin_addr,
4379 &satosin(sa2)->sin_addr, mask));
4383 if (satosin6(sa1)->sin6_scope_id !=
4384 satosin6(sa2)->sin6_scope_id)
4386 return (!key_bbcmp(&satosin6(sa1)->sin6_addr,
4387 &satosin6(sa2)->sin6_addr, mask));
4396 * compare two buffers with mask.
4400 * bits: Number of bits to compare
4406 key_bbcmp(const void *a1, const void *a2, u_int bits)
4408 const unsigned char *p1 = a1;
4409 const unsigned char *p2 = a2;
4411 /* XXX: This could be considerably faster if we compare a word
4412 * at a time, but it is complicated on LSB Endian machines */
4414 /* Handle null pointers */
4415 if (p1 == NULL || p2 == NULL)
4425 u_int8_t mask = ~((1<<(8-bits))-1);
4426 if ((*p1 & mask) != (*p2 & mask))
4429 return 1; /* Match! */
4433 key_flush_spd(time_t now)
4435 SPTREE_RLOCK_TRACKER;
4436 struct secpolicy_list drainq;
4437 struct secpolicy *sp, *nextsp;
4442 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4443 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
4444 if (sp->lifetime == 0 && sp->validtime == 0)
4446 if ((sp->lifetime &&
4447 now - sp->created > sp->lifetime) ||
4449 now - sp->lastused > sp->validtime)) {
4450 /* Hold extra reference to send SPDEXPIRE */
4452 LIST_INSERT_HEAD(&drainq, sp, drainq);
4457 if (LIST_EMPTY(&drainq))
4461 sp = LIST_FIRST(&drainq);
4462 while (sp != NULL) {
4463 nextsp = LIST_NEXT(sp, drainq);
4464 /* Check that SP is still linked */
4465 if (sp->state != IPSEC_SPSTATE_ALIVE) {
4466 LIST_REMOVE(sp, drainq);
4467 key_freesp(&sp); /* release extra reference */
4471 TAILQ_REMOVE(&V_sptree[sp->spidx.dir], sp, chain);
4473 LIST_REMOVE(sp, idhash);
4474 sp->state = IPSEC_SPSTATE_DEAD;
4479 if (SPDCACHE_ENABLED())
4482 sp = LIST_FIRST(&drainq);
4483 while (sp != NULL) {
4484 nextsp = LIST_NEXT(sp, drainq);
4486 key_freesp(&sp); /* release extra reference */
4487 key_freesp(&sp); /* release last reference */
4493 key_flush_sad(time_t now)
4495 SAHTREE_RLOCK_TRACKER;
4496 struct secashead_list emptyq;
4497 struct secasvar_list drainq, hexpireq, sexpireq, freeq;
4498 struct secashead *sah, *nextsah;
4499 struct secasvar *sav, *nextsav;
4502 LIST_INIT(&hexpireq);
4503 LIST_INIT(&sexpireq);
4507 TAILQ_FOREACH(sah, &V_sahtree, chain) {
4508 /* Check for empty SAH */
4509 if (TAILQ_EMPTY(&sah->savtree_larval) &&
4510 TAILQ_EMPTY(&sah->savtree_alive)) {
4512 LIST_INSERT_HEAD(&emptyq, sah, drainq);
4515 /* Add all stale LARVAL SAs into drainq */
4516 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
4517 if (now - sav->created < V_key_larval_lifetime)
4520 LIST_INSERT_HEAD(&drainq, sav, drainq);
4522 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
4523 /* lifetimes aren't specified */
4524 if (sav->lft_h == NULL)
4528 * Check again with lock held, because it may
4529 * be updated by SADB_UPDATE.
4531 if (sav->lft_h == NULL) {
4532 SECASVAR_UNLOCK(sav);
4537 * HARD lifetimes MUST take precedence over SOFT
4538 * lifetimes, meaning if the HARD and SOFT lifetimes
4539 * are the same, the HARD lifetime will appear on the
4542 /* check HARD lifetime */
4543 if ((sav->lft_h->addtime != 0 &&
4544 now - sav->created > sav->lft_h->addtime) ||
4545 (sav->lft_h->usetime != 0 && sav->firstused &&
4546 now - sav->firstused > sav->lft_h->usetime) ||
4547 (sav->lft_h->bytes != 0 && counter_u64_fetch(
4548 sav->lft_c_bytes) > sav->lft_h->bytes)) {
4549 SECASVAR_UNLOCK(sav);
4551 LIST_INSERT_HEAD(&hexpireq, sav, drainq);
4554 /* check SOFT lifetime (only for MATURE SAs) */
4555 if (sav->state == SADB_SASTATE_MATURE && (
4556 (sav->lft_s->addtime != 0 &&
4557 now - sav->created > sav->lft_s->addtime) ||
4558 (sav->lft_s->usetime != 0 && sav->firstused &&
4559 now - sav->firstused > sav->lft_s->usetime) ||
4560 (sav->lft_s->bytes != 0 && counter_u64_fetch(
4561 sav->lft_c_bytes) > sav->lft_s->bytes))) {
4562 SECASVAR_UNLOCK(sav);
4564 LIST_INSERT_HEAD(&sexpireq, sav, drainq);
4567 SECASVAR_UNLOCK(sav);
4572 if (LIST_EMPTY(&emptyq) && LIST_EMPTY(&drainq) &&
4573 LIST_EMPTY(&hexpireq) && LIST_EMPTY(&sexpireq))
4578 /* Unlink stale LARVAL SAs */
4579 sav = LIST_FIRST(&drainq);
4580 while (sav != NULL) {
4581 nextsav = LIST_NEXT(sav, drainq);
4582 /* Check that SA is still LARVAL */
4583 if (sav->state != SADB_SASTATE_LARVAL) {
4584 LIST_REMOVE(sav, drainq);
4585 LIST_INSERT_HEAD(&freeq, sav, drainq);
4589 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
4590 LIST_REMOVE(sav, spihash);
4591 sav->state = SADB_SASTATE_DEAD;
4594 /* Unlink all SAs with expired HARD lifetime */
4595 sav = LIST_FIRST(&hexpireq);
4596 while (sav != NULL) {
4597 nextsav = LIST_NEXT(sav, drainq);
4598 /* Check that SA is not unlinked */
4599 if (sav->state == SADB_SASTATE_DEAD) {
4600 LIST_REMOVE(sav, drainq);
4601 LIST_INSERT_HEAD(&freeq, sav, drainq);
4605 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
4606 LIST_REMOVE(sav, spihash);
4607 sav->state = SADB_SASTATE_DEAD;
4610 /* Mark all SAs with expired SOFT lifetime as DYING */
4611 sav = LIST_FIRST(&sexpireq);
4612 while (sav != NULL) {
4613 nextsav = LIST_NEXT(sav, drainq);
4614 /* Check that SA is not unlinked */
4615 if (sav->state == SADB_SASTATE_DEAD) {
4616 LIST_REMOVE(sav, drainq);
4617 LIST_INSERT_HEAD(&freeq, sav, drainq);
4622 * NOTE: this doesn't change SA order in the chain.
4624 sav->state = SADB_SASTATE_DYING;
4627 /* Unlink empty SAHs */
4628 sah = LIST_FIRST(&emptyq);
4629 while (sah != NULL) {
4630 nextsah = LIST_NEXT(sah, drainq);
4631 /* Check that SAH is still empty and not unlinked */
4632 if (sah->state == SADB_SASTATE_DEAD ||
4633 !TAILQ_EMPTY(&sah->savtree_larval) ||
4634 !TAILQ_EMPTY(&sah->savtree_alive)) {
4635 LIST_REMOVE(sah, drainq);
4636 key_freesah(&sah); /* release extra reference */
4640 TAILQ_REMOVE(&V_sahtree, sah, chain);
4641 LIST_REMOVE(sah, addrhash);
4642 sah->state = SADB_SASTATE_DEAD;
4647 /* Send SPDEXPIRE messages */
4648 sav = LIST_FIRST(&hexpireq);
4649 while (sav != NULL) {
4650 nextsav = LIST_NEXT(sav, drainq);
4652 key_freesah(&sav->sah); /* release reference from SAV */
4653 key_freesav(&sav); /* release extra reference */
4654 key_freesav(&sav); /* release last reference */
4657 sav = LIST_FIRST(&sexpireq);
4658 while (sav != NULL) {
4659 nextsav = LIST_NEXT(sav, drainq);
4661 key_freesav(&sav); /* release extra reference */
4664 /* Free stale LARVAL SAs */
4665 sav = LIST_FIRST(&drainq);
4666 while (sav != NULL) {
4667 nextsav = LIST_NEXT(sav, drainq);
4668 key_freesah(&sav->sah); /* release reference from SAV */
4669 key_freesav(&sav); /* release extra reference */
4670 key_freesav(&sav); /* release last reference */
4673 /* Free SAs that were unlinked/changed by someone else */
4674 sav = LIST_FIRST(&freeq);
4675 while (sav != NULL) {
4676 nextsav = LIST_NEXT(sav, drainq);
4677 key_freesav(&sav); /* release extra reference */
4680 /* Free empty SAH */
4681 sah = LIST_FIRST(&emptyq);
4682 while (sah != NULL) {
4683 nextsah = LIST_NEXT(sah, drainq);
4684 key_freesah(&sah); /* release extra reference */
4685 key_freesah(&sah); /* release last reference */
4691 key_flush_acq(time_t now)
4693 struct secacq *acq, *nextacq;
4697 acq = LIST_FIRST(&V_acqtree);
4698 while (acq != NULL) {
4699 nextacq = LIST_NEXT(acq, chain);
4700 if (now - acq->created > V_key_blockacq_lifetime) {
4701 LIST_REMOVE(acq, chain);
4702 LIST_REMOVE(acq, addrhash);
4703 LIST_REMOVE(acq, seqhash);
4704 free(acq, M_IPSEC_SAQ);
4712 key_flush_spacq(time_t now)
4714 struct secspacq *acq, *nextacq;
4718 for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4719 nextacq = LIST_NEXT(acq, chain);
4720 if (now - acq->created > V_key_blockacq_lifetime
4721 && __LIST_CHAINED(acq)) {
4722 LIST_REMOVE(acq, chain);
4723 free(acq, M_IPSEC_SAQ);
4731 * scanning SPD and SAD to check status for each entries,
4732 * and do to remove or to expire.
4733 * XXX: year 2038 problem may remain.
4736 key_timehandler(void *arg)
4738 VNET_ITERATOR_DECL(vnet_iter);
4739 time_t now = time_second;
4741 VNET_LIST_RLOCK_NOSLEEP();
4742 VNET_FOREACH(vnet_iter) {
4743 CURVNET_SET(vnet_iter);
4747 key_flush_spacq(now);
4750 VNET_LIST_RUNLOCK_NOSLEEP();
4752 #ifndef IPSEC_DEBUG2
4753 /* do exchange to tick time !! */
4754 callout_schedule(&key_timer, hz);
4755 #endif /* IPSEC_DEBUG2 */
4763 key_randomfill(&value, sizeof(value));
4768 key_randomfill(void *p, size_t l)
4772 static int warn = 1;
4775 n = (size_t)read_random(p, (u_int)l);
4779 bcopy(&v, (u_int8_t *)p + n,
4780 l - n < sizeof(v) ? l - n : sizeof(v));
4784 printf("WARNING: pseudo-random number generator "
4785 "used for IPsec processing\n");
4792 * map SADB_SATYPE_* to IPPROTO_*.
4793 * if satype == SADB_SATYPE then satype is mapped to ~0.
4795 * 0: invalid satype.
4798 key_satype2proto(uint8_t satype)
4801 case SADB_SATYPE_UNSPEC:
4802 return IPSEC_PROTO_ANY;
4803 case SADB_SATYPE_AH:
4805 case SADB_SATYPE_ESP:
4807 case SADB_X_SATYPE_IPCOMP:
4808 return IPPROTO_IPCOMP;
4809 case SADB_X_SATYPE_TCPSIGNATURE:
4818 * map IPPROTO_* to SADB_SATYPE_*
4820 * 0: invalid protocol type.
4823 key_proto2satype(uint8_t proto)
4827 return SADB_SATYPE_AH;
4829 return SADB_SATYPE_ESP;
4830 case IPPROTO_IPCOMP:
4831 return SADB_X_SATYPE_IPCOMP;
4833 return SADB_X_SATYPE_TCPSIGNATURE;
4842 * SADB_GETSPI processing is to receive
4843 * <base, (SA2), src address, dst address, (SPI range)>
4844 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4845 * tree with the status of LARVAL, and send
4846 * <base, SA(*), address(SD)>
4849 * IN: mhp: pointer to the pointer to each header.
4850 * OUT: NULL if fail.
4851 * other if success, return pointer to the message to send.
4854 key_getspi(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4856 struct secasindex saidx;
4857 struct sadb_address *src0, *dst0;
4858 struct secasvar *sav;
4859 uint32_t reqid, spi;
4861 uint8_t mode, proto;
4863 IPSEC_ASSERT(so != NULL, ("null socket"));
4864 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4865 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4866 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4868 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
4869 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST)
4870 #ifdef PFKEY_STRICT_CHECKS
4871 || SADB_CHECKHDR(mhp, SADB_EXT_SPIRANGE)
4874 ipseclog((LOG_DEBUG,
4875 "%s: invalid message: missing required header.\n",
4880 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
4881 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)
4882 #ifdef PFKEY_STRICT_CHECKS
4883 || SADB_CHECKLEN(mhp, SADB_EXT_SPIRANGE)
4886 ipseclog((LOG_DEBUG,
4887 "%s: invalid message: wrong header size.\n", __func__));
4891 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
4892 mode = IPSEC_MODE_ANY;
4895 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
4896 ipseclog((LOG_DEBUG,
4897 "%s: invalid message: wrong header size.\n",
4902 mode = ((struct sadb_x_sa2 *)
4903 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4904 reqid = ((struct sadb_x_sa2 *)
4905 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4908 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4909 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4911 /* map satype to proto */
4912 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4913 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4918 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
4919 (struct sockaddr *)(dst0 + 1));
4921 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
4925 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4927 /* SPI allocation */
4928 spi = key_do_getnewspi(
4929 (struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE], &saidx);
4932 * Requested SPI or SPI range is not available or
4938 sav = key_newsav(mhp, &saidx, spi, &error);
4942 if (sav->seq != 0) {
4945 * If the SADB_GETSPI message is in response to a
4946 * kernel-generated SADB_ACQUIRE, the sadb_msg_seq
4947 * MUST be the same as the SADB_ACQUIRE message.
4949 * XXXAE: However it doesn't definethe behaviour how to
4950 * check this and what to do if it doesn't match.
4951 * Also what we should do if it matches?
4953 * We can compare saidx used in SADB_ACQUIRE with saidx
4954 * used in SADB_GETSPI, but this probably can break
4955 * existing software. For now just warn if it doesn't match.
4957 * XXXAE: anyway it looks useless.
4959 key_acqdone(&saidx, sav->seq);
4962 printf("%s: SA(%p)\n", __func__, sav));
4963 KEYDBG(KEY_DATA, kdebug_secasv(sav));
4966 struct mbuf *n, *nn;
4967 struct sadb_sa *m_sa;
4968 struct sadb_msg *newmsg;
4971 /* create new sadb_msg to reply. */
4972 len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4973 PFKEY_ALIGN8(sizeof(struct sadb_sa));
4975 MGETHDR(n, M_NOWAIT, MT_DATA);
4977 if (!(MCLGET(n, M_NOWAIT))) {
4991 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4992 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4994 m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4995 m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4996 m_sa->sadb_sa_exttype = SADB_EXT_SA;
4997 m_sa->sadb_sa_spi = spi; /* SPI is already in network byte order */
4998 off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
5000 IPSEC_ASSERT(off == len,
5001 ("length inconsistency (off %u len %u)", off, len));
5003 n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
5004 SADB_EXT_ADDRESS_DST);
5011 if (n->m_len < sizeof(struct sadb_msg)) {
5012 n = m_pullup(n, sizeof(struct sadb_msg));
5014 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
5017 n->m_pkthdr.len = 0;
5018 for (nn = n; nn; nn = nn->m_next)
5019 n->m_pkthdr.len += nn->m_len;
5021 newmsg = mtod(n, struct sadb_msg *);
5022 newmsg->sadb_msg_seq = sav->seq;
5023 newmsg->sadb_msg_errno = 0;
5024 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5027 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5031 return (key_senderror(so, m, error));
5035 * allocating new SPI
5036 * called by key_getspi().
5039 * others: success, SPI in network byte order.
5042 key_do_getnewspi(struct sadb_spirange *spirange, struct secasindex *saidx)
5044 uint32_t min, max, newspi, t;
5045 int count = V_key_spi_trycnt;
5047 /* set spi range to allocate */
5048 if (spirange != NULL) {
5049 min = spirange->sadb_spirange_min;
5050 max = spirange->sadb_spirange_max;
5052 min = V_key_spi_minval;
5053 max = V_key_spi_maxval;
5055 /* IPCOMP needs 2-byte SPI */
5056 if (saidx->proto == IPPROTO_IPCOMP) {
5062 t = min; min = max; max = t;
5067 if (!key_checkspidup(htonl(min))) {
5068 ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
5073 count--; /* taking one cost. */
5080 /* when requesting to allocate spi ranged */
5082 /* generate pseudo-random SPI value ranged. */
5083 newspi = min + (key_random() % (max - min + 1));
5084 if (!key_checkspidup(htonl(newspi)))
5088 if (count == 0 || newspi == 0) {
5089 ipseclog((LOG_DEBUG,
5090 "%s: failed to allocate SPI.\n", __func__));
5096 keystat.getspi_count =
5097 (keystat.getspi_count + V_key_spi_trycnt - count) / 2;
5099 return (htonl(newspi));
5103 * Find TCP-MD5 SA with corresponding secasindex.
5104 * If not found, return NULL and fill SPI with usable value if needed.
5106 static struct secasvar *
5107 key_getsav_tcpmd5(struct secasindex *saidx, uint32_t *spi)
5109 SAHTREE_RLOCK_TRACKER;
5110 struct secashead *sah;
5111 struct secasvar *sav;
5113 IPSEC_ASSERT(saidx->proto == IPPROTO_TCP, ("wrong proto"));
5115 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
5116 if (sah->saidx.proto != IPPROTO_TCP)
5118 if (!key_sockaddrcmp(&saidx->dst.sa, &sah->saidx.dst.sa, 0) &&
5119 !key_sockaddrcmp(&saidx->src.sa, &sah->saidx.src.sa, 0))
5123 if (V_key_preferred_oldsa)
5124 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
5126 sav = TAILQ_FIRST(&sah->savtree_alive);
5134 /* No SPI required */
5138 /* Check that SPI is unique */
5139 LIST_FOREACH(sav, SAVHASH_HASH(*spi), spihash) {
5140 if (sav->spi == *spi)
5145 /* SPI is already unique */
5149 /* XXX: not optimal */
5150 *spi = key_do_getnewspi(NULL, saidx);
5155 key_updateaddresses(struct socket *so, struct mbuf *m,
5156 const struct sadb_msghdr *mhp, struct secasvar *sav,
5157 struct secasindex *saidx)
5159 struct sockaddr *newaddr;
5160 struct secashead *sah;
5161 struct secasvar *newsav, *tmp;
5165 /* Check that we need to change SAH */
5166 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC)) {
5167 newaddr = (struct sockaddr *)(
5168 ((struct sadb_address *)
5169 mhp->ext[SADB_X_EXT_NEW_ADDRESS_SRC]) + 1);
5170 bcopy(newaddr, &saidx->src, newaddr->sa_len);
5171 key_porttosaddr(&saidx->src.sa, 0);
5173 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST)) {
5174 newaddr = (struct sockaddr *)(
5175 ((struct sadb_address *)
5176 mhp->ext[SADB_X_EXT_NEW_ADDRESS_DST]) + 1);
5177 bcopy(newaddr, &saidx->dst, newaddr->sa_len);
5178 key_porttosaddr(&saidx->dst.sa, 0);
5180 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC) ||
5181 !SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST)) {
5182 error = key_checksockaddrs(&saidx->src.sa, &saidx->dst.sa);
5184 ipseclog((LOG_DEBUG, "%s: invalid new sockaddr.\n",
5189 sah = key_getsah(saidx);
5191 /* create a new SA index */
5192 sah = key_newsah(saidx);
5194 ipseclog((LOG_DEBUG,
5195 "%s: No more memory.\n", __func__));
5198 isnew = 2; /* SAH is new */
5200 isnew = 1; /* existing SAH is referenced */
5203 * src and dst addresses are still the same.
5204 * Do we want to change NAT-T config?
5206 if (sav->sah->saidx.proto != IPPROTO_ESP ||
5207 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5208 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_SPORT) ||
5209 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5210 ipseclog((LOG_DEBUG,
5211 "%s: invalid message: missing required header.\n",
5215 /* We hold reference to SA, thus SAH will be referenced too. */
5220 newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA,
5222 if (newsav == NULL) {
5223 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5228 /* Clone SA's content into newsav */
5229 SAV_INITREF(newsav);
5230 bcopy(sav, newsav, offsetof(struct secasvar, chain));
5232 * We create new NAT-T config if it is needed.
5233 * Old NAT-T config will be freed by key_cleansav() when
5234 * last reference to SA will be released.
5236 newsav->natt = NULL;
5238 newsav->state = SADB_SASTATE_MATURE;
5239 error = key_setnatt(newsav, mhp);
5244 /* Check that SA is still alive */
5245 if (sav->state == SADB_SASTATE_DEAD) {
5246 /* SA was unlinked */
5252 /* Unlink SA from SAH and SPI hash */
5253 IPSEC_ASSERT((sav->flags & SADB_X_EXT_F_CLONED) == 0,
5254 ("SA is already cloned"));
5255 IPSEC_ASSERT(sav->state == SADB_SASTATE_MATURE ||
5256 sav->state == SADB_SASTATE_DYING,
5257 ("Wrong SA state %u\n", sav->state));
5258 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
5259 LIST_REMOVE(sav, spihash);
5260 sav->state = SADB_SASTATE_DEAD;
5263 * Link new SA with SAH. Keep SAs ordered by
5264 * create time (newer are first).
5266 TAILQ_FOREACH(tmp, &sah->savtree_alive, chain) {
5267 if (newsav->created > tmp->created) {
5268 TAILQ_INSERT_BEFORE(tmp, newsav, chain);
5273 TAILQ_INSERT_TAIL(&sah->savtree_alive, newsav, chain);
5275 /* Add new SA into SPI hash. */
5276 LIST_INSERT_HEAD(SAVHASH_HASH(newsav->spi), newsav, spihash);
5278 /* Add new SAH into SADB. */
5280 TAILQ_INSERT_HEAD(&V_sahtree, sah, chain);
5281 LIST_INSERT_HEAD(SAHADDRHASH_HASH(saidx), sah, addrhash);
5282 sah->state = SADB_SASTATE_MATURE;
5283 SAH_ADDREF(sah); /* newsav references new SAH */
5286 * isnew == 1 -> @sah was referenced by key_getsah().
5287 * isnew == 0 -> we use the same @sah, that was used by @sav,
5288 * and we use its reference for @newsav.
5291 /* XXX: replace cntr with pointer? */
5292 newsav->cntr = sav->cntr;
5293 sav->flags |= SADB_X_EXT_F_CLONED;
5294 SECASVAR_UNLOCK(sav);
5299 printf("%s: SA(%p) cloned into SA(%p)\n",
5300 __func__, sav, newsav));
5301 KEYDBG(KEY_DATA, kdebug_secasv(newsav));
5303 key_freesav(&sav); /* release last reference */
5305 /* set msg buf from mhp */
5306 n = key_getmsgbuf_x1(m, mhp);
5308 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5312 key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5317 if (newsav != NULL) {
5318 if (newsav->natt != NULL)
5319 free(newsav->natt, M_IPSEC_MISC);
5320 free(newsav, M_IPSEC_SA);
5326 * SADB_UPDATE processing
5328 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5329 * key(AE), (identity(SD),) (sensitivity)>
5330 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
5332 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5333 * (identity(SD),) (sensitivity)>
5336 * m will always be freed.
5339 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5341 struct secasindex saidx;
5342 struct sadb_address *src0, *dst0;
5343 struct sadb_sa *sa0;
5344 struct secasvar *sav;
5347 uint8_t mode, proto;
5349 IPSEC_ASSERT(so != NULL, ("null socket"));
5350 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5351 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5352 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5354 /* map satype to proto */
5355 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5356 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5358 return key_senderror(so, m, EINVAL);
5361 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
5362 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5363 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5364 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
5365 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
5366 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
5367 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
5368 ipseclog((LOG_DEBUG,
5369 "%s: invalid message: missing required header.\n",
5371 return key_senderror(so, m, EINVAL);
5373 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
5374 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5375 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5376 ipseclog((LOG_DEBUG,
5377 "%s: invalid message: wrong header size.\n", __func__));
5378 return key_senderror(so, m, EINVAL);
5380 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
5381 mode = IPSEC_MODE_ANY;
5384 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
5385 ipseclog((LOG_DEBUG,
5386 "%s: invalid message: wrong header size.\n",
5388 return key_senderror(so, m, EINVAL);
5390 mode = ((struct sadb_x_sa2 *)
5391 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5392 reqid = ((struct sadb_x_sa2 *)
5393 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5396 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5397 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5398 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5401 * Only SADB_SASTATE_MATURE SAs may be submitted in an
5402 * SADB_UPDATE message.
5404 if (sa0->sadb_sa_state != SADB_SASTATE_MATURE) {
5405 ipseclog((LOG_DEBUG, "%s: invalid state.\n", __func__));
5406 #ifdef PFKEY_STRICT_CHECKS
5407 return key_senderror(so, m, EINVAL);
5410 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
5411 (struct sockaddr *)(dst0 + 1));
5413 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5414 return key_senderror(so, m, error);
5416 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5417 sav = key_getsavbyspi(sa0->sadb_sa_spi);
5419 ipseclog((LOG_DEBUG, "%s: no SA found for SPI %u\n",
5420 __func__, ntohl(sa0->sadb_sa_spi)));
5421 return key_senderror(so, m, EINVAL);
5424 * Check that SADB_UPDATE issued by the same process that did
5425 * SADB_GETSPI or SADB_ADD.
5427 if (sav->pid != mhp->msg->sadb_msg_pid) {
5428 ipseclog((LOG_DEBUG,
5429 "%s: pid mismatched (SPI %u, pid %u vs. %u)\n", __func__,
5430 ntohl(sav->spi), sav->pid, mhp->msg->sadb_msg_pid));
5432 return key_senderror(so, m, EINVAL);
5434 /* saidx should match with SA. */
5435 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_MODE_REQID) == 0) {
5436 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u\n",
5437 __func__, ntohl(sav->spi)));
5439 return key_senderror(so, m, ESRCH);
5442 if (sav->state == SADB_SASTATE_LARVAL) {
5443 if ((mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5444 SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT)) ||
5445 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5446 SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH))) {
5447 ipseclog((LOG_DEBUG,
5448 "%s: invalid message: missing required header.\n",
5451 return key_senderror(so, m, EINVAL);
5454 * We can set any values except src, dst and SPI.
5456 error = key_setsaval(sav, mhp);
5459 return (key_senderror(so, m, error));
5461 /* Change SA state to MATURE */
5463 if (sav->state != SADB_SASTATE_LARVAL) {
5464 /* SA was deleted or another thread made it MATURE. */
5467 return (key_senderror(so, m, ESRCH));
5470 * NOTE: we keep SAs in savtree_alive ordered by created
5471 * time. When SA's state changed from LARVAL to MATURE,
5472 * we update its created time in key_setsaval() and move
5473 * it into head of savtree_alive.
5475 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
5476 TAILQ_INSERT_HEAD(&sav->sah->savtree_alive, sav, chain);
5477 sav->state = SADB_SASTATE_MATURE;
5481 * For DYING and MATURE SA we can change only state
5482 * and lifetimes. Report EINVAL if something else attempted
5485 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT) ||
5486 !SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH)) {
5488 return (key_senderror(so, m, EINVAL));
5490 error = key_updatelifetimes(sav, mhp);
5493 return (key_senderror(so, m, error));
5496 * This is FreeBSD extension to RFC2367.
5497 * IKEd can specify SADB_X_EXT_NEW_ADDRESS_SRC and/or
5498 * SADB_X_EXT_NEW_ADDRESS_DST when it wants to change
5499 * SA addresses (for example to implement MOBIKE protocol
5500 * as described in RFC4555). Also we allow to change
5503 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC) ||
5504 !SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST) ||
5505 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5506 sav->natt != NULL) {
5507 error = key_updateaddresses(so, m, mhp, sav, &saidx);
5510 return (key_senderror(so, m, error));
5513 /* Check that SA is still alive */
5515 if (sav->state == SADB_SASTATE_DEAD) {
5516 /* SA was unlinked */
5519 return (key_senderror(so, m, ESRCH));
5522 * NOTE: there is possible state moving from DYING to MATURE,
5523 * but this doesn't change created time, so we won't reorder
5526 sav->state = SADB_SASTATE_MATURE;
5530 printf("%s: SA(%p)\n", __func__, sav));
5531 KEYDBG(KEY_DATA, kdebug_secasv(sav));
5537 /* set msg buf from mhp */
5538 n = key_getmsgbuf_x1(m, mhp);
5540 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5541 return key_senderror(so, m, ENOBUFS);
5545 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5550 * SADB_ADD processing
5551 * add an entry to SA database, when received
5552 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5553 * key(AE), (identity(SD),) (sensitivity)>
5556 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5557 * (identity(SD),) (sensitivity)>
5560 * IGNORE identity and sensitivity messages.
5562 * m will always be freed.
5565 key_add(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5567 struct secasindex saidx;
5568 struct sadb_address *src0, *dst0;
5569 struct sadb_sa *sa0;
5570 struct secasvar *sav;
5571 uint32_t reqid, spi;
5572 uint8_t mode, proto;
5575 IPSEC_ASSERT(so != NULL, ("null socket"));
5576 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5577 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5578 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5580 /* map satype to proto */
5581 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5582 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5584 return key_senderror(so, m, EINVAL);
5587 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
5588 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5589 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5590 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP && (
5591 SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT) ||
5592 SADB_CHECKLEN(mhp, SADB_EXT_KEY_ENCRYPT))) ||
5593 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH && (
5594 SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH) ||
5595 SADB_CHECKLEN(mhp, SADB_EXT_KEY_AUTH))) ||
5596 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
5597 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
5598 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
5599 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
5600 ipseclog((LOG_DEBUG,
5601 "%s: invalid message: missing required header.\n",
5603 return key_senderror(so, m, EINVAL);
5605 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
5606 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5607 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5608 ipseclog((LOG_DEBUG,
5609 "%s: invalid message: wrong header size.\n", __func__));
5610 return key_senderror(so, m, EINVAL);
5612 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
5613 mode = IPSEC_MODE_ANY;
5616 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
5617 ipseclog((LOG_DEBUG,
5618 "%s: invalid message: wrong header size.\n",
5620 return key_senderror(so, m, EINVAL);
5622 mode = ((struct sadb_x_sa2 *)
5623 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5624 reqid = ((struct sadb_x_sa2 *)
5625 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5628 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5629 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5630 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5633 * Only SADB_SASTATE_MATURE SAs may be submitted in an
5636 if (sa0->sadb_sa_state != SADB_SASTATE_MATURE) {
5637 ipseclog((LOG_DEBUG, "%s: invalid state.\n", __func__));
5638 #ifdef PFKEY_STRICT_CHECKS
5639 return key_senderror(so, m, EINVAL);
5642 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
5643 (struct sockaddr *)(dst0 + 1));
5645 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5646 return key_senderror(so, m, error);
5648 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5649 spi = sa0->sadb_sa_spi;
5651 * For TCP-MD5 SAs we don't use SPI. Check the uniqueness using
5653 * XXXAE: IPComp seems also doesn't use SPI.
5655 if (proto == IPPROTO_TCP) {
5656 sav = key_getsav_tcpmd5(&saidx, &spi);
5657 if (sav == NULL && spi == 0) {
5658 /* Failed to allocate SPI */
5659 ipseclog((LOG_DEBUG, "%s: SA already exists.\n",
5661 return key_senderror(so, m, EEXIST);
5663 /* XXX: SPI that we report back can have another value */
5665 /* We can create new SA only if SPI is different. */
5666 sav = key_getsavbyspi(spi);
5670 ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5671 return key_senderror(so, m, EEXIST);
5674 sav = key_newsav(mhp, &saidx, spi, &error);
5676 return key_senderror(so, m, error);
5678 printf("%s: return SA(%p)\n", __func__, sav));
5679 KEYDBG(KEY_DATA, kdebug_secasv(sav));
5681 * If SADB_ADD was in response to SADB_ACQUIRE, we need to schedule
5685 key_acqdone(&saidx, sav->seq);
5689 * Don't call key_freesav() on error here, as we would like to
5690 * keep the SA in the database.
5694 /* set msg buf from mhp */
5695 n = key_getmsgbuf_x1(m, mhp);
5697 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5698 return key_senderror(so, m, ENOBUFS);
5702 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5708 * IKEd may request the use ESP in UDP encapsulation when it detects the
5709 * presence of NAT. It uses NAT-T extension headers for such SAs to specify
5710 * parameters needed for encapsulation and decapsulation. These PF_KEY
5711 * extension headers are not standardized, so this comment addresses our
5713 * SADB_X_EXT_NAT_T_TYPE specifies type of encapsulation, we support only
5714 * UDP_ENCAP_ESPINUDP as described in RFC3948.
5715 * SADB_X_EXT_NAT_T_SPORT/DPORT specifies source and destination ports for
5716 * UDP header. We use these ports in UDP encapsulation procedure, also we
5717 * can check them in UDP decapsulation procedure.
5718 * SADB_X_EXT_NAT_T_OA[IR] specifies original address of initiator or
5719 * responder. These addresses can be used for transport mode to adjust
5720 * checksum after decapsulation and decryption. Since original IP addresses
5721 * used by peer usually different (we detected presence of NAT), TCP/UDP
5722 * pseudo header checksum and IP header checksum was calculated using original
5723 * addresses. After decapsulation and decryption we need to adjust checksum
5724 * to have correct datagram.
5726 * We expect presence of NAT-T extension headers only in SADB_ADD and
5727 * SADB_UPDATE messages. We report NAT-T extension headers in replies
5728 * to SADB_ADD, SADB_UPDATE, SADB_GET, and SADB_DUMP messages.
5731 key_setnatt(struct secasvar *sav, const struct sadb_msghdr *mhp)
5733 struct sadb_x_nat_t_port *port;
5734 struct sadb_x_nat_t_type *type;
5735 struct sadb_address *oai, *oar;
5736 struct sockaddr *sa;
5740 IPSEC_ASSERT(sav->natt == NULL, ("natt is already initialized"));
5742 * Ignore NAT-T headers if sproto isn't ESP.
5744 if (sav->sah->saidx.proto != IPPROTO_ESP)
5747 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) &&
5748 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_SPORT) &&
5749 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5750 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5751 SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_SPORT) ||
5752 SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5753 ipseclog((LOG_DEBUG,
5754 "%s: invalid message: wrong header size.\n",
5761 type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5762 if (type->sadb_x_nat_t_type_type != UDP_ENCAP_ESPINUDP) {
5763 ipseclog((LOG_DEBUG, "%s: unsupported NAT-T type %u.\n",
5764 __func__, type->sadb_x_nat_t_type_type));
5768 * Allocate storage for NAT-T config.
5769 * On error it will be released by key_cleansav().
5771 sav->natt = malloc(sizeof(struct secnatt), M_IPSEC_MISC,
5773 if (sav->natt == NULL) {
5774 PFKEYSTAT_INC(in_nomem);
5775 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5778 port = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5779 if (port->sadb_x_nat_t_port_port == 0) {
5780 ipseclog((LOG_DEBUG, "%s: invalid NAT-T sport specified.\n",
5784 sav->natt->sport = port->sadb_x_nat_t_port_port;
5785 port = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5786 if (port->sadb_x_nat_t_port_port == 0) {
5787 ipseclog((LOG_DEBUG, "%s: invalid NAT-T dport specified.\n",
5791 sav->natt->dport = port->sadb_x_nat_t_port_port;
5794 * SADB_X_EXT_NAT_T_OAI and SADB_X_EXT_NAT_T_OAR are optional
5795 * and needed only for transport mode IPsec.
5796 * Usually NAT translates only one address, but it is possible,
5797 * that both addresses could be translated.
5798 * NOTE: Value of SADB_X_EXT_NAT_T_OAI is equal to SADB_X_EXT_NAT_T_OA.
5800 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_OAI)) {
5801 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_OAI)) {
5802 ipseclog((LOG_DEBUG,
5803 "%s: invalid message: wrong header size.\n",
5807 oai = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5810 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_OAR)) {
5811 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_OAR)) {
5812 ipseclog((LOG_DEBUG,
5813 "%s: invalid message: wrong header size.\n",
5817 oar = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5821 /* Initialize addresses only for transport mode */
5822 if (sav->sah->saidx.mode != IPSEC_MODE_TUNNEL) {
5825 /* Currently we support only AF_INET */
5826 sa = (struct sockaddr *)(oai + 1);
5827 if (sa->sa_family != AF_INET ||
5828 sa->sa_len != sizeof(struct sockaddr_in)) {
5829 ipseclog((LOG_DEBUG,
5830 "%s: wrong NAT-OAi header.\n",
5834 /* Ignore address if it the same */
5835 if (((struct sockaddr_in *)sa)->sin_addr.s_addr !=
5836 sav->sah->saidx.src.sin.sin_addr.s_addr) {
5837 bcopy(sa, &sav->natt->oai.sa, sa->sa_len);
5838 sav->natt->flags |= IPSEC_NATT_F_OAI;
5839 /* Calculate checksum delta */
5840 addr = sav->sah->saidx.src.sin.sin_addr.s_addr;
5841 cksum = in_addword(cksum, ~addr >> 16);
5842 cksum = in_addword(cksum, ~addr & 0xffff);
5843 addr = sav->natt->oai.sin.sin_addr.s_addr;
5844 cksum = in_addword(cksum, addr >> 16);
5845 cksum = in_addword(cksum, addr & 0xffff);
5849 /* Currently we support only AF_INET */
5850 sa = (struct sockaddr *)(oar + 1);
5851 if (sa->sa_family != AF_INET ||
5852 sa->sa_len != sizeof(struct sockaddr_in)) {
5853 ipseclog((LOG_DEBUG,
5854 "%s: wrong NAT-OAr header.\n",
5858 /* Ignore address if it the same */
5859 if (((struct sockaddr_in *)sa)->sin_addr.s_addr !=
5860 sav->sah->saidx.dst.sin.sin_addr.s_addr) {
5861 bcopy(sa, &sav->natt->oar.sa, sa->sa_len);
5862 sav->natt->flags |= IPSEC_NATT_F_OAR;
5863 /* Calculate checksum delta */
5864 addr = sav->sah->saidx.dst.sin.sin_addr.s_addr;
5865 cksum = in_addword(cksum, ~addr >> 16);
5866 cksum = in_addword(cksum, ~addr & 0xffff);
5867 addr = sav->natt->oar.sin.sin_addr.s_addr;
5868 cksum = in_addword(cksum, addr >> 16);
5869 cksum = in_addword(cksum, addr & 0xffff);
5872 sav->natt->cksum = cksum;
5878 key_setident(struct secashead *sah, const struct sadb_msghdr *mhp)
5880 const struct sadb_ident *idsrc, *iddst;
5882 IPSEC_ASSERT(sah != NULL, ("null secashead"));
5883 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5884 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5886 /* don't make buffer if not there */
5887 if (SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_SRC) &&
5888 SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_DST)) {
5894 if (SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_SRC) ||
5895 SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_DST)) {
5896 ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5900 idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5901 iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5903 /* validity check */
5904 if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5905 ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5909 switch (idsrc->sadb_ident_type) {
5910 case SADB_IDENTTYPE_PREFIX:
5911 case SADB_IDENTTYPE_FQDN:
5912 case SADB_IDENTTYPE_USERFQDN:
5914 /* XXX do nothing */
5920 /* make structure */
5921 sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5922 if (sah->idents == NULL) {
5923 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5926 sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5927 if (sah->identd == NULL) {
5928 free(sah->idents, M_IPSEC_MISC);
5930 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5933 sah->idents->type = idsrc->sadb_ident_type;
5934 sah->idents->id = idsrc->sadb_ident_id;
5936 sah->identd->type = iddst->sadb_ident_type;
5937 sah->identd->id = iddst->sadb_ident_id;
5943 * m will not be freed on return.
5944 * it is caller's responsibility to free the result.
5946 * Called from SADB_ADD and SADB_UPDATE. Reply will contain headers
5947 * from the request in defined order.
5949 static struct mbuf *
5950 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
5954 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5955 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5956 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5958 /* create new sadb_msg to reply. */
5959 n = key_gather_mbuf(m, mhp, 1, 16, SADB_EXT_RESERVED,
5960 SADB_EXT_SA, SADB_X_EXT_SA2,
5961 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5962 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5963 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
5964 SADB_X_EXT_NAT_T_TYPE, SADB_X_EXT_NAT_T_SPORT,
5965 SADB_X_EXT_NAT_T_DPORT, SADB_X_EXT_NAT_T_OAI,
5966 SADB_X_EXT_NAT_T_OAR, SADB_X_EXT_NEW_ADDRESS_SRC,
5967 SADB_X_EXT_NEW_ADDRESS_DST);
5971 if (n->m_len < sizeof(struct sadb_msg)) {
5972 n = m_pullup(n, sizeof(struct sadb_msg));
5976 mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5977 mtod(n, struct sadb_msg *)->sadb_msg_len =
5978 PFKEY_UNIT64(n->m_pkthdr.len);
5984 * SADB_DELETE processing
5986 * <base, SA(*), address(SD)>
5987 * from the ikmpd, and set SADB_SASTATE_DEAD,
5989 * <base, SA(*), address(SD)>
5992 * m will always be freed.
5995 key_delete(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5997 struct secasindex saidx;
5998 struct sadb_address *src0, *dst0;
5999 struct secasvar *sav;
6000 struct sadb_sa *sa0;
6003 IPSEC_ASSERT(so != NULL, ("null socket"));
6004 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6005 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6006 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6008 /* map satype to proto */
6009 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6010 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6012 return key_senderror(so, m, EINVAL);
6015 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
6016 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
6017 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
6018 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
6019 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6021 return key_senderror(so, m, EINVAL);
6024 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
6025 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
6027 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
6028 (struct sockaddr *)(dst0 + 1)) != 0) {
6029 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
6030 return (key_senderror(so, m, EINVAL));
6032 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6033 if (SADB_CHECKHDR(mhp, SADB_EXT_SA)) {
6035 * Caller wants us to delete all non-LARVAL SAs
6036 * that match the src/dst. This is used during
6037 * IKE INITIAL-CONTACT.
6038 * XXXAE: this looks like some extension to RFC2367.
6040 ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
6041 return (key_delete_all(so, m, mhp, &saidx));
6043 if (SADB_CHECKLEN(mhp, SADB_EXT_SA)) {
6044 ipseclog((LOG_DEBUG,
6045 "%s: invalid message: wrong header size.\n", __func__));
6046 return (key_senderror(so, m, EINVAL));
6048 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
6049 if (proto == IPPROTO_TCP)
6050 sav = key_getsav_tcpmd5(&saidx, NULL);
6052 sav = key_getsavbyspi(sa0->sadb_sa_spi);
6054 ipseclog((LOG_DEBUG, "%s: no SA found for SPI %u.\n",
6055 __func__, ntohl(sa0->sadb_sa_spi)));
6056 return (key_senderror(so, m, ESRCH));
6058 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_HEAD) == 0) {
6059 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u.\n",
6060 __func__, ntohl(sav->spi)));
6062 return (key_senderror(so, m, ESRCH));
6065 printf("%s: SA(%p)\n", __func__, sav));
6066 KEYDBG(KEY_DATA, kdebug_secasv(sav));
6072 struct sadb_msg *newmsg;
6074 /* create new sadb_msg to reply. */
6075 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
6076 SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
6078 return key_senderror(so, m, ENOBUFS);
6080 if (n->m_len < sizeof(struct sadb_msg)) {
6081 n = m_pullup(n, sizeof(struct sadb_msg));
6083 return key_senderror(so, m, ENOBUFS);
6085 newmsg = mtod(n, struct sadb_msg *);
6086 newmsg->sadb_msg_errno = 0;
6087 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
6090 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
6095 * delete all SAs for src/dst. Called from key_delete().
6098 key_delete_all(struct socket *so, struct mbuf *m,
6099 const struct sadb_msghdr *mhp, struct secasindex *saidx)
6101 struct secasvar_queue drainq;
6102 struct secashead *sah;
6103 struct secasvar *sav, *nextsav;
6105 TAILQ_INIT(&drainq);
6107 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
6108 if (key_cmpsaidx(&sah->saidx, saidx, CMP_HEAD) == 0)
6110 /* Move all ALIVE SAs into drainq */
6111 TAILQ_CONCAT(&drainq, &sah->savtree_alive, chain);
6113 /* Unlink all queued SAs from SPI hash */
6114 TAILQ_FOREACH(sav, &drainq, chain) {
6115 sav->state = SADB_SASTATE_DEAD;
6116 LIST_REMOVE(sav, spihash);
6119 /* Now we can release reference for all SAs in drainq */
6120 sav = TAILQ_FIRST(&drainq);
6121 while (sav != NULL) {
6123 printf("%s: SA(%p)\n", __func__, sav));
6124 KEYDBG(KEY_DATA, kdebug_secasv(sav));
6125 nextsav = TAILQ_NEXT(sav, chain);
6126 key_freesah(&sav->sah); /* release reference from SAV */
6127 key_freesav(&sav); /* release last reference */
6133 struct sadb_msg *newmsg;
6135 /* create new sadb_msg to reply. */
6136 n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
6137 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
6139 return key_senderror(so, m, ENOBUFS);
6141 if (n->m_len < sizeof(struct sadb_msg)) {
6142 n = m_pullup(n, sizeof(struct sadb_msg));
6144 return key_senderror(so, m, ENOBUFS);
6146 newmsg = mtod(n, struct sadb_msg *);
6147 newmsg->sadb_msg_errno = 0;
6148 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
6151 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
6156 * Delete all alive SAs for corresponding xform.
6157 * Larval SAs have not initialized tdb_xform, so it is safe to leave them
6158 * here when xform disappears.
6161 key_delete_xform(const struct xformsw *xsp)
6163 struct secasvar_queue drainq;
6164 struct secashead *sah;
6165 struct secasvar *sav, *nextsav;
6167 TAILQ_INIT(&drainq);
6169 TAILQ_FOREACH(sah, &V_sahtree, chain) {
6170 sav = TAILQ_FIRST(&sah->savtree_alive);
6173 if (sav->tdb_xform != xsp)
6176 * It is supposed that all SAs in the chain are related to
6179 TAILQ_CONCAT(&drainq, &sah->savtree_alive, chain);
6181 /* Unlink all queued SAs from SPI hash */
6182 TAILQ_FOREACH(sav, &drainq, chain) {
6183 sav->state = SADB_SASTATE_DEAD;
6184 LIST_REMOVE(sav, spihash);
6188 /* Now we can release reference for all SAs in drainq */
6189 sav = TAILQ_FIRST(&drainq);
6190 while (sav != NULL) {
6192 printf("%s: SA(%p)\n", __func__, sav));
6193 KEYDBG(KEY_DATA, kdebug_secasv(sav));
6194 nextsav = TAILQ_NEXT(sav, chain);
6195 key_freesah(&sav->sah); /* release reference from SAV */
6196 key_freesav(&sav); /* release last reference */
6202 * SADB_GET processing
6204 * <base, SA(*), address(SD)>
6205 * from the ikmpd, and get a SP and a SA to respond,
6207 * <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
6208 * (identity(SD),) (sensitivity)>
6211 * m will always be freed.
6214 key_get(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6216 struct secasindex saidx;
6217 struct sadb_address *src0, *dst0;
6218 struct sadb_sa *sa0;
6219 struct secasvar *sav;
6222 IPSEC_ASSERT(so != NULL, ("null socket"));
6223 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6224 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6225 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6227 /* map satype to proto */
6228 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6229 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6231 return key_senderror(so, m, EINVAL);
6234 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
6235 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
6236 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST)) {
6237 ipseclog((LOG_DEBUG,
6238 "%s: invalid message: missing required header.\n",
6240 return key_senderror(so, m, EINVAL);
6242 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
6243 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
6244 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
6245 ipseclog((LOG_DEBUG,
6246 "%s: invalid message: wrong header size.\n", __func__));
6247 return key_senderror(so, m, EINVAL);
6250 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
6251 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6252 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6254 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
6255 (struct sockaddr *)(dst0 + 1)) != 0) {
6256 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
6257 return key_senderror(so, m, EINVAL);
6259 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6261 if (proto == IPPROTO_TCP)
6262 sav = key_getsav_tcpmd5(&saidx, NULL);
6264 sav = key_getsavbyspi(sa0->sadb_sa_spi);
6266 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
6267 return key_senderror(so, m, ESRCH);
6269 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_HEAD) == 0) {
6270 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u.\n",
6271 __func__, ntohl(sa0->sadb_sa_spi)));
6273 return (key_senderror(so, m, ESRCH));
6280 /* map proto to satype */
6281 if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0) {
6282 ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
6285 return key_senderror(so, m, EINVAL);
6288 /* create new sadb_msg to reply. */
6289 n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
6290 mhp->msg->sadb_msg_pid);
6294 return key_senderror(so, m, ENOBUFS);
6297 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6301 /* XXX make it sysctl-configurable? */
6303 key_getcomb_setlifetime(struct sadb_comb *comb)
6306 comb->sadb_comb_soft_allocations = 1;
6307 comb->sadb_comb_hard_allocations = 1;
6308 comb->sadb_comb_soft_bytes = 0;
6309 comb->sadb_comb_hard_bytes = 0;
6310 comb->sadb_comb_hard_addtime = 86400; /* 1 day */
6311 comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
6312 comb->sadb_comb_soft_usetime = 28800; /* 8 hours */
6313 comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
6317 * XXX reorder combinations by preference
6318 * XXX no idea if the user wants ESP authentication or not
6320 static struct mbuf *
6321 key_getcomb_ealg(void)
6323 struct sadb_comb *comb;
6324 const struct enc_xform *algo;
6325 struct mbuf *result = NULL, *m, *n;
6329 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6332 for (i = 1; i <= SADB_EALG_MAX; i++) {
6333 algo = enc_algorithm_lookup(i);
6337 /* discard algorithms with key size smaller than system min */
6338 if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6340 if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6341 encmin = V_ipsec_esp_keymin;
6343 encmin = _BITS(algo->minkey);
6345 if (V_ipsec_esp_auth)
6346 m = key_getcomb_ah();
6348 IPSEC_ASSERT(l <= MLEN,
6349 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6350 MGET(m, M_NOWAIT, MT_DATA);
6355 bzero(mtod(m, caddr_t), m->m_len);
6362 for (n = m; n; n = n->m_next)
6364 IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6366 for (off = 0; off < totlen; off += l) {
6367 n = m_pulldown(m, off, l, &o);
6369 /* m is already freed */
6372 comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6373 bzero(comb, sizeof(*comb));
6374 key_getcomb_setlifetime(comb);
6375 comb->sadb_comb_encrypt = i;
6376 comb->sadb_comb_encrypt_minbits = encmin;
6377 comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6395 key_getsizes_ah(const struct auth_hash *ah, int alg, u_int16_t* min,
6399 *min = *max = ah->hashsize;
6400 if (ah->keysize == 0) {
6402 * Transform takes arbitrary key size but algorithm
6403 * key size is restricted. Enforce this here.
6406 case SADB_X_AALG_MD5: *min = *max = 16; break;
6407 case SADB_X_AALG_SHA: *min = *max = 20; break;
6408 case SADB_X_AALG_NULL: *min = 1; *max = 256; break;
6409 case SADB_X_AALG_SHA2_256: *min = *max = 32; break;
6410 case SADB_X_AALG_SHA2_384: *min = *max = 48; break;
6411 case SADB_X_AALG_SHA2_512: *min = *max = 64; break;
6413 DPRINTF(("%s: unknown AH algorithm %u\n",
6421 * XXX reorder combinations by preference
6423 static struct mbuf *
6426 const struct auth_hash *algo;
6427 struct sadb_comb *comb;
6429 u_int16_t minkeysize, maxkeysize;
6431 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6434 for (i = 1; i <= SADB_AALG_MAX; i++) {
6436 /* we prefer HMAC algorithms, not old algorithms */
6437 if (i != SADB_AALG_SHA1HMAC &&
6438 i != SADB_AALG_MD5HMAC &&
6439 i != SADB_X_AALG_SHA2_256 &&
6440 i != SADB_X_AALG_SHA2_384 &&
6441 i != SADB_X_AALG_SHA2_512)
6444 algo = auth_algorithm_lookup(i);
6447 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6448 /* discard algorithms with key size smaller than system min */
6449 if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6453 IPSEC_ASSERT(l <= MLEN,
6454 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6455 MGET(m, M_NOWAIT, MT_DATA);
6462 M_PREPEND(m, l, M_NOWAIT);
6466 comb = mtod(m, struct sadb_comb *);
6467 bzero(comb, sizeof(*comb));
6468 key_getcomb_setlifetime(comb);
6469 comb->sadb_comb_auth = i;
6470 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6471 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6478 * not really an official behavior. discussed in pf_key@inner.net in Sep2000.
6479 * XXX reorder combinations by preference
6481 static struct mbuf *
6482 key_getcomb_ipcomp()
6484 const struct comp_algo *algo;
6485 struct sadb_comb *comb;
6488 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6491 for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6492 algo = comp_algorithm_lookup(i);
6497 IPSEC_ASSERT(l <= MLEN,
6498 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6499 MGET(m, M_NOWAIT, MT_DATA);
6506 M_PREPEND(m, l, M_NOWAIT);
6510 comb = mtod(m, struct sadb_comb *);
6511 bzero(comb, sizeof(*comb));
6512 key_getcomb_setlifetime(comb);
6513 comb->sadb_comb_encrypt = i;
6514 /* what should we set into sadb_comb_*_{min,max}bits? */
6521 * XXX no way to pass mode (transport/tunnel) to userland
6522 * XXX replay checking?
6523 * XXX sysctl interface to ipsec_{ah,esp}_keymin
6525 static struct mbuf *
6526 key_getprop(const struct secasindex *saidx)
6528 struct sadb_prop *prop;
6530 const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6533 switch (saidx->proto) {
6535 m = key_getcomb_ealg();
6538 m = key_getcomb_ah();
6540 case IPPROTO_IPCOMP:
6541 m = key_getcomb_ipcomp();
6549 M_PREPEND(m, l, M_NOWAIT);
6554 for (n = m; n; n = n->m_next)
6557 prop = mtod(m, struct sadb_prop *);
6558 bzero(prop, sizeof(*prop));
6559 prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6560 prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6561 prop->sadb_prop_replay = 32; /* XXX */
6567 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6569 * <base, SA, address(SD), (address(P)), x_policy,
6570 * (identity(SD),) (sensitivity,) proposal>
6571 * to KMD, and expect to receive
6572 * <base> with SADB_ACQUIRE if error occurred,
6574 * <base, src address, dst address, (SPI range)> with SADB_GETSPI
6575 * from KMD by PF_KEY.
6577 * XXX x_policy is outside of RFC2367 (KAME extension).
6578 * XXX sensitivity is not supported.
6579 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6580 * see comment for key_getcomb_ipcomp().
6584 * others: error number
6587 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6589 union sockaddr_union addr;
6590 struct mbuf *result, *m;
6594 uint8_t mask, satype;
6596 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6597 satype = key_proto2satype(saidx->proto);
6598 IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6602 ul_proto = IPSEC_ULPROTO_ANY;
6604 /* Get seq number to check whether sending message or not. */
6605 seq = key_getacq(saidx, &error);
6609 m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6617 * set sadb_address for saidx's.
6619 * Note that if sp is supplied, then we're being called from
6620 * key_allocsa_policy() and should supply port and protocol
6622 * XXXAE: why only TCP and UDP? ICMP and SCTP looks applicable too.
6623 * XXXAE: probably we can handle this in the ipsec[46]_allocsa().
6624 * XXXAE: it looks like we should save this info in the ACQ entry.
6626 if (sp != NULL && (sp->spidx.ul_proto == IPPROTO_TCP ||
6627 sp->spidx.ul_proto == IPPROTO_UDP))
6628 ul_proto = sp->spidx.ul_proto;
6632 if (ul_proto != IPSEC_ULPROTO_ANY) {
6633 switch (sp->spidx.src.sa.sa_family) {
6635 if (sp->spidx.src.sin.sin_port != IPSEC_PORT_ANY) {
6636 addr.sin.sin_port = sp->spidx.src.sin.sin_port;
6637 mask = sp->spidx.prefs;
6641 if (sp->spidx.src.sin6.sin6_port != IPSEC_PORT_ANY) {
6642 addr.sin6.sin6_port =
6643 sp->spidx.src.sin6.sin6_port;
6644 mask = sp->spidx.prefs;
6651 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &addr.sa, mask, ul_proto);
6660 if (ul_proto != IPSEC_ULPROTO_ANY) {
6661 switch (sp->spidx.dst.sa.sa_family) {
6663 if (sp->spidx.dst.sin.sin_port != IPSEC_PORT_ANY) {
6664 addr.sin.sin_port = sp->spidx.dst.sin.sin_port;
6665 mask = sp->spidx.prefd;
6669 if (sp->spidx.dst.sin6.sin6_port != IPSEC_PORT_ANY) {
6670 addr.sin6.sin6_port =
6671 sp->spidx.dst.sin6.sin6_port;
6672 mask = sp->spidx.prefd;
6679 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &addr.sa, mask, ul_proto);
6686 /* XXX proxy address (optional) */
6689 * Set sadb_x_policy. This is KAME extension to RFC2367.
6692 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id,
6702 * Set sadb_x_sa2 extension if saidx->reqid is not zero.
6703 * This is FreeBSD extension to RFC2367.
6705 if (saidx->reqid != 0) {
6706 m = key_setsadbxsa2(saidx->mode, 0, saidx->reqid);
6713 /* XXX identity (optional) */
6715 if (idexttype && fqdn) {
6716 /* create identity extension (FQDN) */
6717 struct sadb_ident *id;
6720 fqdnlen = strlen(fqdn) + 1; /* +1 for terminating-NUL */
6721 id = (struct sadb_ident *)p;
6722 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6723 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6724 id->sadb_ident_exttype = idexttype;
6725 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6726 bcopy(fqdn, id + 1, fqdnlen);
6727 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6731 /* create identity extension (USERFQDN) */
6732 struct sadb_ident *id;
6736 /* +1 for terminating-NUL */
6737 userfqdnlen = strlen(userfqdn) + 1;
6740 id = (struct sadb_ident *)p;
6741 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6742 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6743 id->sadb_ident_exttype = idexttype;
6744 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6745 /* XXX is it correct? */
6746 if (curproc && curproc->p_cred)
6747 id->sadb_ident_id = curproc->p_cred->p_ruid;
6748 if (userfqdn && userfqdnlen)
6749 bcopy(userfqdn, id + 1, userfqdnlen);
6750 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6754 /* XXX sensitivity (optional) */
6756 /* create proposal/combination extension */
6757 m = key_getprop(saidx);
6760 * spec conformant: always attach proposal/combination extension,
6761 * the problem is that we have no way to attach it for ipcomp,
6762 * due to the way sadb_comb is declared in RFC2367.
6771 * outside of spec; make proposal/combination extension optional.
6777 if ((result->m_flags & M_PKTHDR) == 0) {
6782 if (result->m_len < sizeof(struct sadb_msg)) {
6783 result = m_pullup(result, sizeof(struct sadb_msg));
6784 if (result == NULL) {
6790 result->m_pkthdr.len = 0;
6791 for (m = result; m; m = m->m_next)
6792 result->m_pkthdr.len += m->m_len;
6794 mtod(result, struct sadb_msg *)->sadb_msg_len =
6795 PFKEY_UNIT64(result->m_pkthdr.len);
6798 printf("%s: SP(%p)\n", __func__, sp));
6799 KEYDBG(KEY_DATA, kdebug_secasindex(saidx, NULL));
6801 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6810 key_newacq(const struct secasindex *saidx, int *perror)
6815 acq = malloc(sizeof(*acq), M_IPSEC_SAQ, M_NOWAIT | M_ZERO);
6817 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6823 bcopy(saidx, &acq->saidx, sizeof(acq->saidx));
6824 acq->created = time_second;
6827 /* add to acqtree */
6829 seq = acq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6830 LIST_INSERT_HEAD(&V_acqtree, acq, chain);
6831 LIST_INSERT_HEAD(ACQADDRHASH_HASH(saidx), acq, addrhash);
6832 LIST_INSERT_HEAD(ACQSEQHASH_HASH(seq), acq, seqhash);
6839 key_getacq(const struct secasindex *saidx, int *perror)
6845 LIST_FOREACH(acq, ACQADDRHASH_HASH(saidx), addrhash) {
6846 if (key_cmpsaidx(&acq->saidx, saidx, CMP_EXACTLY)) {
6847 if (acq->count > V_key_blockacq_count) {
6849 * Reset counter and send message.
6850 * Also reset created time to keep ACQ for
6853 acq->created = time_second;
6858 * Increment counter and do nothing.
6859 * We send SADB_ACQUIRE message only
6860 * for each V_key_blockacq_count packet.
6873 /* allocate new entry */
6874 return (key_newacq(saidx, perror));
6878 key_acqreset(uint32_t seq)
6883 LIST_FOREACH(acq, ACQSEQHASH_HASH(seq), seqhash) {
6884 if (acq->seq == seq) {
6886 acq->created = time_second;
6896 * Mark ACQ entry as stale to remove it in key_flush_acq().
6897 * Called after successful SADB_GETSPI message.
6900 key_acqdone(const struct secasindex *saidx, uint32_t seq)
6905 LIST_FOREACH(acq, ACQSEQHASH_HASH(seq), seqhash) {
6906 if (acq->seq == seq)
6910 if (key_cmpsaidx(&acq->saidx, saidx, CMP_EXACTLY) == 0) {
6911 ipseclog((LOG_DEBUG,
6912 "%s: Mismatched saidx for ACQ %u\n", __func__, seq));
6918 ipseclog((LOG_DEBUG,
6919 "%s: ACQ %u is not found.\n", __func__, seq));
6927 static struct secspacq *
6928 key_newspacq(struct secpolicyindex *spidx)
6930 struct secspacq *acq;
6933 acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6935 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6940 bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6941 acq->created = time_second;
6944 /* add to spacqtree */
6946 LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6952 static struct secspacq *
6953 key_getspacq(struct secpolicyindex *spidx)
6955 struct secspacq *acq;
6958 LIST_FOREACH(acq, &V_spacqtree, chain) {
6959 if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6960 /* NB: return holding spacq_lock */
6970 * SADB_ACQUIRE processing,
6971 * in first situation, is receiving
6973 * from the ikmpd, and clear sequence of its secasvar entry.
6975 * In second situation, is receiving
6976 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6977 * from a user land process, and return
6978 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6981 * m will always be freed.
6984 key_acquire2(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6986 SAHTREE_RLOCK_TRACKER;
6987 struct sadb_address *src0, *dst0;
6988 struct secasindex saidx;
6989 struct secashead *sah;
6992 uint8_t mode, proto;
6994 IPSEC_ASSERT(so != NULL, ("null socket"));
6995 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6996 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6997 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7000 * Error message from KMd.
7001 * We assume that if error was occurred in IKEd, the length of PFKEY
7002 * message is equal to the size of sadb_msg structure.
7003 * We do not raise error even if error occurred in this function.
7005 if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
7006 /* check sequence number */
7007 if (mhp->msg->sadb_msg_seq == 0 ||
7008 mhp->msg->sadb_msg_errno == 0) {
7009 ipseclog((LOG_DEBUG, "%s: must specify sequence "
7010 "number and errno.\n", __func__));
7013 * IKEd reported that error occurred.
7014 * XXXAE: what it expects from the kernel?
7015 * Probably we should send SADB_ACQUIRE again?
7016 * If so, reset ACQ's state.
7017 * XXXAE: it looks useless.
7019 key_acqreset(mhp->msg->sadb_msg_seq);
7026 * This message is from user land.
7029 /* map satype to proto */
7030 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7031 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7033 return key_senderror(so, m, EINVAL);
7036 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
7037 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
7038 SADB_CHECKHDR(mhp, SADB_EXT_PROPOSAL)) {
7039 ipseclog((LOG_DEBUG,
7040 "%s: invalid message: missing required header.\n",
7042 return key_senderror(so, m, EINVAL);
7044 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
7045 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
7046 SADB_CHECKLEN(mhp, SADB_EXT_PROPOSAL)) {
7047 ipseclog((LOG_DEBUG,
7048 "%s: invalid message: wrong header size.\n", __func__));
7049 return key_senderror(so, m, EINVAL);
7052 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
7053 mode = IPSEC_MODE_ANY;
7056 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
7057 ipseclog((LOG_DEBUG,
7058 "%s: invalid message: wrong header size.\n",
7060 return key_senderror(so, m, EINVAL);
7062 mode = ((struct sadb_x_sa2 *)
7063 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
7064 reqid = ((struct sadb_x_sa2 *)
7065 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
7068 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
7069 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
7071 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
7072 (struct sockaddr *)(dst0 + 1));
7074 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
7075 return key_senderror(so, m, EINVAL);
7077 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
7079 /* get a SA index */
7081 LIST_FOREACH(sah, SAHADDRHASH_HASH(&saidx), addrhash) {
7082 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
7087 ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
7088 return key_senderror(so, m, EEXIST);
7091 error = key_acquire(&saidx, NULL);
7093 ipseclog((LOG_DEBUG,
7094 "%s: error %d returned from key_acquire()\n",
7096 return key_senderror(so, m, error);
7103 * SADB_REGISTER processing.
7104 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
7107 * from the ikmpd, and register a socket to send PF_KEY messages,
7111 * If socket is detached, must free from regnode.
7113 * m will always be freed.
7116 key_register(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7118 struct secreg *reg, *newreg = NULL;
7120 IPSEC_ASSERT(so != NULL, ("null socket"));
7121 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7122 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7123 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7125 /* check for invalid register message */
7126 if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
7127 return key_senderror(so, m, EINVAL);
7129 /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
7130 if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
7133 /* check whether existing or not */
7135 LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
7136 if (reg->so == so) {
7138 ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
7140 return key_senderror(so, m, EEXIST);
7144 /* create regnode */
7145 newreg = malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
7146 if (newreg == NULL) {
7148 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7149 return key_senderror(so, m, ENOBUFS);
7153 ((struct keycb *)sotorawcb(so))->kp_registered++;
7155 /* add regnode to regtree. */
7156 LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
7162 struct sadb_msg *newmsg;
7163 struct sadb_supported *sup;
7164 u_int len, alen, elen;
7167 struct sadb_alg *alg;
7169 /* create new sadb_msg to reply. */
7171 for (i = 1; i <= SADB_AALG_MAX; i++) {
7172 if (auth_algorithm_lookup(i))
7173 alen += sizeof(struct sadb_alg);
7176 alen += sizeof(struct sadb_supported);
7178 for (i = 1; i <= SADB_EALG_MAX; i++) {
7179 if (enc_algorithm_lookup(i))
7180 elen += sizeof(struct sadb_alg);
7183 elen += sizeof(struct sadb_supported);
7185 len = sizeof(struct sadb_msg) + alen + elen;
7188 return key_senderror(so, m, ENOBUFS);
7190 MGETHDR(n, M_NOWAIT, MT_DATA);
7192 if (!(MCLGET(n, M_NOWAIT))) {
7198 return key_senderror(so, m, ENOBUFS);
7200 n->m_pkthdr.len = n->m_len = len;
7204 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
7205 newmsg = mtod(n, struct sadb_msg *);
7206 newmsg->sadb_msg_errno = 0;
7207 newmsg->sadb_msg_len = PFKEY_UNIT64(len);
7208 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
7210 /* for authentication algorithm */
7212 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
7213 sup->sadb_supported_len = PFKEY_UNIT64(alen);
7214 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
7215 off += PFKEY_ALIGN8(sizeof(*sup));
7217 for (i = 1; i <= SADB_AALG_MAX; i++) {
7218 const struct auth_hash *aalgo;
7219 u_int16_t minkeysize, maxkeysize;
7221 aalgo = auth_algorithm_lookup(i);
7224 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
7225 alg->sadb_alg_id = i;
7226 alg->sadb_alg_ivlen = 0;
7227 key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
7228 alg->sadb_alg_minbits = _BITS(minkeysize);
7229 alg->sadb_alg_maxbits = _BITS(maxkeysize);
7230 off += PFKEY_ALIGN8(sizeof(*alg));
7234 /* for encryption algorithm */
7236 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
7237 sup->sadb_supported_len = PFKEY_UNIT64(elen);
7238 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
7239 off += PFKEY_ALIGN8(sizeof(*sup));
7241 for (i = 1; i <= SADB_EALG_MAX; i++) {
7242 const struct enc_xform *ealgo;
7244 ealgo = enc_algorithm_lookup(i);
7247 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
7248 alg->sadb_alg_id = i;
7249 alg->sadb_alg_ivlen = ealgo->ivsize;
7250 alg->sadb_alg_minbits = _BITS(ealgo->minkey);
7251 alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
7252 off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
7256 IPSEC_ASSERT(off == len,
7257 ("length assumption failed (off %u len %u)", off, len));
7260 return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
7265 * free secreg entry registered.
7266 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
7269 key_freereg(struct socket *so)
7274 IPSEC_ASSERT(so != NULL, ("NULL so"));
7277 * check whether existing or not.
7278 * check all type of SA, because there is a potential that
7279 * one socket is registered to multiple type of SA.
7282 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7283 LIST_FOREACH(reg, &V_regtree[i], chain) {
7284 if (reg->so == so && __LIST_CHAINED(reg)) {
7285 LIST_REMOVE(reg, chain);
7286 free(reg, M_IPSEC_SAR);
7295 * SADB_EXPIRE processing
7297 * <base, SA, SA2, lifetime(C and one of HS), address(SD)>
7299 * NOTE: We send only soft lifetime extension.
7302 * others : error number
7305 key_expire(struct secasvar *sav, int hard)
7307 struct mbuf *result = NULL, *m;
7308 struct sadb_lifetime *lt;
7309 uint32_t replay_count;
7313 IPSEC_ASSERT (sav != NULL, ("null sav"));
7314 IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
7317 printf("%s: SA(%p) expired %s lifetime\n", __func__,
7318 sav, hard ? "hard": "soft"));
7319 KEYDBG(KEY_DATA, kdebug_secasv(sav));
7320 /* set msg header */
7321 satype = key_proto2satype(sav->sah->saidx.proto);
7322 IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
7323 m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
7330 /* create SA extension */
7331 m = key_setsadbsa(sav);
7338 /* create SA extension */
7340 replay_count = sav->replay ? sav->replay->count : 0;
7341 SECASVAR_UNLOCK(sav);
7343 m = key_setsadbxsa2(sav->sah->saidx.mode, replay_count,
7344 sav->sah->saidx.reqid);
7351 if (sav->replay && sav->replay->wsize > UINT8_MAX) {
7352 m = key_setsadbxsareplay(sav->replay->wsize);
7360 /* create lifetime extension (current and soft) */
7361 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
7362 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
7369 bzero(mtod(m, caddr_t), len);
7370 lt = mtod(m, struct sadb_lifetime *);
7371 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7372 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
7373 lt->sadb_lifetime_allocations =
7374 (uint32_t)counter_u64_fetch(sav->lft_c_allocations);
7375 lt->sadb_lifetime_bytes =
7376 counter_u64_fetch(sav->lft_c_bytes);
7377 lt->sadb_lifetime_addtime = sav->created;
7378 lt->sadb_lifetime_usetime = sav->firstused;
7379 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
7380 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7382 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
7383 lt->sadb_lifetime_allocations = sav->lft_h->allocations;
7384 lt->sadb_lifetime_bytes = sav->lft_h->bytes;
7385 lt->sadb_lifetime_addtime = sav->lft_h->addtime;
7386 lt->sadb_lifetime_usetime = sav->lft_h->usetime;
7388 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
7389 lt->sadb_lifetime_allocations = sav->lft_s->allocations;
7390 lt->sadb_lifetime_bytes = sav->lft_s->bytes;
7391 lt->sadb_lifetime_addtime = sav->lft_s->addtime;
7392 lt->sadb_lifetime_usetime = sav->lft_s->usetime;
7396 /* set sadb_address for source */
7397 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
7398 &sav->sah->saidx.src.sa,
7399 FULLMASK, IPSEC_ULPROTO_ANY);
7406 /* set sadb_address for destination */
7407 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
7408 &sav->sah->saidx.dst.sa,
7409 FULLMASK, IPSEC_ULPROTO_ANY);
7417 * XXX-BZ Handle NAT-T extensions here.
7418 * XXXAE: it doesn't seem quite useful. IKEs should not depend on
7419 * this information, we report only significant SA fields.
7422 if ((result->m_flags & M_PKTHDR) == 0) {
7427 if (result->m_len < sizeof(struct sadb_msg)) {
7428 result = m_pullup(result, sizeof(struct sadb_msg));
7429 if (result == NULL) {
7435 result->m_pkthdr.len = 0;
7436 for (m = result; m; m = m->m_next)
7437 result->m_pkthdr.len += m->m_len;
7439 mtod(result, struct sadb_msg *)->sadb_msg_len =
7440 PFKEY_UNIT64(result->m_pkthdr.len);
7442 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7451 key_freesah_flushed(struct secashead_queue *flushq)
7453 struct secashead *sah, *nextsah;
7454 struct secasvar *sav, *nextsav;
7456 sah = TAILQ_FIRST(flushq);
7457 while (sah != NULL) {
7458 sav = TAILQ_FIRST(&sah->savtree_larval);
7459 while (sav != NULL) {
7460 nextsav = TAILQ_NEXT(sav, chain);
7461 TAILQ_REMOVE(&sah->savtree_larval, sav, chain);
7462 key_freesav(&sav); /* release last reference */
7463 key_freesah(&sah); /* release reference from SAV */
7466 sav = TAILQ_FIRST(&sah->savtree_alive);
7467 while (sav != NULL) {
7468 nextsav = TAILQ_NEXT(sav, chain);
7469 TAILQ_REMOVE(&sah->savtree_alive, sav, chain);
7470 key_freesav(&sav); /* release last reference */
7471 key_freesah(&sah); /* release reference from SAV */
7474 nextsah = TAILQ_NEXT(sah, chain);
7475 key_freesah(&sah); /* release last reference */
7481 * SADB_FLUSH processing
7484 * from the ikmpd, and free all entries in secastree.
7488 * NOTE: to do is only marking SADB_SASTATE_DEAD.
7490 * m will always be freed.
7493 key_flush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7495 struct secashead_queue flushq;
7496 struct sadb_msg *newmsg;
7497 struct secashead *sah, *nextsah;
7498 struct secasvar *sav;
7502 IPSEC_ASSERT(so != NULL, ("null socket"));
7503 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7504 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7506 /* map satype to proto */
7507 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7508 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7510 return key_senderror(so, m, EINVAL);
7513 printf("%s: proto %u\n", __func__, proto));
7515 TAILQ_INIT(&flushq);
7516 if (proto == IPSEC_PROTO_ANY) {
7517 /* no SATYPE specified, i.e. flushing all SA. */
7519 /* Move all SAHs into flushq */
7520 TAILQ_CONCAT(&flushq, &V_sahtree, chain);
7521 /* Flush all buckets in SPI hash */
7522 for (i = 0; i < V_savhash_mask + 1; i++)
7523 LIST_INIT(&V_savhashtbl[i]);
7524 /* Flush all buckets in SAHADDRHASH */
7525 for (i = 0; i < V_sahaddrhash_mask + 1; i++)
7526 LIST_INIT(&V_sahaddrhashtbl[i]);
7527 /* Mark all SAHs as unlinked */
7528 TAILQ_FOREACH(sah, &flushq, chain) {
7529 sah->state = SADB_SASTATE_DEAD;
7531 * Callout handler makes its job using
7532 * RLOCK and drain queues. In case, when this
7533 * function will be called just before it
7534 * acquires WLOCK, we need to mark SAs as
7535 * unlinked to prevent second unlink.
7537 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7538 sav->state = SADB_SASTATE_DEAD;
7540 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7541 sav->state = SADB_SASTATE_DEAD;
7547 sah = TAILQ_FIRST(&V_sahtree);
7548 while (sah != NULL) {
7549 IPSEC_ASSERT(sah->state != SADB_SASTATE_DEAD,
7550 ("DEAD SAH %p in SADB_FLUSH", sah));
7551 nextsah = TAILQ_NEXT(sah, chain);
7552 if (sah->saidx.proto != proto) {
7556 sah->state = SADB_SASTATE_DEAD;
7557 TAILQ_REMOVE(&V_sahtree, sah, chain);
7558 LIST_REMOVE(sah, addrhash);
7559 /* Unlink all SAs from SPI hash */
7560 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7561 LIST_REMOVE(sav, spihash);
7562 sav->state = SADB_SASTATE_DEAD;
7564 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7565 LIST_REMOVE(sav, spihash);
7566 sav->state = SADB_SASTATE_DEAD;
7568 /* Add SAH into flushq */
7569 TAILQ_INSERT_HEAD(&flushq, sah, chain);
7575 key_freesah_flushed(&flushq);
7576 /* Free all queued SAs and SAHs */
7577 if (m->m_len < sizeof(struct sadb_msg) ||
7578 sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7579 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7580 return key_senderror(so, m, ENOBUFS);
7586 m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7587 newmsg = mtod(m, struct sadb_msg *);
7588 newmsg->sadb_msg_errno = 0;
7589 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7591 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7595 * SADB_DUMP processing
7596 * dump all entries including status of DEAD in SAD.
7599 * from the ikmpd, and dump all secasvar leaves
7604 * m will always be freed.
7607 key_dump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7609 SAHTREE_RLOCK_TRACKER;
7610 struct secashead *sah;
7611 struct secasvar *sav;
7614 uint8_t proto, satype;
7616 IPSEC_ASSERT(so != NULL, ("null socket"));
7617 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7618 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7619 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7621 /* map satype to proto */
7622 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7623 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7625 return key_senderror(so, m, EINVAL);
7628 /* count sav entries to be sent to the userland. */
7631 TAILQ_FOREACH(sah, &V_sahtree, chain) {
7632 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
7633 proto != sah->saidx.proto)
7636 TAILQ_FOREACH(sav, &sah->savtree_larval, chain)
7638 TAILQ_FOREACH(sav, &sah->savtree_alive, chain)
7644 return key_senderror(so, m, ENOENT);
7647 /* send this to the userland, one at a time. */
7648 TAILQ_FOREACH(sah, &V_sahtree, chain) {
7649 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
7650 proto != sah->saidx.proto)
7653 /* map proto to satype */
7654 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7656 ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7657 "SAD.\n", __func__));
7658 return key_senderror(so, m, EINVAL);
7660 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7661 n = key_setdumpsa(sav, SADB_DUMP, satype,
7662 --cnt, mhp->msg->sadb_msg_pid);
7665 return key_senderror(so, m, ENOBUFS);
7667 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7669 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7670 n = key_setdumpsa(sav, SADB_DUMP, satype,
7671 --cnt, mhp->msg->sadb_msg_pid);
7674 return key_senderror(so, m, ENOBUFS);
7676 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7684 * SADB_X_PROMISC processing
7686 * m will always be freed.
7689 key_promisc(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7693 IPSEC_ASSERT(so != NULL, ("null socket"));
7694 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7695 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7696 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7698 olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7700 if (olen < sizeof(struct sadb_msg)) {
7702 return key_senderror(so, m, EINVAL);
7707 } else if (olen == sizeof(struct sadb_msg)) {
7708 /* enable/disable promisc mode */
7711 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7712 return key_senderror(so, m, EINVAL);
7713 mhp->msg->sadb_msg_errno = 0;
7714 switch (mhp->msg->sadb_msg_satype) {
7717 kp->kp_promisc = mhp->msg->sadb_msg_satype;
7720 return key_senderror(so, m, EINVAL);
7723 /* send the original message back to everyone */
7724 mhp->msg->sadb_msg_errno = 0;
7725 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7727 /* send packet as is */
7729 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7731 /* TODO: if sadb_msg_seq is specified, send to specific pid */
7732 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7736 static int (*key_typesw[])(struct socket *, struct mbuf *,
7737 const struct sadb_msghdr *) = {
7738 NULL, /* SADB_RESERVED */
7739 key_getspi, /* SADB_GETSPI */
7740 key_update, /* SADB_UPDATE */
7741 key_add, /* SADB_ADD */
7742 key_delete, /* SADB_DELETE */
7743 key_get, /* SADB_GET */
7744 key_acquire2, /* SADB_ACQUIRE */
7745 key_register, /* SADB_REGISTER */
7746 NULL, /* SADB_EXPIRE */
7747 key_flush, /* SADB_FLUSH */
7748 key_dump, /* SADB_DUMP */
7749 key_promisc, /* SADB_X_PROMISC */
7750 NULL, /* SADB_X_PCHANGE */
7751 key_spdadd, /* SADB_X_SPDUPDATE */
7752 key_spdadd, /* SADB_X_SPDADD */
7753 key_spddelete, /* SADB_X_SPDDELETE */
7754 key_spdget, /* SADB_X_SPDGET */
7755 NULL, /* SADB_X_SPDACQUIRE */
7756 key_spddump, /* SADB_X_SPDDUMP */
7757 key_spdflush, /* SADB_X_SPDFLUSH */
7758 key_spdadd, /* SADB_X_SPDSETIDX */
7759 NULL, /* SADB_X_SPDEXPIRE */
7760 key_spddelete2, /* SADB_X_SPDDELETE2 */
7764 * parse sadb_msg buffer to process PFKEYv2,
7765 * and create a data to response if needed.
7766 * I think to be dealed with mbuf directly.
7768 * msgp : pointer to pointer to a received buffer pulluped.
7769 * This is rewrited to response.
7770 * so : pointer to socket.
7772 * length for buffer to send to user process.
7775 key_parse(struct mbuf *m, struct socket *so)
7777 struct sadb_msg *msg;
7778 struct sadb_msghdr mh;
7783 IPSEC_ASSERT(so != NULL, ("null socket"));
7784 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7786 if (m->m_len < sizeof(struct sadb_msg)) {
7787 m = m_pullup(m, sizeof(struct sadb_msg));
7791 msg = mtod(m, struct sadb_msg *);
7792 orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7793 target = KEY_SENDUP_ONE;
7795 if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len != orglen) {
7796 ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7797 PFKEYSTAT_INC(out_invlen);
7802 if (msg->sadb_msg_version != PF_KEY_V2) {
7803 ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7804 __func__, msg->sadb_msg_version));
7805 PFKEYSTAT_INC(out_invver);
7810 if (msg->sadb_msg_type > SADB_MAX) {
7811 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7812 __func__, msg->sadb_msg_type));
7813 PFKEYSTAT_INC(out_invmsgtype);
7818 /* for old-fashioned code - should be nuked */
7819 if (m->m_pkthdr.len > MCLBYTES) {
7826 MGETHDR(n, M_NOWAIT, MT_DATA);
7827 if (n && m->m_pkthdr.len > MHLEN) {
7828 if (!(MCLGET(n, M_NOWAIT))) {
7837 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7838 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7844 /* align the mbuf chain so that extensions are in contiguous region. */
7845 error = key_align(m, &mh);
7851 /* We use satype as scope mask for spddump */
7852 if (msg->sadb_msg_type == SADB_X_SPDDUMP) {
7853 switch (msg->sadb_msg_satype) {
7854 case IPSEC_POLICYSCOPE_ANY:
7855 case IPSEC_POLICYSCOPE_GLOBAL:
7856 case IPSEC_POLICYSCOPE_IFNET:
7857 case IPSEC_POLICYSCOPE_PCB:
7860 ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7861 __func__, msg->sadb_msg_type));
7862 PFKEYSTAT_INC(out_invsatype);
7867 switch (msg->sadb_msg_satype) { /* check SA type */
7868 case SADB_SATYPE_UNSPEC:
7869 switch (msg->sadb_msg_type) {
7877 ipseclog((LOG_DEBUG, "%s: must specify satype "
7878 "when msg type=%u.\n", __func__,
7879 msg->sadb_msg_type));
7880 PFKEYSTAT_INC(out_invsatype);
7885 case SADB_SATYPE_AH:
7886 case SADB_SATYPE_ESP:
7887 case SADB_X_SATYPE_IPCOMP:
7888 case SADB_X_SATYPE_TCPSIGNATURE:
7889 switch (msg->sadb_msg_type) {
7891 case SADB_X_SPDDELETE:
7893 case SADB_X_SPDFLUSH:
7894 case SADB_X_SPDSETIDX:
7895 case SADB_X_SPDUPDATE:
7896 case SADB_X_SPDDELETE2:
7897 ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7898 __func__, msg->sadb_msg_type));
7899 PFKEYSTAT_INC(out_invsatype);
7904 case SADB_SATYPE_RSVP:
7905 case SADB_SATYPE_OSPFV2:
7906 case SADB_SATYPE_RIPV2:
7907 case SADB_SATYPE_MIP:
7908 ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7909 __func__, msg->sadb_msg_satype));
7910 PFKEYSTAT_INC(out_invsatype);
7913 case 1: /* XXX: What does it do? */
7914 if (msg->sadb_msg_type == SADB_X_PROMISC)
7918 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7919 __func__, msg->sadb_msg_satype));
7920 PFKEYSTAT_INC(out_invsatype);
7926 /* check field of upper layer protocol and address family */
7927 if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7928 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7929 struct sadb_address *src0, *dst0;
7932 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7933 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7935 /* check upper layer protocol */
7936 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7937 ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7938 "mismatched.\n", __func__));
7939 PFKEYSTAT_INC(out_invaddr);
7945 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7946 PFKEY_ADDR_SADDR(dst0)->sa_family) {
7947 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7949 PFKEYSTAT_INC(out_invaddr);
7953 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7954 PFKEY_ADDR_SADDR(dst0)->sa_len) {
7955 ipseclog((LOG_DEBUG, "%s: address struct size "
7956 "mismatched.\n", __func__));
7957 PFKEYSTAT_INC(out_invaddr);
7962 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7964 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7965 sizeof(struct sockaddr_in)) {
7966 PFKEYSTAT_INC(out_invaddr);
7972 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7973 sizeof(struct sockaddr_in6)) {
7974 PFKEYSTAT_INC(out_invaddr);
7980 ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7982 PFKEYSTAT_INC(out_invaddr);
7983 error = EAFNOSUPPORT;
7987 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7989 plen = sizeof(struct in_addr) << 3;
7992 plen = sizeof(struct in6_addr) << 3;
7995 plen = 0; /*fool gcc*/
7999 /* check max prefix length */
8000 if (src0->sadb_address_prefixlen > plen ||
8001 dst0->sadb_address_prefixlen > plen) {
8002 ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
8004 PFKEYSTAT_INC(out_invaddr);
8010 * prefixlen == 0 is valid because there can be a case when
8011 * all addresses are matched.
8015 if (msg->sadb_msg_type >= nitems(key_typesw) ||
8016 key_typesw[msg->sadb_msg_type] == NULL) {
8017 PFKEYSTAT_INC(out_invmsgtype);
8022 return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
8025 msg->sadb_msg_errno = error;
8026 return key_sendup_mbuf(so, m, target);
8030 key_senderror(struct socket *so, struct mbuf *m, int code)
8032 struct sadb_msg *msg;
8034 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
8035 ("mbuf too small, len %u", m->m_len));
8037 msg = mtod(m, struct sadb_msg *);
8038 msg->sadb_msg_errno = code;
8039 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
8043 * set the pointer to each header into message buffer.
8044 * m will be freed on error.
8045 * XXX larger-than-MCLBYTES extension?
8048 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
8051 struct sadb_ext *ext;
8056 IPSEC_ASSERT(m != NULL, ("null mbuf"));
8057 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
8058 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
8059 ("mbuf too small, len %u", m->m_len));
8062 bzero(mhp, sizeof(*mhp));
8064 mhp->msg = mtod(m, struct sadb_msg *);
8065 mhp->ext[0] = (struct sadb_ext *)mhp->msg; /*XXX backward compat */
8067 end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
8068 extlen = end; /*just in case extlen is not updated*/
8069 for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
8070 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
8072 /* m is already freed */
8075 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
8078 switch (ext->sadb_ext_type) {
8080 case SADB_EXT_ADDRESS_SRC:
8081 case SADB_EXT_ADDRESS_DST:
8082 case SADB_EXT_ADDRESS_PROXY:
8083 case SADB_EXT_LIFETIME_CURRENT:
8084 case SADB_EXT_LIFETIME_HARD:
8085 case SADB_EXT_LIFETIME_SOFT:
8086 case SADB_EXT_KEY_AUTH:
8087 case SADB_EXT_KEY_ENCRYPT:
8088 case SADB_EXT_IDENTITY_SRC:
8089 case SADB_EXT_IDENTITY_DST:
8090 case SADB_EXT_SENSITIVITY:
8091 case SADB_EXT_PROPOSAL:
8092 case SADB_EXT_SUPPORTED_AUTH:
8093 case SADB_EXT_SUPPORTED_ENCRYPT:
8094 case SADB_EXT_SPIRANGE:
8095 case SADB_X_EXT_POLICY:
8096 case SADB_X_EXT_SA2:
8097 case SADB_X_EXT_NAT_T_TYPE:
8098 case SADB_X_EXT_NAT_T_SPORT:
8099 case SADB_X_EXT_NAT_T_DPORT:
8100 case SADB_X_EXT_NAT_T_OAI:
8101 case SADB_X_EXT_NAT_T_OAR:
8102 case SADB_X_EXT_NAT_T_FRAG:
8103 case SADB_X_EXT_SA_REPLAY:
8104 case SADB_X_EXT_NEW_ADDRESS_SRC:
8105 case SADB_X_EXT_NEW_ADDRESS_DST:
8106 /* duplicate check */
8108 * XXX Are there duplication payloads of either
8109 * KEY_AUTH or KEY_ENCRYPT ?
8111 if (mhp->ext[ext->sadb_ext_type] != NULL) {
8112 ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
8113 "%u\n", __func__, ext->sadb_ext_type));
8115 PFKEYSTAT_INC(out_dupext);
8120 ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
8121 __func__, ext->sadb_ext_type));
8123 PFKEYSTAT_INC(out_invexttype);
8127 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
8129 if (key_validate_ext(ext, extlen)) {
8131 PFKEYSTAT_INC(out_invlen);
8135 n = m_pulldown(m, off, extlen, &toff);
8137 /* m is already freed */
8140 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
8142 mhp->ext[ext->sadb_ext_type] = ext;
8143 mhp->extoff[ext->sadb_ext_type] = off;
8144 mhp->extlen[ext->sadb_ext_type] = extlen;
8149 PFKEYSTAT_INC(out_invlen);
8157 key_validate_ext(const struct sadb_ext *ext, int len)
8159 const struct sockaddr *sa;
8160 enum { NONE, ADDR } checktype = NONE;
8162 const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
8164 if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
8167 /* if it does not match minimum/maximum length, bail */
8168 if (ext->sadb_ext_type >= nitems(minsize) ||
8169 ext->sadb_ext_type >= nitems(maxsize))
8171 if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
8173 if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
8176 /* more checks based on sadb_ext_type XXX need more */
8177 switch (ext->sadb_ext_type) {
8178 case SADB_EXT_ADDRESS_SRC:
8179 case SADB_EXT_ADDRESS_DST:
8180 case SADB_EXT_ADDRESS_PROXY:
8181 case SADB_X_EXT_NAT_T_OAI:
8182 case SADB_X_EXT_NAT_T_OAR:
8183 case SADB_X_EXT_NEW_ADDRESS_SRC:
8184 case SADB_X_EXT_NEW_ADDRESS_DST:
8185 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
8188 case SADB_EXT_IDENTITY_SRC:
8189 case SADB_EXT_IDENTITY_DST:
8190 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
8191 SADB_X_IDENTTYPE_ADDR) {
8192 baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
8202 switch (checktype) {
8206 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
8207 if (len < baselen + sal)
8209 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
8222 TUNABLE_INT_FETCH("net.key.spdcache.maxentries",
8223 &V_key_spdcache_maxentries);
8224 TUNABLE_INT_FETCH("net.key.spdcache.threshold",
8225 &V_key_spdcache_threshold);
8227 if (V_key_spdcache_maxentries) {
8228 V_key_spdcache_maxentries = MAX(V_key_spdcache_maxentries,
8229 SPDCACHE_MAX_ENTRIES_PER_HASH);
8230 V_spdcachehashtbl = hashinit(V_key_spdcache_maxentries /
8231 SPDCACHE_MAX_ENTRIES_PER_HASH,
8232 M_IPSEC_SPDCACHE, &V_spdcachehash_mask);
8233 V_key_spdcache_maxentries = (V_spdcachehash_mask + 1)
8234 * SPDCACHE_MAX_ENTRIES_PER_HASH;
8236 V_spdcache_lock = malloc(sizeof(struct mtx) *
8237 (V_spdcachehash_mask + 1),
8238 M_IPSEC_SPDCACHE, M_WAITOK|M_ZERO);
8240 for (i = 0; i < V_spdcachehash_mask + 1; ++i)
8241 SPDCACHE_LOCK_INIT(i);
8245 struct spdcache_entry *
8246 spdcache_entry_alloc(const struct secpolicyindex *spidx, struct secpolicy *sp)
8248 struct spdcache_entry *entry;
8250 entry = malloc(sizeof(struct spdcache_entry),
8251 M_IPSEC_SPDCACHE, M_NOWAIT|M_ZERO);
8258 entry->spidx = *spidx;
8265 spdcache_entry_free(struct spdcache_entry *entry)
8268 if (entry->sp != NULL)
8269 key_freesp(&entry->sp);
8270 free(entry, M_IPSEC_SPDCACHE);
8274 spdcache_clear(void)
8276 struct spdcache_entry *entry;
8279 for (i = 0; i < V_spdcachehash_mask + 1; ++i) {
8281 while (!LIST_EMPTY(&V_spdcachehashtbl[i])) {
8282 entry = LIST_FIRST(&V_spdcachehashtbl[i]);
8283 LIST_REMOVE(entry, chain);
8284 spdcache_entry_free(entry);
8292 spdcache_destroy(void)
8296 if (SPDCACHE_ENABLED()) {
8298 hashdestroy(V_spdcachehashtbl, M_IPSEC_SPDCACHE, V_spdcachehash_mask);
8300 for (i = 0; i < V_spdcachehash_mask + 1; ++i)
8301 SPDCACHE_LOCK_DESTROY(i);
8303 free(V_spdcache_lock, M_IPSEC_SPDCACHE);
8312 for (i = 0; i < IPSEC_DIR_MAX; i++) {
8313 TAILQ_INIT(&V_sptree[i]);
8314 TAILQ_INIT(&V_sptree_ifnet[i]);
8317 V_key_lft_zone = uma_zcreate("IPsec SA lft_c",
8318 sizeof(uint64_t) * 2, NULL, NULL, NULL, NULL,
8319 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
8321 TAILQ_INIT(&V_sahtree);
8322 V_sphashtbl = hashinit(SPHASH_NHASH, M_IPSEC_SP, &V_sphash_mask);
8323 V_savhashtbl = hashinit(SAVHASH_NHASH, M_IPSEC_SA, &V_savhash_mask);
8324 V_sahaddrhashtbl = hashinit(SAHHASH_NHASH, M_IPSEC_SAH,
8325 &V_sahaddrhash_mask);
8326 V_acqaddrhashtbl = hashinit(ACQHASH_NHASH, M_IPSEC_SAQ,
8327 &V_acqaddrhash_mask);
8328 V_acqseqhashtbl = hashinit(ACQHASH_NHASH, M_IPSEC_SAQ,
8329 &V_acqseqhash_mask);
8333 for (i = 0; i <= SADB_SATYPE_MAX; i++)
8334 LIST_INIT(&V_regtree[i]);
8336 LIST_INIT(&V_acqtree);
8337 LIST_INIT(&V_spacqtree);
8339 if (!IS_DEFAULT_VNET(curvnet))
8343 REGTREE_LOCK_INIT();
8344 SAHTREE_LOCK_INIT();
8348 #ifndef IPSEC_DEBUG2
8349 callout_init(&key_timer, 1);
8350 callout_reset(&key_timer, hz, key_timehandler, NULL);
8351 #endif /*IPSEC_DEBUG2*/
8353 /* initialize key statistics */
8354 keystat.getspi_count = 1;
8357 printf("IPsec: Initialized Security Association Processing.\n");
8364 struct secashead_queue sahdrainq;
8365 struct secpolicy_queue drainq;
8366 struct secpolicy *sp, *nextsp;
8367 struct secacq *acq, *nextacq;
8368 struct secspacq *spacq, *nextspacq;
8369 struct secashead *sah;
8370 struct secasvar *sav;
8375 * XXX: can we just call free() for each object without
8376 * walking through safe way with releasing references?
8378 TAILQ_INIT(&drainq);
8380 for (i = 0; i < IPSEC_DIR_MAX; i++) {
8381 TAILQ_CONCAT(&drainq, &V_sptree[i], chain);
8382 TAILQ_CONCAT(&drainq, &V_sptree_ifnet[i], chain);
8384 for (i = 0; i < V_sphash_mask + 1; i++)
8385 LIST_INIT(&V_sphashtbl[i]);
8389 sp = TAILQ_FIRST(&drainq);
8390 while (sp != NULL) {
8391 nextsp = TAILQ_NEXT(sp, chain);
8396 TAILQ_INIT(&sahdrainq);
8398 TAILQ_CONCAT(&sahdrainq, &V_sahtree, chain);
8399 for (i = 0; i < V_savhash_mask + 1; i++)
8400 LIST_INIT(&V_savhashtbl[i]);
8401 for (i = 0; i < V_sahaddrhash_mask + 1; i++)
8402 LIST_INIT(&V_sahaddrhashtbl[i]);
8403 TAILQ_FOREACH(sah, &sahdrainq, chain) {
8404 sah->state = SADB_SASTATE_DEAD;
8405 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
8406 sav->state = SADB_SASTATE_DEAD;
8408 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
8409 sav->state = SADB_SASTATE_DEAD;
8414 key_freesah_flushed(&sahdrainq);
8415 hashdestroy(V_sphashtbl, M_IPSEC_SP, V_sphash_mask);
8416 hashdestroy(V_savhashtbl, M_IPSEC_SA, V_savhash_mask);
8417 hashdestroy(V_sahaddrhashtbl, M_IPSEC_SAH, V_sahaddrhash_mask);
8420 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
8421 LIST_FOREACH(reg, &V_regtree[i], chain) {
8422 if (__LIST_CHAINED(reg)) {
8423 LIST_REMOVE(reg, chain);
8424 free(reg, M_IPSEC_SAR);
8432 acq = LIST_FIRST(&V_acqtree);
8433 while (acq != NULL) {
8434 nextacq = LIST_NEXT(acq, chain);
8435 LIST_REMOVE(acq, chain);
8436 free(acq, M_IPSEC_SAQ);
8439 for (i = 0; i < V_acqaddrhash_mask + 1; i++)
8440 LIST_INIT(&V_acqaddrhashtbl[i]);
8441 for (i = 0; i < V_acqseqhash_mask + 1; i++)
8442 LIST_INIT(&V_acqseqhashtbl[i]);
8446 for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
8447 spacq = nextspacq) {
8448 nextspacq = LIST_NEXT(spacq, chain);
8449 if (__LIST_CHAINED(spacq)) {
8450 LIST_REMOVE(spacq, chain);
8451 free(spacq, M_IPSEC_SAQ);
8455 hashdestroy(V_acqaddrhashtbl, M_IPSEC_SAQ, V_acqaddrhash_mask);
8456 hashdestroy(V_acqseqhashtbl, M_IPSEC_SAQ, V_acqseqhash_mask);
8457 uma_zdestroy(V_key_lft_zone);
8459 if (!IS_DEFAULT_VNET(curvnet))
8461 #ifndef IPSEC_DEBUG2
8462 callout_drain(&key_timer);
8464 SPTREE_LOCK_DESTROY();
8465 REGTREE_LOCK_DESTROY();
8466 SAHTREE_LOCK_DESTROY();
8468 SPACQ_LOCK_DESTROY();
8472 /* record data transfer on SA, and update timestamps */
8474 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
8476 IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
8477 IPSEC_ASSERT(m != NULL, ("Null mbuf"));
8480 * XXX Currently, there is a difference of bytes size
8481 * between inbound and outbound processing.
8483 counter_u64_add(sav->lft_c_bytes, m->m_pkthdr.len);
8486 * We use the number of packets as the unit of
8487 * allocations. We increment the variable
8488 * whenever {esp,ah}_{in,out}put is called.
8490 counter_u64_add(sav->lft_c_allocations, 1);
8493 * NOTE: We record CURRENT usetime by using wall clock,
8494 * in seconds. HARD and SOFT lifetime are measured by the time
8495 * difference (again in seconds) from usetime.
8499 * -----+-----+--------+---> t
8500 * <--------------> HARD
8503 if (sav->firstused == 0)
8504 sav->firstused = time_second;
8508 * Take one of the kernel's security keys and convert it into a PF_KEY
8509 * structure within an mbuf, suitable for sending up to a waiting
8510 * application in user land.
8513 * src: A pointer to a kernel security key.
8514 * exttype: Which type of key this is. Refer to the PF_KEY data structures.
8516 * a valid mbuf or NULL indicating an error
8520 static struct mbuf *
8521 key_setkey(struct seckey *src, uint16_t exttype)
8530 len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8531 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
8536 p = mtod(m, struct sadb_key *);
8538 p->sadb_key_len = PFKEY_UNIT64(len);
8539 p->sadb_key_exttype = exttype;
8540 p->sadb_key_bits = src->bits;
8541 bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8547 * Take one of the kernel's lifetime data structures and convert it
8548 * into a PF_KEY structure within an mbuf, suitable for sending up to
8549 * a waiting application in user land.
8552 * src: A pointer to a kernel lifetime structure.
8553 * exttype: Which type of lifetime this is. Refer to the PF_KEY
8554 * data structures for more information.
8556 * a valid mbuf or NULL indicating an error
8560 static struct mbuf *
8561 key_setlifetime(struct seclifetime *src, uint16_t exttype)
8563 struct mbuf *m = NULL;
8564 struct sadb_lifetime *p;
8565 int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8570 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
8575 p = mtod(m, struct sadb_lifetime *);
8578 p->sadb_lifetime_len = PFKEY_UNIT64(len);
8579 p->sadb_lifetime_exttype = exttype;
8580 p->sadb_lifetime_allocations = src->allocations;
8581 p->sadb_lifetime_bytes = src->bytes;
8582 p->sadb_lifetime_addtime = src->addtime;
8583 p->sadb_lifetime_usetime = src->usetime;
8589 const struct enc_xform *
8590 enc_algorithm_lookup(int alg)
8594 for (i = 0; i < nitems(supported_ealgs); i++)
8595 if (alg == supported_ealgs[i].sadb_alg)
8596 return (supported_ealgs[i].xform);
8600 const struct auth_hash *
8601 auth_algorithm_lookup(int alg)
8605 for (i = 0; i < nitems(supported_aalgs); i++)
8606 if (alg == supported_aalgs[i].sadb_alg)
8607 return (supported_aalgs[i].xform);
8611 const struct comp_algo *
8612 comp_algorithm_lookup(int alg)
8616 for (i = 0; i < nitems(supported_calgs); i++)
8617 if (alg == supported_calgs[i].sadb_alg)
8618 return (supported_calgs[i].xform);