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>
70 #include <netinet/in.h>
71 #include <netinet/in_systm.h>
72 #include <netinet/ip.h>
73 #include <netinet/in_var.h>
74 #include <netinet/udp.h>
77 #include <netinet/ip6.h>
78 #include <netinet6/in6_var.h>
79 #include <netinet6/ip6_var.h>
82 #include <net/pfkeyv2.h>
83 #include <netipsec/keydb.h>
84 #include <netipsec/key.h>
85 #include <netipsec/keysock.h>
86 #include <netipsec/key_debug.h>
88 #include <netipsec/ipsec.h>
90 #include <netipsec/ipsec6.h>
93 #include <netipsec/xform.h>
94 #include <machine/in_cksum.h>
95 #include <machine/stdarg.h>
98 #include <sys/random.h>
100 #define FULLMASK 0xff
101 #define _BITS(bytes) ((bytes) << 3)
103 #define UINT32_80PCT 0xcccccccc
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]);
218 static struct sx spi_alloc_lock;
219 #define SPI_ALLOC_LOCK_INIT() sx_init(&spi_alloc_lock, "spialloc")
220 #define SPI_ALLOC_LOCK_DESTROY() sx_destroy(&spi_alloc_lock)
221 #define SPI_ALLOC_LOCK() sx_xlock(&spi_alloc_lock)
222 #define SPI_ALLOC_UNLOCK() sx_unlock(&spi_alloc_lock)
223 #define SPI_ALLOC_LOCK_ASSERT() sx_assert(&spi_alloc_lock, SA_XLOCKED)
226 TAILQ_HEAD(secashead_queue, secashead);
227 LIST_HEAD(secashead_list, secashead);
228 VNET_DEFINE_STATIC(struct secashead_queue, sahtree);
229 static struct rmlock sahtree_lock;
230 #define V_sahtree VNET(sahtree)
231 #define SAHTREE_LOCK_INIT() rm_init(&sahtree_lock, "sahtree")
232 #define SAHTREE_LOCK_DESTROY() rm_destroy(&sahtree_lock)
233 #define SAHTREE_RLOCK_TRACKER struct rm_priotracker sahtree_tracker
234 #define SAHTREE_RLOCK() rm_rlock(&sahtree_lock, &sahtree_tracker)
235 #define SAHTREE_RUNLOCK() rm_runlock(&sahtree_lock, &sahtree_tracker)
236 #define SAHTREE_RLOCK_ASSERT() rm_assert(&sahtree_lock, RA_RLOCKED)
237 #define SAHTREE_WLOCK() rm_wlock(&sahtree_lock)
238 #define SAHTREE_WUNLOCK() rm_wunlock(&sahtree_lock)
239 #define SAHTREE_WLOCK_ASSERT() rm_assert(&sahtree_lock, RA_WLOCKED)
240 #define SAHTREE_UNLOCK_ASSERT() rm_assert(&sahtree_lock, RA_UNLOCKED)
242 /* Hash table for lookup in SAD using SA addresses */
243 VNET_DEFINE_STATIC(struct secashead_list *, sahaddrhashtbl);
244 VNET_DEFINE_STATIC(u_long, sahaddrhash_mask);
245 #define V_sahaddrhashtbl VNET(sahaddrhashtbl)
246 #define V_sahaddrhash_mask VNET(sahaddrhash_mask)
248 #define SAHHASH_NHASH_LOG2 7
249 #define SAHHASH_NHASH (1 << SAHHASH_NHASH_LOG2)
250 #define SAHADDRHASH_HASHVAL(idx) \
251 (key_addrprotohash(&(idx)->src, &(idx)->dst, &(idx)->proto) & \
253 #define SAHADDRHASH_HASH(saidx) \
254 &V_sahaddrhashtbl[SAHADDRHASH_HASHVAL(saidx)]
256 /* Hash table for lookup in SAD using SPI */
257 LIST_HEAD(secasvar_list, secasvar);
258 VNET_DEFINE_STATIC(struct secasvar_list *, savhashtbl);
259 VNET_DEFINE_STATIC(u_long, savhash_mask);
260 #define V_savhashtbl VNET(savhashtbl)
261 #define V_savhash_mask VNET(savhash_mask)
262 #define SAVHASH_NHASH_LOG2 7
263 #define SAVHASH_NHASH (1 << SAVHASH_NHASH_LOG2)
264 #define SAVHASH_HASHVAL(spi) (key_u32hash(spi) & V_savhash_mask)
265 #define SAVHASH_HASH(spi) &V_savhashtbl[SAVHASH_HASHVAL(spi)]
268 key_addrprotohash(const union sockaddr_union *src,
269 const union sockaddr_union *dst, const uint8_t *proto)
273 hval = fnv_32_buf(proto, sizeof(*proto),
275 switch (dst->sa.sa_family) {
278 hval = fnv_32_buf(&src->sin.sin_addr,
279 sizeof(in_addr_t), hval);
280 hval = fnv_32_buf(&dst->sin.sin_addr,
281 sizeof(in_addr_t), hval);
286 hval = fnv_32_buf(&src->sin6.sin6_addr,
287 sizeof(struct in6_addr), hval);
288 hval = fnv_32_buf(&dst->sin6.sin6_addr,
289 sizeof(struct in6_addr), hval);
294 ipseclog((LOG_DEBUG, "%s: unknown address family %d\n",
295 __func__, dst->sa.sa_family));
301 key_u32hash(uint32_t val)
304 return (fnv_32_buf(&val, sizeof(val), FNV1_32_INIT));
308 VNET_DEFINE_STATIC(LIST_HEAD(_regtree, secreg), regtree[SADB_SATYPE_MAX + 1]);
309 #define V_regtree VNET(regtree)
310 static struct mtx regtree_lock;
311 #define REGTREE_LOCK_INIT() \
312 mtx_init(®tree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
313 #define REGTREE_LOCK_DESTROY() mtx_destroy(®tree_lock)
314 #define REGTREE_LOCK() mtx_lock(®tree_lock)
315 #define REGTREE_UNLOCK() mtx_unlock(®tree_lock)
316 #define REGTREE_LOCK_ASSERT() mtx_assert(®tree_lock, MA_OWNED)
319 LIST_HEAD(secacq_list, secacq);
320 VNET_DEFINE_STATIC(struct secacq_list, acqtree);
321 #define V_acqtree VNET(acqtree)
322 static struct mtx acq_lock;
323 #define ACQ_LOCK_INIT() \
324 mtx_init(&acq_lock, "acqtree", "ipsec SA acquiring list", MTX_DEF)
325 #define ACQ_LOCK_DESTROY() mtx_destroy(&acq_lock)
326 #define ACQ_LOCK() mtx_lock(&acq_lock)
327 #define ACQ_UNLOCK() mtx_unlock(&acq_lock)
328 #define ACQ_LOCK_ASSERT() mtx_assert(&acq_lock, MA_OWNED)
330 /* Hash table for lookup in ACQ list using SA addresses */
331 VNET_DEFINE_STATIC(struct secacq_list *, acqaddrhashtbl);
332 VNET_DEFINE_STATIC(u_long, acqaddrhash_mask);
333 #define V_acqaddrhashtbl VNET(acqaddrhashtbl)
334 #define V_acqaddrhash_mask VNET(acqaddrhash_mask)
336 /* Hash table for lookup in ACQ list using SEQ number */
337 VNET_DEFINE_STATIC(struct secacq_list *, acqseqhashtbl);
338 VNET_DEFINE_STATIC(u_long, acqseqhash_mask);
339 #define V_acqseqhashtbl VNET(acqseqhashtbl)
340 #define V_acqseqhash_mask VNET(acqseqhash_mask)
342 #define ACQHASH_NHASH_LOG2 7
343 #define ACQHASH_NHASH (1 << ACQHASH_NHASH_LOG2)
344 #define ACQADDRHASH_HASHVAL(idx) \
345 (key_addrprotohash(&(idx)->src, &(idx)->dst, &(idx)->proto) & \
347 #define ACQSEQHASH_HASHVAL(seq) \
348 (key_u32hash(seq) & V_acqseqhash_mask)
349 #define ACQADDRHASH_HASH(saidx) \
350 &V_acqaddrhashtbl[ACQADDRHASH_HASHVAL(saidx)]
351 #define ACQSEQHASH_HASH(seq) \
352 &V_acqseqhashtbl[ACQSEQHASH_HASHVAL(seq)]
353 /* SP acquiring list */
354 VNET_DEFINE_STATIC(LIST_HEAD(_spacqtree, secspacq), spacqtree);
355 #define V_spacqtree VNET(spacqtree)
356 static struct mtx spacq_lock;
357 #define SPACQ_LOCK_INIT() \
358 mtx_init(&spacq_lock, "spacqtree", \
359 "fast ipsec security policy acquire list", MTX_DEF)
360 #define SPACQ_LOCK_DESTROY() mtx_destroy(&spacq_lock)
361 #define SPACQ_LOCK() mtx_lock(&spacq_lock)
362 #define SPACQ_UNLOCK() mtx_unlock(&spacq_lock)
363 #define SPACQ_LOCK_ASSERT() mtx_assert(&spacq_lock, MA_OWNED)
365 static const int minsize[] = {
366 [SADB_EXT_RESERVED] = sizeof(struct sadb_msg),
367 [SADB_EXT_SA] = sizeof(struct sadb_sa),
368 [SADB_EXT_LIFETIME_CURRENT] = sizeof(struct sadb_lifetime),
369 [SADB_EXT_LIFETIME_HARD] = sizeof(struct sadb_lifetime),
370 [SADB_EXT_LIFETIME_SOFT] = sizeof(struct sadb_lifetime),
371 [SADB_EXT_ADDRESS_SRC] = sizeof(struct sadb_address),
372 [SADB_EXT_ADDRESS_DST] = sizeof(struct sadb_address),
373 [SADB_EXT_ADDRESS_PROXY] = sizeof(struct sadb_address),
374 [SADB_EXT_KEY_AUTH] = sizeof(struct sadb_key),
375 [SADB_EXT_KEY_ENCRYPT] = sizeof(struct sadb_key),
376 [SADB_EXT_IDENTITY_SRC] = sizeof(struct sadb_ident),
377 [SADB_EXT_IDENTITY_DST] = sizeof(struct sadb_ident),
378 [SADB_EXT_SENSITIVITY] = sizeof(struct sadb_sens),
379 [SADB_EXT_PROPOSAL] = sizeof(struct sadb_prop),
380 [SADB_EXT_SUPPORTED_AUTH] = sizeof(struct sadb_supported),
381 [SADB_EXT_SUPPORTED_ENCRYPT] = sizeof(struct sadb_supported),
382 [SADB_EXT_SPIRANGE] = sizeof(struct sadb_spirange),
383 [SADB_X_EXT_KMPRIVATE] = 0,
384 [SADB_X_EXT_POLICY] = sizeof(struct sadb_x_policy),
385 [SADB_X_EXT_SA2] = sizeof(struct sadb_x_sa2),
386 [SADB_X_EXT_NAT_T_TYPE] = sizeof(struct sadb_x_nat_t_type),
387 [SADB_X_EXT_NAT_T_SPORT] = sizeof(struct sadb_x_nat_t_port),
388 [SADB_X_EXT_NAT_T_DPORT] = sizeof(struct sadb_x_nat_t_port),
389 [SADB_X_EXT_NAT_T_OAI] = sizeof(struct sadb_address),
390 [SADB_X_EXT_NAT_T_OAR] = sizeof(struct sadb_address),
391 [SADB_X_EXT_NAT_T_FRAG] = sizeof(struct sadb_x_nat_t_frag),
392 [SADB_X_EXT_SA_REPLAY] = sizeof(struct sadb_x_sa_replay),
393 [SADB_X_EXT_NEW_ADDRESS_SRC] = sizeof(struct sadb_address),
394 [SADB_X_EXT_NEW_ADDRESS_DST] = sizeof(struct sadb_address),
396 _Static_assert(nitems(minsize) == SADB_EXT_MAX + 1, "minsize size mismatch");
398 static const int maxsize[] = {
399 [SADB_EXT_RESERVED] = sizeof(struct sadb_msg),
400 [SADB_EXT_SA] = sizeof(struct sadb_sa),
401 [SADB_EXT_LIFETIME_CURRENT] = sizeof(struct sadb_lifetime),
402 [SADB_EXT_LIFETIME_HARD] = sizeof(struct sadb_lifetime),
403 [SADB_EXT_LIFETIME_SOFT] = sizeof(struct sadb_lifetime),
404 [SADB_EXT_ADDRESS_SRC] = 0,
405 [SADB_EXT_ADDRESS_DST] = 0,
406 [SADB_EXT_ADDRESS_PROXY] = 0,
407 [SADB_EXT_KEY_AUTH] = 0,
408 [SADB_EXT_KEY_ENCRYPT] = 0,
409 [SADB_EXT_IDENTITY_SRC] = 0,
410 [SADB_EXT_IDENTITY_DST] = 0,
411 [SADB_EXT_SENSITIVITY] = 0,
412 [SADB_EXT_PROPOSAL] = 0,
413 [SADB_EXT_SUPPORTED_AUTH] = 0,
414 [SADB_EXT_SUPPORTED_ENCRYPT] = 0,
415 [SADB_EXT_SPIRANGE] = sizeof(struct sadb_spirange),
416 [SADB_X_EXT_KMPRIVATE] = 0,
417 [SADB_X_EXT_POLICY] = 0,
418 [SADB_X_EXT_SA2] = sizeof(struct sadb_x_sa2),
419 [SADB_X_EXT_NAT_T_TYPE] = sizeof(struct sadb_x_nat_t_type),
420 [SADB_X_EXT_NAT_T_SPORT] = sizeof(struct sadb_x_nat_t_port),
421 [SADB_X_EXT_NAT_T_DPORT] = sizeof(struct sadb_x_nat_t_port),
422 [SADB_X_EXT_NAT_T_OAI] = 0,
423 [SADB_X_EXT_NAT_T_OAR] = 0,
424 [SADB_X_EXT_NAT_T_FRAG] = sizeof(struct sadb_x_nat_t_frag),
425 [SADB_X_EXT_SA_REPLAY] = sizeof(struct sadb_x_sa_replay),
426 [SADB_X_EXT_NEW_ADDRESS_SRC] = 0,
427 [SADB_X_EXT_NEW_ADDRESS_DST] = 0,
429 _Static_assert(nitems(maxsize) == SADB_EXT_MAX + 1, "maxsize size mismatch");
432 * Internal values for SA flags:
433 * SADB_X_EXT_F_CLONED means that SA was cloned by key_updateaddresses,
434 * thus we will not free the most of SA content in key_delsav().
436 #define SADB_X_EXT_F_CLONED 0x80000000
438 #define SADB_CHECKLEN(_mhp, _ext) \
439 ((_mhp)->extlen[(_ext)] < minsize[(_ext)] || (maxsize[(_ext)] != 0 && \
440 ((_mhp)->extlen[(_ext)] > maxsize[(_ext)])))
441 #define SADB_CHECKHDR(_mhp, _ext) ((_mhp)->ext[(_ext)] == NULL)
443 VNET_DEFINE_STATIC(int, ipsec_esp_keymin) = 256;
444 VNET_DEFINE_STATIC(int, ipsec_esp_auth) = 0;
445 VNET_DEFINE_STATIC(int, ipsec_ah_keymin) = 128;
447 #define V_ipsec_esp_keymin VNET(ipsec_esp_keymin)
448 #define V_ipsec_esp_auth VNET(ipsec_esp_auth)
449 #define V_ipsec_ah_keymin VNET(ipsec_ah_keymin)
452 VNET_DEFINE(int, ipsec_debug) = 1;
454 VNET_DEFINE(int, ipsec_debug) = 0;
458 SYSCTL_DECL(_net_inet_ipsec);
459 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEBUG, debug,
460 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_debug), 0,
461 "Enable IPsec debugging output when set.");
464 SYSCTL_DECL(_net_inet6_ipsec6);
465 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEBUG, debug,
466 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_debug), 0,
467 "Enable IPsec debugging output when set.");
470 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL, debug,
471 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_debug_level), 0, "");
473 /* max count of trial for the decision of spi value */
474 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt,
475 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_trycnt), 0, "");
477 /* minimum spi value to allocate automatically. */
478 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE, spi_minval,
479 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_minval), 0, "");
481 /* maximun spi value to allocate automatically. */
482 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE, spi_maxval,
483 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_maxval), 0, "");
485 /* interval to initialize randseed */
486 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random,
487 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_int_random), 0, "");
489 /* lifetime for larval SA */
490 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME, larval_lifetime,
491 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_larval_lifetime), 0, "");
493 /* counter for blocking to send SADB_ACQUIRE to IKEd */
494 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT, blockacq_count,
495 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_blockacq_count), 0, "");
497 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
498 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME, blockacq_lifetime,
499 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_blockacq_lifetime), 0, "");
502 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH, esp_auth,
503 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_esp_auth), 0, "");
505 /* minimum ESP key length */
506 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin,
507 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_esp_keymin), 0, "");
509 /* minimum AH key length */
510 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN, ah_keymin,
511 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_ah_keymin), 0, "");
513 /* perfered old SA rather than new SA */
514 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA, preferred_oldsa,
515 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_preferred_oldsa), 0, "");
517 SYSCTL_NODE(_net_key, OID_AUTO, spdcache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
520 SYSCTL_UINT(_net_key_spdcache, OID_AUTO, maxentries,
521 CTLFLAG_VNET | CTLFLAG_RDTUN, &VNET_NAME(key_spdcache_maxentries), 0,
522 "Maximum number of entries in the SPD cache"
523 " (power of 2, 0 to disable)");
525 SYSCTL_UINT(_net_key_spdcache, OID_AUTO, threshold,
526 CTLFLAG_VNET | CTLFLAG_RDTUN, &VNET_NAME(key_spdcache_threshold), 0,
527 "Number of SPs that make the SPD cache active");
529 #define __LIST_CHAINED(elm) \
530 (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
532 MALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
533 MALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
534 MALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
535 MALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
536 MALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
537 MALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
538 MALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
539 MALLOC_DEFINE(M_IPSEC_SPDCACHE, "ipsec-spdcache", "ipsec SPD cache");
541 static uma_zone_t __read_mostly ipsec_key_lft_zone;
544 * set parameters into secpolicyindex buffer.
545 * Must allocate secpolicyindex buffer passed to this function.
547 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
549 bzero((idx), sizeof(struct secpolicyindex)); \
550 (idx)->dir = (_dir); \
551 (idx)->prefs = (ps); \
552 (idx)->prefd = (pd); \
553 (idx)->ul_proto = (ulp); \
554 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
555 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
559 * set parameters into secasindex buffer.
560 * Must allocate secasindex buffer before calling this function.
562 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
564 bzero((idx), sizeof(struct secasindex)); \
565 (idx)->proto = (p); \
567 (idx)->reqid = (r); \
568 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
569 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
570 key_porttosaddr(&(idx)->src.sa, 0); \
571 key_porttosaddr(&(idx)->dst.sa, 0); \
576 u_long getspi_count; /* the avarage of count to try to get new SPI */
580 struct sadb_msg *msg;
581 struct sadb_ext *ext[SADB_EXT_MAX + 1];
582 int extoff[SADB_EXT_MAX + 1];
583 int extlen[SADB_EXT_MAX + 1];
586 static struct supported_ealgs {
588 const struct enc_xform *xform;
589 } supported_ealgs[] = {
590 { SADB_X_EALG_AES, &enc_xform_aes_cbc },
591 { SADB_EALG_NULL, &enc_xform_null },
592 { SADB_X_EALG_AESCTR, &enc_xform_aes_icm },
593 { SADB_X_EALG_AESGCM16, &enc_xform_aes_nist_gcm },
594 { SADB_X_EALG_AESGMAC, &enc_xform_aes_nist_gmac },
595 { SADB_X_EALG_CHACHA20POLY1305, &enc_xform_chacha20_poly1305 },
598 static struct supported_aalgs {
600 const struct auth_hash *xform;
601 } supported_aalgs[] = {
602 { SADB_X_AALG_NULL, &auth_hash_null },
603 { SADB_AALG_SHA1HMAC, &auth_hash_hmac_sha1 },
604 { SADB_X_AALG_SHA2_256, &auth_hash_hmac_sha2_256 },
605 { SADB_X_AALG_SHA2_384, &auth_hash_hmac_sha2_384 },
606 { SADB_X_AALG_SHA2_512, &auth_hash_hmac_sha2_512 },
607 { SADB_X_AALG_AES128GMAC, &auth_hash_nist_gmac_aes_128 },
608 { SADB_X_AALG_AES192GMAC, &auth_hash_nist_gmac_aes_192 },
609 { SADB_X_AALG_AES256GMAC, &auth_hash_nist_gmac_aes_256 },
610 { SADB_X_AALG_CHACHA20POLY1305, &auth_hash_poly1305 },
613 static struct supported_calgs {
615 const struct comp_algo *xform;
616 } supported_calgs[] = {
617 { SADB_X_CALG_DEFLATE, &comp_algo_deflate },
621 static struct callout key_timer;
624 static void key_unlink(struct secpolicy *);
625 static void key_detach(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 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
810 ("invalid direction %u", dir));
811 return (TAILQ_FIRST(&V_sptree[dir]) != NULL);
818 return (V_spd_size != 0);
822 * Allocate a single mbuf with a buffer of the desired length. The buffer is
823 * pre-zeroed to help ensure that uninitialized pad bytes are not leaked.
830 KASSERT(len <= MCLBYTES,
831 ("%s: invalid buffer length %u", __func__, len));
833 m = m_get2(len, M_NOWAIT, MT_DATA, M_PKTHDR);
836 memset(mtod(m, void *), 0, len);
840 /* %%% IPsec policy management */
842 * Return current SPDB generation.
859 key_checksockaddrs(struct sockaddr *src, struct sockaddr *dst)
863 if (src->sa_family != dst->sa_family)
866 if (src->sa_len != dst->sa_len)
868 switch (src->sa_family) {
871 if (src->sa_len != sizeof(struct sockaddr_in))
877 if (src->sa_len != sizeof(struct sockaddr_in6))
882 return (EAFNOSUPPORT);
888 key_do_allocsp(struct secpolicyindex *spidx, u_int dir)
890 SPTREE_RLOCK_TRACKER;
891 struct secpolicy *sp;
893 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
894 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
895 ("invalid direction %u", dir));
898 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
899 if (key_cmpspidx_withmask(&sp->spidx, spidx)) {
909 * allocating a SP for OUTBOUND or INBOUND packet.
910 * Must call key_freesp() later.
911 * OUT: NULL: not found
912 * others: found and return the pointer.
915 key_allocsp(struct secpolicyindex *spidx, u_int dir)
917 struct spdcache_entry *entry, *lastentry, *tmpentry;
918 struct secpolicy *sp;
923 if (!SPDCACHE_ACTIVE()) {
924 sp = key_do_allocsp(spidx, dir);
928 hashv = SPDCACHE_HASHVAL(spidx);
929 SPDCACHE_LOCK(hashv);
931 LIST_FOREACH_SAFE(entry, &V_spdcachehashtbl[hashv], chain, tmpentry) {
932 /* Removed outdated entries */
933 if (entry->sp != NULL &&
934 entry->sp->state == IPSEC_SPSTATE_DEAD) {
935 LIST_REMOVE(entry, chain);
936 spdcache_entry_free(entry);
941 if (!key_cmpspidx_exactly(&entry->spidx, spidx)) {
947 if (entry->sp != NULL)
950 /* IPSECSTAT_INC(ips_spdcache_hits); */
952 SPDCACHE_UNLOCK(hashv);
956 /* IPSECSTAT_INC(ips_spdcache_misses); */
958 sp = key_do_allocsp(spidx, dir);
959 entry = spdcache_entry_alloc(spidx, sp);
961 if (nb_entries >= SPDCACHE_MAX_ENTRIES_PER_HASH) {
962 LIST_REMOVE(lastentry, chain);
963 spdcache_entry_free(lastentry);
966 LIST_INSERT_HEAD(&V_spdcachehashtbl[hashv], entry, chain);
969 SPDCACHE_UNLOCK(hashv);
972 if (sp != NULL) { /* found a SPD entry */
974 if (__predict_false(sp->lastused != ts))
977 printf("%s: return SP(%p)\n", __func__, sp));
978 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
981 printf("%s: lookup failed for ", __func__);
982 kdebug_secpolicyindex(spidx, NULL));
988 * Allocating an SA entry for an *INBOUND* or *OUTBOUND* TCP packet, signed
989 * or should be signed by MD5 signature.
990 * We don't use key_allocsa() for such lookups, because we don't know SPI.
991 * Unlike ESP and AH protocols, SPI isn't transmitted in the TCP header with
992 * signed packet. We use SADB only as storage for password.
993 * OUT: positive: corresponding SA for given saidx found.
997 key_allocsa_tcpmd5(struct secasindex *saidx)
999 SAHTREE_RLOCK_TRACKER;
1000 struct secashead *sah;
1001 struct secasvar *sav;
1003 IPSEC_ASSERT(saidx->proto == IPPROTO_TCP,
1004 ("unexpected security protocol %u", saidx->proto));
1005 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TCPMD5,
1006 ("unexpected mode %u", saidx->mode));
1009 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
1011 printf("%s: checking SAH\n", __func__);
1012 kdebug_secash(sah, " "));
1013 if (sah->saidx.proto != IPPROTO_TCP)
1015 if (!key_sockaddrcmp(&saidx->dst.sa, &sah->saidx.dst.sa, 0) &&
1016 !key_sockaddrcmp(&saidx->src.sa, &sah->saidx.src.sa, 0))
1020 if (V_key_preferred_oldsa)
1021 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
1023 sav = TAILQ_FIRST(&sah->savtree_alive);
1032 printf("%s: return SA(%p)\n", __func__, sav));
1033 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1036 printf("%s: SA not found\n", __func__));
1037 KEYDBG(IPSEC_DATA, kdebug_secasindex(saidx, NULL));
1043 * Allocating an SA entry for an *OUTBOUND* packet.
1044 * OUT: positive: corresponding SA for given saidx found.
1045 * NULL: SA not found, but will be acquired, check *error
1046 * for acquiring status.
1049 key_allocsa_policy(struct secpolicy *sp, const struct secasindex *saidx,
1052 SAHTREE_RLOCK_TRACKER;
1053 struct secashead *sah;
1054 struct secasvar *sav;
1056 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
1057 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
1058 saidx->mode == IPSEC_MODE_TUNNEL,
1059 ("unexpected policy %u", saidx->mode));
1062 * We check new SA in the IPsec request because a different
1063 * SA may be involved each time this request is checked, either
1064 * because new SAs are being configured, or this request is
1065 * associated with an unconnected datagram socket, or this request
1066 * is associated with a system default policy.
1069 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
1071 printf("%s: checking SAH\n", __func__);
1072 kdebug_secash(sah, " "));
1073 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID))
1078 * Allocate the oldest SA available according to
1079 * draft-jenkins-ipsec-rekeying-03.
1081 if (V_key_preferred_oldsa)
1082 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
1084 sav = TAILQ_FIRST(&sah->savtree_alive);
1094 printf("%s: chosen SA(%p) for SP(%p)\n", __func__,
1096 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1097 return (sav); /* return referenced SA */
1100 /* there is no SA */
1101 *error = key_acquire(saidx, sp);
1103 ipseclog((LOG_DEBUG,
1104 "%s: error %d returned from key_acquire()\n",
1107 printf("%s: acquire SA for SP(%p), error %d\n",
1108 __func__, sp, *error));
1109 KEYDBG(IPSEC_DATA, kdebug_secasindex(saidx, NULL));
1114 * allocating a usable SA entry for a *INBOUND* packet.
1115 * Must call key_freesav() later.
1116 * OUT: positive: pointer to a usable sav (i.e. MATURE or DYING state).
1117 * NULL: not found, or error occurred.
1119 * According to RFC 2401 SA is uniquely identified by a triple SPI,
1120 * destination address, and security protocol. But according to RFC 4301,
1121 * SPI by itself suffices to specify an SA.
1123 * Note that, however, we do need to keep source address in IPsec SA.
1124 * IKE specification and PF_KEY specification do assume that we
1125 * keep source address in IPsec SA. We see a tricky situation here.
1128 key_allocsa(union sockaddr_union *dst, uint8_t proto, uint32_t spi)
1130 SAHTREE_RLOCK_TRACKER;
1131 struct secasvar *sav;
1133 IPSEC_ASSERT(proto == IPPROTO_ESP || proto == IPPROTO_AH ||
1134 proto == IPPROTO_IPCOMP, ("unexpected security protocol %u",
1138 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
1139 if (sav->spi == spi)
1143 * We use single SPI namespace for all protocols, so it is
1144 * impossible to have SPI duplicates in the SAVHASH.
1147 if (sav->state != SADB_SASTATE_LARVAL &&
1148 sav->sah->saidx.proto == proto &&
1149 key_sockaddrcmp(&dst->sa,
1150 &sav->sah->saidx.dst.sa, 0) == 0)
1159 char buf[IPSEC_ADDRSTRLEN];
1160 printf("%s: SA not found for spi %u proto %u dst %s\n",
1161 __func__, ntohl(spi), proto, ipsec_address(dst, buf,
1165 printf("%s: return SA(%p)\n", __func__, sav));
1166 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1172 key_allocsa_tunnel(union sockaddr_union *src, union sockaddr_union *dst,
1175 SAHTREE_RLOCK_TRACKER;
1176 struct secasindex saidx;
1177 struct secashead *sah;
1178 struct secasvar *sav;
1180 IPSEC_ASSERT(src != NULL, ("null src address"));
1181 IPSEC_ASSERT(dst != NULL, ("null dst address"));
1183 KEY_SETSECASIDX(proto, IPSEC_MODE_TUNNEL, 0, &src->sa,
1188 LIST_FOREACH(sah, SAHADDRHASH_HASH(&saidx), addrhash) {
1189 if (IPSEC_MODE_TUNNEL != sah->saidx.mode)
1191 if (proto != sah->saidx.proto)
1193 if (key_sockaddrcmp(&src->sa, &sah->saidx.src.sa, 0) != 0)
1195 if (key_sockaddrcmp(&dst->sa, &sah->saidx.dst.sa, 0) != 0)
1197 /* XXXAE: is key_preferred_oldsa reasonably?*/
1198 if (V_key_preferred_oldsa)
1199 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
1201 sav = TAILQ_FIRST(&sah->savtree_alive);
1209 printf("%s: return SA(%p)\n", __func__, sav));
1211 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1216 * Must be called after calling key_allocsp().
1219 key_freesp(struct secpolicy **spp)
1221 struct secpolicy *sp = *spp;
1223 IPSEC_ASSERT(sp != NULL, ("null sp"));
1224 if (SP_DELREF(sp) == 0)
1228 printf("%s: last reference to SP(%p)\n", __func__, sp));
1229 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1232 while (sp->tcount > 0)
1233 ipsec_delisr(sp->req[--sp->tcount]);
1234 free(sp, M_IPSEC_SP);
1238 key_unlink(struct secpolicy *sp)
1243 if (SPDCACHE_ENABLED())
1249 key_detach(struct secpolicy *sp)
1251 IPSEC_ASSERT(sp->spidx.dir == IPSEC_DIR_INBOUND ||
1252 sp->spidx.dir == IPSEC_DIR_OUTBOUND,
1253 ("invalid direction %u", sp->spidx.dir));
1254 SPTREE_WLOCK_ASSERT();
1257 printf("%s: SP(%p)\n", __func__, sp));
1258 if (sp->state != IPSEC_SPSTATE_ALIVE) {
1259 /* SP is already unlinked */
1262 sp->state = IPSEC_SPSTATE_DEAD;
1263 TAILQ_REMOVE(&V_sptree[sp->spidx.dir], sp, chain);
1265 LIST_REMOVE(sp, idhash);
1270 * insert a secpolicy into the SP database. Lower priorities first
1273 key_insertsp(struct secpolicy *newsp)
1275 struct secpolicy *sp;
1277 SPTREE_WLOCK_ASSERT();
1278 TAILQ_FOREACH(sp, &V_sptree[newsp->spidx.dir], chain) {
1279 if (newsp->priority < sp->priority) {
1280 TAILQ_INSERT_BEFORE(sp, newsp, chain);
1284 TAILQ_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, chain);
1286 LIST_INSERT_HEAD(SPHASH_HASH(newsp->id), newsp, idhash);
1287 newsp->state = IPSEC_SPSTATE_ALIVE;
1293 * Insert a bunch of VTI secpolicies into the SPDB.
1294 * We keep VTI policies in the separate list due to following reasons:
1295 * 1) they should be immutable to user's or some deamon's attempts to
1296 * delete. The only way delete such policies - destroy or unconfigure
1297 * corresponding virtual inteface.
1298 * 2) such policies have traffic selector that matches all traffic per
1300 * Since all VTI policies have the same priority, we don't care about
1304 key_register_ifnet(struct secpolicy **spp, u_int count)
1311 * First of try to acquire id for each SP.
1313 for (i = 0; i < count; i++) {
1314 IPSEC_ASSERT(spp[i]->spidx.dir == IPSEC_DIR_INBOUND ||
1315 spp[i]->spidx.dir == IPSEC_DIR_OUTBOUND,
1316 ("invalid direction %u", spp[i]->spidx.dir));
1318 if ((spp[i]->id = key_getnewspid()) == 0) {
1323 for (i = 0; i < count; i++) {
1324 TAILQ_INSERT_TAIL(&V_sptree_ifnet[spp[i]->spidx.dir],
1327 * NOTE: despite the fact that we keep VTI SP in the
1328 * separate list, SPHASH contains policies from both
1329 * sources. Thus SADB_X_SPDGET will correctly return
1330 * SP by id, because it uses SPHASH for lookups.
1332 LIST_INSERT_HEAD(SPHASH_HASH(spp[i]->id), spp[i], idhash);
1333 spp[i]->state = IPSEC_SPSTATE_IFNET;
1337 * Notify user processes about new SP.
1339 for (i = 0; i < count; i++) {
1340 m = key_setdumpsp(spp[i], SADB_X_SPDADD, 0, 0);
1342 key_sendup_mbuf(NULL, m, KEY_SENDUP_ALL);
1348 key_unregister_ifnet(struct secpolicy **spp, u_int count)
1354 for (i = 0; i < count; i++) {
1355 IPSEC_ASSERT(spp[i]->spidx.dir == IPSEC_DIR_INBOUND ||
1356 spp[i]->spidx.dir == IPSEC_DIR_OUTBOUND,
1357 ("invalid direction %u", spp[i]->spidx.dir));
1359 if (spp[i]->state != IPSEC_SPSTATE_IFNET)
1361 spp[i]->state = IPSEC_SPSTATE_DEAD;
1362 TAILQ_REMOVE(&V_sptree_ifnet[spp[i]->spidx.dir],
1365 LIST_REMOVE(spp[i], idhash);
1368 if (SPDCACHE_ENABLED())
1371 for (i = 0; i < count; i++) {
1372 m = key_setdumpsp(spp[i], SADB_X_SPDDELETE, 0, 0);
1374 key_sendup_mbuf(NULL, m, KEY_SENDUP_ALL);
1379 * Must be called after calling key_allocsa().
1380 * This function is called by key_freesp() to free some SA allocated
1384 key_freesav(struct secasvar **psav)
1386 struct secasvar *sav = *psav;
1388 IPSEC_ASSERT(sav != NULL, ("null sav"));
1389 CURVNET_ASSERT_SET();
1390 if (SAV_DELREF(sav) == 0)
1394 printf("%s: last reference to SA(%p)\n", __func__, sav));
1401 * Unlink SA from SAH and SPI hash under SAHTREE_WLOCK.
1402 * Expect that SA has extra reference due to lookup.
1403 * Release this references, also release SAH reference after unlink.
1406 key_unlinksav(struct secasvar *sav)
1408 struct secashead *sah;
1411 printf("%s: SA(%p)\n", __func__, sav));
1413 CURVNET_ASSERT_SET();
1414 SAHTREE_UNLOCK_ASSERT();
1416 if (sav->state == SADB_SASTATE_DEAD) {
1417 /* SA is already unlinked */
1421 /* Unlink from SAH */
1422 if (sav->state == SADB_SASTATE_LARVAL)
1423 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
1425 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
1426 /* Unlink from SPI hash */
1427 LIST_REMOVE(sav, spihash);
1428 sav->state = SADB_SASTATE_DEAD;
1432 /* Since we are unlinked, release reference to SAH */
1436 /* %%% SPD management */
1439 * OUT: NULL : not found
1440 * others : found, pointer to a SP.
1442 static struct secpolicy *
1443 key_getsp(struct secpolicyindex *spidx)
1445 SPTREE_RLOCK_TRACKER;
1446 struct secpolicy *sp;
1448 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1451 TAILQ_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1452 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1464 * OUT: NULL : not found
1465 * others : found, pointer to referenced SP.
1467 static struct secpolicy *
1468 key_getspbyid(uint32_t id)
1470 SPTREE_RLOCK_TRACKER;
1471 struct secpolicy *sp;
1474 LIST_FOREACH(sp, SPHASH_HASH(id), idhash) {
1487 struct secpolicy *sp;
1489 sp = malloc(sizeof(*sp), M_IPSEC_SP, M_NOWAIT | M_ZERO);
1495 struct ipsecrequest *
1499 return (malloc(sizeof(struct ipsecrequest), M_IPSEC_SR,
1500 M_NOWAIT | M_ZERO));
1504 ipsec_delisr(struct ipsecrequest *p)
1507 free(p, M_IPSEC_SR);
1511 * create secpolicy structure from sadb_x_policy structure.
1512 * NOTE: `state', `secpolicyindex' and 'id' in secpolicy structure
1513 * are not set, so must be set properly later.
1516 key_msg2sp(struct sadb_x_policy *xpl0, size_t len, int *error)
1518 struct secpolicy *newsp;
1520 IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1521 IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1523 if (len != PFKEY_EXTLEN(xpl0)) {
1524 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1529 if ((newsp = key_newsp()) == NULL) {
1534 newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1535 newsp->policy = xpl0->sadb_x_policy_type;
1536 newsp->priority = xpl0->sadb_x_policy_priority;
1540 switch (xpl0->sadb_x_policy_type) {
1541 case IPSEC_POLICY_DISCARD:
1542 case IPSEC_POLICY_NONE:
1543 case IPSEC_POLICY_ENTRUST:
1544 case IPSEC_POLICY_BYPASS:
1547 case IPSEC_POLICY_IPSEC:
1549 struct sadb_x_ipsecrequest *xisr;
1550 struct ipsecrequest *isr;
1553 /* validity check */
1554 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1555 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1562 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1563 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1567 if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr) ||
1568 xisr->sadb_x_ipsecrequest_len > tlen) {
1569 ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1570 "length.\n", __func__));
1576 if (newsp->tcount >= IPSEC_MAXREQ) {
1577 ipseclog((LOG_DEBUG,
1578 "%s: too many ipsecrequests.\n",
1585 /* allocate request buffer */
1586 /* NB: data structure is zero'd */
1587 isr = ipsec_newisr();
1589 ipseclog((LOG_DEBUG,
1590 "%s: No more memory.\n", __func__));
1596 newsp->req[newsp->tcount++] = isr;
1599 switch (xisr->sadb_x_ipsecrequest_proto) {
1602 case IPPROTO_IPCOMP:
1605 ipseclog((LOG_DEBUG,
1606 "%s: invalid proto type=%u\n", __func__,
1607 xisr->sadb_x_ipsecrequest_proto));
1609 *error = EPROTONOSUPPORT;
1613 (uint8_t)xisr->sadb_x_ipsecrequest_proto;
1615 switch (xisr->sadb_x_ipsecrequest_mode) {
1616 case IPSEC_MODE_TRANSPORT:
1617 case IPSEC_MODE_TUNNEL:
1619 case IPSEC_MODE_ANY:
1621 ipseclog((LOG_DEBUG,
1622 "%s: invalid mode=%u\n", __func__,
1623 xisr->sadb_x_ipsecrequest_mode));
1628 isr->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1630 switch (xisr->sadb_x_ipsecrequest_level) {
1631 case IPSEC_LEVEL_DEFAULT:
1632 case IPSEC_LEVEL_USE:
1633 case IPSEC_LEVEL_REQUIRE:
1635 case IPSEC_LEVEL_UNIQUE:
1636 /* validity check */
1638 * If range violation of reqid, kernel will
1639 * update it, don't refuse it.
1641 if (xisr->sadb_x_ipsecrequest_reqid
1642 > IPSEC_MANUAL_REQID_MAX) {
1643 ipseclog((LOG_DEBUG,
1644 "%s: reqid=%d range "
1645 "violation, updated by kernel.\n",
1647 xisr->sadb_x_ipsecrequest_reqid));
1648 xisr->sadb_x_ipsecrequest_reqid = 0;
1651 /* allocate new reqid id if reqid is zero. */
1652 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1654 if ((reqid = key_newreqid()) == 0) {
1659 isr->saidx.reqid = reqid;
1660 xisr->sadb_x_ipsecrequest_reqid = reqid;
1662 /* set it for manual keying. */
1664 xisr->sadb_x_ipsecrequest_reqid;
1669 ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1671 xisr->sadb_x_ipsecrequest_level));
1676 isr->level = xisr->sadb_x_ipsecrequest_level;
1678 /* set IP addresses if there */
1679 if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1680 struct sockaddr *paddr;
1682 len = tlen - sizeof(*xisr);
1683 paddr = (struct sockaddr *)(xisr + 1);
1684 /* validity check */
1685 if (len < sizeof(struct sockaddr) ||
1686 len < 2 * paddr->sa_len ||
1687 paddr->sa_len > sizeof(isr->saidx.src)) {
1688 ipseclog((LOG_DEBUG, "%s: invalid "
1689 "request address length.\n",
1696 * Request length should be enough to keep
1697 * source and destination addresses.
1699 if (xisr->sadb_x_ipsecrequest_len <
1700 sizeof(*xisr) + 2 * paddr->sa_len) {
1701 ipseclog((LOG_DEBUG, "%s: invalid "
1702 "ipsecrequest length.\n",
1708 bcopy(paddr, &isr->saidx.src, paddr->sa_len);
1709 paddr = (struct sockaddr *)((caddr_t)paddr +
1712 /* validity check */
1713 if (paddr->sa_len !=
1714 isr->saidx.src.sa.sa_len) {
1715 ipseclog((LOG_DEBUG, "%s: invalid "
1716 "request address length.\n",
1722 /* AF family should match */
1723 if (paddr->sa_family !=
1724 isr->saidx.src.sa.sa_family) {
1725 ipseclog((LOG_DEBUG, "%s: address "
1726 "family doesn't match.\n",
1732 bcopy(paddr, &isr->saidx.dst, paddr->sa_len);
1735 * Addresses for TUNNEL mode requests are
1738 if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
1739 ipseclog((LOG_DEBUG, "%s: missing "
1740 "request addresses.\n", __func__));
1746 tlen -= xisr->sadb_x_ipsecrequest_len;
1748 /* validity check */
1750 ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1757 xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1758 + xisr->sadb_x_ipsecrequest_len);
1760 /* XXXAE: LARVAL SP */
1761 if (newsp->tcount < 1) {
1762 ipseclog((LOG_DEBUG, "%s: valid IPSEC transforms "
1763 "not found.\n", __func__));
1771 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1784 static uint32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1786 if (auto_reqid == ~0)
1787 auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1791 /* XXX should be unique check */
1792 return (auto_reqid);
1796 * copy secpolicy struct to sadb_x_policy structure indicated.
1798 static struct mbuf *
1799 key_sp2mbuf(struct secpolicy *sp)
1804 tlen = key_getspreqmsglen(sp);
1805 m = m_get2(tlen, M_NOWAIT, MT_DATA, 0);
1810 if (key_sp2msg(sp, m->m_data, &tlen) != 0) {
1818 key_sp2msg(struct secpolicy *sp, void *request, size_t *len)
1820 struct sadb_x_ipsecrequest *xisr;
1821 struct sadb_x_policy *xpl;
1822 struct ipsecrequest *isr;
1827 IPSEC_ASSERT(sp != NULL, ("null policy"));
1829 xlen = sizeof(*xpl);
1834 bzero(request, *len);
1835 xpl = (struct sadb_x_policy *)request;
1836 xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1837 xpl->sadb_x_policy_type = sp->policy;
1838 xpl->sadb_x_policy_dir = sp->spidx.dir;
1839 xpl->sadb_x_policy_id = sp->id;
1840 xpl->sadb_x_policy_priority = sp->priority;
1841 switch (sp->state) {
1842 case IPSEC_SPSTATE_IFNET:
1843 xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_IFNET;
1845 case IPSEC_SPSTATE_PCB:
1846 xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_PCB;
1849 xpl->sadb_x_policy_scope = IPSEC_POLICYSCOPE_GLOBAL;
1852 /* if is the policy for ipsec ? */
1853 if (sp->policy == IPSEC_POLICY_IPSEC) {
1854 p = (caddr_t)xpl + sizeof(*xpl);
1855 for (i = 0; i < sp->tcount; i++) {
1857 ilen = PFKEY_ALIGN8(sizeof(*xisr) +
1858 isr->saidx.src.sa.sa_len +
1859 isr->saidx.dst.sa.sa_len);
1863 /* Calculate needed size */
1866 xisr = (struct sadb_x_ipsecrequest *)p;
1867 xisr->sadb_x_ipsecrequest_len = ilen;
1868 xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1869 xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1870 xisr->sadb_x_ipsecrequest_level = isr->level;
1871 xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1874 bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1875 p += isr->saidx.src.sa.sa_len;
1876 bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1877 p += isr->saidx.dst.sa.sa_len;
1880 xpl->sadb_x_policy_len = PFKEY_UNIT64(xlen);
1884 *len = sizeof(*xpl);
1888 /* m will not be freed nor modified */
1889 static struct mbuf *
1890 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1891 int ndeep, int nitem, ...)
1896 struct mbuf *result = NULL, *n;
1899 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1900 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1902 va_start(ap, nitem);
1903 for (i = 0; i < nitem; i++) {
1904 idx = va_arg(ap, int);
1905 if (idx < 0 || idx > SADB_EXT_MAX)
1907 /* don't attempt to pull empty extension */
1908 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1910 if (idx != SADB_EXT_RESERVED &&
1911 (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1914 if (idx == SADB_EXT_RESERVED) {
1915 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1917 IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1919 MGETHDR(n, M_NOWAIT, MT_DATA);
1924 m_copydata(m, 0, sizeof(struct sadb_msg),
1926 } else if (i < ndeep) {
1927 len = mhp->extlen[idx];
1928 n = m_get2(len, M_NOWAIT, MT_DATA, 0);
1933 m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1936 n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1949 if ((result->m_flags & M_PKTHDR) != 0) {
1950 result->m_pkthdr.len = 0;
1951 for (n = result; n; n = n->m_next)
1952 result->m_pkthdr.len += n->m_len;
1964 * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1965 * add an entry to SP database, when received
1966 * <base, address(SD), (lifetime(H),) policy>
1968 * Adding to SP database,
1970 * <base, address(SD), (lifetime(H),) policy>
1971 * to the socket which was send.
1973 * SPDADD set a unique policy entry.
1974 * SPDSETIDX like SPDADD without a part of policy requests.
1975 * SPDUPDATE replace a unique policy entry.
1977 * XXXAE: serialize this in PF_KEY to avoid races.
1978 * m will always be freed.
1981 key_spdadd(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
1983 struct secpolicyindex spidx;
1984 struct sadb_address *src0, *dst0;
1985 struct sadb_x_policy *xpl0, *xpl;
1986 struct sadb_lifetime *lft = NULL;
1987 struct secpolicy *newsp, *oldsp;
1990 IPSEC_ASSERT(so != NULL, ("null socket"));
1991 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1992 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1993 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1995 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
1996 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
1997 SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY)) {
1998 ipseclog((LOG_DEBUG,
1999 "%s: invalid message: missing required header.\n",
2001 return key_senderror(so, m, EINVAL);
2003 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
2004 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
2005 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2006 ipseclog((LOG_DEBUG,
2007 "%s: invalid message: wrong header size.\n", __func__));
2008 return key_senderror(so, m, EINVAL);
2010 if (!SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD)) {
2011 if (SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_HARD)) {
2012 ipseclog((LOG_DEBUG,
2013 "%s: invalid message: wrong header size.\n",
2015 return key_senderror(so, m, EINVAL);
2017 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
2020 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2021 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2022 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2024 /* check the direciton */
2025 switch (xpl0->sadb_x_policy_dir) {
2026 case IPSEC_DIR_INBOUND:
2027 case IPSEC_DIR_OUTBOUND:
2030 ipseclog((LOG_DEBUG, "%s: invalid SP direction.\n", __func__));
2031 return key_senderror(so, m, EINVAL);
2033 /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
2034 if (xpl0->sadb_x_policy_type != IPSEC_POLICY_DISCARD &&
2035 xpl0->sadb_x_policy_type != IPSEC_POLICY_NONE &&
2036 xpl0->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
2037 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
2038 return key_senderror(so, m, EINVAL);
2041 /* policy requests are mandatory when action is ipsec. */
2042 if (xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
2043 mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
2044 ipseclog((LOG_DEBUG,
2045 "%s: policy requests required.\n", __func__));
2046 return key_senderror(so, m, EINVAL);
2049 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
2050 (struct sockaddr *)(dst0 + 1));
2052 src0->sadb_address_proto != dst0->sadb_address_proto) {
2053 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
2054 return key_senderror(so, m, error);
2057 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2060 src0->sadb_address_prefixlen,
2061 dst0->sadb_address_prefixlen,
2062 src0->sadb_address_proto,
2064 /* Checking there is SP already or not. */
2065 oldsp = key_getsp(&spidx);
2066 if (oldsp != NULL) {
2067 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
2069 printf("%s: unlink SP(%p) for SPDUPDATE\n",
2071 KEYDBG(KEY_DATA, kdebug_secpolicy(oldsp));
2074 ipseclog((LOG_DEBUG,
2075 "%s: a SP entry exists already.\n", __func__));
2076 return (key_senderror(so, m, EEXIST));
2080 /* allocate new SP entry */
2081 if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
2082 if (oldsp != NULL) {
2084 key_freesp(&oldsp); /* second for our reference */
2086 return key_senderror(so, m, error);
2089 newsp->lastused = newsp->created = time_second;
2090 newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
2091 newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
2092 bcopy(&spidx, &newsp->spidx, sizeof(spidx));
2095 if ((newsp->id = key_getnewspid()) == 0) {
2099 if (oldsp != NULL) {
2100 key_freesp(&oldsp); /* first for key_detach */
2101 IPSEC_ASSERT(oldsp != NULL, ("null oldsp: refcount bug"));
2102 key_freesp(&oldsp); /* second for our reference */
2103 if (SPDCACHE_ENABLED()) /* refresh cache because of key_detach */
2107 return key_senderror(so, m, ENOBUFS);
2111 key_insertsp(newsp);
2113 if (oldsp != NULL) {
2114 key_freesp(&oldsp); /* first for key_detach */
2115 IPSEC_ASSERT(oldsp != NULL, ("null oldsp: refcount bug"));
2116 key_freesp(&oldsp); /* second for our reference */
2118 if (SPDCACHE_ENABLED())
2121 printf("%s: SP(%p)\n", __func__, newsp));
2122 KEYDBG(KEY_DATA, kdebug_secpolicy(newsp));
2125 struct mbuf *n, *mpolicy;
2126 struct sadb_msg *newmsg;
2129 /* create new sadb_msg to reply. */
2131 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
2132 SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
2133 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2135 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
2137 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2140 return key_senderror(so, m, ENOBUFS);
2142 if (n->m_len < sizeof(*newmsg)) {
2143 n = m_pullup(n, sizeof(*newmsg));
2145 return key_senderror(so, m, ENOBUFS);
2147 newmsg = mtod(n, struct sadb_msg *);
2148 newmsg->sadb_msg_errno = 0;
2149 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2152 mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
2153 sizeof(*xpl), &off);
2154 if (mpolicy == NULL) {
2155 /* n is already freed */
2156 return key_senderror(so, m, ENOBUFS);
2158 xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
2159 if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
2161 return key_senderror(so, m, EINVAL);
2163 xpl->sadb_x_policy_id = newsp->id;
2166 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2171 * get new policy id.
2177 key_getnewspid(void)
2179 struct secpolicy *sp;
2183 SPTREE_WLOCK_ASSERT();
2185 limit = atomic_load_int(&V_key_spi_trycnt);
2186 for (tries = 0; tries < limit; tries++) {
2187 if (V_policy_id == ~0) /* overflowed */
2188 newid = V_policy_id = 1;
2190 newid = ++V_policy_id;
2191 LIST_FOREACH(sp, SPHASH_HASH(newid), idhash) {
2192 if (sp->id == newid)
2198 if (tries == limit || newid == 0) {
2199 ipseclog((LOG_DEBUG, "%s: failed to allocate policy id.\n",
2207 * SADB_SPDDELETE processing
2209 * <base, address(SD), policy(*)>
2210 * from the user(?), and set SADB_SASTATE_DEAD,
2212 * <base, address(SD), policy(*)>
2214 * policy(*) including direction of policy.
2216 * m will always be freed.
2219 key_spddelete(struct socket *so, struct mbuf *m,
2220 const struct sadb_msghdr *mhp)
2222 struct secpolicyindex spidx;
2223 struct sadb_address *src0, *dst0;
2224 struct sadb_x_policy *xpl0;
2225 struct secpolicy *sp;
2227 IPSEC_ASSERT(so != NULL, ("null so"));
2228 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2229 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2230 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2232 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
2233 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
2234 SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY)) {
2235 ipseclog((LOG_DEBUG,
2236 "%s: invalid message: missing required header.\n",
2238 return key_senderror(so, m, EINVAL);
2240 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
2241 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
2242 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2243 ipseclog((LOG_DEBUG,
2244 "%s: invalid message: wrong header size.\n", __func__));
2245 return key_senderror(so, m, EINVAL);
2248 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2249 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2250 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2252 /* check the direciton */
2253 switch (xpl0->sadb_x_policy_dir) {
2254 case IPSEC_DIR_INBOUND:
2255 case IPSEC_DIR_OUTBOUND:
2258 ipseclog((LOG_DEBUG, "%s: invalid SP direction.\n", __func__));
2259 return key_senderror(so, m, EINVAL);
2261 /* Only DISCARD, NONE and IPSEC are allowed */
2262 if (xpl0->sadb_x_policy_type != IPSEC_POLICY_DISCARD &&
2263 xpl0->sadb_x_policy_type != IPSEC_POLICY_NONE &&
2264 xpl0->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
2265 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
2266 return key_senderror(so, m, EINVAL);
2268 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
2269 (struct sockaddr *)(dst0 + 1)) != 0 ||
2270 src0->sadb_address_proto != dst0->sadb_address_proto) {
2271 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
2272 return key_senderror(so, m, EINVAL);
2275 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2278 src0->sadb_address_prefixlen,
2279 dst0->sadb_address_prefixlen,
2280 src0->sadb_address_proto,
2283 /* Is there SP in SPD ? */
2284 if ((sp = key_getsp(&spidx)) == NULL) {
2285 ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2286 return key_senderror(so, m, EINVAL);
2289 /* save policy id to buffer to be returned. */
2290 xpl0->sadb_x_policy_id = sp->id;
2293 printf("%s: SP(%p)\n", __func__, sp));
2294 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2300 struct sadb_msg *newmsg;
2302 /* create new sadb_msg to reply. */
2303 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2304 SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2306 return key_senderror(so, m, ENOBUFS);
2308 newmsg = mtod(n, struct sadb_msg *);
2309 newmsg->sadb_msg_errno = 0;
2310 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2313 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2318 * SADB_SPDDELETE2 processing
2321 * from the user(?), and set SADB_SASTATE_DEAD,
2325 * policy(*) including direction of policy.
2327 * m will always be freed.
2330 key_spddelete2(struct socket *so, struct mbuf *m,
2331 const struct sadb_msghdr *mhp)
2333 struct secpolicy *sp;
2336 IPSEC_ASSERT(so != NULL, ("null socket"));
2337 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2338 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2339 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2341 if (SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY) ||
2342 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2343 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2345 return key_senderror(so, m, EINVAL);
2348 id = ((struct sadb_x_policy *)
2349 mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2351 /* Is there SP in SPD ? */
2352 if ((sp = key_getspbyid(id)) == NULL) {
2353 ipseclog((LOG_DEBUG, "%s: no SP found for id %u.\n",
2355 return key_senderror(so, m, EINVAL);
2359 printf("%s: SP(%p)\n", __func__, sp));
2360 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2362 if (sp->state != IPSEC_SPSTATE_DEAD) {
2363 ipseclog((LOG_DEBUG, "%s: failed to delete SP with id %u.\n",
2366 return (key_senderror(so, m, EACCES));
2371 struct mbuf *n, *nn;
2372 struct sadb_msg *newmsg;
2375 /* create new sadb_msg to reply. */
2376 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2380 return key_senderror(so, m, ENOBUFS);
2386 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2387 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2389 IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2392 n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2393 mhp->extlen[SADB_X_EXT_POLICY], M_NOWAIT);
2396 return key_senderror(so, m, ENOBUFS);
2399 n->m_pkthdr.len = 0;
2400 for (nn = n; nn; nn = nn->m_next)
2401 n->m_pkthdr.len += nn->m_len;
2403 newmsg = mtod(n, struct sadb_msg *);
2404 newmsg->sadb_msg_errno = 0;
2405 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2408 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2413 * SADB_X_SPDGET processing
2418 * <base, address(SD), policy>
2420 * policy(*) including direction of policy.
2422 * m will always be freed.
2425 key_spdget(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2427 struct secpolicy *sp;
2431 IPSEC_ASSERT(so != NULL, ("null socket"));
2432 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2433 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2434 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2436 if (SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY) ||
2437 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2438 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2440 return key_senderror(so, m, EINVAL);
2443 id = ((struct sadb_x_policy *)
2444 mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2446 /* Is there SP in SPD ? */
2447 if ((sp = key_getspbyid(id)) == NULL) {
2448 ipseclog((LOG_DEBUG, "%s: no SP found for id %u.\n",
2450 return key_senderror(so, m, ENOENT);
2453 n = key_setdumpsp(sp, SADB_X_SPDGET, mhp->msg->sadb_msg_seq,
2454 mhp->msg->sadb_msg_pid);
2458 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2460 return key_senderror(so, m, ENOBUFS);
2464 * SADB_X_SPDACQUIRE processing.
2465 * Acquire policy and SA(s) for a *OUTBOUND* packet.
2468 * to KMD, and expect to receive
2469 * <base> with SADB_X_SPDACQUIRE if error occurred,
2472 * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2473 * policy(*) is without policy requests.
2476 * others: error number
2479 key_spdacquire(struct secpolicy *sp)
2481 struct mbuf *result = NULL, *m;
2482 struct secspacq *newspacq;
2484 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2485 IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2486 IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2487 ("policy not IPSEC %u", sp->policy));
2489 /* Get an entry to check whether sent message or not. */
2490 newspacq = key_getspacq(&sp->spidx);
2491 if (newspacq != NULL) {
2492 if (V_key_blockacq_count < newspacq->count) {
2493 /* reset counter and do send message. */
2494 newspacq->count = 0;
2496 /* increment counter and do nothing. */
2503 /* make new entry for blocking to send SADB_ACQUIRE. */
2504 newspacq = key_newspacq(&sp->spidx);
2505 if (newspacq == NULL)
2509 /* create new sadb_msg to reply. */
2510 m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2516 result->m_pkthdr.len = 0;
2517 for (m = result; m; m = m->m_next)
2518 result->m_pkthdr.len += m->m_len;
2520 mtod(result, struct sadb_msg *)->sadb_msg_len =
2521 PFKEY_UNIT64(result->m_pkthdr.len);
2523 return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2527 * SADB_SPDFLUSH processing
2530 * from the user, and free all entries in secpctree.
2534 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2536 * m will always be freed.
2539 key_spdflush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2541 struct secpolicy_queue drainq;
2542 struct sadb_msg *newmsg;
2543 struct secpolicy *sp, *nextsp;
2546 IPSEC_ASSERT(so != NULL, ("null socket"));
2547 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2548 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2549 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2551 if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2552 return key_senderror(so, m, EINVAL);
2554 TAILQ_INIT(&drainq);
2556 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2557 TAILQ_CONCAT(&drainq, &V_sptree[dir], chain);
2560 * We need to set state to DEAD for each policy to be sure,
2561 * that another thread won't try to unlink it.
2562 * Also remove SP from sphash.
2564 TAILQ_FOREACH(sp, &drainq, chain) {
2565 sp->state = IPSEC_SPSTATE_DEAD;
2566 LIST_REMOVE(sp, idhash);
2571 if (SPDCACHE_ENABLED())
2573 sp = TAILQ_FIRST(&drainq);
2574 while (sp != NULL) {
2575 nextsp = TAILQ_NEXT(sp, chain);
2580 if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2581 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2582 return key_senderror(so, m, ENOBUFS);
2588 m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2589 newmsg = mtod(m, struct sadb_msg *);
2590 newmsg->sadb_msg_errno = 0;
2591 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2593 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2597 key_satype2scopemask(uint8_t satype)
2600 if (satype == IPSEC_POLICYSCOPE_ANY)
2605 * SADB_SPDDUMP processing
2608 * from the user, and dump all SP leaves and send,
2613 * sadb_msg_satype is considered as mask of policy scopes.
2614 * m will always be freed.
2617 key_spddump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2619 SPTREE_RLOCK_TRACKER;
2620 struct secpolicy *sp;
2625 IPSEC_ASSERT(so != NULL, ("null socket"));
2626 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2627 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2628 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2630 /* search SPD entry and get buffer size. */
2632 scope = key_satype2scopemask(mhp->msg->sadb_msg_satype);
2634 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2635 if (scope & IPSEC_POLICYSCOPE_GLOBAL) {
2636 TAILQ_FOREACH(sp, &V_sptree[dir], chain)
2639 if (scope & IPSEC_POLICYSCOPE_IFNET) {
2640 TAILQ_FOREACH(sp, &V_sptree_ifnet[dir], chain)
2647 return key_senderror(so, m, ENOENT);
2650 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2651 if (scope & IPSEC_POLICYSCOPE_GLOBAL) {
2652 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
2654 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2655 mhp->msg->sadb_msg_pid);
2658 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2661 if (scope & IPSEC_POLICYSCOPE_IFNET) {
2662 TAILQ_FOREACH(sp, &V_sptree_ifnet[dir], chain) {
2664 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2665 mhp->msg->sadb_msg_pid);
2668 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2678 static struct mbuf *
2679 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq,
2682 struct mbuf *result = NULL, *m;
2683 struct seclifetime lt;
2685 m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2690 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2691 &sp->spidx.src.sa, sp->spidx.prefs,
2692 sp->spidx.ul_proto);
2697 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2698 &sp->spidx.dst.sa, sp->spidx.prefd,
2699 sp->spidx.ul_proto);
2704 m = key_sp2mbuf(sp);
2710 lt.addtime=sp->created;
2711 lt.usetime= sp->lastused;
2712 m = key_setlifetime(<, SADB_EXT_LIFETIME_CURRENT);
2717 lt.addtime=sp->lifetime;
2718 lt.usetime= sp->validtime;
2719 m = key_setlifetime(<, SADB_EXT_LIFETIME_HARD);
2725 if ((result->m_flags & M_PKTHDR) == 0)
2728 if (result->m_len < sizeof(struct sadb_msg)) {
2729 result = m_pullup(result, sizeof(struct sadb_msg));
2734 result->m_pkthdr.len = 0;
2735 for (m = result; m; m = m->m_next)
2736 result->m_pkthdr.len += m->m_len;
2738 mtod(result, struct sadb_msg *)->sadb_msg_len =
2739 PFKEY_UNIT64(result->m_pkthdr.len);
2748 * get PFKEY message length for security policy and request.
2751 key_getspreqmsglen(struct secpolicy *sp)
2756 tlen = sizeof(struct sadb_x_policy);
2757 /* if is the policy for ipsec ? */
2758 if (sp->policy != IPSEC_POLICY_IPSEC)
2761 /* get length of ipsec requests */
2762 for (i = 0; i < sp->tcount; i++) {
2763 len = sizeof(struct sadb_x_ipsecrequest)
2764 + sp->req[i]->saidx.src.sa.sa_len
2765 + sp->req[i]->saidx.dst.sa.sa_len;
2767 tlen += PFKEY_ALIGN8(len);
2773 * SADB_SPDEXPIRE processing
2775 * <base, address(SD), lifetime(CH), policy>
2779 * others : error number
2782 key_spdexpire(struct secpolicy *sp)
2784 struct sadb_lifetime *lt;
2785 struct mbuf *result = NULL, *m;
2786 int len, error = -1;
2788 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2791 printf("%s: SP(%p)\n", __func__, sp));
2792 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2794 /* set msg header */
2795 m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2802 /* create lifetime extension (current and hard) */
2803 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2804 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
2811 bzero(mtod(m, caddr_t), len);
2812 lt = mtod(m, struct sadb_lifetime *);
2813 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2814 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2815 lt->sadb_lifetime_allocations = 0;
2816 lt->sadb_lifetime_bytes = 0;
2817 lt->sadb_lifetime_addtime = sp->created;
2818 lt->sadb_lifetime_usetime = sp->lastused;
2819 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2820 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2821 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2822 lt->sadb_lifetime_allocations = 0;
2823 lt->sadb_lifetime_bytes = 0;
2824 lt->sadb_lifetime_addtime = sp->lifetime;
2825 lt->sadb_lifetime_usetime = sp->validtime;
2828 /* set sadb_address for source */
2829 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2831 sp->spidx.prefs, sp->spidx.ul_proto);
2838 /* set sadb_address for destination */
2839 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2841 sp->spidx.prefd, sp->spidx.ul_proto);
2849 m = key_sp2mbuf(sp);
2856 if ((result->m_flags & M_PKTHDR) == 0) {
2861 if (result->m_len < sizeof(struct sadb_msg)) {
2862 result = m_pullup(result, sizeof(struct sadb_msg));
2863 if (result == NULL) {
2869 result->m_pkthdr.len = 0;
2870 for (m = result; m; m = m->m_next)
2871 result->m_pkthdr.len += m->m_len;
2873 mtod(result, struct sadb_msg *)->sadb_msg_len =
2874 PFKEY_UNIT64(result->m_pkthdr.len);
2876 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2884 /* %%% SAD management */
2886 * allocating and initialize new SA head.
2887 * OUT: NULL : failure due to the lack of memory.
2888 * others : pointer to new SA head.
2890 static struct secashead *
2891 key_newsah(struct secasindex *saidx)
2893 struct secashead *sah;
2895 sah = malloc(sizeof(struct secashead), M_IPSEC_SAH,
2898 PFKEYSTAT_INC(in_nomem);
2901 TAILQ_INIT(&sah->savtree_larval);
2902 TAILQ_INIT(&sah->savtree_alive);
2903 sah->saidx = *saidx;
2904 sah->state = SADB_SASTATE_DEAD;
2908 printf("%s: SAH(%p)\n", __func__, sah));
2909 KEYDBG(KEY_DATA, kdebug_secash(sah, NULL));
2914 key_freesah(struct secashead **psah)
2916 struct secashead *sah = *psah;
2918 CURVNET_ASSERT_SET();
2920 if (SAH_DELREF(sah) == 0)
2924 printf("%s: last reference to SAH(%p)\n", __func__, sah));
2925 KEYDBG(KEY_DATA, kdebug_secash(sah, NULL));
2932 key_delsah(struct secashead *sah)
2934 IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2935 IPSEC_ASSERT(sah->state == SADB_SASTATE_DEAD,
2936 ("Attempt to free non DEAD SAH %p", sah));
2937 IPSEC_ASSERT(TAILQ_EMPTY(&sah->savtree_larval),
2938 ("Attempt to free SAH %p with LARVAL SA", sah));
2939 IPSEC_ASSERT(TAILQ_EMPTY(&sah->savtree_alive),
2940 ("Attempt to free SAH %p with ALIVE SA", sah));
2942 free(sah, M_IPSEC_SAH);
2946 * allocating a new SA for key_add() and key_getspi() call,
2947 * and copy the values of mhp into new buffer.
2948 * When SAD message type is SADB_GETSPI set SA state to LARVAL.
2949 * For SADB_ADD create and initialize SA with MATURE state.
2951 * others : pointer to new secasvar.
2953 static struct secasvar *
2954 key_newsav(const struct sadb_msghdr *mhp, struct secasindex *saidx,
2955 uint32_t spi, int *errp)
2957 struct secashead *sah;
2958 struct secasvar *sav;
2961 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2962 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2963 IPSEC_ASSERT(mhp->msg->sadb_msg_type == SADB_GETSPI ||
2964 mhp->msg->sadb_msg_type == SADB_ADD, ("wrong message type"));
2968 /* check SPI value */
2969 switch (saidx->proto) {
2973 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
2974 * 1-255 reserved by IANA for future use,
2975 * 0 for implementation specific, local use.
2977 if (ntohl(spi) <= 255) {
2978 ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
2979 __func__, ntohl(spi)));
2986 sav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT | M_ZERO);
2991 sav->lock = malloc_aligned(max(sizeof(struct rmlock),
2992 CACHE_LINE_SIZE), CACHE_LINE_SIZE, M_IPSEC_MISC,
2994 if (sav->lock == NULL) {
2998 rm_init(sav->lock, "ipsec association");
2999 sav->lft_c = uma_zalloc_pcpu(ipsec_key_lft_zone, M_NOWAIT | M_ZERO);
3000 if (sav->lft_c == NULL) {
3006 sav->seq = mhp->msg->sadb_msg_seq;
3007 sav->state = SADB_SASTATE_LARVAL;
3008 sav->pid = (pid_t)mhp->msg->sadb_msg_pid;
3011 sah = key_getsah(saidx);
3013 /* create a new SA index */
3014 sah = key_newsah(saidx);
3016 ipseclog((LOG_DEBUG,
3017 "%s: No more memory.\n", __func__));
3026 if (mhp->msg->sadb_msg_type == SADB_GETSPI) {
3027 sav->created = time_second;
3028 } else if (sav->state == SADB_SASTATE_LARVAL) {
3030 * Do not call key_setsaval() second time in case
3031 * of `goto again`. We will have MATURE state.
3033 *errp = key_setsaval(sav, mhp);
3036 sav->state = SADB_SASTATE_MATURE;
3041 * Check that existing SAH wasn't unlinked.
3042 * Since we didn't hold the SAHTREE lock, it is possible,
3043 * that callout handler or key_flush() or key_delete() could
3046 if (isnew == 0 && sah->state == SADB_SASTATE_DEAD) {
3048 key_freesah(&sah); /* reference from key_getsah() */
3053 * Add new SAH into SADB.
3055 * XXXAE: we can serialize key_add and key_getspi calls, so
3056 * several threads will not fight in the race.
3057 * Otherwise we should check under SAHTREE lock, that this
3058 * SAH would not added twice.
3060 TAILQ_INSERT_HEAD(&V_sahtree, sah, chain);
3061 /* Add new SAH into hash by addresses */
3062 LIST_INSERT_HEAD(SAHADDRHASH_HASH(saidx), sah, addrhash);
3063 /* Now we are linked in the chain */
3064 sah->state = SADB_SASTATE_MATURE;
3066 * SAV references this new SAH.
3067 * In case of existing SAH we reuse reference
3068 * from key_getsah().
3072 /* Link SAV with SAH */
3073 if (sav->state == SADB_SASTATE_MATURE)
3074 TAILQ_INSERT_HEAD(&sah->savtree_alive, sav, chain);
3076 TAILQ_INSERT_HEAD(&sah->savtree_larval, sav, chain);
3077 /* Add SAV into SPI hash */
3078 LIST_INSERT_HEAD(SAVHASH_HASH(sav->spi), sav, spihash);
3080 *errp = 0; /* success */
3084 if (sav->lock != NULL) {
3085 rm_destroy(sav->lock);
3086 free(sav->lock, M_IPSEC_MISC);
3088 if (sav->lft_c != NULL)
3089 uma_zfree_pcpu(ipsec_key_lft_zone, sav->lft_c);
3090 free(sav, M_IPSEC_SA), sav = NULL;
3094 if (*errp == ENOBUFS) {
3095 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3097 PFKEYSTAT_INC(in_nomem);
3104 * free() SA variable entry.
3107 key_cleansav(struct secasvar *sav)
3110 if (sav->natt != NULL) {
3111 free(sav->natt, M_IPSEC_MISC);
3114 if (sav->flags & SADB_X_EXT_F_CLONED)
3116 if (sav->tdb_xform != NULL) {
3117 sav->tdb_xform->xf_cleanup(sav);
3118 sav->tdb_xform = NULL;
3120 if (sav->key_auth != NULL) {
3121 zfree(sav->key_auth->key_data, M_IPSEC_MISC);
3122 free(sav->key_auth, M_IPSEC_MISC);
3123 sav->key_auth = NULL;
3125 if (sav->key_enc != NULL) {
3126 zfree(sav->key_enc->key_data, M_IPSEC_MISC);
3127 free(sav->key_enc, M_IPSEC_MISC);
3128 sav->key_enc = NULL;
3130 if (sav->replay != NULL) {
3131 mtx_destroy(&sav->replay->lock);
3132 if (sav->replay->bitmap != NULL)
3133 free(sav->replay->bitmap, M_IPSEC_MISC);
3134 free(sav->replay, M_IPSEC_MISC);
3137 if (sav->lft_h != NULL) {
3138 free(sav->lft_h, M_IPSEC_MISC);
3141 if (sav->lft_s != NULL) {
3142 free(sav->lft_s, M_IPSEC_MISC);
3148 * free() SA variable entry.
3151 key_delsav(struct secasvar *sav)
3153 IPSEC_ASSERT(sav != NULL, ("null sav"));
3154 IPSEC_ASSERT(sav->state == SADB_SASTATE_DEAD,
3155 ("attempt to free non DEAD SA %p", sav));
3156 IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0",
3160 * SA must be unlinked from the chain and hashtbl.
3161 * If SA was cloned, we leave all fields untouched,
3162 * except NAT-T config.
3165 if ((sav->flags & SADB_X_EXT_F_CLONED) == 0) {
3166 rm_destroy(sav->lock);
3167 free(sav->lock, M_IPSEC_MISC);
3168 uma_zfree_pcpu(ipsec_key_lft_zone, sav->lft_c);
3170 free(sav, M_IPSEC_SA);
3177 * others : found, referenced pointer to a SAH.
3179 static struct secashead *
3180 key_getsah(struct secasindex *saidx)
3182 SAHTREE_RLOCK_TRACKER;
3183 struct secashead *sah;
3186 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
3187 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID) != 0) {
3197 * Check not to be duplicated SPI.
3200 * 1 : found SA with given SPI.
3203 key_checkspidup(uint32_t spi)
3205 SAHTREE_RLOCK_TRACKER;
3206 struct secasvar *sav;
3208 /* Assume SPI is in network byte order */
3210 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
3211 if (sav->spi == spi)
3215 return (sav != NULL);
3222 * others : found, referenced pointer to a SA.
3224 static struct secasvar *
3225 key_getsavbyspi(uint32_t spi)
3227 SAHTREE_RLOCK_TRACKER;
3228 struct secasvar *sav;
3230 /* Assume SPI is in network byte order */
3232 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
3233 if (sav->spi != spi)
3243 key_updatelifetimes(struct secasvar *sav, const struct sadb_msghdr *mhp)
3245 struct seclifetime *lft_h, *lft_s, *tmp;
3247 /* Lifetime extension is optional, check that it is present. */
3248 if (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
3249 SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) {
3251 * In case of SADB_UPDATE we may need to change
3252 * existing lifetimes.
3254 if (sav->state == SADB_SASTATE_MATURE) {
3255 lft_h = lft_s = NULL;
3260 /* Both HARD and SOFT extensions must present */
3261 if ((SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
3262 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
3263 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
3264 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
3265 ipseclog((LOG_DEBUG,
3266 "%s: invalid message: missing required header.\n",
3270 if (SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_HARD) ||
3271 SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_SOFT)) {
3272 ipseclog((LOG_DEBUG,
3273 "%s: invalid message: wrong header size.\n", __func__));
3276 lft_h = key_dup_lifemsg((const struct sadb_lifetime *)
3277 mhp->ext[SADB_EXT_LIFETIME_HARD], M_IPSEC_MISC);
3278 if (lft_h == NULL) {
3279 PFKEYSTAT_INC(in_nomem);
3280 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3283 lft_s = key_dup_lifemsg((const struct sadb_lifetime *)
3284 mhp->ext[SADB_EXT_LIFETIME_SOFT], M_IPSEC_MISC);
3285 if (lft_s == NULL) {
3286 PFKEYSTAT_INC(in_nomem);
3287 free(lft_h, M_IPSEC_MISC);
3288 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3292 if (sav->state != SADB_SASTATE_LARVAL) {
3294 * key_update() holds reference to this SA,
3295 * so it won't be deleted in meanwhile.
3297 SECASVAR_WLOCK(sav);
3305 SECASVAR_WUNLOCK(sav);
3307 free(lft_h, M_IPSEC_MISC);
3309 free(lft_s, M_IPSEC_MISC);
3312 /* We can update lifetime without holding a lock */
3313 IPSEC_ASSERT(sav->lft_h == NULL, ("lft_h is already initialized\n"));
3314 IPSEC_ASSERT(sav->lft_s == NULL, ("lft_s is already initialized\n"));
3321 * copy SA values from PF_KEY message except *SPI, SEQ, PID and TYPE*.
3322 * You must update these if need. Expects only LARVAL SAs.
3327 key_setsaval(struct secasvar *sav, const struct sadb_msghdr *mhp)
3329 const struct sadb_sa *sa0;
3330 const struct sadb_key *key0;
3335 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3336 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3337 IPSEC_ASSERT(sav->state == SADB_SASTATE_LARVAL,
3338 ("Attempt to update non LARVAL SA"));
3341 error = key_setident(sav->sah, mhp);
3346 if (!SADB_CHECKHDR(mhp, SADB_EXT_SA)) {
3347 if (SADB_CHECKLEN(mhp, SADB_EXT_SA)) {
3351 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3352 sav->alg_auth = sa0->sadb_sa_auth;
3353 sav->alg_enc = sa0->sadb_sa_encrypt;
3354 sav->flags = sa0->sadb_sa_flags;
3355 if ((sav->flags & SADB_KEY_FLAGS_MAX) != sav->flags) {
3356 ipseclog((LOG_DEBUG,
3357 "%s: invalid sa_flags 0x%08x.\n", __func__,
3363 /* Optional replay window */
3365 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0)
3366 replay = sa0->sadb_sa_replay;
3367 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_SA_REPLAY)) {
3368 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA_REPLAY)) {
3372 replay = ((const struct sadb_x_sa_replay *)
3373 mhp->ext[SADB_X_EXT_SA_REPLAY])->sadb_x_sa_replay_replay;
3375 if (replay > UINT32_MAX - 32) {
3376 ipseclog((LOG_DEBUG,
3377 "%s: replay window too big.\n", __func__));
3382 replay = (replay + 7) >> 3;
3385 sav->replay = malloc(sizeof(struct secreplay), M_IPSEC_MISC,
3387 if (sav->replay == NULL) {
3388 PFKEYSTAT_INC(in_nomem);
3389 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3394 mtx_init(&sav->replay->lock, "ipsec replay", NULL, MTX_DEF);
3397 /* number of 32b blocks to be allocated */
3398 uint32_t bitmap_size;
3401 * - the allocated replay window size must be
3403 * - use an extra 32b block as a redundant window.
3406 while (replay + 4 > bitmap_size)
3408 bitmap_size = bitmap_size / 4;
3410 sav->replay->bitmap = malloc(
3411 bitmap_size * sizeof(uint32_t), M_IPSEC_MISC,
3413 if (sav->replay->bitmap == NULL) {
3414 PFKEYSTAT_INC(in_nomem);
3415 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3420 sav->replay->bitmap_size = bitmap_size;
3421 sav->replay->wsize = replay;
3425 /* Authentication keys */
3426 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH)) {
3427 if (SADB_CHECKLEN(mhp, SADB_EXT_KEY_AUTH)) {
3432 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3433 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3434 switch (mhp->msg->sadb_msg_satype) {
3435 case SADB_SATYPE_AH:
3436 case SADB_SATYPE_ESP:
3437 case SADB_X_SATYPE_TCPSIGNATURE:
3438 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3439 sav->alg_auth != SADB_X_AALG_NULL)
3442 case SADB_X_SATYPE_IPCOMP:
3448 ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3453 sav->key_auth = key_dup_keymsg(key0, len, M_IPSEC_MISC);
3454 if (sav->key_auth == NULL ) {
3455 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3457 PFKEYSTAT_INC(in_nomem);
3463 /* Encryption key */
3464 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT)) {
3465 if (SADB_CHECKLEN(mhp, SADB_EXT_KEY_ENCRYPT)) {
3470 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3471 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3472 switch (mhp->msg->sadb_msg_satype) {
3473 case SADB_SATYPE_ESP:
3474 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3475 sav->alg_enc != SADB_EALG_NULL) {
3479 sav->key_enc = key_dup_keymsg(key0, len, M_IPSEC_MISC);
3480 if (sav->key_enc == NULL) {
3481 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3483 PFKEYSTAT_INC(in_nomem);
3488 case SADB_X_SATYPE_IPCOMP:
3489 if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3491 sav->key_enc = NULL; /*just in case*/
3493 case SADB_SATYPE_AH:
3494 case SADB_X_SATYPE_TCPSIGNATURE:
3500 ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3508 switch (mhp->msg->sadb_msg_satype) {
3509 case SADB_SATYPE_AH:
3510 if (sav->flags & SADB_X_EXT_DERIV) {
3511 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3512 "given to AH SA.\n", __func__));
3516 if (sav->alg_enc != SADB_EALG_NONE) {
3517 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3518 "mismated.\n", __func__));
3522 error = xform_init(sav, XF_AH);
3524 case SADB_SATYPE_ESP:
3525 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_DERIV)) ==
3526 (SADB_X_EXT_OLD | SADB_X_EXT_DERIV)) {
3527 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3528 "given to old-esp.\n", __func__));
3532 error = xform_init(sav, XF_ESP);
3534 case SADB_X_SATYPE_IPCOMP:
3535 if (sav->alg_auth != SADB_AALG_NONE) {
3536 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3537 "mismated.\n", __func__));
3541 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0 &&
3542 ntohl(sav->spi) >= 0x10000) {
3543 ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3548 error = xform_init(sav, XF_IPCOMP);
3550 case SADB_X_SATYPE_TCPSIGNATURE:
3551 if (sav->alg_enc != SADB_EALG_NONE) {
3552 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3553 "mismated.\n", __func__));
3557 error = xform_init(sav, XF_TCPSIGNATURE);
3560 ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3561 error = EPROTONOSUPPORT;
3565 ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3566 __func__, mhp->msg->sadb_msg_satype));
3570 /* Handle NAT-T headers */
3571 error = key_setnatt(sav, mhp);
3575 /* Initialize lifetime for CURRENT */
3577 sav->created = time_second;
3579 /* lifetimes for HARD and SOFT */
3580 error = key_updatelifetimes(sav, mhp);
3589 * subroutine for SADB_GET and SADB_DUMP.
3591 static struct mbuf *
3592 key_setdumpsa(struct secasvar *sav, uint8_t type, uint8_t satype,
3593 uint32_t seq, uint32_t pid)
3595 struct seclifetime lft_c;
3596 struct mbuf *result = NULL, *tres = NULL, *m;
3597 int i, dumporder[] = {
3598 SADB_EXT_SA, SADB_X_EXT_SA2, SADB_X_EXT_SA_REPLAY,
3599 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3600 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3601 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY,
3602 SADB_EXT_KEY_AUTH, SADB_EXT_KEY_ENCRYPT,
3603 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
3604 SADB_EXT_SENSITIVITY,
3605 SADB_X_EXT_NAT_T_TYPE,
3606 SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3607 SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3608 SADB_X_EXT_NAT_T_FRAG,
3610 uint32_t replay_count;
3612 SECASVAR_RLOCK_TRACKER;
3614 m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3619 for (i = nitems(dumporder) - 1; i >= 0; i--) {
3621 switch (dumporder[i]) {
3623 m = key_setsadbsa(sav);
3628 case SADB_X_EXT_SA2: {
3629 SECASVAR_RLOCK(sav);
3630 replay_count = sav->replay ? sav->replay->count : 0;
3631 SECASVAR_RUNLOCK(sav);
3632 m = key_setsadbxsa2(sav->sah->saidx.mode, replay_count,
3633 sav->sah->saidx.reqid);
3638 case SADB_X_EXT_SA_REPLAY:
3639 if (sav->replay == NULL ||
3640 sav->replay->wsize <= UINT8_MAX)
3643 m = key_setsadbxsareplay(sav->replay->wsize);
3648 case SADB_EXT_ADDRESS_SRC:
3649 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3650 &sav->sah->saidx.src.sa,
3651 FULLMASK, IPSEC_ULPROTO_ANY);
3656 case SADB_EXT_ADDRESS_DST:
3657 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3658 &sav->sah->saidx.dst.sa,
3659 FULLMASK, IPSEC_ULPROTO_ANY);
3664 case SADB_EXT_KEY_AUTH:
3667 m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3672 case SADB_EXT_KEY_ENCRYPT:
3675 m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3680 case SADB_EXT_LIFETIME_CURRENT:
3681 lft_c.addtime = sav->created;
3682 lft_c.allocations = (uint32_t)counter_u64_fetch(
3683 sav->lft_c_allocations);
3684 lft_c.bytes = counter_u64_fetch(sav->lft_c_bytes);
3685 lft_c.usetime = sav->firstused;
3686 m = key_setlifetime(&lft_c, SADB_EXT_LIFETIME_CURRENT);
3691 case SADB_EXT_LIFETIME_HARD:
3694 m = key_setlifetime(sav->lft_h,
3695 SADB_EXT_LIFETIME_HARD);
3700 case SADB_EXT_LIFETIME_SOFT:
3703 m = key_setlifetime(sav->lft_s,
3704 SADB_EXT_LIFETIME_SOFT);
3710 case SADB_X_EXT_NAT_T_TYPE:
3711 if (sav->natt == NULL)
3713 m = key_setsadbxtype(UDP_ENCAP_ESPINUDP);
3718 case SADB_X_EXT_NAT_T_DPORT:
3719 if (sav->natt == NULL)
3721 m = key_setsadbxport(sav->natt->dport,
3722 SADB_X_EXT_NAT_T_DPORT);
3727 case SADB_X_EXT_NAT_T_SPORT:
3728 if (sav->natt == NULL)
3730 m = key_setsadbxport(sav->natt->sport,
3731 SADB_X_EXT_NAT_T_SPORT);
3736 case SADB_X_EXT_NAT_T_OAI:
3737 if (sav->natt == NULL ||
3738 (sav->natt->flags & IPSEC_NATT_F_OAI) == 0)
3740 m = key_setsadbaddr(SADB_X_EXT_NAT_T_OAI,
3741 &sav->natt->oai.sa, FULLMASK, IPSEC_ULPROTO_ANY);
3745 case SADB_X_EXT_NAT_T_OAR:
3746 if (sav->natt == NULL ||
3747 (sav->natt->flags & IPSEC_NATT_F_OAR) == 0)
3749 m = key_setsadbaddr(SADB_X_EXT_NAT_T_OAR,
3750 &sav->natt->oar.sa, FULLMASK, IPSEC_ULPROTO_ANY);
3754 case SADB_X_EXT_NAT_T_FRAG:
3755 /* We do not (yet) support those. */
3758 case SADB_EXT_ADDRESS_PROXY:
3759 case SADB_EXT_IDENTITY_SRC:
3760 case SADB_EXT_IDENTITY_DST:
3761 /* XXX: should we brought from SPD ? */
3762 case SADB_EXT_SENSITIVITY:
3774 m_cat(result, tres);
3776 if (result->m_len < sizeof(struct sadb_msg)) {
3777 result = m_pullup(result, sizeof(struct sadb_msg));
3782 result->m_pkthdr.len = 0;
3783 for (m = result; m; m = m->m_next)
3784 result->m_pkthdr.len += m->m_len;
3786 mtod(result, struct sadb_msg *)->sadb_msg_len =
3787 PFKEY_UNIT64(result->m_pkthdr.len);
3798 * set data into sadb_msg.
3800 static struct mbuf *
3801 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3802 pid_t pid, u_int16_t reserved)
3808 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3814 m->m_pkthdr.len = m->m_len = len;
3817 p = mtod(m, struct sadb_msg *);
3820 p->sadb_msg_version = PF_KEY_V2;
3821 p->sadb_msg_type = type;
3822 p->sadb_msg_errno = 0;
3823 p->sadb_msg_satype = satype;
3824 p->sadb_msg_len = PFKEY_UNIT64(tlen);
3825 p->sadb_msg_reserved = reserved;
3826 p->sadb_msg_seq = seq;
3827 p->sadb_msg_pid = (u_int32_t)pid;
3833 * copy secasvar data into sadb_address.
3835 static struct mbuf *
3836 key_setsadbsa(struct secasvar *sav)
3842 len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3843 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3848 p = mtod(m, struct sadb_sa *);
3850 p->sadb_sa_len = PFKEY_UNIT64(len);
3851 p->sadb_sa_exttype = SADB_EXT_SA;
3852 p->sadb_sa_spi = sav->spi;
3853 p->sadb_sa_replay = sav->replay ?
3854 (sav->replay->wsize > UINT8_MAX ? UINT8_MAX :
3855 sav->replay->wsize): 0;
3856 p->sadb_sa_state = sav->state;
3857 p->sadb_sa_auth = sav->alg_auth;
3858 p->sadb_sa_encrypt = sav->alg_enc;
3859 p->sadb_sa_flags = sav->flags & SADB_KEY_FLAGS_MAX;
3864 * set data into sadb_address.
3866 static struct mbuf *
3867 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
3868 u_int8_t prefixlen, u_int16_t ul_proto)
3871 struct sadb_address *p;
3874 len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3875 PFKEY_ALIGN8(saddr->sa_len);
3876 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3881 p = mtod(m, struct sadb_address *);
3884 p->sadb_address_len = PFKEY_UNIT64(len);
3885 p->sadb_address_exttype = exttype;
3886 p->sadb_address_proto = ul_proto;
3887 if (prefixlen == FULLMASK) {
3888 switch (saddr->sa_family) {
3890 prefixlen = sizeof(struct in_addr) << 3;
3893 prefixlen = sizeof(struct in6_addr) << 3;
3899 p->sadb_address_prefixlen = prefixlen;
3900 p->sadb_address_reserved = 0;
3903 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3910 * set data into sadb_x_sa2.
3912 static struct mbuf *
3913 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3916 struct sadb_x_sa2 *p;
3919 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3920 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3925 p = mtod(m, struct sadb_x_sa2 *);
3928 p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3929 p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3930 p->sadb_x_sa2_mode = mode;
3931 p->sadb_x_sa2_reserved1 = 0;
3932 p->sadb_x_sa2_reserved2 = 0;
3933 p->sadb_x_sa2_sequence = seq;
3934 p->sadb_x_sa2_reqid = reqid;
3940 * Set data into sadb_x_sa_replay.
3942 static struct mbuf *
3943 key_setsadbxsareplay(u_int32_t replay)
3946 struct sadb_x_sa_replay *p;
3949 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa_replay));
3950 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3955 p = mtod(m, struct sadb_x_sa_replay *);
3958 p->sadb_x_sa_replay_len = PFKEY_UNIT64(len);
3959 p->sadb_x_sa_replay_exttype = SADB_X_EXT_SA_REPLAY;
3960 p->sadb_x_sa_replay_replay = (replay << 3);
3966 * Set a type in sadb_x_nat_t_type.
3968 static struct mbuf *
3969 key_setsadbxtype(u_int16_t type)
3973 struct sadb_x_nat_t_type *p;
3975 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3977 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3982 p = mtod(m, struct sadb_x_nat_t_type *);
3985 p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3986 p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3987 p->sadb_x_nat_t_type_type = type;
3992 * Set a port in sadb_x_nat_t_port.
3993 * In contrast to default RFC 2367 behaviour, port is in network byte order.
3995 static struct mbuf *
3996 key_setsadbxport(u_int16_t port, u_int16_t type)
4000 struct sadb_x_nat_t_port *p;
4002 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
4004 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
4009 p = mtod(m, struct sadb_x_nat_t_port *);
4012 p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
4013 p->sadb_x_nat_t_port_exttype = type;
4014 p->sadb_x_nat_t_port_port = port;
4020 * Get port from sockaddr. Port is in network byte order.
4023 key_portfromsaddr(struct sockaddr *sa)
4026 switch (sa->sa_family) {
4029 return ((struct sockaddr_in *)sa)->sin_port;
4033 return ((struct sockaddr_in6 *)sa)->sin6_port;
4040 * Set port in struct sockaddr. Port is in network byte order.
4043 key_porttosaddr(struct sockaddr *sa, uint16_t port)
4046 switch (sa->sa_family) {
4049 ((struct sockaddr_in *)sa)->sin_port = port;
4054 ((struct sockaddr_in6 *)sa)->sin6_port = port;
4058 ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
4059 __func__, sa->sa_family));
4065 * set data into sadb_x_policy
4067 static struct mbuf *
4068 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id, u_int32_t priority)
4071 struct sadb_x_policy *p;
4074 len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
4075 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
4080 p = mtod(m, struct sadb_x_policy *);
4083 p->sadb_x_policy_len = PFKEY_UNIT64(len);
4084 p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
4085 p->sadb_x_policy_type = type;
4086 p->sadb_x_policy_dir = dir;
4087 p->sadb_x_policy_id = id;
4088 p->sadb_x_policy_priority = priority;
4094 /* Take a key message (sadb_key) from the socket and turn it into one
4095 * of the kernel's key structures (seckey).
4097 * IN: pointer to the src
4098 * OUT: NULL no more memory
4101 key_dup_keymsg(const struct sadb_key *src, size_t len,
4102 struct malloc_type *type)
4106 dst = malloc(sizeof(*dst), type, M_NOWAIT);
4108 dst->bits = src->sadb_key_bits;
4109 dst->key_data = malloc(len, type, M_NOWAIT);
4110 if (dst->key_data != NULL) {
4111 bcopy((const char *)(src + 1), dst->key_data, len);
4113 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
4119 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
4125 /* Take a lifetime message (sadb_lifetime) passed in on a socket and
4126 * turn it into one of the kernel's lifetime structures (seclifetime).
4128 * IN: pointer to the destination, source and malloc type
4129 * OUT: NULL, no more memory
4132 static struct seclifetime *
4133 key_dup_lifemsg(const struct sadb_lifetime *src, struct malloc_type *type)
4135 struct seclifetime *dst;
4137 dst = malloc(sizeof(*dst), type, M_NOWAIT);
4139 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4142 dst->allocations = src->sadb_lifetime_allocations;
4143 dst->bytes = src->sadb_lifetime_bytes;
4144 dst->addtime = src->sadb_lifetime_addtime;
4145 dst->usetime = src->sadb_lifetime_usetime;
4150 * compare two secasindex structure.
4151 * flag can specify to compare 2 saidxes.
4152 * compare two secasindex structure without both mode and reqid.
4153 * don't compare port.
4155 * saidx0: source, it can be in SAD.
4162 key_cmpsaidx(const struct secasindex *saidx0, const struct secasindex *saidx1,
4167 if (saidx0 == NULL && saidx1 == NULL)
4170 if (saidx0 == NULL || saidx1 == NULL)
4173 if (saidx0->proto != saidx1->proto)
4176 if (flag == CMP_EXACTLY) {
4177 if (saidx0->mode != saidx1->mode)
4179 if (saidx0->reqid != saidx1->reqid)
4181 if (bcmp(&saidx0->src, &saidx1->src,
4182 saidx0->src.sa.sa_len) != 0 ||
4183 bcmp(&saidx0->dst, &saidx1->dst,
4184 saidx0->dst.sa.sa_len) != 0)
4187 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4188 if (flag == CMP_MODE_REQID || flag == CMP_REQID) {
4190 * If reqid of SPD is non-zero, unique SA is required.
4191 * The result must be of same reqid in this case.
4193 if (saidx1->reqid != 0 &&
4194 saidx0->reqid != saidx1->reqid)
4198 if (flag == CMP_MODE_REQID) {
4199 if (saidx0->mode != IPSEC_MODE_ANY
4200 && saidx0->mode != saidx1->mode)
4204 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0)
4206 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0)
4214 * compare two secindex structure exactly.
4216 * spidx0: source, it is often in SPD.
4217 * spidx1: object, it is often from PFKEY message.
4223 key_cmpspidx_exactly(struct secpolicyindex *spidx0,
4224 struct secpolicyindex *spidx1)
4227 if (spidx0 == NULL && spidx1 == NULL)
4230 if (spidx0 == NULL || spidx1 == NULL)
4233 if (spidx0->prefs != spidx1->prefs
4234 || spidx0->prefd != spidx1->prefd
4235 || spidx0->ul_proto != spidx1->ul_proto
4236 || spidx0->dir != spidx1->dir)
4239 return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4240 key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4244 * compare two secindex structure with mask.
4246 * spidx0: source, it is often in SPD.
4247 * spidx1: object, it is often from IP header.
4253 key_cmpspidx_withmask(struct secpolicyindex *spidx0,
4254 struct secpolicyindex *spidx1)
4257 if (spidx0 == NULL && spidx1 == NULL)
4260 if (spidx0 == NULL || spidx1 == NULL)
4263 if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4264 spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4265 spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4266 spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4269 /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4270 if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4271 && spidx0->ul_proto != spidx1->ul_proto)
4274 switch (spidx0->src.sa.sa_family) {
4276 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4277 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4279 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4280 &spidx1->src.sin.sin_addr, spidx0->prefs))
4284 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4285 && spidx0->src.sin6.sin6_port != spidx1->src.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->src.sin6.sin6_scope_id &&
4292 spidx1->src.sin6.sin6_scope_id &&
4293 spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4295 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4296 &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4301 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4306 switch (spidx0->dst.sa.sa_family) {
4308 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4309 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4311 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4312 &spidx1->dst.sin.sin_addr, spidx0->prefd))
4316 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4317 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4320 * scope_id check. if sin6_scope_id is 0, we regard it
4321 * as a wildcard scope, which matches any scope zone ID.
4323 if (spidx0->dst.sin6.sin6_scope_id &&
4324 spidx1->dst.sin6.sin6_scope_id &&
4325 spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4327 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4328 &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4333 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4338 /* XXX Do we check other field ? e.g. flowinfo */
4346 #define satosin(s) ((const struct sockaddr_in *)s)
4350 #define satosin6(s) ((const struct sockaddr_in6 *)s)
4351 /* returns 0 on match */
4353 key_sockaddrcmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
4356 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4359 switch (sa1->sa_family) {
4362 if (sa1->sa_len != sizeof(struct sockaddr_in))
4364 if (satosin(sa1)->sin_addr.s_addr !=
4365 satosin(sa2)->sin_addr.s_addr) {
4368 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4374 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4375 return 1; /*EINVAL*/
4376 if (satosin6(sa1)->sin6_scope_id !=
4377 satosin6(sa2)->sin6_scope_id) {
4380 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4381 &satosin6(sa2)->sin6_addr)) {
4385 satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4391 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4399 /* returns 0 on match */
4401 key_sockaddrcmp_withmask(const struct sockaddr *sa1,
4402 const struct sockaddr *sa2, size_t mask)
4404 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4407 switch (sa1->sa_family) {
4410 return (!key_bbcmp(&satosin(sa1)->sin_addr,
4411 &satosin(sa2)->sin_addr, mask));
4415 if (satosin6(sa1)->sin6_scope_id !=
4416 satosin6(sa2)->sin6_scope_id)
4418 return (!key_bbcmp(&satosin6(sa1)->sin6_addr,
4419 &satosin6(sa2)->sin6_addr, mask));
4428 * compare two buffers with mask.
4432 * bits: Number of bits to compare
4438 key_bbcmp(const void *a1, const void *a2, u_int bits)
4440 const unsigned char *p1 = a1;
4441 const unsigned char *p2 = a2;
4443 /* XXX: This could be considerably faster if we compare a word
4444 * at a time, but it is complicated on LSB Endian machines */
4446 /* Handle null pointers */
4447 if (p1 == NULL || p2 == NULL)
4457 u_int8_t mask = ~((1<<(8-bits))-1);
4458 if ((*p1 & mask) != (*p2 & mask))
4461 return 1; /* Match! */
4465 key_flush_spd(time_t now)
4467 SPTREE_RLOCK_TRACKER;
4468 struct secpolicy_list drainq;
4469 struct secpolicy *sp, *nextsp;
4474 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4475 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
4476 if (sp->lifetime == 0 && sp->validtime == 0)
4478 if ((sp->lifetime &&
4479 now - sp->created > sp->lifetime) ||
4481 now - sp->lastused > sp->validtime)) {
4482 /* Hold extra reference to send SPDEXPIRE */
4484 LIST_INSERT_HEAD(&drainq, sp, drainq);
4489 if (LIST_EMPTY(&drainq))
4493 sp = LIST_FIRST(&drainq);
4494 while (sp != NULL) {
4495 nextsp = LIST_NEXT(sp, drainq);
4496 /* Check that SP is still linked */
4497 if (sp->state != IPSEC_SPSTATE_ALIVE) {
4498 LIST_REMOVE(sp, drainq);
4499 key_freesp(&sp); /* release extra reference */
4503 TAILQ_REMOVE(&V_sptree[sp->spidx.dir], sp, chain);
4505 LIST_REMOVE(sp, idhash);
4506 sp->state = IPSEC_SPSTATE_DEAD;
4511 if (SPDCACHE_ENABLED())
4514 sp = LIST_FIRST(&drainq);
4515 while (sp != NULL) {
4516 nextsp = LIST_NEXT(sp, drainq);
4518 key_freesp(&sp); /* release extra reference */
4519 key_freesp(&sp); /* release last reference */
4525 key_flush_sad(time_t now)
4527 SAHTREE_RLOCK_TRACKER;
4528 struct secashead_list emptyq;
4529 struct secasvar_list drainq, hexpireq, sexpireq, freeq;
4530 struct secashead *sah, *nextsah;
4531 struct secasvar *sav, *nextsav;
4533 SECASVAR_RLOCK_TRACKER;
4536 LIST_INIT(&hexpireq);
4537 LIST_INIT(&sexpireq);
4541 TAILQ_FOREACH(sah, &V_sahtree, chain) {
4542 /* Check for empty SAH */
4543 if (TAILQ_EMPTY(&sah->savtree_larval) &&
4544 TAILQ_EMPTY(&sah->savtree_alive)) {
4546 LIST_INSERT_HEAD(&emptyq, sah, drainq);
4549 /* Add all stale LARVAL SAs into drainq */
4550 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
4551 if (now - sav->created < V_key_larval_lifetime)
4554 LIST_INSERT_HEAD(&drainq, sav, drainq);
4556 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
4557 /* lifetimes aren't specified */
4558 if (sav->lft_h == NULL)
4560 SECASVAR_RLOCK(sav);
4562 * Check again with lock held, because it may
4563 * be updated by SADB_UPDATE.
4565 if (sav->lft_h == NULL) {
4566 SECASVAR_RUNLOCK(sav);
4571 * HARD lifetimes MUST take precedence over SOFT
4572 * lifetimes, meaning if the HARD and SOFT lifetimes
4573 * are the same, the HARD lifetime will appear on the
4576 /* check HARD lifetime */
4577 if ((sav->lft_h->addtime != 0 &&
4578 now - sav->created > sav->lft_h->addtime) ||
4579 (sav->lft_h->usetime != 0 && sav->firstused &&
4580 now - sav->firstused > sav->lft_h->usetime) ||
4581 (sav->lft_h->bytes != 0 && counter_u64_fetch(
4582 sav->lft_c_bytes) > sav->lft_h->bytes)) {
4583 SECASVAR_RUNLOCK(sav);
4585 LIST_INSERT_HEAD(&hexpireq, sav, drainq);
4588 /* check SOFT lifetime (only for MATURE SAs) */
4589 if (sav->state == SADB_SASTATE_MATURE && (
4590 (sav->lft_s->addtime != 0 &&
4591 now - sav->created > sav->lft_s->addtime) ||
4592 (sav->lft_s->usetime != 0 && sav->firstused &&
4593 now - sav->firstused > sav->lft_s->usetime) ||
4594 (sav->lft_s->bytes != 0 && counter_u64_fetch(
4595 sav->lft_c_bytes) > sav->lft_s->bytes) ||
4596 (!(sav->flags & SADB_X_SAFLAGS_ESN) &&
4597 (sav->replay != NULL) && (
4598 (sav->replay->count > UINT32_80PCT) ||
4599 (sav->replay->last > UINT32_80PCT))))) {
4600 SECASVAR_RUNLOCK(sav);
4602 LIST_INSERT_HEAD(&sexpireq, sav, drainq);
4605 SECASVAR_RUNLOCK(sav);
4610 if (LIST_EMPTY(&emptyq) && LIST_EMPTY(&drainq) &&
4611 LIST_EMPTY(&hexpireq) && LIST_EMPTY(&sexpireq))
4616 /* Unlink stale LARVAL SAs */
4617 sav = LIST_FIRST(&drainq);
4618 while (sav != NULL) {
4619 nextsav = LIST_NEXT(sav, drainq);
4620 /* Check that SA is still LARVAL */
4621 if (sav->state != SADB_SASTATE_LARVAL) {
4622 LIST_REMOVE(sav, drainq);
4623 LIST_INSERT_HEAD(&freeq, sav, drainq);
4627 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
4628 LIST_REMOVE(sav, spihash);
4629 sav->state = SADB_SASTATE_DEAD;
4632 /* Unlink all SAs with expired HARD lifetime */
4633 sav = LIST_FIRST(&hexpireq);
4634 while (sav != NULL) {
4635 nextsav = LIST_NEXT(sav, drainq);
4636 /* Check that SA is not unlinked */
4637 if (sav->state == SADB_SASTATE_DEAD) {
4638 LIST_REMOVE(sav, drainq);
4639 LIST_INSERT_HEAD(&freeq, sav, drainq);
4643 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
4644 LIST_REMOVE(sav, spihash);
4645 sav->state = SADB_SASTATE_DEAD;
4648 /* Mark all SAs with expired SOFT lifetime as DYING */
4649 sav = LIST_FIRST(&sexpireq);
4650 while (sav != NULL) {
4651 nextsav = LIST_NEXT(sav, drainq);
4652 /* Check that SA is not unlinked */
4653 if (sav->state == SADB_SASTATE_DEAD) {
4654 LIST_REMOVE(sav, drainq);
4655 LIST_INSERT_HEAD(&freeq, sav, drainq);
4660 * NOTE: this doesn't change SA order in the chain.
4662 sav->state = SADB_SASTATE_DYING;
4665 /* Unlink empty SAHs */
4666 sah = LIST_FIRST(&emptyq);
4667 while (sah != NULL) {
4668 nextsah = LIST_NEXT(sah, drainq);
4669 /* Check that SAH is still empty and not unlinked */
4670 if (sah->state == SADB_SASTATE_DEAD ||
4671 !TAILQ_EMPTY(&sah->savtree_larval) ||
4672 !TAILQ_EMPTY(&sah->savtree_alive)) {
4673 LIST_REMOVE(sah, drainq);
4674 key_freesah(&sah); /* release extra reference */
4678 TAILQ_REMOVE(&V_sahtree, sah, chain);
4679 LIST_REMOVE(sah, addrhash);
4680 sah->state = SADB_SASTATE_DEAD;
4685 /* Send SPDEXPIRE messages */
4686 sav = LIST_FIRST(&hexpireq);
4687 while (sav != NULL) {
4688 nextsav = LIST_NEXT(sav, drainq);
4690 key_freesah(&sav->sah); /* release reference from SAV */
4691 key_freesav(&sav); /* release extra reference */
4692 key_freesav(&sav); /* release last reference */
4695 sav = LIST_FIRST(&sexpireq);
4696 while (sav != NULL) {
4697 nextsav = LIST_NEXT(sav, drainq);
4699 key_freesav(&sav); /* release extra reference */
4702 /* Free stale LARVAL SAs */
4703 sav = LIST_FIRST(&drainq);
4704 while (sav != NULL) {
4705 nextsav = LIST_NEXT(sav, drainq);
4706 key_freesah(&sav->sah); /* release reference from SAV */
4707 key_freesav(&sav); /* release extra reference */
4708 key_freesav(&sav); /* release last reference */
4711 /* Free SAs that were unlinked/changed by someone else */
4712 sav = LIST_FIRST(&freeq);
4713 while (sav != NULL) {
4714 nextsav = LIST_NEXT(sav, drainq);
4715 key_freesav(&sav); /* release extra reference */
4718 /* Free empty SAH */
4719 sah = LIST_FIRST(&emptyq);
4720 while (sah != NULL) {
4721 nextsah = LIST_NEXT(sah, drainq);
4722 key_freesah(&sah); /* release extra reference */
4723 key_freesah(&sah); /* release last reference */
4729 key_flush_acq(time_t now)
4731 struct secacq *acq, *nextacq;
4735 acq = LIST_FIRST(&V_acqtree);
4736 while (acq != NULL) {
4737 nextacq = LIST_NEXT(acq, chain);
4738 if (now - acq->created > V_key_blockacq_lifetime) {
4739 LIST_REMOVE(acq, chain);
4740 LIST_REMOVE(acq, addrhash);
4741 LIST_REMOVE(acq, seqhash);
4742 free(acq, M_IPSEC_SAQ);
4750 key_flush_spacq(time_t now)
4752 struct secspacq *acq, *nextacq;
4756 for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4757 nextacq = LIST_NEXT(acq, chain);
4758 if (now - acq->created > V_key_blockacq_lifetime
4759 && __LIST_CHAINED(acq)) {
4760 LIST_REMOVE(acq, chain);
4761 free(acq, M_IPSEC_SAQ);
4769 * scanning SPD and SAD to check status for each entries,
4770 * and do to remove or to expire.
4771 * XXX: year 2038 problem may remain.
4774 key_timehandler(void *arg)
4776 VNET_ITERATOR_DECL(vnet_iter);
4777 time_t now = time_second;
4779 VNET_LIST_RLOCK_NOSLEEP();
4780 VNET_FOREACH(vnet_iter) {
4781 CURVNET_SET(vnet_iter);
4785 key_flush_spacq(now);
4788 VNET_LIST_RUNLOCK_NOSLEEP();
4790 #ifndef IPSEC_DEBUG2
4791 /* do exchange to tick time !! */
4792 callout_schedule(&key_timer, hz);
4793 #endif /* IPSEC_DEBUG2 */
4801 arc4random_buf(&value, sizeof(value));
4806 * map SADB_SATYPE_* to IPPROTO_*.
4807 * if satype == SADB_SATYPE then satype is mapped to ~0.
4809 * 0: invalid satype.
4812 key_satype2proto(uint8_t satype)
4815 case SADB_SATYPE_UNSPEC:
4816 return IPSEC_PROTO_ANY;
4817 case SADB_SATYPE_AH:
4819 case SADB_SATYPE_ESP:
4821 case SADB_X_SATYPE_IPCOMP:
4822 return IPPROTO_IPCOMP;
4823 case SADB_X_SATYPE_TCPSIGNATURE:
4832 * map IPPROTO_* to SADB_SATYPE_*
4834 * 0: invalid protocol type.
4837 key_proto2satype(uint8_t proto)
4841 return SADB_SATYPE_AH;
4843 return SADB_SATYPE_ESP;
4844 case IPPROTO_IPCOMP:
4845 return SADB_X_SATYPE_IPCOMP;
4847 return SADB_X_SATYPE_TCPSIGNATURE;
4856 * SADB_GETSPI processing is to receive
4857 * <base, (SA2), src address, dst address, (SPI range)>
4858 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4859 * tree with the status of LARVAL, and send
4860 * <base, SA(*), address(SD)>
4863 * IN: mhp: pointer to the pointer to each header.
4864 * OUT: NULL if fail.
4865 * other if success, return pointer to the message to send.
4868 key_getspi(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4870 struct secasindex saidx;
4871 struct sadb_address *src0, *dst0;
4872 struct secasvar *sav;
4873 uint32_t reqid, spi;
4875 uint8_t mode, proto;
4877 IPSEC_ASSERT(so != NULL, ("null socket"));
4878 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4879 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4880 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4882 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
4883 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST)
4884 #ifdef PFKEY_STRICT_CHECKS
4885 || SADB_CHECKHDR(mhp, SADB_EXT_SPIRANGE)
4888 ipseclog((LOG_DEBUG,
4889 "%s: invalid message: missing required header.\n",
4894 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
4895 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)
4896 #ifdef PFKEY_STRICT_CHECKS
4897 || SADB_CHECKLEN(mhp, SADB_EXT_SPIRANGE)
4900 ipseclog((LOG_DEBUG,
4901 "%s: invalid message: wrong header size.\n", __func__));
4905 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
4906 mode = IPSEC_MODE_ANY;
4909 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
4910 ipseclog((LOG_DEBUG,
4911 "%s: invalid message: wrong header size.\n",
4916 mode = ((struct sadb_x_sa2 *)
4917 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4918 reqid = ((struct sadb_x_sa2 *)
4919 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4922 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4923 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4925 /* map satype to proto */
4926 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4927 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4932 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
4933 (struct sockaddr *)(dst0 + 1));
4935 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
4939 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4941 /* SPI allocation */
4943 spi = key_do_getnewspi(
4944 (struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE], &saidx);
4947 * Requested SPI or SPI range is not available or
4954 sav = key_newsav(mhp, &saidx, spi, &error);
4959 if (sav->seq != 0) {
4962 * If the SADB_GETSPI message is in response to a
4963 * kernel-generated SADB_ACQUIRE, the sadb_msg_seq
4964 * MUST be the same as the SADB_ACQUIRE message.
4966 * XXXAE: However it doesn't definethe behaviour how to
4967 * check this and what to do if it doesn't match.
4968 * Also what we should do if it matches?
4970 * We can compare saidx used in SADB_ACQUIRE with saidx
4971 * used in SADB_GETSPI, but this probably can break
4972 * existing software. For now just warn if it doesn't match.
4974 * XXXAE: anyway it looks useless.
4976 key_acqdone(&saidx, sav->seq);
4979 printf("%s: SA(%p)\n", __func__, sav));
4980 KEYDBG(KEY_DATA, kdebug_secasv(sav));
4983 struct mbuf *n, *nn;
4984 struct sadb_sa *m_sa;
4985 struct sadb_msg *newmsg;
4988 /* create new sadb_msg to reply. */
4989 len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4990 PFKEY_ALIGN8(sizeof(struct sadb_sa));
5002 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
5003 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
5005 m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
5006 m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
5007 m_sa->sadb_sa_exttype = SADB_EXT_SA;
5008 m_sa->sadb_sa_spi = spi; /* SPI is already in network byte order */
5009 off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
5011 IPSEC_ASSERT(off == len,
5012 ("length inconsistency (off %u len %u)", off, len));
5014 n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
5015 SADB_EXT_ADDRESS_DST);
5022 if (n->m_len < sizeof(struct sadb_msg)) {
5023 n = m_pullup(n, sizeof(struct sadb_msg));
5025 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
5028 n->m_pkthdr.len = 0;
5029 for (nn = n; nn; nn = nn->m_next)
5030 n->m_pkthdr.len += nn->m_len;
5032 newmsg = mtod(n, struct sadb_msg *);
5033 newmsg->sadb_msg_seq = sav->seq;
5034 newmsg->sadb_msg_errno = 0;
5035 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5038 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5042 return (key_senderror(so, m, error));
5046 * allocating new SPI
5047 * called by key_getspi().
5050 * others: success, SPI in network byte order.
5053 key_do_getnewspi(struct sadb_spirange *spirange, struct secasindex *saidx)
5055 uint32_t min, max, newspi, t;
5058 SPI_ALLOC_LOCK_ASSERT();
5060 /* set spi range to allocate */
5061 if (spirange != NULL) {
5062 min = spirange->sadb_spirange_min;
5063 max = spirange->sadb_spirange_max;
5065 min = V_key_spi_minval;
5066 max = V_key_spi_maxval;
5068 /* IPCOMP needs 2-byte SPI */
5069 if (saidx->proto == IPPROTO_IPCOMP) {
5075 t = min; min = max; max = t;
5080 if (key_checkspidup(htonl(min))) {
5081 ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
5092 limit = atomic_load_int(&V_key_spi_trycnt);
5093 /* when requesting to allocate spi ranged */
5094 for (tries = 0; tries < limit; tries++) {
5095 /* generate pseudo-random SPI value ranged. */
5096 newspi = min + (key_random() % (max - min + 1));
5097 if (!key_checkspidup(htonl(newspi)))
5101 if (tries == limit || newspi == 0) {
5102 ipseclog((LOG_DEBUG,
5103 "%s: failed to allocate SPI.\n", __func__));
5109 keystat.getspi_count =
5110 (keystat.getspi_count + tries) / 2;
5112 return (htonl(newspi));
5116 * Find TCP-MD5 SA with corresponding secasindex.
5117 * If not found, return NULL and fill SPI with usable value if needed.
5119 static struct secasvar *
5120 key_getsav_tcpmd5(struct secasindex *saidx, uint32_t *spi)
5122 SAHTREE_RLOCK_TRACKER;
5123 struct secashead *sah;
5124 struct secasvar *sav;
5126 IPSEC_ASSERT(saidx->proto == IPPROTO_TCP, ("wrong proto"));
5128 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
5129 if (sah->saidx.proto != IPPROTO_TCP)
5131 if (!key_sockaddrcmp(&saidx->dst.sa, &sah->saidx.dst.sa, 0) &&
5132 !key_sockaddrcmp(&saidx->src.sa, &sah->saidx.src.sa, 0))
5136 if (V_key_preferred_oldsa)
5137 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
5139 sav = TAILQ_FIRST(&sah->savtree_alive);
5147 /* No SPI required */
5151 /* Check that SPI is unique */
5152 LIST_FOREACH(sav, SAVHASH_HASH(*spi), spihash) {
5153 if (sav->spi == *spi)
5158 /* SPI is already unique */
5162 /* XXX: not optimal */
5163 *spi = key_do_getnewspi(NULL, saidx);
5168 key_updateaddresses(struct socket *so, struct mbuf *m,
5169 const struct sadb_msghdr *mhp, struct secasvar *sav,
5170 struct secasindex *saidx)
5172 struct sockaddr *newaddr;
5173 struct secashead *sah;
5174 struct secasvar *newsav, *tmp;
5178 /* Check that we need to change SAH */
5179 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC)) {
5180 newaddr = (struct sockaddr *)(
5181 ((struct sadb_address *)
5182 mhp->ext[SADB_X_EXT_NEW_ADDRESS_SRC]) + 1);
5183 bcopy(newaddr, &saidx->src, newaddr->sa_len);
5184 key_porttosaddr(&saidx->src.sa, 0);
5186 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST)) {
5187 newaddr = (struct sockaddr *)(
5188 ((struct sadb_address *)
5189 mhp->ext[SADB_X_EXT_NEW_ADDRESS_DST]) + 1);
5190 bcopy(newaddr, &saidx->dst, newaddr->sa_len);
5191 key_porttosaddr(&saidx->dst.sa, 0);
5193 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC) ||
5194 !SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST)) {
5195 error = key_checksockaddrs(&saidx->src.sa, &saidx->dst.sa);
5197 ipseclog((LOG_DEBUG, "%s: invalid new sockaddr.\n",
5202 sah = key_getsah(saidx);
5204 /* create a new SA index */
5205 sah = key_newsah(saidx);
5207 ipseclog((LOG_DEBUG,
5208 "%s: No more memory.\n", __func__));
5211 isnew = 2; /* SAH is new */
5213 isnew = 1; /* existing SAH is referenced */
5216 * src and dst addresses are still the same.
5217 * Do we want to change NAT-T config?
5219 if (sav->sah->saidx.proto != IPPROTO_ESP ||
5220 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5221 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_SPORT) ||
5222 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5223 ipseclog((LOG_DEBUG,
5224 "%s: invalid message: missing required header.\n",
5228 /* We hold reference to SA, thus SAH will be referenced too. */
5233 newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA,
5235 if (newsav == NULL) {
5236 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5241 /* Clone SA's content into newsav */
5242 SAV_INITREF(newsav);
5243 bcopy(sav, newsav, offsetof(struct secasvar, chain));
5245 * We create new NAT-T config if it is needed.
5246 * Old NAT-T config will be freed by key_cleansav() when
5247 * last reference to SA will be released.
5249 newsav->natt = NULL;
5251 newsav->state = SADB_SASTATE_MATURE;
5252 error = key_setnatt(newsav, mhp);
5257 /* Check that SA is still alive */
5258 if (sav->state == SADB_SASTATE_DEAD) {
5259 /* SA was unlinked */
5265 /* Unlink SA from SAH and SPI hash */
5266 IPSEC_ASSERT((sav->flags & SADB_X_EXT_F_CLONED) == 0,
5267 ("SA is already cloned"));
5268 IPSEC_ASSERT(sav->state == SADB_SASTATE_MATURE ||
5269 sav->state == SADB_SASTATE_DYING,
5270 ("Wrong SA state %u\n", sav->state));
5271 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
5272 LIST_REMOVE(sav, spihash);
5273 sav->state = SADB_SASTATE_DEAD;
5276 * Link new SA with SAH. Keep SAs ordered by
5277 * create time (newer are first).
5279 TAILQ_FOREACH(tmp, &sah->savtree_alive, chain) {
5280 if (newsav->created > tmp->created) {
5281 TAILQ_INSERT_BEFORE(tmp, newsav, chain);
5286 TAILQ_INSERT_TAIL(&sah->savtree_alive, newsav, chain);
5288 /* Add new SA into SPI hash. */
5289 LIST_INSERT_HEAD(SAVHASH_HASH(newsav->spi), newsav, spihash);
5291 /* Add new SAH into SADB. */
5293 TAILQ_INSERT_HEAD(&V_sahtree, sah, chain);
5294 LIST_INSERT_HEAD(SAHADDRHASH_HASH(saidx), sah, addrhash);
5295 sah->state = SADB_SASTATE_MATURE;
5296 SAH_ADDREF(sah); /* newsav references new SAH */
5299 * isnew == 1 -> @sah was referenced by key_getsah().
5300 * isnew == 0 -> we use the same @sah, that was used by @sav,
5301 * and we use its reference for @newsav.
5303 SECASVAR_WLOCK(sav);
5304 /* XXX: replace cntr with pointer? */
5305 newsav->cntr = sav->cntr;
5306 sav->flags |= SADB_X_EXT_F_CLONED;
5307 SECASVAR_WUNLOCK(sav);
5312 printf("%s: SA(%p) cloned into SA(%p)\n",
5313 __func__, sav, newsav));
5314 KEYDBG(KEY_DATA, kdebug_secasv(newsav));
5316 key_freesav(&sav); /* release last reference */
5318 /* set msg buf from mhp */
5319 n = key_getmsgbuf_x1(m, mhp);
5321 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5325 key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5330 if (newsav != NULL) {
5331 if (newsav->natt != NULL)
5332 free(newsav->natt, M_IPSEC_MISC);
5333 free(newsav, M_IPSEC_SA);
5339 * SADB_UPDATE processing
5341 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5342 * key(AE), (identity(SD),) (sensitivity)>
5343 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
5345 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5346 * (identity(SD),) (sensitivity)>
5349 * m will always be freed.
5352 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5354 struct secasindex saidx;
5355 struct sadb_address *src0, *dst0;
5356 struct sadb_sa *sa0;
5357 struct secasvar *sav;
5360 uint8_t mode, proto;
5362 IPSEC_ASSERT(so != NULL, ("null socket"));
5363 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5364 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5365 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5367 /* map satype to proto */
5368 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5369 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5371 return key_senderror(so, m, EINVAL);
5374 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
5375 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5376 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5377 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
5378 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
5379 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
5380 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
5381 ipseclog((LOG_DEBUG,
5382 "%s: invalid message: missing required header.\n",
5384 return key_senderror(so, m, EINVAL);
5386 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
5387 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5388 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5389 ipseclog((LOG_DEBUG,
5390 "%s: invalid message: wrong header size.\n", __func__));
5391 return key_senderror(so, m, EINVAL);
5393 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
5394 mode = IPSEC_MODE_ANY;
5397 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
5398 ipseclog((LOG_DEBUG,
5399 "%s: invalid message: wrong header size.\n",
5401 return key_senderror(so, m, EINVAL);
5403 mode = ((struct sadb_x_sa2 *)
5404 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5405 reqid = ((struct sadb_x_sa2 *)
5406 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5409 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5410 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5411 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5414 * Only SADB_SASTATE_MATURE SAs may be submitted in an
5415 * SADB_UPDATE message.
5417 if (sa0->sadb_sa_state != SADB_SASTATE_MATURE) {
5418 ipseclog((LOG_DEBUG, "%s: invalid state.\n", __func__));
5419 #ifdef PFKEY_STRICT_CHECKS
5420 return key_senderror(so, m, EINVAL);
5423 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
5424 (struct sockaddr *)(dst0 + 1));
5426 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5427 return key_senderror(so, m, error);
5429 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5430 sav = key_getsavbyspi(sa0->sadb_sa_spi);
5432 ipseclog((LOG_DEBUG, "%s: no SA found for SPI %u\n",
5433 __func__, ntohl(sa0->sadb_sa_spi)));
5434 return key_senderror(so, m, EINVAL);
5437 * Check that SADB_UPDATE issued by the same process that did
5438 * SADB_GETSPI or SADB_ADD.
5440 if (sav->pid != mhp->msg->sadb_msg_pid) {
5441 ipseclog((LOG_DEBUG,
5442 "%s: pid mismatched (SPI %u, pid %u vs. %u)\n", __func__,
5443 ntohl(sav->spi), sav->pid, mhp->msg->sadb_msg_pid));
5445 return key_senderror(so, m, EINVAL);
5447 /* saidx should match with SA. */
5448 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_MODE_REQID) == 0) {
5449 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u\n",
5450 __func__, ntohl(sav->spi)));
5452 return key_senderror(so, m, ESRCH);
5455 if (sav->state == SADB_SASTATE_LARVAL) {
5456 if ((mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5457 SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT)) ||
5458 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5459 SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH))) {
5460 ipseclog((LOG_DEBUG,
5461 "%s: invalid message: missing required header.\n",
5464 return key_senderror(so, m, EINVAL);
5467 * We can set any values except src, dst and SPI.
5469 error = key_setsaval(sav, mhp);
5472 return (key_senderror(so, m, error));
5474 /* Change SA state to MATURE */
5476 if (sav->state != SADB_SASTATE_LARVAL) {
5477 /* SA was deleted or another thread made it MATURE. */
5480 return (key_senderror(so, m, ESRCH));
5483 * NOTE: we keep SAs in savtree_alive ordered by created
5484 * time. When SA's state changed from LARVAL to MATURE,
5485 * we update its created time in key_setsaval() and move
5486 * it into head of savtree_alive.
5488 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
5489 TAILQ_INSERT_HEAD(&sav->sah->savtree_alive, sav, chain);
5490 sav->state = SADB_SASTATE_MATURE;
5494 * For DYING and MATURE SA we can change only state
5495 * and lifetimes. Report EINVAL if something else attempted
5498 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT) ||
5499 !SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH)) {
5501 return (key_senderror(so, m, EINVAL));
5503 error = key_updatelifetimes(sav, mhp);
5506 return (key_senderror(so, m, error));
5509 * This is FreeBSD extension to RFC2367.
5510 * IKEd can specify SADB_X_EXT_NEW_ADDRESS_SRC and/or
5511 * SADB_X_EXT_NEW_ADDRESS_DST when it wants to change
5512 * SA addresses (for example to implement MOBIKE protocol
5513 * as described in RFC4555). Also we allow to change
5516 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC) ||
5517 !SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST) ||
5518 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5519 sav->natt != NULL) {
5520 error = key_updateaddresses(so, m, mhp, sav, &saidx);
5523 return (key_senderror(so, m, error));
5526 /* Check that SA is still alive */
5528 if (sav->state == SADB_SASTATE_DEAD) {
5529 /* SA was unlinked */
5532 return (key_senderror(so, m, ESRCH));
5535 * NOTE: there is possible state moving from DYING to MATURE,
5536 * but this doesn't change created time, so we won't reorder
5539 sav->state = SADB_SASTATE_MATURE;
5543 printf("%s: SA(%p)\n", __func__, sav));
5544 KEYDBG(KEY_DATA, kdebug_secasv(sav));
5550 /* set msg buf from mhp */
5551 n = key_getmsgbuf_x1(m, mhp);
5553 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5554 return key_senderror(so, m, ENOBUFS);
5558 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5563 * SADB_ADD processing
5564 * add an entry to SA database, when received
5565 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5566 * key(AE), (identity(SD),) (sensitivity)>
5569 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5570 * (identity(SD),) (sensitivity)>
5573 * IGNORE identity and sensitivity messages.
5575 * m will always be freed.
5578 key_add(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5580 struct secasindex saidx;
5581 struct sadb_address *src0, *dst0;
5582 struct sadb_sa *sa0;
5583 struct secasvar *sav;
5584 uint32_t reqid, spi;
5585 uint8_t mode, proto;
5588 IPSEC_ASSERT(so != NULL, ("null socket"));
5589 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5590 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5591 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5593 /* map satype to proto */
5594 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5595 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5597 return key_senderror(so, m, EINVAL);
5600 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
5601 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5602 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5603 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP && (
5604 SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT) ||
5605 SADB_CHECKLEN(mhp, SADB_EXT_KEY_ENCRYPT))) ||
5606 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH && (
5607 SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH) ||
5608 SADB_CHECKLEN(mhp, SADB_EXT_KEY_AUTH))) ||
5609 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
5610 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
5611 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
5612 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
5613 ipseclog((LOG_DEBUG,
5614 "%s: invalid message: missing required header.\n",
5616 return key_senderror(so, m, EINVAL);
5618 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
5619 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5620 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5621 ipseclog((LOG_DEBUG,
5622 "%s: invalid message: wrong header size.\n", __func__));
5623 return key_senderror(so, m, EINVAL);
5625 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
5626 mode = IPSEC_MODE_ANY;
5629 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
5630 ipseclog((LOG_DEBUG,
5631 "%s: invalid message: wrong header size.\n",
5633 return key_senderror(so, m, EINVAL);
5635 mode = ((struct sadb_x_sa2 *)
5636 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5637 reqid = ((struct sadb_x_sa2 *)
5638 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5641 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5642 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5643 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5646 * Only SADB_SASTATE_MATURE SAs may be submitted in an
5649 if (sa0->sadb_sa_state != SADB_SASTATE_MATURE) {
5650 ipseclog((LOG_DEBUG, "%s: invalid state.\n", __func__));
5651 #ifdef PFKEY_STRICT_CHECKS
5652 return key_senderror(so, m, EINVAL);
5655 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
5656 (struct sockaddr *)(dst0 + 1));
5658 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5659 return key_senderror(so, m, error);
5661 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5662 spi = sa0->sadb_sa_spi;
5664 * For TCP-MD5 SAs we don't use SPI. Check the uniqueness using
5666 * XXXAE: IPComp seems also doesn't use SPI.
5669 if (proto == IPPROTO_TCP) {
5670 sav = key_getsav_tcpmd5(&saidx, &spi);
5671 if (sav == NULL && spi == 0) {
5673 /* Failed to allocate SPI */
5674 ipseclog((LOG_DEBUG, "%s: SA already exists.\n",
5676 return key_senderror(so, m, EEXIST);
5678 /* XXX: SPI that we report back can have another value */
5680 /* We can create new SA only if SPI is different. */
5681 sav = key_getsavbyspi(spi);
5686 ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5687 return key_senderror(so, m, EEXIST);
5690 sav = key_newsav(mhp, &saidx, spi, &error);
5693 return key_senderror(so, m, error);
5695 printf("%s: return SA(%p)\n", __func__, sav));
5696 KEYDBG(KEY_DATA, kdebug_secasv(sav));
5698 * If SADB_ADD was in response to SADB_ACQUIRE, we need to schedule
5702 key_acqdone(&saidx, sav->seq);
5706 * Don't call key_freesav() on error here, as we would like to
5707 * keep the SA in the database.
5711 /* set msg buf from mhp */
5712 n = key_getmsgbuf_x1(m, mhp);
5714 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5715 return key_senderror(so, m, ENOBUFS);
5719 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5725 * IKEd may request the use ESP in UDP encapsulation when it detects the
5726 * presence of NAT. It uses NAT-T extension headers for such SAs to specify
5727 * parameters needed for encapsulation and decapsulation. These PF_KEY
5728 * extension headers are not standardized, so this comment addresses our
5730 * SADB_X_EXT_NAT_T_TYPE specifies type of encapsulation, we support only
5731 * UDP_ENCAP_ESPINUDP as described in RFC3948.
5732 * SADB_X_EXT_NAT_T_SPORT/DPORT specifies source and destination ports for
5733 * UDP header. We use these ports in UDP encapsulation procedure, also we
5734 * can check them in UDP decapsulation procedure.
5735 * SADB_X_EXT_NAT_T_OA[IR] specifies original address of initiator or
5736 * responder. These addresses can be used for transport mode to adjust
5737 * checksum after decapsulation and decryption. Since original IP addresses
5738 * used by peer usually different (we detected presence of NAT), TCP/UDP
5739 * pseudo header checksum and IP header checksum was calculated using original
5740 * addresses. After decapsulation and decryption we need to adjust checksum
5741 * to have correct datagram.
5743 * We expect presence of NAT-T extension headers only in SADB_ADD and
5744 * SADB_UPDATE messages. We report NAT-T extension headers in replies
5745 * to SADB_ADD, SADB_UPDATE, SADB_GET, and SADB_DUMP messages.
5748 key_setnatt(struct secasvar *sav, const struct sadb_msghdr *mhp)
5750 struct sadb_x_nat_t_port *port;
5751 struct sadb_x_nat_t_type *type;
5752 struct sadb_address *oai, *oar;
5753 struct sockaddr *sa;
5757 IPSEC_ASSERT(sav->natt == NULL, ("natt is already initialized"));
5759 * Ignore NAT-T headers if sproto isn't ESP.
5761 if (sav->sah->saidx.proto != IPPROTO_ESP)
5764 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) &&
5765 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_SPORT) &&
5766 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5767 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5768 SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_SPORT) ||
5769 SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5770 ipseclog((LOG_DEBUG,
5771 "%s: invalid message: wrong header size.\n",
5778 type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5779 if (type->sadb_x_nat_t_type_type != UDP_ENCAP_ESPINUDP) {
5780 ipseclog((LOG_DEBUG, "%s: unsupported NAT-T type %u.\n",
5781 __func__, type->sadb_x_nat_t_type_type));
5785 * Allocate storage for NAT-T config.
5786 * On error it will be released by key_cleansav().
5788 sav->natt = malloc(sizeof(struct secnatt), M_IPSEC_MISC,
5790 if (sav->natt == NULL) {
5791 PFKEYSTAT_INC(in_nomem);
5792 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5795 port = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5796 if (port->sadb_x_nat_t_port_port == 0) {
5797 ipseclog((LOG_DEBUG, "%s: invalid NAT-T sport specified.\n",
5801 sav->natt->sport = port->sadb_x_nat_t_port_port;
5802 port = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5803 if (port->sadb_x_nat_t_port_port == 0) {
5804 ipseclog((LOG_DEBUG, "%s: invalid NAT-T dport specified.\n",
5808 sav->natt->dport = port->sadb_x_nat_t_port_port;
5811 * SADB_X_EXT_NAT_T_OAI and SADB_X_EXT_NAT_T_OAR are optional
5812 * and needed only for transport mode IPsec.
5813 * Usually NAT translates only one address, but it is possible,
5814 * that both addresses could be translated.
5815 * NOTE: Value of SADB_X_EXT_NAT_T_OAI is equal to SADB_X_EXT_NAT_T_OA.
5817 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_OAI)) {
5818 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_OAI)) {
5819 ipseclog((LOG_DEBUG,
5820 "%s: invalid message: wrong header size.\n",
5824 oai = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5827 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_OAR)) {
5828 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_OAR)) {
5829 ipseclog((LOG_DEBUG,
5830 "%s: invalid message: wrong header size.\n",
5834 oar = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5838 /* Initialize addresses only for transport mode */
5839 if (sav->sah->saidx.mode != IPSEC_MODE_TUNNEL) {
5842 /* Currently we support only AF_INET */
5843 sa = (struct sockaddr *)(oai + 1);
5844 if (sa->sa_family != AF_INET ||
5845 sa->sa_len != sizeof(struct sockaddr_in)) {
5846 ipseclog((LOG_DEBUG,
5847 "%s: wrong NAT-OAi header.\n",
5851 /* Ignore address if it the same */
5852 if (((struct sockaddr_in *)sa)->sin_addr.s_addr !=
5853 sav->sah->saidx.src.sin.sin_addr.s_addr) {
5854 bcopy(sa, &sav->natt->oai.sa, sa->sa_len);
5855 sav->natt->flags |= IPSEC_NATT_F_OAI;
5856 /* Calculate checksum delta */
5857 addr = sav->sah->saidx.src.sin.sin_addr.s_addr;
5858 cksum = in_addword(cksum, ~addr >> 16);
5859 cksum = in_addword(cksum, ~addr & 0xffff);
5860 addr = sav->natt->oai.sin.sin_addr.s_addr;
5861 cksum = in_addword(cksum, addr >> 16);
5862 cksum = in_addword(cksum, addr & 0xffff);
5866 /* Currently we support only AF_INET */
5867 sa = (struct sockaddr *)(oar + 1);
5868 if (sa->sa_family != AF_INET ||
5869 sa->sa_len != sizeof(struct sockaddr_in)) {
5870 ipseclog((LOG_DEBUG,
5871 "%s: wrong NAT-OAr header.\n",
5875 /* Ignore address if it the same */
5876 if (((struct sockaddr_in *)sa)->sin_addr.s_addr !=
5877 sav->sah->saidx.dst.sin.sin_addr.s_addr) {
5878 bcopy(sa, &sav->natt->oar.sa, sa->sa_len);
5879 sav->natt->flags |= IPSEC_NATT_F_OAR;
5880 /* Calculate checksum delta */
5881 addr = sav->sah->saidx.dst.sin.sin_addr.s_addr;
5882 cksum = in_addword(cksum, ~addr >> 16);
5883 cksum = in_addword(cksum, ~addr & 0xffff);
5884 addr = sav->natt->oar.sin.sin_addr.s_addr;
5885 cksum = in_addword(cksum, addr >> 16);
5886 cksum = in_addword(cksum, addr & 0xffff);
5889 sav->natt->cksum = cksum;
5895 key_setident(struct secashead *sah, const struct sadb_msghdr *mhp)
5897 const struct sadb_ident *idsrc, *iddst;
5899 IPSEC_ASSERT(sah != NULL, ("null secashead"));
5900 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5901 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5903 /* don't make buffer if not there */
5904 if (SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_SRC) &&
5905 SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_DST)) {
5911 if (SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_SRC) ||
5912 SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_DST)) {
5913 ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5917 idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5918 iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5920 /* validity check */
5921 if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5922 ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5926 switch (idsrc->sadb_ident_type) {
5927 case SADB_IDENTTYPE_PREFIX:
5928 case SADB_IDENTTYPE_FQDN:
5929 case SADB_IDENTTYPE_USERFQDN:
5931 /* XXX do nothing */
5937 /* make structure */
5938 sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5939 if (sah->idents == NULL) {
5940 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5943 sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5944 if (sah->identd == NULL) {
5945 free(sah->idents, M_IPSEC_MISC);
5947 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5950 sah->idents->type = idsrc->sadb_ident_type;
5951 sah->idents->id = idsrc->sadb_ident_id;
5953 sah->identd->type = iddst->sadb_ident_type;
5954 sah->identd->id = iddst->sadb_ident_id;
5960 * m will not be freed on return.
5961 * it is caller's responsibility to free the result.
5963 * Called from SADB_ADD and SADB_UPDATE. Reply will contain headers
5964 * from the request in defined order.
5966 static struct mbuf *
5967 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
5971 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5972 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5973 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5975 /* create new sadb_msg to reply. */
5976 n = key_gather_mbuf(m, mhp, 1, 16, SADB_EXT_RESERVED,
5977 SADB_EXT_SA, SADB_X_EXT_SA2,
5978 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5979 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5980 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
5981 SADB_X_EXT_NAT_T_TYPE, SADB_X_EXT_NAT_T_SPORT,
5982 SADB_X_EXT_NAT_T_DPORT, SADB_X_EXT_NAT_T_OAI,
5983 SADB_X_EXT_NAT_T_OAR, SADB_X_EXT_NEW_ADDRESS_SRC,
5984 SADB_X_EXT_NEW_ADDRESS_DST);
5988 if (n->m_len < sizeof(struct sadb_msg)) {
5989 n = m_pullup(n, sizeof(struct sadb_msg));
5993 mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5994 mtod(n, struct sadb_msg *)->sadb_msg_len =
5995 PFKEY_UNIT64(n->m_pkthdr.len);
6001 * SADB_DELETE processing
6003 * <base, SA(*), address(SD)>
6004 * from the ikmpd, and set SADB_SASTATE_DEAD,
6006 * <base, SA(*), address(SD)>
6009 * m will always be freed.
6012 key_delete(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6014 struct secasindex saidx;
6015 struct sadb_address *src0, *dst0;
6016 struct secasvar *sav;
6017 struct sadb_sa *sa0;
6020 IPSEC_ASSERT(so != NULL, ("null socket"));
6021 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6022 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6023 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6025 /* map satype to proto */
6026 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6027 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6029 return key_senderror(so, m, EINVAL);
6032 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
6033 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
6034 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
6035 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
6036 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6038 return key_senderror(so, m, EINVAL);
6041 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
6042 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
6044 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
6045 (struct sockaddr *)(dst0 + 1)) != 0) {
6046 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
6047 return (key_senderror(so, m, EINVAL));
6049 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6050 if (SADB_CHECKHDR(mhp, SADB_EXT_SA)) {
6052 * Caller wants us to delete all non-LARVAL SAs
6053 * that match the src/dst. This is used during
6054 * IKE INITIAL-CONTACT.
6055 * XXXAE: this looks like some extension to RFC2367.
6057 ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
6058 return (key_delete_all(so, m, mhp, &saidx));
6060 if (SADB_CHECKLEN(mhp, SADB_EXT_SA)) {
6061 ipseclog((LOG_DEBUG,
6062 "%s: invalid message: wrong header size.\n", __func__));
6063 return (key_senderror(so, m, EINVAL));
6065 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
6067 if (proto == IPPROTO_TCP)
6068 sav = key_getsav_tcpmd5(&saidx, NULL);
6070 sav = key_getsavbyspi(sa0->sadb_sa_spi);
6073 ipseclog((LOG_DEBUG, "%s: no SA found for SPI %u.\n",
6074 __func__, ntohl(sa0->sadb_sa_spi)));
6075 return (key_senderror(so, m, ESRCH));
6077 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_HEAD) == 0) {
6078 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u.\n",
6079 __func__, ntohl(sav->spi)));
6081 return (key_senderror(so, m, ESRCH));
6084 printf("%s: SA(%p)\n", __func__, sav));
6085 KEYDBG(KEY_DATA, kdebug_secasv(sav));
6091 struct sadb_msg *newmsg;
6093 /* create new sadb_msg to reply. */
6094 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
6095 SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
6097 return key_senderror(so, m, ENOBUFS);
6099 if (n->m_len < sizeof(struct sadb_msg)) {
6100 n = m_pullup(n, sizeof(struct sadb_msg));
6102 return key_senderror(so, m, ENOBUFS);
6104 newmsg = mtod(n, struct sadb_msg *);
6105 newmsg->sadb_msg_errno = 0;
6106 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
6109 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
6114 * delete all SAs for src/dst. Called from key_delete().
6117 key_delete_all(struct socket *so, struct mbuf *m,
6118 const struct sadb_msghdr *mhp, struct secasindex *saidx)
6120 struct secasvar_queue drainq;
6121 struct secashead *sah;
6122 struct secasvar *sav, *nextsav;
6124 TAILQ_INIT(&drainq);
6126 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
6127 if (key_cmpsaidx(&sah->saidx, saidx, CMP_HEAD) == 0)
6129 /* Move all ALIVE SAs into drainq */
6130 TAILQ_CONCAT(&drainq, &sah->savtree_alive, chain);
6132 /* Unlink all queued SAs from SPI hash */
6133 TAILQ_FOREACH(sav, &drainq, chain) {
6134 sav->state = SADB_SASTATE_DEAD;
6135 LIST_REMOVE(sav, spihash);
6138 /* Now we can release reference for all SAs in drainq */
6139 sav = TAILQ_FIRST(&drainq);
6140 while (sav != NULL) {
6142 printf("%s: SA(%p)\n", __func__, sav));
6143 KEYDBG(KEY_DATA, kdebug_secasv(sav));
6144 nextsav = TAILQ_NEXT(sav, chain);
6145 key_freesah(&sav->sah); /* release reference from SAV */
6146 key_freesav(&sav); /* release last reference */
6152 struct sadb_msg *newmsg;
6154 /* create new sadb_msg to reply. */
6155 n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
6156 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
6158 return key_senderror(so, m, ENOBUFS);
6160 if (n->m_len < sizeof(struct sadb_msg)) {
6161 n = m_pullup(n, sizeof(struct sadb_msg));
6163 return key_senderror(so, m, ENOBUFS);
6165 newmsg = mtod(n, struct sadb_msg *);
6166 newmsg->sadb_msg_errno = 0;
6167 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
6170 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
6175 * Delete all alive SAs for corresponding xform.
6176 * Larval SAs have not initialized tdb_xform, so it is safe to leave them
6177 * here when xform disappears.
6180 key_delete_xform(const struct xformsw *xsp)
6182 struct secasvar_queue drainq;
6183 struct secashead *sah;
6184 struct secasvar *sav, *nextsav;
6186 TAILQ_INIT(&drainq);
6188 TAILQ_FOREACH(sah, &V_sahtree, chain) {
6189 sav = TAILQ_FIRST(&sah->savtree_alive);
6192 if (sav->tdb_xform != xsp)
6195 * It is supposed that all SAs in the chain are related to
6198 TAILQ_CONCAT(&drainq, &sah->savtree_alive, chain);
6200 /* Unlink all queued SAs from SPI hash */
6201 TAILQ_FOREACH(sav, &drainq, chain) {
6202 sav->state = SADB_SASTATE_DEAD;
6203 LIST_REMOVE(sav, spihash);
6207 /* Now we can release reference for all SAs in drainq */
6208 sav = TAILQ_FIRST(&drainq);
6209 while (sav != NULL) {
6211 printf("%s: SA(%p)\n", __func__, sav));
6212 KEYDBG(KEY_DATA, kdebug_secasv(sav));
6213 nextsav = TAILQ_NEXT(sav, chain);
6214 key_freesah(&sav->sah); /* release reference from SAV */
6215 key_freesav(&sav); /* release last reference */
6221 * SADB_GET processing
6223 * <base, SA(*), address(SD)>
6224 * from the ikmpd, and get a SP and a SA to respond,
6226 * <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
6227 * (identity(SD),) (sensitivity)>
6230 * m will always be freed.
6233 key_get(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6235 struct secasindex saidx;
6236 struct sadb_address *src0, *dst0;
6237 struct sadb_sa *sa0;
6238 struct secasvar *sav;
6241 IPSEC_ASSERT(so != NULL, ("null socket"));
6242 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6243 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6244 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6246 /* map satype to proto */
6247 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6248 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6250 return key_senderror(so, m, EINVAL);
6253 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
6254 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
6255 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST)) {
6256 ipseclog((LOG_DEBUG,
6257 "%s: invalid message: missing required header.\n",
6259 return key_senderror(so, m, EINVAL);
6261 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
6262 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
6263 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
6264 ipseclog((LOG_DEBUG,
6265 "%s: invalid message: wrong header size.\n", __func__));
6266 return key_senderror(so, m, EINVAL);
6269 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
6270 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6271 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6273 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
6274 (struct sockaddr *)(dst0 + 1)) != 0) {
6275 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
6276 return key_senderror(so, m, EINVAL);
6278 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6281 if (proto == IPPROTO_TCP)
6282 sav = key_getsav_tcpmd5(&saidx, NULL);
6284 sav = key_getsavbyspi(sa0->sadb_sa_spi);
6287 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
6288 return key_senderror(so, m, ESRCH);
6290 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_HEAD) == 0) {
6291 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u.\n",
6292 __func__, ntohl(sa0->sadb_sa_spi)));
6294 return (key_senderror(so, m, ESRCH));
6301 /* map proto to satype */
6302 if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0) {
6303 ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
6306 return key_senderror(so, m, EINVAL);
6309 /* create new sadb_msg to reply. */
6310 n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
6311 mhp->msg->sadb_msg_pid);
6315 return key_senderror(so, m, ENOBUFS);
6318 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6322 /* XXX make it sysctl-configurable? */
6324 key_getcomb_setlifetime(struct sadb_comb *comb)
6327 comb->sadb_comb_soft_allocations = 1;
6328 comb->sadb_comb_hard_allocations = 1;
6329 comb->sadb_comb_soft_bytes = 0;
6330 comb->sadb_comb_hard_bytes = 0;
6331 comb->sadb_comb_hard_addtime = 86400; /* 1 day */
6332 comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
6333 comb->sadb_comb_soft_usetime = 28800; /* 8 hours */
6334 comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
6338 * XXX reorder combinations by preference
6339 * XXX no idea if the user wants ESP authentication or not
6341 static struct mbuf *
6342 key_getcomb_ealg(void)
6344 struct sadb_comb *comb;
6345 const struct enc_xform *algo;
6346 struct mbuf *result = NULL, *m, *n;
6350 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6353 for (i = 1; i <= SADB_EALG_MAX; i++) {
6354 algo = enc_algorithm_lookup(i);
6358 /* discard algorithms with key size smaller than system min */
6359 if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6361 if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6362 encmin = V_ipsec_esp_keymin;
6364 encmin = _BITS(algo->minkey);
6366 if (V_ipsec_esp_auth)
6367 m = key_getcomb_ah();
6369 IPSEC_ASSERT(l <= MLEN,
6370 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6371 MGET(m, M_NOWAIT, MT_DATA);
6376 bzero(mtod(m, caddr_t), m->m_len);
6383 for (n = m; n; n = n->m_next)
6385 IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6387 for (off = 0; off < totlen; off += l) {
6388 n = m_pulldown(m, off, l, &o);
6390 /* m is already freed */
6393 comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6394 bzero(comb, sizeof(*comb));
6395 key_getcomb_setlifetime(comb);
6396 comb->sadb_comb_encrypt = i;
6397 comb->sadb_comb_encrypt_minbits = encmin;
6398 comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6416 key_getsizes_ah(const struct auth_hash *ah, int alg, u_int16_t* min,
6420 *min = *max = ah->hashsize;
6421 if (ah->keysize == 0) {
6423 * Transform takes arbitrary key size but algorithm
6424 * key size is restricted. Enforce this here.
6427 case SADB_X_AALG_NULL: *min = 1; *max = 256; break;
6428 case SADB_X_AALG_SHA2_256: *min = *max = 32; break;
6429 case SADB_X_AALG_SHA2_384: *min = *max = 48; break;
6430 case SADB_X_AALG_SHA2_512: *min = *max = 64; break;
6432 DPRINTF(("%s: unknown AH algorithm %u\n",
6440 * XXX reorder combinations by preference
6442 static struct mbuf *
6443 key_getcomb_ah(void)
6445 const struct auth_hash *algo;
6446 struct sadb_comb *comb;
6448 u_int16_t minkeysize, maxkeysize;
6450 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6453 for (i = 1; i <= SADB_AALG_MAX; i++) {
6455 /* we prefer HMAC algorithms, not old algorithms */
6456 if (i != SADB_AALG_SHA1HMAC &&
6457 i != SADB_X_AALG_SHA2_256 &&
6458 i != SADB_X_AALG_SHA2_384 &&
6459 i != SADB_X_AALG_SHA2_512)
6462 algo = auth_algorithm_lookup(i);
6465 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6466 /* discard algorithms with key size smaller than system min */
6467 if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6471 IPSEC_ASSERT(l <= MLEN,
6472 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6473 MGET(m, M_NOWAIT, MT_DATA);
6480 M_PREPEND(m, l, M_NOWAIT);
6484 comb = mtod(m, struct sadb_comb *);
6485 bzero(comb, sizeof(*comb));
6486 key_getcomb_setlifetime(comb);
6487 comb->sadb_comb_auth = i;
6488 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6489 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6496 * not really an official behavior. discussed in pf_key@inner.net in Sep2000.
6497 * XXX reorder combinations by preference
6499 static struct mbuf *
6500 key_getcomb_ipcomp(void)
6502 const struct comp_algo *algo;
6503 struct sadb_comb *comb;
6506 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6509 for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6510 algo = comp_algorithm_lookup(i);
6515 IPSEC_ASSERT(l <= MLEN,
6516 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6517 MGET(m, M_NOWAIT, MT_DATA);
6524 M_PREPEND(m, l, M_NOWAIT);
6528 comb = mtod(m, struct sadb_comb *);
6529 bzero(comb, sizeof(*comb));
6530 key_getcomb_setlifetime(comb);
6531 comb->sadb_comb_encrypt = i;
6532 /* what should we set into sadb_comb_*_{min,max}bits? */
6539 * XXX no way to pass mode (transport/tunnel) to userland
6540 * XXX replay checking?
6541 * XXX sysctl interface to ipsec_{ah,esp}_keymin
6543 static struct mbuf *
6544 key_getprop(const struct secasindex *saidx)
6546 struct sadb_prop *prop;
6548 const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6551 switch (saidx->proto) {
6553 m = key_getcomb_ealg();
6556 m = key_getcomb_ah();
6558 case IPPROTO_IPCOMP:
6559 m = key_getcomb_ipcomp();
6567 M_PREPEND(m, l, M_NOWAIT);
6572 for (n = m; n; n = n->m_next)
6575 prop = mtod(m, struct sadb_prop *);
6576 bzero(prop, sizeof(*prop));
6577 prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6578 prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6579 prop->sadb_prop_replay = 32; /* XXX */
6585 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6587 * <base, SA, address(SD), (address(P)), x_policy,
6588 * (identity(SD),) (sensitivity,) proposal>
6589 * to KMD, and expect to receive
6590 * <base> with SADB_ACQUIRE if error occurred,
6592 * <base, src address, dst address, (SPI range)> with SADB_GETSPI
6593 * from KMD by PF_KEY.
6595 * XXX x_policy is outside of RFC2367 (KAME extension).
6596 * XXX sensitivity is not supported.
6597 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6598 * see comment for key_getcomb_ipcomp().
6602 * others: error number
6605 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6607 union sockaddr_union addr;
6608 struct mbuf *result, *m;
6612 uint8_t mask, satype;
6614 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6615 satype = key_proto2satype(saidx->proto);
6616 IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6620 ul_proto = IPSEC_ULPROTO_ANY;
6622 /* Get seq number to check whether sending message or not. */
6623 seq = key_getacq(saidx, &error);
6627 m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6635 * set sadb_address for saidx's.
6637 * Note that if sp is supplied, then we're being called from
6638 * key_allocsa_policy() and should supply port and protocol
6640 * XXXAE: why only TCP and UDP? ICMP and SCTP looks applicable too.
6641 * XXXAE: probably we can handle this in the ipsec[46]_allocsa().
6642 * XXXAE: it looks like we should save this info in the ACQ entry.
6644 if (sp != NULL && (sp->spidx.ul_proto == IPPROTO_TCP ||
6645 sp->spidx.ul_proto == IPPROTO_UDP))
6646 ul_proto = sp->spidx.ul_proto;
6650 if (ul_proto != IPSEC_ULPROTO_ANY) {
6651 switch (sp->spidx.src.sa.sa_family) {
6653 if (sp->spidx.src.sin.sin_port != IPSEC_PORT_ANY) {
6654 addr.sin.sin_port = sp->spidx.src.sin.sin_port;
6655 mask = sp->spidx.prefs;
6659 if (sp->spidx.src.sin6.sin6_port != IPSEC_PORT_ANY) {
6660 addr.sin6.sin6_port =
6661 sp->spidx.src.sin6.sin6_port;
6662 mask = sp->spidx.prefs;
6669 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &addr.sa, mask, ul_proto);
6678 if (ul_proto != IPSEC_ULPROTO_ANY) {
6679 switch (sp->spidx.dst.sa.sa_family) {
6681 if (sp->spidx.dst.sin.sin_port != IPSEC_PORT_ANY) {
6682 addr.sin.sin_port = sp->spidx.dst.sin.sin_port;
6683 mask = sp->spidx.prefd;
6687 if (sp->spidx.dst.sin6.sin6_port != IPSEC_PORT_ANY) {
6688 addr.sin6.sin6_port =
6689 sp->spidx.dst.sin6.sin6_port;
6690 mask = sp->spidx.prefd;
6697 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &addr.sa, mask, ul_proto);
6704 /* XXX proxy address (optional) */
6707 * Set sadb_x_policy. This is KAME extension to RFC2367.
6710 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id,
6720 * Set sadb_x_sa2 extension if saidx->reqid is not zero.
6721 * This is FreeBSD extension to RFC2367.
6723 if (saidx->reqid != 0) {
6724 m = key_setsadbxsa2(saidx->mode, 0, saidx->reqid);
6731 /* XXX identity (optional) */
6733 if (idexttype && fqdn) {
6734 /* create identity extension (FQDN) */
6735 struct sadb_ident *id;
6738 fqdnlen = strlen(fqdn) + 1; /* +1 for terminating-NUL */
6739 id = (struct sadb_ident *)p;
6740 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6741 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6742 id->sadb_ident_exttype = idexttype;
6743 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6744 bcopy(fqdn, id + 1, fqdnlen);
6745 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6749 /* create identity extension (USERFQDN) */
6750 struct sadb_ident *id;
6754 /* +1 for terminating-NUL */
6755 userfqdnlen = strlen(userfqdn) + 1;
6758 id = (struct sadb_ident *)p;
6759 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6760 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6761 id->sadb_ident_exttype = idexttype;
6762 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6763 /* XXX is it correct? */
6764 if (curproc && curproc->p_cred)
6765 id->sadb_ident_id = curproc->p_cred->p_ruid;
6766 if (userfqdn && userfqdnlen)
6767 bcopy(userfqdn, id + 1, userfqdnlen);
6768 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6772 /* XXX sensitivity (optional) */
6774 /* create proposal/combination extension */
6775 m = key_getprop(saidx);
6778 * spec conformant: always attach proposal/combination extension,
6779 * the problem is that we have no way to attach it for ipcomp,
6780 * due to the way sadb_comb is declared in RFC2367.
6789 * outside of spec; make proposal/combination extension optional.
6795 if ((result->m_flags & M_PKTHDR) == 0) {
6800 if (result->m_len < sizeof(struct sadb_msg)) {
6801 result = m_pullup(result, sizeof(struct sadb_msg));
6802 if (result == NULL) {
6808 result->m_pkthdr.len = 0;
6809 for (m = result; m; m = m->m_next)
6810 result->m_pkthdr.len += m->m_len;
6812 mtod(result, struct sadb_msg *)->sadb_msg_len =
6813 PFKEY_UNIT64(result->m_pkthdr.len);
6816 printf("%s: SP(%p)\n", __func__, sp));
6817 KEYDBG(KEY_DATA, kdebug_secasindex(saidx, NULL));
6819 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6828 key_newacq(const struct secasindex *saidx, int *perror)
6833 acq = malloc(sizeof(*acq), M_IPSEC_SAQ, M_NOWAIT | M_ZERO);
6835 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6841 bcopy(saidx, &acq->saidx, sizeof(acq->saidx));
6842 acq->created = time_second;
6845 /* add to acqtree */
6847 seq = acq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6848 LIST_INSERT_HEAD(&V_acqtree, acq, chain);
6849 LIST_INSERT_HEAD(ACQADDRHASH_HASH(saidx), acq, addrhash);
6850 LIST_INSERT_HEAD(ACQSEQHASH_HASH(seq), acq, seqhash);
6857 key_getacq(const struct secasindex *saidx, int *perror)
6863 LIST_FOREACH(acq, ACQADDRHASH_HASH(saidx), addrhash) {
6864 if (key_cmpsaidx(&acq->saidx, saidx, CMP_EXACTLY)) {
6865 if (acq->count > V_key_blockacq_count) {
6867 * Reset counter and send message.
6868 * Also reset created time to keep ACQ for
6871 acq->created = time_second;
6876 * Increment counter and do nothing.
6877 * We send SADB_ACQUIRE message only
6878 * for each V_key_blockacq_count packet.
6891 /* allocate new entry */
6892 return (key_newacq(saidx, perror));
6896 key_acqreset(uint32_t seq)
6901 LIST_FOREACH(acq, ACQSEQHASH_HASH(seq), seqhash) {
6902 if (acq->seq == seq) {
6904 acq->created = time_second;
6914 * Mark ACQ entry as stale to remove it in key_flush_acq().
6915 * Called after successful SADB_GETSPI message.
6918 key_acqdone(const struct secasindex *saidx, uint32_t seq)
6923 LIST_FOREACH(acq, ACQSEQHASH_HASH(seq), seqhash) {
6924 if (acq->seq == seq)
6928 if (key_cmpsaidx(&acq->saidx, saidx, CMP_EXACTLY) == 0) {
6929 ipseclog((LOG_DEBUG,
6930 "%s: Mismatched saidx for ACQ %u\n", __func__, seq));
6936 ipseclog((LOG_DEBUG,
6937 "%s: ACQ %u is not found.\n", __func__, seq));
6945 static struct secspacq *
6946 key_newspacq(struct secpolicyindex *spidx)
6948 struct secspacq *acq;
6951 acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6953 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6958 bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6959 acq->created = time_second;
6962 /* add to spacqtree */
6964 LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6970 static struct secspacq *
6971 key_getspacq(struct secpolicyindex *spidx)
6973 struct secspacq *acq;
6976 LIST_FOREACH(acq, &V_spacqtree, chain) {
6977 if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6978 /* NB: return holding spacq_lock */
6988 * SADB_ACQUIRE processing,
6989 * in first situation, is receiving
6991 * from the ikmpd, and clear sequence of its secasvar entry.
6993 * In second situation, is receiving
6994 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6995 * from a user land process, and return
6996 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6999 * m will always be freed.
7002 key_acquire2(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7004 SAHTREE_RLOCK_TRACKER;
7005 struct sadb_address *src0, *dst0;
7006 struct secasindex saidx;
7007 struct secashead *sah;
7010 uint8_t mode, proto;
7012 IPSEC_ASSERT(so != NULL, ("null socket"));
7013 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7014 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7015 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7018 * Error message from KMd.
7019 * We assume that if error was occurred in IKEd, the length of PFKEY
7020 * message is equal to the size of sadb_msg structure.
7021 * We do not raise error even if error occurred in this function.
7023 if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
7024 /* check sequence number */
7025 if (mhp->msg->sadb_msg_seq == 0 ||
7026 mhp->msg->sadb_msg_errno == 0) {
7027 ipseclog((LOG_DEBUG, "%s: must specify sequence "
7028 "number and errno.\n", __func__));
7031 * IKEd reported that error occurred.
7032 * XXXAE: what it expects from the kernel?
7033 * Probably we should send SADB_ACQUIRE again?
7034 * If so, reset ACQ's state.
7035 * XXXAE: it looks useless.
7037 key_acqreset(mhp->msg->sadb_msg_seq);
7044 * This message is from user land.
7047 /* map satype to proto */
7048 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7049 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7051 return key_senderror(so, m, EINVAL);
7054 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
7055 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
7056 SADB_CHECKHDR(mhp, SADB_EXT_PROPOSAL)) {
7057 ipseclog((LOG_DEBUG,
7058 "%s: invalid message: missing required header.\n",
7060 return key_senderror(so, m, EINVAL);
7062 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
7063 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
7064 SADB_CHECKLEN(mhp, SADB_EXT_PROPOSAL)) {
7065 ipseclog((LOG_DEBUG,
7066 "%s: invalid message: wrong header size.\n", __func__));
7067 return key_senderror(so, m, EINVAL);
7070 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
7071 mode = IPSEC_MODE_ANY;
7074 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
7075 ipseclog((LOG_DEBUG,
7076 "%s: invalid message: wrong header size.\n",
7078 return key_senderror(so, m, EINVAL);
7080 mode = ((struct sadb_x_sa2 *)
7081 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
7082 reqid = ((struct sadb_x_sa2 *)
7083 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
7086 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
7087 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
7089 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
7090 (struct sockaddr *)(dst0 + 1));
7092 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
7093 return key_senderror(so, m, EINVAL);
7095 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
7097 /* get a SA index */
7099 LIST_FOREACH(sah, SAHADDRHASH_HASH(&saidx), addrhash) {
7100 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
7105 ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
7106 return key_senderror(so, m, EEXIST);
7109 error = key_acquire(&saidx, NULL);
7111 ipseclog((LOG_DEBUG,
7112 "%s: error %d returned from key_acquire()\n",
7114 return key_senderror(so, m, error);
7121 * SADB_REGISTER processing.
7122 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
7125 * from the ikmpd, and register a socket to send PF_KEY messages,
7129 * If socket is detached, must free from regnode.
7131 * m will always be freed.
7134 key_register(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7136 struct secreg *reg, *newreg = NULL;
7138 IPSEC_ASSERT(so != NULL, ("null socket"));
7139 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7140 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7141 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7143 /* check for invalid register message */
7144 if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
7145 return key_senderror(so, m, EINVAL);
7147 /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
7148 if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
7151 /* check whether existing or not */
7153 LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
7154 if (reg->so == so) {
7156 ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
7158 return key_senderror(so, m, EEXIST);
7162 /* create regnode */
7163 newreg = malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
7164 if (newreg == NULL) {
7166 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7167 return key_senderror(so, m, ENOBUFS);
7171 ((struct keycb *)(so->so_pcb))->kp_registered++;
7173 /* add regnode to regtree. */
7174 LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
7180 struct sadb_msg *newmsg;
7181 struct sadb_supported *sup;
7182 u_int len, alen, elen;
7185 struct sadb_alg *alg;
7187 /* create new sadb_msg to reply. */
7189 for (i = 1; i <= SADB_AALG_MAX; i++) {
7190 if (auth_algorithm_lookup(i))
7191 alen += sizeof(struct sadb_alg);
7194 alen += sizeof(struct sadb_supported);
7196 for (i = 1; i <= SADB_EALG_MAX; i++) {
7197 if (enc_algorithm_lookup(i))
7198 elen += sizeof(struct sadb_alg);
7201 elen += sizeof(struct sadb_supported);
7203 len = sizeof(struct sadb_msg) + alen + elen;
7206 return key_senderror(so, m, ENOBUFS);
7210 return key_senderror(so, m, ENOBUFS);
7212 n->m_pkthdr.len = n->m_len = len;
7216 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
7217 newmsg = mtod(n, struct sadb_msg *);
7218 newmsg->sadb_msg_errno = 0;
7219 newmsg->sadb_msg_len = PFKEY_UNIT64(len);
7220 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
7222 /* for authentication algorithm */
7224 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
7225 sup->sadb_supported_len = PFKEY_UNIT64(alen);
7226 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
7227 off += PFKEY_ALIGN8(sizeof(*sup));
7229 for (i = 1; i <= SADB_AALG_MAX; i++) {
7230 const struct auth_hash *aalgo;
7231 u_int16_t minkeysize, maxkeysize;
7233 aalgo = auth_algorithm_lookup(i);
7236 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
7237 alg->sadb_alg_id = i;
7238 alg->sadb_alg_ivlen = 0;
7239 key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
7240 alg->sadb_alg_minbits = _BITS(minkeysize);
7241 alg->sadb_alg_maxbits = _BITS(maxkeysize);
7242 off += PFKEY_ALIGN8(sizeof(*alg));
7246 /* for encryption algorithm */
7248 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
7249 sup->sadb_supported_len = PFKEY_UNIT64(elen);
7250 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
7251 off += PFKEY_ALIGN8(sizeof(*sup));
7253 for (i = 1; i <= SADB_EALG_MAX; i++) {
7254 const struct enc_xform *ealgo;
7256 ealgo = enc_algorithm_lookup(i);
7259 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
7260 alg->sadb_alg_id = i;
7261 alg->sadb_alg_ivlen = ealgo->ivsize;
7262 alg->sadb_alg_minbits = _BITS(ealgo->minkey);
7263 alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
7264 off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
7268 IPSEC_ASSERT(off == len,
7269 ("length assumption failed (off %u len %u)", off, len));
7272 return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
7277 * free secreg entry registered.
7278 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
7281 key_freereg(struct socket *so)
7286 IPSEC_ASSERT(so != NULL, ("NULL so"));
7289 * check whether existing or not.
7290 * check all type of SA, because there is a potential that
7291 * one socket is registered to multiple type of SA.
7294 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7295 LIST_FOREACH(reg, &V_regtree[i], chain) {
7296 if (reg->so == so && __LIST_CHAINED(reg)) {
7297 LIST_REMOVE(reg, chain);
7298 free(reg, M_IPSEC_SAR);
7307 * SADB_EXPIRE processing
7309 * <base, SA, SA2, lifetime(C and one of HS), address(SD)>
7311 * NOTE: We send only soft lifetime extension.
7314 * others : error number
7317 key_expire(struct secasvar *sav, int hard)
7319 struct mbuf *result = NULL, *m;
7320 struct sadb_lifetime *lt;
7321 uint32_t replay_count;
7325 SECASVAR_RLOCK_TRACKER;
7327 IPSEC_ASSERT (sav != NULL, ("null sav"));
7328 IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
7331 printf("%s: SA(%p) expired %s lifetime\n", __func__,
7332 sav, hard ? "hard": "soft"));
7333 KEYDBG(KEY_DATA, kdebug_secasv(sav));
7334 /* set msg header */
7335 satype = key_proto2satype(sav->sah->saidx.proto);
7336 IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
7337 m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
7344 /* create SA extension */
7345 m = key_setsadbsa(sav);
7352 /* create SA extension */
7353 SECASVAR_RLOCK(sav);
7354 replay_count = sav->replay ? sav->replay->count : 0;
7355 SECASVAR_RUNLOCK(sav);
7357 m = key_setsadbxsa2(sav->sah->saidx.mode, replay_count,
7358 sav->sah->saidx.reqid);
7365 if (sav->replay && sav->replay->wsize > UINT8_MAX) {
7366 m = key_setsadbxsareplay(sav->replay->wsize);
7374 /* create lifetime extension (current and soft) */
7375 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
7376 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
7383 bzero(mtod(m, caddr_t), len);
7384 lt = mtod(m, struct sadb_lifetime *);
7385 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7386 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
7387 lt->sadb_lifetime_allocations =
7388 (uint32_t)counter_u64_fetch(sav->lft_c_allocations);
7389 lt->sadb_lifetime_bytes =
7390 counter_u64_fetch(sav->lft_c_bytes);
7391 lt->sadb_lifetime_addtime = sav->created;
7392 lt->sadb_lifetime_usetime = sav->firstused;
7393 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
7394 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7396 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
7397 lt->sadb_lifetime_allocations = sav->lft_h->allocations;
7398 lt->sadb_lifetime_bytes = sav->lft_h->bytes;
7399 lt->sadb_lifetime_addtime = sav->lft_h->addtime;
7400 lt->sadb_lifetime_usetime = sav->lft_h->usetime;
7402 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
7403 lt->sadb_lifetime_allocations = sav->lft_s->allocations;
7404 lt->sadb_lifetime_bytes = sav->lft_s->bytes;
7405 lt->sadb_lifetime_addtime = sav->lft_s->addtime;
7406 lt->sadb_lifetime_usetime = sav->lft_s->usetime;
7410 /* set sadb_address for source */
7411 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
7412 &sav->sah->saidx.src.sa,
7413 FULLMASK, IPSEC_ULPROTO_ANY);
7420 /* set sadb_address for destination */
7421 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
7422 &sav->sah->saidx.dst.sa,
7423 FULLMASK, IPSEC_ULPROTO_ANY);
7431 * XXX-BZ Handle NAT-T extensions here.
7432 * XXXAE: it doesn't seem quite useful. IKEs should not depend on
7433 * this information, we report only significant SA fields.
7436 if ((result->m_flags & M_PKTHDR) == 0) {
7441 if (result->m_len < sizeof(struct sadb_msg)) {
7442 result = m_pullup(result, sizeof(struct sadb_msg));
7443 if (result == NULL) {
7449 result->m_pkthdr.len = 0;
7450 for (m = result; m; m = m->m_next)
7451 result->m_pkthdr.len += m->m_len;
7453 mtod(result, struct sadb_msg *)->sadb_msg_len =
7454 PFKEY_UNIT64(result->m_pkthdr.len);
7456 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7465 key_freesah_flushed(struct secashead_queue *flushq)
7467 struct secashead *sah, *nextsah;
7468 struct secasvar *sav, *nextsav;
7470 sah = TAILQ_FIRST(flushq);
7471 while (sah != NULL) {
7472 sav = TAILQ_FIRST(&sah->savtree_larval);
7473 while (sav != NULL) {
7474 nextsav = TAILQ_NEXT(sav, chain);
7475 TAILQ_REMOVE(&sah->savtree_larval, sav, chain);
7476 key_freesav(&sav); /* release last reference */
7477 key_freesah(&sah); /* release reference from SAV */
7480 sav = TAILQ_FIRST(&sah->savtree_alive);
7481 while (sav != NULL) {
7482 nextsav = TAILQ_NEXT(sav, chain);
7483 TAILQ_REMOVE(&sah->savtree_alive, sav, chain);
7484 key_freesav(&sav); /* release last reference */
7485 key_freesah(&sah); /* release reference from SAV */
7488 nextsah = TAILQ_NEXT(sah, chain);
7489 key_freesah(&sah); /* release last reference */
7495 * SADB_FLUSH processing
7498 * from the ikmpd, and free all entries in secastree.
7502 * NOTE: to do is only marking SADB_SASTATE_DEAD.
7504 * m will always be freed.
7507 key_flush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7509 struct secashead_queue flushq;
7510 struct sadb_msg *newmsg;
7511 struct secashead *sah, *nextsah;
7512 struct secasvar *sav;
7516 IPSEC_ASSERT(so != NULL, ("null socket"));
7517 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7518 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7520 /* map satype to proto */
7521 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7522 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7524 return key_senderror(so, m, EINVAL);
7527 printf("%s: proto %u\n", __func__, proto));
7529 TAILQ_INIT(&flushq);
7530 if (proto == IPSEC_PROTO_ANY) {
7531 /* no SATYPE specified, i.e. flushing all SA. */
7533 /* Move all SAHs into flushq */
7534 TAILQ_CONCAT(&flushq, &V_sahtree, chain);
7535 /* Flush all buckets in SPI hash */
7536 for (i = 0; i < V_savhash_mask + 1; i++)
7537 LIST_INIT(&V_savhashtbl[i]);
7538 /* Flush all buckets in SAHADDRHASH */
7539 for (i = 0; i < V_sahaddrhash_mask + 1; i++)
7540 LIST_INIT(&V_sahaddrhashtbl[i]);
7541 /* Mark all SAHs as unlinked */
7542 TAILQ_FOREACH(sah, &flushq, chain) {
7543 sah->state = SADB_SASTATE_DEAD;
7545 * Callout handler makes its job using
7546 * RLOCK and drain queues. In case, when this
7547 * function will be called just before it
7548 * acquires WLOCK, we need to mark SAs as
7549 * unlinked to prevent second unlink.
7551 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7552 sav->state = SADB_SASTATE_DEAD;
7554 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7555 sav->state = SADB_SASTATE_DEAD;
7561 sah = TAILQ_FIRST(&V_sahtree);
7562 while (sah != NULL) {
7563 IPSEC_ASSERT(sah->state != SADB_SASTATE_DEAD,
7564 ("DEAD SAH %p in SADB_FLUSH", sah));
7565 nextsah = TAILQ_NEXT(sah, chain);
7566 if (sah->saidx.proto != proto) {
7570 sah->state = SADB_SASTATE_DEAD;
7571 TAILQ_REMOVE(&V_sahtree, sah, chain);
7572 LIST_REMOVE(sah, addrhash);
7573 /* Unlink all SAs from SPI hash */
7574 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7575 LIST_REMOVE(sav, spihash);
7576 sav->state = SADB_SASTATE_DEAD;
7578 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7579 LIST_REMOVE(sav, spihash);
7580 sav->state = SADB_SASTATE_DEAD;
7582 /* Add SAH into flushq */
7583 TAILQ_INSERT_HEAD(&flushq, sah, chain);
7589 key_freesah_flushed(&flushq);
7590 /* Free all queued SAs and SAHs */
7591 if (m->m_len < sizeof(struct sadb_msg) ||
7592 sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7593 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7594 return key_senderror(so, m, ENOBUFS);
7600 m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7601 newmsg = mtod(m, struct sadb_msg *);
7602 newmsg->sadb_msg_errno = 0;
7603 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7605 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7609 * SADB_DUMP processing
7610 * dump all entries including status of DEAD in SAD.
7613 * from the ikmpd, and dump all secasvar leaves
7618 * m will always be freed.
7621 key_dump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7623 SAHTREE_RLOCK_TRACKER;
7624 struct secashead *sah;
7625 struct secasvar *sav;
7628 uint8_t proto, satype;
7630 IPSEC_ASSERT(so != NULL, ("null socket"));
7631 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7632 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7633 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7635 /* map satype to proto */
7636 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7637 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7639 return key_senderror(so, m, EINVAL);
7642 /* count sav entries to be sent to the userland. */
7645 TAILQ_FOREACH(sah, &V_sahtree, chain) {
7646 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
7647 proto != sah->saidx.proto)
7650 TAILQ_FOREACH(sav, &sah->savtree_larval, chain)
7652 TAILQ_FOREACH(sav, &sah->savtree_alive, chain)
7658 return key_senderror(so, m, ENOENT);
7661 /* send this to the userland, one at a time. */
7662 TAILQ_FOREACH(sah, &V_sahtree, chain) {
7663 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
7664 proto != sah->saidx.proto)
7667 /* map proto to satype */
7668 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7670 ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7671 "SAD.\n", __func__));
7672 return key_senderror(so, m, EINVAL);
7674 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7675 n = key_setdumpsa(sav, SADB_DUMP, satype,
7676 --cnt, mhp->msg->sadb_msg_pid);
7679 return key_senderror(so, m, ENOBUFS);
7681 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7683 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7684 n = key_setdumpsa(sav, SADB_DUMP, satype,
7685 --cnt, mhp->msg->sadb_msg_pid);
7688 return key_senderror(so, m, ENOBUFS);
7690 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7698 * SADB_X_PROMISC processing
7700 * m will always be freed.
7703 key_promisc(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7707 IPSEC_ASSERT(so != NULL, ("null socket"));
7708 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7709 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7710 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7712 olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7714 if (olen < sizeof(struct sadb_msg)) {
7716 return key_senderror(so, m, EINVAL);
7721 } else if (olen == sizeof(struct sadb_msg)) {
7722 /* enable/disable promisc mode */
7725 if ((kp = so->so_pcb) == NULL)
7726 return key_senderror(so, m, EINVAL);
7727 mhp->msg->sadb_msg_errno = 0;
7728 switch (mhp->msg->sadb_msg_satype) {
7731 kp->kp_promisc = mhp->msg->sadb_msg_satype;
7734 return key_senderror(so, m, EINVAL);
7737 /* send the original message back to everyone */
7738 mhp->msg->sadb_msg_errno = 0;
7739 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7741 /* send packet as is */
7743 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7745 /* TODO: if sadb_msg_seq is specified, send to specific pid */
7746 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7750 static int (*key_typesw[])(struct socket *, struct mbuf *,
7751 const struct sadb_msghdr *) = {
7752 [SADB_RESERVED] = NULL,
7753 [SADB_GETSPI] = key_getspi,
7754 [SADB_UPDATE] = key_update,
7755 [SADB_ADD] = key_add,
7756 [SADB_DELETE] = key_delete,
7757 [SADB_GET] = key_get,
7758 [SADB_ACQUIRE] = key_acquire2,
7759 [SADB_REGISTER] = key_register,
7760 [SADB_EXPIRE] = NULL,
7761 [SADB_FLUSH] = key_flush,
7762 [SADB_DUMP] = key_dump,
7763 [SADB_X_PROMISC] = key_promisc,
7764 [SADB_X_PCHANGE] = NULL,
7765 [SADB_X_SPDUPDATE] = key_spdadd,
7766 [SADB_X_SPDADD] = key_spdadd,
7767 [SADB_X_SPDDELETE] = key_spddelete,
7768 [SADB_X_SPDGET] = key_spdget,
7769 [SADB_X_SPDACQUIRE] = NULL,
7770 [SADB_X_SPDDUMP] = key_spddump,
7771 [SADB_X_SPDFLUSH] = key_spdflush,
7772 [SADB_X_SPDSETIDX] = key_spdadd,
7773 [SADB_X_SPDEXPIRE] = NULL,
7774 [SADB_X_SPDDELETE2] = key_spddelete2,
7778 * parse sadb_msg buffer to process PFKEYv2,
7779 * and create a data to response if needed.
7780 * I think to be dealed with mbuf directly.
7782 * msgp : pointer to pointer to a received buffer pulluped.
7783 * This is rewrited to response.
7784 * so : pointer to socket.
7786 * length for buffer to send to user process.
7789 key_parse(struct mbuf *m, struct socket *so)
7791 struct sadb_msg *msg;
7792 struct sadb_msghdr mh;
7797 IPSEC_ASSERT(so != NULL, ("null socket"));
7798 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7800 if (m->m_len < sizeof(struct sadb_msg)) {
7801 m = m_pullup(m, sizeof(struct sadb_msg));
7805 msg = mtod(m, struct sadb_msg *);
7806 orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7807 target = KEY_SENDUP_ONE;
7809 if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len != orglen) {
7810 ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7811 PFKEYSTAT_INC(out_invlen);
7816 if (msg->sadb_msg_version != PF_KEY_V2) {
7817 ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7818 __func__, msg->sadb_msg_version));
7819 PFKEYSTAT_INC(out_invver);
7824 if (msg->sadb_msg_type > SADB_MAX) {
7825 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7826 __func__, msg->sadb_msg_type));
7827 PFKEYSTAT_INC(out_invmsgtype);
7832 /* for old-fashioned code - should be nuked */
7833 if (m->m_pkthdr.len > MCLBYTES) {
7840 n = key_mget(m->m_pkthdr.len);
7845 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7846 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7852 /* align the mbuf chain so that extensions are in contiguous region. */
7853 error = key_align(m, &mh);
7859 /* We use satype as scope mask for spddump */
7860 if (msg->sadb_msg_type == SADB_X_SPDDUMP) {
7861 switch (msg->sadb_msg_satype) {
7862 case IPSEC_POLICYSCOPE_ANY:
7863 case IPSEC_POLICYSCOPE_GLOBAL:
7864 case IPSEC_POLICYSCOPE_IFNET:
7865 case IPSEC_POLICYSCOPE_PCB:
7868 ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7869 __func__, msg->sadb_msg_type));
7870 PFKEYSTAT_INC(out_invsatype);
7875 switch (msg->sadb_msg_satype) { /* check SA type */
7876 case SADB_SATYPE_UNSPEC:
7877 switch (msg->sadb_msg_type) {
7885 ipseclog((LOG_DEBUG, "%s: must specify satype "
7886 "when msg type=%u.\n", __func__,
7887 msg->sadb_msg_type));
7888 PFKEYSTAT_INC(out_invsatype);
7893 case SADB_SATYPE_AH:
7894 case SADB_SATYPE_ESP:
7895 case SADB_X_SATYPE_IPCOMP:
7896 case SADB_X_SATYPE_TCPSIGNATURE:
7897 switch (msg->sadb_msg_type) {
7899 case SADB_X_SPDDELETE:
7901 case SADB_X_SPDFLUSH:
7902 case SADB_X_SPDSETIDX:
7903 case SADB_X_SPDUPDATE:
7904 case SADB_X_SPDDELETE2:
7905 ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7906 __func__, msg->sadb_msg_type));
7907 PFKEYSTAT_INC(out_invsatype);
7912 case SADB_SATYPE_RSVP:
7913 case SADB_SATYPE_OSPFV2:
7914 case SADB_SATYPE_RIPV2:
7915 case SADB_SATYPE_MIP:
7916 ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7917 __func__, msg->sadb_msg_satype));
7918 PFKEYSTAT_INC(out_invsatype);
7921 case 1: /* XXX: What does it do? */
7922 if (msg->sadb_msg_type == SADB_X_PROMISC)
7926 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7927 __func__, msg->sadb_msg_satype));
7928 PFKEYSTAT_INC(out_invsatype);
7934 /* check field of upper layer protocol and address family */
7935 if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7936 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7937 struct sadb_address *src0, *dst0;
7940 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7941 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7943 /* check upper layer protocol */
7944 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7945 ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7946 "mismatched.\n", __func__));
7947 PFKEYSTAT_INC(out_invaddr);
7953 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7954 PFKEY_ADDR_SADDR(dst0)->sa_family) {
7955 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7957 PFKEYSTAT_INC(out_invaddr);
7961 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7962 PFKEY_ADDR_SADDR(dst0)->sa_len) {
7963 ipseclog((LOG_DEBUG, "%s: address struct size "
7964 "mismatched.\n", __func__));
7965 PFKEYSTAT_INC(out_invaddr);
7970 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7972 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7973 sizeof(struct sockaddr_in)) {
7974 PFKEYSTAT_INC(out_invaddr);
7980 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7981 sizeof(struct sockaddr_in6)) {
7982 PFKEYSTAT_INC(out_invaddr);
7988 ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7990 PFKEYSTAT_INC(out_invaddr);
7991 error = EAFNOSUPPORT;
7995 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7997 plen = sizeof(struct in_addr) << 3;
8000 plen = sizeof(struct in6_addr) << 3;
8003 plen = 0; /*fool gcc*/
8007 /* check max prefix length */
8008 if (src0->sadb_address_prefixlen > plen ||
8009 dst0->sadb_address_prefixlen > plen) {
8010 ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
8012 PFKEYSTAT_INC(out_invaddr);
8018 * prefixlen == 0 is valid because there can be a case when
8019 * all addresses are matched.
8023 if (msg->sadb_msg_type >= nitems(key_typesw) ||
8024 key_typesw[msg->sadb_msg_type] == NULL) {
8025 PFKEYSTAT_INC(out_invmsgtype);
8030 return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
8033 msg->sadb_msg_errno = error;
8034 return key_sendup_mbuf(so, m, target);
8038 key_senderror(struct socket *so, struct mbuf *m, int code)
8040 struct sadb_msg *msg;
8042 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
8043 ("mbuf too small, len %u", m->m_len));
8045 msg = mtod(m, struct sadb_msg *);
8046 msg->sadb_msg_errno = code;
8047 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
8051 * set the pointer to each header into message buffer.
8052 * m will be freed on error.
8053 * XXX larger-than-MCLBYTES extension?
8056 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
8059 struct sadb_ext *ext;
8064 IPSEC_ASSERT(m != NULL, ("null mbuf"));
8065 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
8066 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
8067 ("mbuf too small, len %u", m->m_len));
8070 bzero(mhp, sizeof(*mhp));
8072 mhp->msg = mtod(m, struct sadb_msg *);
8073 mhp->ext[0] = (struct sadb_ext *)mhp->msg; /*XXX backward compat */
8075 end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
8076 extlen = end; /*just in case extlen is not updated*/
8077 for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
8078 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
8080 /* m is already freed */
8083 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
8086 switch (ext->sadb_ext_type) {
8088 case SADB_EXT_ADDRESS_SRC:
8089 case SADB_EXT_ADDRESS_DST:
8090 case SADB_EXT_ADDRESS_PROXY:
8091 case SADB_EXT_LIFETIME_CURRENT:
8092 case SADB_EXT_LIFETIME_HARD:
8093 case SADB_EXT_LIFETIME_SOFT:
8094 case SADB_EXT_KEY_AUTH:
8095 case SADB_EXT_KEY_ENCRYPT:
8096 case SADB_EXT_IDENTITY_SRC:
8097 case SADB_EXT_IDENTITY_DST:
8098 case SADB_EXT_SENSITIVITY:
8099 case SADB_EXT_PROPOSAL:
8100 case SADB_EXT_SUPPORTED_AUTH:
8101 case SADB_EXT_SUPPORTED_ENCRYPT:
8102 case SADB_EXT_SPIRANGE:
8103 case SADB_X_EXT_POLICY:
8104 case SADB_X_EXT_SA2:
8105 case SADB_X_EXT_NAT_T_TYPE:
8106 case SADB_X_EXT_NAT_T_SPORT:
8107 case SADB_X_EXT_NAT_T_DPORT:
8108 case SADB_X_EXT_NAT_T_OAI:
8109 case SADB_X_EXT_NAT_T_OAR:
8110 case SADB_X_EXT_NAT_T_FRAG:
8111 case SADB_X_EXT_SA_REPLAY:
8112 case SADB_X_EXT_NEW_ADDRESS_SRC:
8113 case SADB_X_EXT_NEW_ADDRESS_DST:
8114 /* duplicate check */
8116 * XXX Are there duplication payloads of either
8117 * KEY_AUTH or KEY_ENCRYPT ?
8119 if (mhp->ext[ext->sadb_ext_type] != NULL) {
8120 ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
8121 "%u\n", __func__, ext->sadb_ext_type));
8123 PFKEYSTAT_INC(out_dupext);
8128 ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
8129 __func__, ext->sadb_ext_type));
8131 PFKEYSTAT_INC(out_invexttype);
8135 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
8137 if (key_validate_ext(ext, extlen)) {
8139 PFKEYSTAT_INC(out_invlen);
8143 n = m_pulldown(m, off, extlen, &toff);
8145 /* m is already freed */
8148 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
8150 mhp->ext[ext->sadb_ext_type] = ext;
8151 mhp->extoff[ext->sadb_ext_type] = off;
8152 mhp->extlen[ext->sadb_ext_type] = extlen;
8157 PFKEYSTAT_INC(out_invlen);
8165 key_validate_ext(const struct sadb_ext *ext, int len)
8167 const struct sockaddr *sa;
8168 enum { NONE, ADDR } checktype = NONE;
8170 const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
8172 if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
8175 /* if it does not match minimum/maximum length, bail */
8176 if (ext->sadb_ext_type >= nitems(minsize) ||
8177 ext->sadb_ext_type >= nitems(maxsize))
8179 if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
8181 if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
8184 /* more checks based on sadb_ext_type XXX need more */
8185 switch (ext->sadb_ext_type) {
8186 case SADB_EXT_ADDRESS_SRC:
8187 case SADB_EXT_ADDRESS_DST:
8188 case SADB_EXT_ADDRESS_PROXY:
8189 case SADB_X_EXT_NAT_T_OAI:
8190 case SADB_X_EXT_NAT_T_OAR:
8191 case SADB_X_EXT_NEW_ADDRESS_SRC:
8192 case SADB_X_EXT_NEW_ADDRESS_DST:
8193 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
8196 case SADB_EXT_IDENTITY_SRC:
8197 case SADB_EXT_IDENTITY_DST:
8198 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
8199 SADB_X_IDENTTYPE_ADDR) {
8200 baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
8210 switch (checktype) {
8214 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
8215 if (len < baselen + sal)
8217 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
8230 TUNABLE_INT_FETCH("net.key.spdcache.maxentries",
8231 &V_key_spdcache_maxentries);
8232 TUNABLE_INT_FETCH("net.key.spdcache.threshold",
8233 &V_key_spdcache_threshold);
8235 if (V_key_spdcache_maxentries) {
8236 V_key_spdcache_maxentries = MAX(V_key_spdcache_maxentries,
8237 SPDCACHE_MAX_ENTRIES_PER_HASH);
8238 V_spdcachehashtbl = hashinit(V_key_spdcache_maxentries /
8239 SPDCACHE_MAX_ENTRIES_PER_HASH,
8240 M_IPSEC_SPDCACHE, &V_spdcachehash_mask);
8241 V_key_spdcache_maxentries = (V_spdcachehash_mask + 1)
8242 * SPDCACHE_MAX_ENTRIES_PER_HASH;
8244 V_spdcache_lock = malloc(sizeof(struct mtx) *
8245 (V_spdcachehash_mask + 1),
8246 M_IPSEC_SPDCACHE, M_WAITOK | M_ZERO);
8248 for (i = 0; i < V_spdcachehash_mask + 1; ++i)
8249 SPDCACHE_LOCK_INIT(i);
8253 struct spdcache_entry *
8254 spdcache_entry_alloc(const struct secpolicyindex *spidx, struct secpolicy *sp)
8256 struct spdcache_entry *entry;
8258 entry = malloc(sizeof(struct spdcache_entry), M_IPSEC_SPDCACHE,
8266 entry->spidx = *spidx;
8273 spdcache_entry_free(struct spdcache_entry *entry)
8276 if (entry->sp != NULL)
8277 key_freesp(&entry->sp);
8278 free(entry, M_IPSEC_SPDCACHE);
8282 spdcache_clear(void)
8284 struct spdcache_entry *entry;
8287 for (i = 0; i < V_spdcachehash_mask + 1; ++i) {
8289 while (!LIST_EMPTY(&V_spdcachehashtbl[i])) {
8290 entry = LIST_FIRST(&V_spdcachehashtbl[i]);
8291 LIST_REMOVE(entry, chain);
8292 spdcache_entry_free(entry);
8300 spdcache_destroy(void)
8304 if (SPDCACHE_ENABLED()) {
8306 hashdestroy(V_spdcachehashtbl, M_IPSEC_SPDCACHE, V_spdcachehash_mask);
8308 for (i = 0; i < V_spdcachehash_mask + 1; ++i)
8309 SPDCACHE_LOCK_DESTROY(i);
8311 free(V_spdcache_lock, M_IPSEC_SPDCACHE);
8317 key_vnet_init(void *arg __unused)
8321 for (i = 0; i < IPSEC_DIR_MAX; i++) {
8322 TAILQ_INIT(&V_sptree[i]);
8323 TAILQ_INIT(&V_sptree_ifnet[i]);
8326 TAILQ_INIT(&V_sahtree);
8327 V_sphashtbl = hashinit(SPHASH_NHASH, M_IPSEC_SP, &V_sphash_mask);
8328 V_savhashtbl = hashinit(SAVHASH_NHASH, M_IPSEC_SA, &V_savhash_mask);
8329 V_sahaddrhashtbl = hashinit(SAHHASH_NHASH, M_IPSEC_SAH,
8330 &V_sahaddrhash_mask);
8331 V_acqaddrhashtbl = hashinit(ACQHASH_NHASH, M_IPSEC_SAQ,
8332 &V_acqaddrhash_mask);
8333 V_acqseqhashtbl = hashinit(ACQHASH_NHASH, M_IPSEC_SAQ,
8334 &V_acqseqhash_mask);
8338 for (i = 0; i <= SADB_SATYPE_MAX; i++)
8339 LIST_INIT(&V_regtree[i]);
8341 LIST_INIT(&V_acqtree);
8342 LIST_INIT(&V_spacqtree);
8344 VNET_SYSINIT(key_vnet_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND,
8345 key_vnet_init, NULL);
8348 key_init(void *arg __unused)
8351 ipsec_key_lft_zone = uma_zcreate("IPsec SA lft_c",
8352 sizeof(uint64_t) * 2, NULL, NULL, NULL, NULL,
8353 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
8356 REGTREE_LOCK_INIT();
8357 SAHTREE_LOCK_INIT();
8360 SPI_ALLOC_LOCK_INIT();
8362 #ifndef IPSEC_DEBUG2
8363 callout_init(&key_timer, 1);
8364 callout_reset(&key_timer, hz, key_timehandler, NULL);
8365 #endif /*IPSEC_DEBUG2*/
8367 /* initialize key statistics */
8368 keystat.getspi_count = 1;
8371 printf("IPsec: Initialized Security Association Processing.\n");
8373 SYSINIT(key_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST, key_init, NULL);
8377 key_vnet_destroy(void *arg __unused)
8379 struct secashead_queue sahdrainq;
8380 struct secpolicy_queue drainq;
8381 struct secpolicy *sp, *nextsp;
8382 struct secacq *acq, *nextacq;
8383 struct secspacq *spacq, *nextspacq;
8384 struct secashead *sah;
8385 struct secasvar *sav;
8390 * XXX: can we just call free() for each object without
8391 * walking through safe way with releasing references?
8393 TAILQ_INIT(&drainq);
8395 for (i = 0; i < IPSEC_DIR_MAX; i++) {
8396 TAILQ_CONCAT(&drainq, &V_sptree[i], chain);
8397 TAILQ_CONCAT(&drainq, &V_sptree_ifnet[i], chain);
8399 for (i = 0; i < V_sphash_mask + 1; i++)
8400 LIST_INIT(&V_sphashtbl[i]);
8404 sp = TAILQ_FIRST(&drainq);
8405 while (sp != NULL) {
8406 nextsp = TAILQ_NEXT(sp, chain);
8411 TAILQ_INIT(&sahdrainq);
8413 TAILQ_CONCAT(&sahdrainq, &V_sahtree, chain);
8414 for (i = 0; i < V_savhash_mask + 1; i++)
8415 LIST_INIT(&V_savhashtbl[i]);
8416 for (i = 0; i < V_sahaddrhash_mask + 1; i++)
8417 LIST_INIT(&V_sahaddrhashtbl[i]);
8418 TAILQ_FOREACH(sah, &sahdrainq, chain) {
8419 sah->state = SADB_SASTATE_DEAD;
8420 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
8421 sav->state = SADB_SASTATE_DEAD;
8423 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
8424 sav->state = SADB_SASTATE_DEAD;
8429 key_freesah_flushed(&sahdrainq);
8430 hashdestroy(V_sphashtbl, M_IPSEC_SP, V_sphash_mask);
8431 hashdestroy(V_savhashtbl, M_IPSEC_SA, V_savhash_mask);
8432 hashdestroy(V_sahaddrhashtbl, M_IPSEC_SAH, V_sahaddrhash_mask);
8435 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
8436 LIST_FOREACH(reg, &V_regtree[i], chain) {
8437 if (__LIST_CHAINED(reg)) {
8438 LIST_REMOVE(reg, chain);
8439 free(reg, M_IPSEC_SAR);
8447 acq = LIST_FIRST(&V_acqtree);
8448 while (acq != NULL) {
8449 nextacq = LIST_NEXT(acq, chain);
8450 LIST_REMOVE(acq, chain);
8451 free(acq, M_IPSEC_SAQ);
8454 for (i = 0; i < V_acqaddrhash_mask + 1; i++)
8455 LIST_INIT(&V_acqaddrhashtbl[i]);
8456 for (i = 0; i < V_acqseqhash_mask + 1; i++)
8457 LIST_INIT(&V_acqseqhashtbl[i]);
8461 for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
8462 spacq = nextspacq) {
8463 nextspacq = LIST_NEXT(spacq, chain);
8464 if (__LIST_CHAINED(spacq)) {
8465 LIST_REMOVE(spacq, chain);
8466 free(spacq, M_IPSEC_SAQ);
8470 hashdestroy(V_acqaddrhashtbl, M_IPSEC_SAQ, V_acqaddrhash_mask);
8471 hashdestroy(V_acqseqhashtbl, M_IPSEC_SAQ, V_acqseqhash_mask);
8473 VNET_SYSUNINIT(key_vnet_destroy, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND,
8474 key_vnet_destroy, NULL);
8478 * XXX: as long as domains are not unloadable, this function is never called,
8479 * provided for consistensy and future unload support.
8482 key_destroy(void *arg __unused)
8484 uma_zdestroy(ipsec_key_lft_zone);
8486 #ifndef IPSEC_DEBUG2
8487 callout_drain(&key_timer);
8489 SPTREE_LOCK_DESTROY();
8490 REGTREE_LOCK_DESTROY();
8491 SAHTREE_LOCK_DESTROY();
8493 SPACQ_LOCK_DESTROY();
8494 SPI_ALLOC_LOCK_DESTROY();
8496 SYSUNINIT(key_destroy, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST, key_destroy, NULL);
8498 /* record data transfer on SA, and update timestamps */
8500 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
8502 IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
8503 IPSEC_ASSERT(m != NULL, ("Null mbuf"));
8506 * XXX Currently, there is a difference of bytes size
8507 * between inbound and outbound processing.
8509 counter_u64_add(sav->lft_c_bytes, m->m_pkthdr.len);
8512 * We use the number of packets as the unit of
8513 * allocations. We increment the variable
8514 * whenever {esp,ah}_{in,out}put is called.
8516 counter_u64_add(sav->lft_c_allocations, 1);
8519 * NOTE: We record CURRENT usetime by using wall clock,
8520 * in seconds. HARD and SOFT lifetime are measured by the time
8521 * difference (again in seconds) from usetime.
8525 * -----+-----+--------+---> t
8526 * <--------------> HARD
8529 if (sav->firstused == 0)
8530 sav->firstused = time_second;
8534 * Take one of the kernel's security keys and convert it into a PF_KEY
8535 * structure within an mbuf, suitable for sending up to a waiting
8536 * application in user land.
8539 * src: A pointer to a kernel security key.
8540 * exttype: Which type of key this is. Refer to the PF_KEY data structures.
8542 * a valid mbuf or NULL indicating an error
8546 static struct mbuf *
8547 key_setkey(struct seckey *src, uint16_t exttype)
8556 len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8557 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
8562 p = mtod(m, struct sadb_key *);
8564 p->sadb_key_len = PFKEY_UNIT64(len);
8565 p->sadb_key_exttype = exttype;
8566 p->sadb_key_bits = src->bits;
8567 bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8573 * Take one of the kernel's lifetime data structures and convert it
8574 * into a PF_KEY structure within an mbuf, suitable for sending up to
8575 * a waiting application in user land.
8578 * src: A pointer to a kernel lifetime structure.
8579 * exttype: Which type of lifetime this is. Refer to the PF_KEY
8580 * data structures for more information.
8582 * a valid mbuf or NULL indicating an error
8586 static struct mbuf *
8587 key_setlifetime(struct seclifetime *src, uint16_t exttype)
8589 struct mbuf *m = NULL;
8590 struct sadb_lifetime *p;
8591 int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8596 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
8601 p = mtod(m, struct sadb_lifetime *);
8604 p->sadb_lifetime_len = PFKEY_UNIT64(len);
8605 p->sadb_lifetime_exttype = exttype;
8606 p->sadb_lifetime_allocations = src->allocations;
8607 p->sadb_lifetime_bytes = src->bytes;
8608 p->sadb_lifetime_addtime = src->addtime;
8609 p->sadb_lifetime_usetime = src->usetime;
8615 const struct enc_xform *
8616 enc_algorithm_lookup(int alg)
8620 for (i = 0; i < nitems(supported_ealgs); i++)
8621 if (alg == supported_ealgs[i].sadb_alg)
8622 return (supported_ealgs[i].xform);
8626 const struct auth_hash *
8627 auth_algorithm_lookup(int alg)
8631 for (i = 0; i < nitems(supported_aalgs); i++)
8632 if (alg == supported_aalgs[i].sadb_alg)
8633 return (supported_aalgs[i].xform);
8637 const struct comp_algo *
8638 comp_algorithm_lookup(int alg)
8642 for (i = 0; i < nitems(supported_calgs); i++)
8643 if (alg == supported_calgs[i].sadb_alg)
8644 return (supported_calgs[i].xform);