2 /* $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $ */
5 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the project nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * This code is referd to RFC 2367
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
41 #include <sys/types.h>
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/fnv_hash.h>
47 #include <sys/mutex.h>
49 #include <sys/domain.h>
50 #include <sys/protosw.h>
51 #include <sys/malloc.h>
52 #include <sys/rmlock.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #include <sys/sysctl.h>
56 #include <sys/errno.h>
58 #include <sys/queue.h>
59 #include <sys/refcount.h>
60 #include <sys/syslog.h>
65 #include <net/if_var.h>
67 #include <net/raw_cb.h>
69 #include <netinet/in.h>
70 #include <netinet/in_systm.h>
71 #include <netinet/ip.h>
72 #include <netinet/in_var.h>
73 #include <netinet/udp.h>
76 #include <netinet/ip6.h>
77 #include <netinet6/in6_var.h>
78 #include <netinet6/ip6_var.h>
81 #include <net/pfkeyv2.h>
82 #include <netipsec/keydb.h>
83 #include <netipsec/key.h>
84 #include <netipsec/keysock.h>
85 #include <netipsec/key_debug.h>
87 #include <netipsec/ipsec.h>
89 #include <netipsec/ipsec6.h>
92 #include <netipsec/xform.h>
93 #include <machine/in_cksum.h>
94 #include <machine/stdarg.h>
97 #include <sys/random.h>
100 #define _BITS(bytes) ((bytes) << 3)
103 * Note on SA reference counting:
104 * - SAs that are not in DEAD state will have (total external reference + 1)
105 * following value in reference count field. they cannot be freed and are
106 * referenced from SA header.
107 * - SAs that are in DEAD state will have (total external reference)
108 * in reference count field. they are ready to be freed. reference from
109 * SA header will be removed in key_delsav(), when the reference count
110 * field hits 0 (= no external reference other than from SA header.
113 VNET_DEFINE(u_int32_t, key_debug_level) = 0;
114 static VNET_DEFINE(u_int, key_spi_trycnt) = 1000;
115 static VNET_DEFINE(u_int32_t, key_spi_minval) = 0x100;
116 static VNET_DEFINE(u_int32_t, key_spi_maxval) = 0x0fffffff; /* XXX */
117 static VNET_DEFINE(u_int32_t, policy_id) = 0;
118 /*interval to initialize randseed,1(m)*/
119 static VNET_DEFINE(u_int, key_int_random) = 60;
120 /* interval to expire acquiring, 30(s)*/
121 static VNET_DEFINE(u_int, key_larval_lifetime) = 30;
122 /* counter for blocking SADB_ACQUIRE.*/
123 static VNET_DEFINE(int, key_blockacq_count) = 10;
124 /* lifetime for blocking SADB_ACQUIRE.*/
125 static VNET_DEFINE(int, key_blockacq_lifetime) = 20;
126 /* preferred old sa rather than new sa.*/
127 static VNET_DEFINE(int, key_preferred_oldsa) = 1;
128 #define V_key_spi_trycnt VNET(key_spi_trycnt)
129 #define V_key_spi_minval VNET(key_spi_minval)
130 #define V_key_spi_maxval VNET(key_spi_maxval)
131 #define V_policy_id VNET(policy_id)
132 #define V_key_int_random VNET(key_int_random)
133 #define V_key_larval_lifetime VNET(key_larval_lifetime)
134 #define V_key_blockacq_count VNET(key_blockacq_count)
135 #define V_key_blockacq_lifetime VNET(key_blockacq_lifetime)
136 #define V_key_preferred_oldsa VNET(key_preferred_oldsa)
138 static VNET_DEFINE(u_int32_t, acq_seq) = 0;
139 #define V_acq_seq VNET(acq_seq)
141 static VNET_DEFINE(uint32_t, sp_genid) = 0;
142 #define V_sp_genid VNET(sp_genid)
145 TAILQ_HEAD(secpolicy_queue, secpolicy);
146 LIST_HEAD(secpolicy_list, secpolicy);
147 static VNET_DEFINE(struct secpolicy_queue, sptree[IPSEC_DIR_MAX]);
148 static VNET_DEFINE(struct secpolicy_queue, sptree_ifnet[IPSEC_DIR_MAX]);
149 static struct rmlock sptree_lock;
150 #define V_sptree VNET(sptree)
151 #define V_sptree_ifnet VNET(sptree_ifnet)
152 #define SPTREE_LOCK_INIT() rm_init(&sptree_lock, "sptree")
153 #define SPTREE_LOCK_DESTROY() rm_destroy(&sptree_lock)
154 #define SPTREE_RLOCK_TRACKER struct rm_priotracker sptree_tracker
155 #define SPTREE_RLOCK() rm_rlock(&sptree_lock, &sptree_tracker)
156 #define SPTREE_RUNLOCK() rm_runlock(&sptree_lock, &sptree_tracker)
157 #define SPTREE_RLOCK_ASSERT() rm_assert(&sptree_lock, RA_RLOCKED)
158 #define SPTREE_WLOCK() rm_wlock(&sptree_lock)
159 #define SPTREE_WUNLOCK() rm_wunlock(&sptree_lock)
160 #define SPTREE_WLOCK_ASSERT() rm_assert(&sptree_lock, RA_WLOCKED)
161 #define SPTREE_UNLOCK_ASSERT() rm_assert(&sptree_lock, RA_UNLOCKED)
163 /* Hash table for lookup SP using unique id */
164 static VNET_DEFINE(struct secpolicy_list *, sphashtbl);
165 static VNET_DEFINE(u_long, sphash_mask);
166 #define V_sphashtbl VNET(sphashtbl)
167 #define V_sphash_mask VNET(sphash_mask)
169 #define SPHASH_NHASH_LOG2 7
170 #define SPHASH_NHASH (1 << SPHASH_NHASH_LOG2)
171 #define SPHASH_HASHVAL(id) (key_u32hash(id) & V_sphash_mask)
172 #define SPHASH_HASH(id) &V_sphashtbl[SPHASH_HASHVAL(id)]
175 TAILQ_HEAD(secashead_queue, secashead);
176 LIST_HEAD(secashead_list, secashead);
177 static VNET_DEFINE(struct secashead_queue, sahtree);
178 static struct rmlock sahtree_lock;
179 #define V_sahtree VNET(sahtree)
180 #define SAHTREE_LOCK_INIT() rm_init(&sahtree_lock, "sahtree")
181 #define SAHTREE_LOCK_DESTROY() rm_destroy(&sahtree_lock)
182 #define SAHTREE_RLOCK_TRACKER struct rm_priotracker sahtree_tracker
183 #define SAHTREE_RLOCK() rm_rlock(&sahtree_lock, &sahtree_tracker)
184 #define SAHTREE_RUNLOCK() rm_runlock(&sahtree_lock, &sahtree_tracker)
185 #define SAHTREE_RLOCK_ASSERT() rm_assert(&sahtree_lock, RA_RLOCKED)
186 #define SAHTREE_WLOCK() rm_wlock(&sahtree_lock)
187 #define SAHTREE_WUNLOCK() rm_wunlock(&sahtree_lock)
188 #define SAHTREE_WLOCK_ASSERT() rm_assert(&sahtree_lock, RA_WLOCKED)
189 #define SAHTREE_UNLOCK_ASSERT() rm_assert(&sahtree_lock, RA_UNLOCKED)
191 /* Hash table for lookup in SAD using SA addresses */
192 static VNET_DEFINE(struct secashead_list *, sahaddrhashtbl);
193 static VNET_DEFINE(u_long, sahaddrhash_mask);
194 #define V_sahaddrhashtbl VNET(sahaddrhashtbl)
195 #define V_sahaddrhash_mask VNET(sahaddrhash_mask)
197 #define SAHHASH_NHASH_LOG2 7
198 #define SAHHASH_NHASH (1 << SAHHASH_NHASH_LOG2)
199 #define SAHADDRHASH_HASHVAL(saidx) \
200 (key_saidxhash(saidx) & V_sahaddrhash_mask)
201 #define SAHADDRHASH_HASH(saidx) \
202 &V_sahaddrhashtbl[SAHADDRHASH_HASHVAL(saidx)]
204 /* Hash table for lookup in SAD using SPI */
205 LIST_HEAD(secasvar_list, secasvar);
206 static VNET_DEFINE(struct secasvar_list *, savhashtbl);
207 static VNET_DEFINE(u_long, savhash_mask);
208 #define V_savhashtbl VNET(savhashtbl)
209 #define V_savhash_mask VNET(savhash_mask)
210 #define SAVHASH_NHASH_LOG2 7
211 #define SAVHASH_NHASH (1 << SAVHASH_NHASH_LOG2)
212 #define SAVHASH_HASHVAL(spi) (key_u32hash(spi) & V_savhash_mask)
213 #define SAVHASH_HASH(spi) &V_savhashtbl[SAVHASH_HASHVAL(spi)]
216 key_saidxhash(const struct secasindex *saidx)
220 hval = fnv_32_buf(&saidx->proto, sizeof(saidx->proto),
222 switch (saidx->dst.sa.sa_family) {
225 hval = fnv_32_buf(&saidx->src.sin.sin_addr,
226 sizeof(in_addr_t), hval);
227 hval = fnv_32_buf(&saidx->dst.sin.sin_addr,
228 sizeof(in_addr_t), hval);
233 hval = fnv_32_buf(&saidx->src.sin6.sin6_addr,
234 sizeof(struct in6_addr), hval);
235 hval = fnv_32_buf(&saidx->dst.sin6.sin6_addr,
236 sizeof(struct in6_addr), hval);
241 ipseclog((LOG_DEBUG, "%s: unknown address family %d",
242 __func__, saidx->dst.sa.sa_family));
248 key_u32hash(uint32_t val)
251 return (fnv_32_buf(&val, sizeof(val), FNV1_32_INIT));
255 static VNET_DEFINE(LIST_HEAD(_regtree, secreg), regtree[SADB_SATYPE_MAX + 1]);
256 #define V_regtree VNET(regtree)
257 static struct mtx regtree_lock;
258 #define REGTREE_LOCK_INIT() \
259 mtx_init(®tree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
260 #define REGTREE_LOCK_DESTROY() mtx_destroy(®tree_lock)
261 #define REGTREE_LOCK() mtx_lock(®tree_lock)
262 #define REGTREE_UNLOCK() mtx_unlock(®tree_lock)
263 #define REGTREE_LOCK_ASSERT() mtx_assert(®tree_lock, MA_OWNED)
266 LIST_HEAD(secacq_list, secacq);
267 static VNET_DEFINE(struct secacq_list, acqtree);
268 #define V_acqtree VNET(acqtree)
269 static struct mtx acq_lock;
270 #define ACQ_LOCK_INIT() \
271 mtx_init(&acq_lock, "acqtree", "ipsec SA acquiring list", MTX_DEF)
272 #define ACQ_LOCK_DESTROY() mtx_destroy(&acq_lock)
273 #define ACQ_LOCK() mtx_lock(&acq_lock)
274 #define ACQ_UNLOCK() mtx_unlock(&acq_lock)
275 #define ACQ_LOCK_ASSERT() mtx_assert(&acq_lock, MA_OWNED)
277 /* Hash table for lookup in ACQ list using SA addresses */
278 static VNET_DEFINE(struct secacq_list *, acqaddrhashtbl);
279 static VNET_DEFINE(u_long, acqaddrhash_mask);
280 #define V_acqaddrhashtbl VNET(acqaddrhashtbl)
281 #define V_acqaddrhash_mask VNET(acqaddrhash_mask)
283 /* Hash table for lookup in ACQ list using SEQ number */
284 static VNET_DEFINE(struct secacq_list *, acqseqhashtbl);
285 static VNET_DEFINE(u_long, acqseqhash_mask);
286 #define V_acqseqhashtbl VNET(acqseqhashtbl)
287 #define V_acqseqhash_mask VNET(acqseqhash_mask)
289 #define ACQHASH_NHASH_LOG2 7
290 #define ACQHASH_NHASH (1 << ACQHASH_NHASH_LOG2)
291 #define ACQADDRHASH_HASHVAL(saidx) \
292 (key_saidxhash(saidx) & V_acqaddrhash_mask)
293 #define ACQSEQHASH_HASHVAL(seq) \
294 (key_u32hash(seq) & V_acqseqhash_mask)
295 #define ACQADDRHASH_HASH(saidx) \
296 &V_acqaddrhashtbl[ACQADDRHASH_HASHVAL(saidx)]
297 #define ACQSEQHASH_HASH(seq) \
298 &V_acqseqhashtbl[ACQSEQHASH_HASHVAL(seq)]
299 /* SP acquiring list */
300 static VNET_DEFINE(LIST_HEAD(_spacqtree, secspacq), spacqtree);
301 #define V_spacqtree VNET(spacqtree)
302 static struct mtx spacq_lock;
303 #define SPACQ_LOCK_INIT() \
304 mtx_init(&spacq_lock, "spacqtree", \
305 "fast ipsec security policy acquire list", MTX_DEF)
306 #define SPACQ_LOCK_DESTROY() mtx_destroy(&spacq_lock)
307 #define SPACQ_LOCK() mtx_lock(&spacq_lock)
308 #define SPACQ_UNLOCK() mtx_unlock(&spacq_lock)
309 #define SPACQ_LOCK_ASSERT() mtx_assert(&spacq_lock, MA_OWNED)
311 static const int minsize[] = {
312 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
313 sizeof(struct sadb_sa), /* SADB_EXT_SA */
314 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
315 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
316 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
317 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_SRC */
318 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_DST */
319 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_PROXY */
320 sizeof(struct sadb_key), /* SADB_EXT_KEY_AUTH */
321 sizeof(struct sadb_key), /* SADB_EXT_KEY_ENCRYPT */
322 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_SRC */
323 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_DST */
324 sizeof(struct sadb_sens), /* SADB_EXT_SENSITIVITY */
325 sizeof(struct sadb_prop), /* SADB_EXT_PROPOSAL */
326 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_AUTH */
327 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_ENCRYPT */
328 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
329 0, /* SADB_X_EXT_KMPRIVATE */
330 sizeof(struct sadb_x_policy), /* SADB_X_EXT_POLICY */
331 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
332 sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
333 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
334 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
335 sizeof(struct sadb_address), /* SADB_X_EXT_NAT_T_OAI */
336 sizeof(struct sadb_address), /* SADB_X_EXT_NAT_T_OAR */
337 sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
338 sizeof(struct sadb_x_sa_replay), /* SADB_X_EXT_SA_REPLAY */
339 sizeof(struct sadb_address), /* SADB_X_EXT_NEW_ADDRESS_SRC */
340 sizeof(struct sadb_address), /* SADB_X_EXT_NEW_ADDRESS_DST */
342 _Static_assert(sizeof(minsize)/sizeof(int) == SADB_EXT_MAX + 1, "minsize size mismatch");
344 static const int maxsize[] = {
345 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
346 sizeof(struct sadb_sa), /* SADB_EXT_SA */
347 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
348 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
349 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
350 0, /* SADB_EXT_ADDRESS_SRC */
351 0, /* SADB_EXT_ADDRESS_DST */
352 0, /* SADB_EXT_ADDRESS_PROXY */
353 0, /* SADB_EXT_KEY_AUTH */
354 0, /* SADB_EXT_KEY_ENCRYPT */
355 0, /* SADB_EXT_IDENTITY_SRC */
356 0, /* SADB_EXT_IDENTITY_DST */
357 0, /* SADB_EXT_SENSITIVITY */
358 0, /* SADB_EXT_PROPOSAL */
359 0, /* SADB_EXT_SUPPORTED_AUTH */
360 0, /* SADB_EXT_SUPPORTED_ENCRYPT */
361 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
362 0, /* SADB_X_EXT_KMPRIVATE */
363 0, /* SADB_X_EXT_POLICY */
364 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
365 sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
366 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
367 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
368 0, /* SADB_X_EXT_NAT_T_OAI */
369 0, /* SADB_X_EXT_NAT_T_OAR */
370 sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
371 sizeof(struct sadb_x_sa_replay), /* SADB_X_EXT_SA_REPLAY */
372 0, /* SADB_X_EXT_NEW_ADDRESS_SRC */
373 0, /* SADB_X_EXT_NEW_ADDRESS_DST */
375 _Static_assert(sizeof(maxsize)/sizeof(int) == SADB_EXT_MAX + 1, "minsize size mismatch");
378 * Internal values for SA flags:
379 * SADB_X_EXT_F_CLONED means that SA was cloned by key_updateaddresses,
380 * thus we will not free the most of SA content in key_delsav().
382 #define SADB_X_EXT_F_CLONED 0x80000000
384 #define SADB_CHECKLEN(_mhp, _ext) \
385 ((_mhp)->extlen[(_ext)] < minsize[(_ext)] || (maxsize[(_ext)] != 0 && \
386 ((_mhp)->extlen[(_ext)] > maxsize[(_ext)])))
387 #define SADB_CHECKHDR(_mhp, _ext) ((_mhp)->ext[(_ext)] == NULL)
389 static VNET_DEFINE(int, ipsec_esp_keymin) = 256;
390 static VNET_DEFINE(int, ipsec_esp_auth) = 0;
391 static VNET_DEFINE(int, ipsec_ah_keymin) = 128;
393 #define V_ipsec_esp_keymin VNET(ipsec_esp_keymin)
394 #define V_ipsec_esp_auth VNET(ipsec_esp_auth)
395 #define V_ipsec_ah_keymin VNET(ipsec_ah_keymin)
398 VNET_DEFINE(int, ipsec_debug) = 1;
400 VNET_DEFINE(int, ipsec_debug) = 0;
404 SYSCTL_DECL(_net_inet_ipsec);
405 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEBUG, debug,
406 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_debug), 0,
407 "Enable IPsec debugging output when set.");
410 SYSCTL_DECL(_net_inet6_ipsec6);
411 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEBUG, debug,
412 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_debug), 0,
413 "Enable IPsec debugging output when set.");
416 SYSCTL_DECL(_net_key);
417 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL, debug,
418 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_debug_level), 0, "");
420 /* max count of trial for the decision of spi value */
421 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt,
422 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_trycnt), 0, "");
424 /* minimum spi value to allocate automatically. */
425 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE, spi_minval,
426 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_minval), 0, "");
428 /* maximun spi value to allocate automatically. */
429 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE, spi_maxval,
430 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_maxval), 0, "");
432 /* interval to initialize randseed */
433 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random,
434 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_int_random), 0, "");
436 /* lifetime for larval SA */
437 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME, larval_lifetime,
438 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_larval_lifetime), 0, "");
440 /* counter for blocking to send SADB_ACQUIRE to IKEd */
441 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT, blockacq_count,
442 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_blockacq_count), 0, "");
444 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
445 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME, blockacq_lifetime,
446 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_blockacq_lifetime), 0, "");
449 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH, esp_auth,
450 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_esp_auth), 0, "");
452 /* minimum ESP key length */
453 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin,
454 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_esp_keymin), 0, "");
456 /* minimum AH key length */
457 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN, ah_keymin,
458 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_ah_keymin), 0, "");
460 /* perfered old SA rather than new SA */
461 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA, preferred_oldsa,
462 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_preferred_oldsa), 0, "");
464 #define __LIST_CHAINED(elm) \
465 (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
467 MALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
468 MALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
469 MALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
470 MALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
471 MALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
472 MALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
473 MALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
475 static VNET_DEFINE(uma_zone_t, key_lft_zone);
476 #define V_key_lft_zone VNET(key_lft_zone)
478 static LIST_HEAD(xforms_list, xformsw) xforms = LIST_HEAD_INITIALIZER();
479 static struct mtx xforms_lock;
480 #define XFORMS_LOCK_INIT() \
481 mtx_init(&xforms_lock, "xforms_list", "IPsec transforms list", MTX_DEF)
482 #define XFORMS_LOCK_DESTROY() mtx_destroy(&xforms_lock)
483 #define XFORMS_LOCK() mtx_lock(&xforms_lock)
484 #define XFORMS_UNLOCK() mtx_unlock(&xforms_lock)
487 * set parameters into secpolicyindex buffer.
488 * Must allocate secpolicyindex buffer passed to this function.
490 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
492 bzero((idx), sizeof(struct secpolicyindex)); \
493 (idx)->dir = (_dir); \
494 (idx)->prefs = (ps); \
495 (idx)->prefd = (pd); \
496 (idx)->ul_proto = (ulp); \
497 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
498 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
502 * set parameters into secasindex buffer.
503 * Must allocate secasindex buffer before calling this function.
505 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
507 bzero((idx), sizeof(struct secasindex)); \
508 (idx)->proto = (p); \
510 (idx)->reqid = (r); \
511 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
512 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
513 key_porttosaddr(&(idx)->src.sa, 0); \
514 key_porttosaddr(&(idx)->dst.sa, 0); \
519 u_long getspi_count; /* the avarage of count to try to get new SPI */
523 struct sadb_msg *msg;
524 struct sadb_ext *ext[SADB_EXT_MAX + 1];
525 int extoff[SADB_EXT_MAX + 1];
526 int extlen[SADB_EXT_MAX + 1];
529 static struct supported_ealgs {
531 const struct enc_xform *xform;
532 } supported_ealgs[] = {
533 { SADB_EALG_DESCBC, &enc_xform_des },
534 { SADB_EALG_3DESCBC, &enc_xform_3des },
535 { SADB_X_EALG_AES, &enc_xform_rijndael128 },
536 { SADB_X_EALG_BLOWFISHCBC, &enc_xform_blf },
537 { SADB_X_EALG_CAST128CBC, &enc_xform_cast5 },
538 { SADB_EALG_NULL, &enc_xform_null },
539 { SADB_X_EALG_CAMELLIACBC, &enc_xform_camellia },
540 { SADB_X_EALG_AESCTR, &enc_xform_aes_icm },
541 { SADB_X_EALG_AESGCM16, &enc_xform_aes_nist_gcm },
542 { SADB_X_EALG_AESGMAC, &enc_xform_aes_nist_gmac },
545 static struct supported_aalgs {
547 const struct auth_hash *xform;
548 } supported_aalgs[] = {
549 { SADB_X_AALG_NULL, &auth_hash_null },
550 { SADB_AALG_MD5HMAC, &auth_hash_hmac_md5 },
551 { SADB_AALG_SHA1HMAC, &auth_hash_hmac_sha1 },
552 { SADB_X_AALG_RIPEMD160HMAC, &auth_hash_hmac_ripemd_160 },
553 { SADB_X_AALG_MD5, &auth_hash_key_md5 },
554 { SADB_X_AALG_SHA, &auth_hash_key_sha1 },
555 { SADB_X_AALG_SHA2_256, &auth_hash_hmac_sha2_256 },
556 { SADB_X_AALG_SHA2_384, &auth_hash_hmac_sha2_384 },
557 { SADB_X_AALG_SHA2_512, &auth_hash_hmac_sha2_512 },
558 { SADB_X_AALG_AES128GMAC, &auth_hash_nist_gmac_aes_128 },
559 { SADB_X_AALG_AES192GMAC, &auth_hash_nist_gmac_aes_192 },
560 { SADB_X_AALG_AES256GMAC, &auth_hash_nist_gmac_aes_256 },
563 static struct supported_calgs {
565 const struct comp_algo *xform;
566 } supported_calgs[] = {
567 { SADB_X_CALG_DEFLATE, &comp_algo_deflate },
571 static struct callout key_timer;
574 static void key_unlink(struct secpolicy *);
575 static struct secpolicy *key_getsp(struct secpolicyindex *);
576 static struct secpolicy *key_getspbyid(u_int32_t);
577 static struct mbuf *key_gather_mbuf(struct mbuf *,
578 const struct sadb_msghdr *, int, int, ...);
579 static int key_spdadd(struct socket *, struct mbuf *,
580 const struct sadb_msghdr *);
581 static uint32_t key_getnewspid(void);
582 static int key_spddelete(struct socket *, struct mbuf *,
583 const struct sadb_msghdr *);
584 static int key_spddelete2(struct socket *, struct mbuf *,
585 const struct sadb_msghdr *);
586 static int key_spdget(struct socket *, struct mbuf *,
587 const struct sadb_msghdr *);
588 static int key_spdflush(struct socket *, struct mbuf *,
589 const struct sadb_msghdr *);
590 static int key_spddump(struct socket *, struct mbuf *,
591 const struct sadb_msghdr *);
592 static struct mbuf *key_setdumpsp(struct secpolicy *,
593 u_int8_t, u_int32_t, u_int32_t);
594 static struct mbuf *key_sp2mbuf(struct secpolicy *);
595 static size_t key_getspreqmsglen(struct secpolicy *);
596 static int key_spdexpire(struct secpolicy *);
597 static struct secashead *key_newsah(struct secasindex *);
598 static void key_freesah(struct secashead **);
599 static void key_delsah(struct secashead *);
600 static struct secasvar *key_newsav(const struct sadb_msghdr *,
601 struct secasindex *, uint32_t, int *);
602 static void key_delsav(struct secasvar *);
603 static void key_unlinksav(struct secasvar *);
604 static struct secashead *key_getsah(struct secasindex *);
605 static int key_checkspidup(uint32_t);
606 static struct secasvar *key_getsavbyspi(uint32_t);
607 static int key_setnatt(struct secasvar *, const struct sadb_msghdr *);
608 static int key_setsaval(struct secasvar *, const struct sadb_msghdr *);
609 static int key_updatelifetimes(struct secasvar *, const struct sadb_msghdr *);
610 static int key_updateaddresses(struct socket *, struct mbuf *,
611 const struct sadb_msghdr *, struct secasvar *, struct secasindex *);
613 static struct mbuf *key_setdumpsa(struct secasvar *, u_int8_t,
614 u_int8_t, u_int32_t, u_int32_t);
615 static struct mbuf *key_setsadbmsg(u_int8_t, u_int16_t, u_int8_t,
616 u_int32_t, pid_t, u_int16_t);
617 static struct mbuf *key_setsadbsa(struct secasvar *);
618 static struct mbuf *key_setsadbaddr(u_int16_t,
619 const struct sockaddr *, u_int8_t, u_int16_t);
620 static struct mbuf *key_setsadbxport(u_int16_t, u_int16_t);
621 static struct mbuf *key_setsadbxtype(u_int16_t);
622 static struct mbuf *key_setsadbxsa2(u_int8_t, u_int32_t, u_int32_t);
623 static struct mbuf *key_setsadbxsareplay(u_int32_t);
624 static struct mbuf *key_setsadbxpolicy(u_int16_t, u_int8_t,
625 u_int32_t, u_int32_t);
626 static struct seckey *key_dup_keymsg(const struct sadb_key *, size_t,
627 struct malloc_type *);
628 static struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
629 struct malloc_type *);
631 /* flags for key_cmpsaidx() */
632 #define CMP_HEAD 1 /* protocol, addresses. */
633 #define CMP_MODE_REQID 2 /* additionally HEAD, reqid, mode. */
634 #define CMP_REQID 3 /* additionally HEAD, reaid. */
635 #define CMP_EXACTLY 4 /* all elements. */
636 static int key_cmpsaidx(const struct secasindex *,
637 const struct secasindex *, int);
638 static int key_cmpspidx_exactly(struct secpolicyindex *,
639 struct secpolicyindex *);
640 static int key_cmpspidx_withmask(struct secpolicyindex *,
641 struct secpolicyindex *);
642 static int key_bbcmp(const void *, const void *, u_int);
643 static uint8_t key_satype2proto(uint8_t);
644 static uint8_t key_proto2satype(uint8_t);
646 static int key_getspi(struct socket *, struct mbuf *,
647 const struct sadb_msghdr *);
648 static uint32_t key_do_getnewspi(struct sadb_spirange *, struct secasindex *);
649 static int key_update(struct socket *, struct mbuf *,
650 const struct sadb_msghdr *);
651 static int key_add(struct socket *, struct mbuf *,
652 const struct sadb_msghdr *);
653 static int key_setident(struct secashead *, const struct sadb_msghdr *);
654 static struct mbuf *key_getmsgbuf_x1(struct mbuf *,
655 const struct sadb_msghdr *);
656 static int key_delete(struct socket *, struct mbuf *,
657 const struct sadb_msghdr *);
658 static int key_delete_all(struct socket *, struct mbuf *,
659 const struct sadb_msghdr *, struct secasindex *);
660 static void key_delete_xform(const struct xformsw *);
661 static int key_get(struct socket *, struct mbuf *,
662 const struct sadb_msghdr *);
664 static void key_getcomb_setlifetime(struct sadb_comb *);
665 static struct mbuf *key_getcomb_ealg(void);
666 static struct mbuf *key_getcomb_ah(void);
667 static struct mbuf *key_getcomb_ipcomp(void);
668 static struct mbuf *key_getprop(const struct secasindex *);
670 static int key_acquire(const struct secasindex *, struct secpolicy *);
671 static uint32_t key_newacq(const struct secasindex *, int *);
672 static uint32_t key_getacq(const struct secasindex *, int *);
673 static int key_acqdone(const struct secasindex *, uint32_t);
674 static int key_acqreset(uint32_t);
675 static struct secspacq *key_newspacq(struct secpolicyindex *);
676 static struct secspacq *key_getspacq(struct secpolicyindex *);
677 static int key_acquire2(struct socket *, struct mbuf *,
678 const struct sadb_msghdr *);
679 static int key_register(struct socket *, struct mbuf *,
680 const struct sadb_msghdr *);
681 static int key_expire(struct secasvar *, int);
682 static int key_flush(struct socket *, struct mbuf *,
683 const struct sadb_msghdr *);
684 static int key_dump(struct socket *, struct mbuf *,
685 const struct sadb_msghdr *);
686 static int key_promisc(struct socket *, struct mbuf *,
687 const struct sadb_msghdr *);
688 static int key_senderror(struct socket *, struct mbuf *, int);
689 static int key_validate_ext(const struct sadb_ext *, int);
690 static int key_align(struct mbuf *, struct sadb_msghdr *);
691 static struct mbuf *key_setlifetime(struct seclifetime *, uint16_t);
692 static struct mbuf *key_setkey(struct seckey *, uint16_t);
693 static int xform_init(struct secasvar *, u_short);
695 #define DBG_IPSEC_INITREF(t, p) do { \
696 refcount_init(&(p)->refcnt, 1); \
698 printf("%s: Initialize refcnt %s(%p) = %u\n", \
699 __func__, #t, (p), (p)->refcnt)); \
701 #define DBG_IPSEC_ADDREF(t, p) do { \
702 refcount_acquire(&(p)->refcnt); \
704 printf("%s: Acquire refcnt %s(%p) -> %u\n", \
705 __func__, #t, (p), (p)->refcnt)); \
707 #define DBG_IPSEC_DELREF(t, p) do { \
709 printf("%s: Release refcnt %s(%p) -> %u\n", \
710 __func__, #t, (p), (p)->refcnt - 1)); \
711 refcount_release(&(p)->refcnt); \
714 #define IPSEC_INITREF(t, p) refcount_init(&(p)->refcnt, 1)
715 #define IPSEC_ADDREF(t, p) refcount_acquire(&(p)->refcnt)
716 #define IPSEC_DELREF(t, p) refcount_release(&(p)->refcnt)
718 #define SP_INITREF(p) IPSEC_INITREF(SP, p)
719 #define SP_ADDREF(p) IPSEC_ADDREF(SP, p)
720 #define SP_DELREF(p) IPSEC_DELREF(SP, p)
722 #define SAH_INITREF(p) IPSEC_INITREF(SAH, p)
723 #define SAH_ADDREF(p) IPSEC_ADDREF(SAH, p)
724 #define SAH_DELREF(p) IPSEC_DELREF(SAH, p)
726 #define SAV_INITREF(p) IPSEC_INITREF(SAV, p)
727 #define SAV_ADDREF(p) IPSEC_ADDREF(SAV, p)
728 #define SAV_DELREF(p) IPSEC_DELREF(SAV, p)
731 * Update the refcnt while holding the SPTREE lock.
734 key_addref(struct secpolicy *sp)
741 * Return 0 when there are known to be no SP's for the specified
742 * direction. Otherwise return 1. This is used by IPsec code
743 * to optimize performance.
746 key_havesp(u_int dir)
749 return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
750 TAILQ_FIRST(&V_sptree[dir]) != NULL : 1);
753 /* %%% IPsec policy management */
755 * Return current SPDB generation.
772 key_checksockaddrs(struct sockaddr *src, struct sockaddr *dst)
776 if (src->sa_family != dst->sa_family)
779 if (src->sa_len != dst->sa_len)
781 switch (src->sa_family) {
784 if (src->sa_len != sizeof(struct sockaddr_in))
790 if (src->sa_len != sizeof(struct sockaddr_in6))
795 return (EAFNOSUPPORT);
801 * allocating a SP for OUTBOUND or INBOUND packet.
802 * Must call key_freesp() later.
803 * OUT: NULL: not found
804 * others: found and return the pointer.
807 key_allocsp(struct secpolicyindex *spidx, u_int dir)
809 SPTREE_RLOCK_TRACKER;
810 struct secpolicy *sp;
812 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
813 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
814 ("invalid direction %u", dir));
817 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
818 if (key_cmpspidx_withmask(&sp->spidx, spidx)) {
825 if (sp != NULL) { /* found a SPD entry */
826 sp->lastused = time_second;
828 printf("%s: return SP(%p)\n", __func__, sp));
829 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
832 printf("%s: lookup failed for ", __func__);
833 kdebug_secpolicyindex(spidx, NULL));
839 * Allocating an SA entry for an *INBOUND* or *OUTBOUND* TCP packet, signed
840 * or should be signed by MD5 signature.
841 * We don't use key_allocsa() for such lookups, because we don't know SPI.
842 * Unlike ESP and AH protocols, SPI isn't transmitted in the TCP header with
843 * signed packet. We use SADB only as storage for password.
844 * OUT: positive: corresponding SA for given saidx found.
848 key_allocsa_tcpmd5(struct secasindex *saidx)
850 SAHTREE_RLOCK_TRACKER;
851 struct secashead *sah;
852 struct secasvar *sav;
854 IPSEC_ASSERT(saidx->proto == IPPROTO_TCP,
855 ("unexpected security protocol %u", saidx->proto));
856 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TCPMD5,
857 ("unexpected mode %u", saidx->mode));
860 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
862 printf("%s: checking SAH\n", __func__);
863 kdebug_secash(sah, " "));
864 if (sah->saidx.proto != IPPROTO_TCP)
866 if (!key_sockaddrcmp(&saidx->dst.sa, &sah->saidx.dst.sa, 0))
870 if (V_key_preferred_oldsa)
871 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
873 sav = TAILQ_FIRST(&sah->savtree_alive);
882 printf("%s: return SA(%p)\n", __func__, sav));
883 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
886 printf("%s: SA not found\n", __func__));
887 KEYDBG(IPSEC_DATA, kdebug_secasindex(saidx, NULL));
893 * Allocating an SA entry for an *OUTBOUND* packet.
894 * OUT: positive: corresponding SA for given saidx found.
895 * NULL: SA not found, but will be acquired, check *error
896 * for acquiring status.
899 key_allocsa_policy(struct secpolicy *sp, const struct secasindex *saidx,
902 SAHTREE_RLOCK_TRACKER;
903 struct secashead *sah;
904 struct secasvar *sav;
906 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
907 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
908 saidx->mode == IPSEC_MODE_TUNNEL,
909 ("unexpected policy %u", saidx->mode));
912 * We check new SA in the IPsec request because a different
913 * SA may be involved each time this request is checked, either
914 * because new SAs are being configured, or this request is
915 * associated with an unconnected datagram socket, or this request
916 * is associated with a system default policy.
919 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
921 printf("%s: checking SAH\n", __func__);
922 kdebug_secash(sah, " "));
923 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID))
929 * Allocate the oldest SA available according to
930 * draft-jenkins-ipsec-rekeying-03.
932 if (V_key_preferred_oldsa)
933 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
935 sav = TAILQ_FIRST(&sah->savtree_alive);
945 printf("%s: chosen SA(%p) for SP(%p)\n", __func__,
947 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
948 return (sav); /* return referenced SA */
952 *error = key_acquire(saidx, sp);
955 "%s: error %d returned from key_acquire()\n",
958 printf("%s: acquire SA for SP(%p), error %d\n",
959 __func__, sp, *error));
960 KEYDBG(IPSEC_DATA, kdebug_secasindex(saidx, NULL));
965 * allocating a usable SA entry for a *INBOUND* packet.
966 * Must call key_freesav() later.
967 * OUT: positive: pointer to a usable sav (i.e. MATURE or DYING state).
968 * NULL: not found, or error occurred.
970 * According to RFC 2401 SA is uniquely identified by a triple SPI,
971 * destination address, and security protocol. But according to RFC 4301,
972 * SPI by itself suffices to specify an SA.
974 * Note that, however, we do need to keep source address in IPsec SA.
975 * IKE specification and PF_KEY specification do assume that we
976 * keep source address in IPsec SA. We see a tricky situation here.
979 key_allocsa(union sockaddr_union *dst, uint8_t proto, uint32_t spi)
981 SAHTREE_RLOCK_TRACKER;
982 struct secasvar *sav;
984 IPSEC_ASSERT(proto == IPPROTO_ESP || proto == IPPROTO_AH ||
985 proto == IPPROTO_IPCOMP, ("unexpected security protocol %u",
989 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
994 * We use single SPI namespace for all protocols, so it is
995 * impossible to have SPI duplicates in the SAVHASH.
998 if (sav->state != SADB_SASTATE_LARVAL &&
999 sav->sah->saidx.proto == proto &&
1000 key_sockaddrcmp(&dst->sa,
1001 &sav->sah->saidx.dst.sa, 0) == 0)
1010 char buf[IPSEC_ADDRSTRLEN];
1011 printf("%s: SA not found for spi %u proto %u dst %s\n",
1012 __func__, ntohl(spi), proto, ipsec_address(dst, buf,
1016 printf("%s: return SA(%p)\n", __func__, sav));
1017 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1023 key_allocsa_tunnel(union sockaddr_union *src, union sockaddr_union *dst,
1026 SAHTREE_RLOCK_TRACKER;
1027 struct secasindex saidx;
1028 struct secashead *sah;
1029 struct secasvar *sav;
1031 IPSEC_ASSERT(src != NULL, ("null src address"));
1032 IPSEC_ASSERT(dst != NULL, ("null dst address"));
1034 KEY_SETSECASIDX(proto, IPSEC_MODE_TUNNEL, 0, &src->sa,
1039 LIST_FOREACH(sah, SAHADDRHASH_HASH(&saidx), addrhash) {
1040 if (IPSEC_MODE_TUNNEL != sah->saidx.mode)
1042 if (proto != sah->saidx.proto)
1044 if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, 0) != 0)
1046 if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, 0) != 0)
1048 /* XXXAE: is key_preferred_oldsa reasonably?*/
1049 if (V_key_preferred_oldsa)
1050 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
1052 sav = TAILQ_FIRST(&sah->savtree_alive);
1060 printf("%s: return SA(%p)\n", __func__, sav));
1062 KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1067 * Must be called after calling key_allocsp().
1070 key_freesp(struct secpolicy **spp)
1072 struct secpolicy *sp = *spp;
1074 IPSEC_ASSERT(sp != NULL, ("null sp"));
1075 if (SP_DELREF(sp) == 0)
1079 printf("%s: last reference to SP(%p)\n", __func__, sp));
1080 KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1083 while (sp->tcount > 0)
1084 ipsec_delisr(sp->req[--sp->tcount]);
1085 free(sp, M_IPSEC_SP);
1089 key_unlink(struct secpolicy *sp)
1092 IPSEC_ASSERT(sp->spidx.dir == IPSEC_DIR_INBOUND ||
1093 sp->spidx.dir == IPSEC_DIR_OUTBOUND,
1094 ("invalid direction %u", sp->spidx.dir));
1095 SPTREE_UNLOCK_ASSERT();
1098 printf("%s: SP(%p)\n", __func__, sp));
1100 if (sp->state != IPSEC_SPSTATE_ALIVE) {
1101 /* SP is already unlinked */
1105 sp->state = IPSEC_SPSTATE_DEAD;
1106 TAILQ_REMOVE(&V_sptree[sp->spidx.dir], sp, chain);
1107 LIST_REMOVE(sp, idhash);
1114 * insert a secpolicy into the SP database. Lower priorities first
1117 key_insertsp(struct secpolicy *newsp)
1119 struct secpolicy *sp;
1121 SPTREE_WLOCK_ASSERT();
1122 TAILQ_FOREACH(sp, &V_sptree[newsp->spidx.dir], chain) {
1123 if (newsp->priority < sp->priority) {
1124 TAILQ_INSERT_BEFORE(sp, newsp, chain);
1128 TAILQ_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, chain);
1130 LIST_INSERT_HEAD(SPHASH_HASH(newsp->id), newsp, idhash);
1131 newsp->state = IPSEC_SPSTATE_ALIVE;
1136 * Insert a bunch of VTI secpolicies into the SPDB.
1137 * We keep VTI policies in the separate list due to following reasons:
1138 * 1) they should be immutable to user's or some deamon's attempts to
1139 * delete. The only way delete such policies - destroy or unconfigure
1140 * corresponding virtual inteface.
1141 * 2) such policies have traffic selector that matches all traffic per
1143 * Since all VTI policies have the same priority, we don't care about
1147 key_register_ifnet(struct secpolicy **spp, u_int count)
1154 * First of try to acquire id for each SP.
1156 for (i = 0; i < count; i++) {
1157 IPSEC_ASSERT(spp[i]->spidx.dir == IPSEC_DIR_INBOUND ||
1158 spp[i]->spidx.dir == IPSEC_DIR_OUTBOUND,
1159 ("invalid direction %u", spp[i]->spidx.dir));
1161 if ((spp[i]->id = key_getnewspid()) == 0) {
1166 for (i = 0; i < count; i++) {
1167 TAILQ_INSERT_TAIL(&V_sptree_ifnet[spp[i]->spidx.dir],
1170 * NOTE: despite the fact that we keep VTI SP in the
1171 * separate list, SPHASH contains policies from both
1172 * sources. Thus SADB_X_SPDGET will correctly return
1173 * SP by id, because it uses SPHASH for lookups.
1175 LIST_INSERT_HEAD(SPHASH_HASH(spp[i]->id), spp[i], idhash);
1176 spp[i]->state = IPSEC_SPSTATE_IFNET;
1180 * Notify user processes about new SP.
1182 for (i = 0; i < count; i++) {
1183 m = key_setdumpsp(spp[i], SADB_X_SPDADD, 0, 0);
1185 key_sendup_mbuf(NULL, m, KEY_SENDUP_ALL);
1191 key_unregister_ifnet(struct secpolicy **spp, u_int count)
1197 for (i = 0; i < count; i++) {
1198 IPSEC_ASSERT(spp[i]->spidx.dir == IPSEC_DIR_INBOUND ||
1199 spp[i]->spidx.dir == IPSEC_DIR_OUTBOUND,
1200 ("invalid direction %u", spp[i]->spidx.dir));
1202 if (spp[i]->state != IPSEC_SPSTATE_IFNET)
1204 spp[i]->state = IPSEC_SPSTATE_DEAD;
1205 TAILQ_REMOVE(&V_sptree_ifnet[spp[i]->spidx.dir],
1207 LIST_REMOVE(spp[i], idhash);
1211 for (i = 0; i < count; i++) {
1212 m = key_setdumpsp(spp[i], SADB_X_SPDDELETE, 0, 0);
1214 key_sendup_mbuf(NULL, m, KEY_SENDUP_ALL);
1219 * Must be called after calling key_allocsa().
1220 * This function is called by key_freesp() to free some SA allocated
1224 key_freesav(struct secasvar **psav)
1226 struct secasvar *sav = *psav;
1228 IPSEC_ASSERT(sav != NULL, ("null sav"));
1229 if (SAV_DELREF(sav) == 0)
1233 printf("%s: last reference to SA(%p)\n", __func__, sav));
1240 * Unlink SA from SAH and SPI hash under SAHTREE_WLOCK.
1241 * Expect that SA has extra reference due to lookup.
1242 * Release this references, also release SAH reference after unlink.
1245 key_unlinksav(struct secasvar *sav)
1247 struct secashead *sah;
1250 printf("%s: SA(%p)\n", __func__, sav));
1252 SAHTREE_UNLOCK_ASSERT();
1254 if (sav->state == SADB_SASTATE_DEAD) {
1255 /* SA is already unlinked */
1259 /* Unlink from SAH */
1260 if (sav->state == SADB_SASTATE_LARVAL)
1261 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
1263 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
1264 /* Unlink from SPI hash */
1265 LIST_REMOVE(sav, spihash);
1266 sav->state = SADB_SASTATE_DEAD;
1270 /* Since we are unlinked, release reference to SAH */
1274 /* %%% SPD management */
1277 * OUT: NULL : not found
1278 * others : found, pointer to a SP.
1280 static struct secpolicy *
1281 key_getsp(struct secpolicyindex *spidx)
1283 SPTREE_RLOCK_TRACKER;
1284 struct secpolicy *sp;
1286 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1289 TAILQ_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1290 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1302 * OUT: NULL : not found
1303 * others : found, pointer to referenced SP.
1305 static struct secpolicy *
1306 key_getspbyid(uint32_t id)
1308 SPTREE_RLOCK_TRACKER;
1309 struct secpolicy *sp;
1312 LIST_FOREACH(sp, SPHASH_HASH(id), idhash) {
1325 struct secpolicy *sp;
1327 sp = malloc(sizeof(*sp), M_IPSEC_SP, M_NOWAIT | M_ZERO);
1333 struct ipsecrequest *
1337 return (malloc(sizeof(struct ipsecrequest), M_IPSEC_SR,
1338 M_NOWAIT | M_ZERO));
1342 ipsec_delisr(struct ipsecrequest *p)
1345 free(p, M_IPSEC_SR);
1349 * create secpolicy structure from sadb_x_policy structure.
1350 * NOTE: `state', `secpolicyindex' and 'id' in secpolicy structure
1351 * are not set, so must be set properly later.
1354 key_msg2sp(struct sadb_x_policy *xpl0, size_t len, int *error)
1356 struct secpolicy *newsp;
1358 IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1359 IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1361 if (len != PFKEY_EXTLEN(xpl0)) {
1362 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1367 if ((newsp = key_newsp()) == NULL) {
1372 newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1373 newsp->policy = xpl0->sadb_x_policy_type;
1374 newsp->priority = xpl0->sadb_x_policy_priority;
1378 switch (xpl0->sadb_x_policy_type) {
1379 case IPSEC_POLICY_DISCARD:
1380 case IPSEC_POLICY_NONE:
1381 case IPSEC_POLICY_ENTRUST:
1382 case IPSEC_POLICY_BYPASS:
1385 case IPSEC_POLICY_IPSEC:
1387 struct sadb_x_ipsecrequest *xisr;
1388 struct ipsecrequest *isr;
1391 /* validity check */
1392 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1393 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1400 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1401 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1405 if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1406 ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1407 "length.\n", __func__));
1413 if (newsp->tcount >= IPSEC_MAXREQ) {
1414 ipseclog((LOG_DEBUG,
1415 "%s: too many ipsecrequests.\n",
1422 /* allocate request buffer */
1423 /* NB: data structure is zero'd */
1424 isr = ipsec_newisr();
1426 ipseclog((LOG_DEBUG,
1427 "%s: No more memory.\n", __func__));
1433 newsp->req[newsp->tcount++] = isr;
1436 switch (xisr->sadb_x_ipsecrequest_proto) {
1439 case IPPROTO_IPCOMP:
1442 ipseclog((LOG_DEBUG,
1443 "%s: invalid proto type=%u\n", __func__,
1444 xisr->sadb_x_ipsecrequest_proto));
1446 *error = EPROTONOSUPPORT;
1450 (uint8_t)xisr->sadb_x_ipsecrequest_proto;
1452 switch (xisr->sadb_x_ipsecrequest_mode) {
1453 case IPSEC_MODE_TRANSPORT:
1454 case IPSEC_MODE_TUNNEL:
1456 case IPSEC_MODE_ANY:
1458 ipseclog((LOG_DEBUG,
1459 "%s: invalid mode=%u\n", __func__,
1460 xisr->sadb_x_ipsecrequest_mode));
1465 isr->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1467 switch (xisr->sadb_x_ipsecrequest_level) {
1468 case IPSEC_LEVEL_DEFAULT:
1469 case IPSEC_LEVEL_USE:
1470 case IPSEC_LEVEL_REQUIRE:
1472 case IPSEC_LEVEL_UNIQUE:
1473 /* validity check */
1475 * If range violation of reqid, kernel will
1476 * update it, don't refuse it.
1478 if (xisr->sadb_x_ipsecrequest_reqid
1479 > IPSEC_MANUAL_REQID_MAX) {
1480 ipseclog((LOG_DEBUG,
1481 "%s: reqid=%d range "
1482 "violation, updated by kernel.\n",
1484 xisr->sadb_x_ipsecrequest_reqid));
1485 xisr->sadb_x_ipsecrequest_reqid = 0;
1488 /* allocate new reqid id if reqid is zero. */
1489 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1491 if ((reqid = key_newreqid()) == 0) {
1496 isr->saidx.reqid = reqid;
1497 xisr->sadb_x_ipsecrequest_reqid = reqid;
1499 /* set it for manual keying. */
1501 xisr->sadb_x_ipsecrequest_reqid;
1506 ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1508 xisr->sadb_x_ipsecrequest_level));
1513 isr->level = xisr->sadb_x_ipsecrequest_level;
1515 /* set IP addresses if there */
1516 if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1517 struct sockaddr *paddr;
1519 paddr = (struct sockaddr *)(xisr + 1);
1520 /* validity check */
1522 > sizeof(isr->saidx.src)) {
1523 ipseclog((LOG_DEBUG, "%s: invalid "
1524 "request address length.\n",
1530 bcopy(paddr, &isr->saidx.src, paddr->sa_len);
1531 paddr = (struct sockaddr *)((caddr_t)paddr +
1534 /* validity check */
1536 > sizeof(isr->saidx.dst)) {
1537 ipseclog((LOG_DEBUG, "%s: invalid "
1538 "request address length.\n",
1544 /* AF family should match */
1545 if (paddr->sa_family !=
1546 isr->saidx.src.sa.sa_family) {
1547 ipseclog((LOG_DEBUG, "%s: address "
1548 "family doesn't match.\n",
1554 bcopy(paddr, &isr->saidx.dst, paddr->sa_len);
1557 * Addresses for TUNNEL mode requests are
1560 if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
1561 ipseclog((LOG_DEBUG, "%s: missing "
1562 "request addresses.\n", __func__));
1568 tlen -= xisr->sadb_x_ipsecrequest_len;
1570 /* validity check */
1572 ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1579 xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1580 + xisr->sadb_x_ipsecrequest_len);
1582 /* XXXAE: LARVAL SP */
1583 if (newsp->tcount < 1) {
1584 ipseclog((LOG_DEBUG, "%s: valid IPSEC transforms "
1585 "not found.\n", __func__));
1593 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1606 static uint32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1608 if (auto_reqid == ~0)
1609 auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1613 /* XXX should be unique check */
1614 return (auto_reqid);
1618 * copy secpolicy struct to sadb_x_policy structure indicated.
1620 static struct mbuf *
1621 key_sp2mbuf(struct secpolicy *sp)
1626 tlen = key_getspreqmsglen(sp);
1627 m = m_get2(tlen, M_NOWAIT, MT_DATA, 0);
1632 if (key_sp2msg(sp, m->m_data, &tlen) != 0) {
1640 key_sp2msg(struct secpolicy *sp, void *request, size_t *len)
1642 struct sadb_x_ipsecrequest *xisr;
1643 struct sadb_x_policy *xpl;
1644 struct ipsecrequest *isr;
1649 IPSEC_ASSERT(sp != NULL, ("null policy"));
1651 xlen = sizeof(*xpl);
1656 bzero(request, *len);
1657 xpl = (struct sadb_x_policy *)request;
1658 xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1659 xpl->sadb_x_policy_type = sp->policy;
1660 xpl->sadb_x_policy_dir = sp->spidx.dir;
1661 xpl->sadb_x_policy_id = sp->id;
1662 xpl->sadb_x_policy_priority = sp->priority;
1664 /* if is the policy for ipsec ? */
1665 if (sp->policy == IPSEC_POLICY_IPSEC) {
1666 p = (caddr_t)xpl + sizeof(*xpl);
1667 for (i = 0; i < sp->tcount; i++) {
1669 ilen = PFKEY_ALIGN8(sizeof(*xisr) +
1670 isr->saidx.src.sa.sa_len +
1671 isr->saidx.dst.sa.sa_len);
1675 /* Calculate needed size */
1678 xisr = (struct sadb_x_ipsecrequest *)p;
1679 xisr->sadb_x_ipsecrequest_len = ilen;
1680 xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1681 xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1682 xisr->sadb_x_ipsecrequest_level = isr->level;
1683 xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1686 bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1687 p += isr->saidx.src.sa.sa_len;
1688 bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1689 p += isr->saidx.dst.sa.sa_len;
1692 xpl->sadb_x_policy_len = PFKEY_UNIT64(xlen);
1696 *len = sizeof(*xpl);
1700 /* m will not be freed nor modified */
1701 static struct mbuf *
1702 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1703 int ndeep, int nitem, ...)
1708 struct mbuf *result = NULL, *n;
1711 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1712 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1714 va_start(ap, nitem);
1715 for (i = 0; i < nitem; i++) {
1716 idx = va_arg(ap, int);
1717 if (idx < 0 || idx > SADB_EXT_MAX)
1719 /* don't attempt to pull empty extension */
1720 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1722 if (idx != SADB_EXT_RESERVED &&
1723 (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1726 if (idx == SADB_EXT_RESERVED) {
1727 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1729 IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1731 MGETHDR(n, M_NOWAIT, MT_DATA);
1736 m_copydata(m, 0, sizeof(struct sadb_msg),
1738 } else if (i < ndeep) {
1739 len = mhp->extlen[idx];
1740 n = m_get2(len, M_NOWAIT, MT_DATA, 0);
1745 m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1748 n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1761 if ((result->m_flags & M_PKTHDR) != 0) {
1762 result->m_pkthdr.len = 0;
1763 for (n = result; n; n = n->m_next)
1764 result->m_pkthdr.len += n->m_len;
1776 * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1777 * add an entry to SP database, when received
1778 * <base, address(SD), (lifetime(H),) policy>
1780 * Adding to SP database,
1782 * <base, address(SD), (lifetime(H),) policy>
1783 * to the socket which was send.
1785 * SPDADD set a unique policy entry.
1786 * SPDSETIDX like SPDADD without a part of policy requests.
1787 * SPDUPDATE replace a unique policy entry.
1789 * XXXAE: serialize this in PF_KEY to avoid races.
1790 * m will always be freed.
1793 key_spdadd(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
1795 struct secpolicyindex spidx;
1796 struct sadb_address *src0, *dst0;
1797 struct sadb_x_policy *xpl0, *xpl;
1798 struct sadb_lifetime *lft = NULL;
1799 struct secpolicy *newsp;
1802 IPSEC_ASSERT(so != NULL, ("null socket"));
1803 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1804 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1805 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1807 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
1808 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
1809 SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY)) {
1810 ipseclog((LOG_DEBUG,
1811 "%s: invalid message: missing required header.\n",
1813 return key_senderror(so, m, EINVAL);
1815 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
1816 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
1817 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
1818 ipseclog((LOG_DEBUG,
1819 "%s: invalid message: wrong header size.\n", __func__));
1820 return key_senderror(so, m, EINVAL);
1822 if (!SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD)) {
1823 if (SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_HARD)) {
1824 ipseclog((LOG_DEBUG,
1825 "%s: invalid message: wrong header size.\n",
1827 return key_senderror(so, m, EINVAL);
1829 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1832 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1833 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1834 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1836 /* check the direciton */
1837 switch (xpl0->sadb_x_policy_dir) {
1838 case IPSEC_DIR_INBOUND:
1839 case IPSEC_DIR_OUTBOUND:
1842 ipseclog((LOG_DEBUG, "%s: invalid SP direction.\n", __func__));
1843 return key_senderror(so, m, EINVAL);
1845 /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1846 if (xpl0->sadb_x_policy_type != IPSEC_POLICY_DISCARD &&
1847 xpl0->sadb_x_policy_type != IPSEC_POLICY_NONE &&
1848 xpl0->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
1849 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1850 return key_senderror(so, m, EINVAL);
1853 /* policy requests are mandatory when action is ipsec. */
1854 if (xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
1855 mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1856 ipseclog((LOG_DEBUG,
1857 "%s: policy requests required.\n", __func__));
1858 return key_senderror(so, m, EINVAL);
1861 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
1862 (struct sockaddr *)(dst0 + 1));
1864 src0->sadb_address_proto != dst0->sadb_address_proto) {
1865 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
1866 return key_senderror(so, m, error);
1869 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1872 src0->sadb_address_prefixlen,
1873 dst0->sadb_address_prefixlen,
1874 src0->sadb_address_proto,
1876 /* Checking there is SP already or not. */
1877 newsp = key_getsp(&spidx);
1878 if (newsp != NULL) {
1879 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1881 printf("%s: unlink SP(%p) for SPDUPDATE\n",
1883 KEYDBG(KEY_DATA, kdebug_secpolicy(newsp));
1888 ipseclog((LOG_DEBUG, "%s: a SP entry exists already.",
1890 return (key_senderror(so, m, EEXIST));
1894 /* allocate new SP entry */
1895 if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1896 return key_senderror(so, m, error);
1899 newsp->lastused = newsp->created = time_second;
1900 newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1901 newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1902 bcopy(&spidx, &newsp->spidx, sizeof(spidx));
1904 /* XXXAE: there is race between key_getsp() and key_insertsp() */
1906 if ((newsp->id = key_getnewspid()) == 0) {
1909 return key_senderror(so, m, ENOBUFS);
1911 key_insertsp(newsp);
1915 printf("%s: SP(%p)\n", __func__, newsp));
1916 KEYDBG(KEY_DATA, kdebug_secpolicy(newsp));
1919 struct mbuf *n, *mpolicy;
1920 struct sadb_msg *newmsg;
1923 /* create new sadb_msg to reply. */
1925 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1926 SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1927 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1929 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1931 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1934 return key_senderror(so, m, ENOBUFS);
1936 if (n->m_len < sizeof(*newmsg)) {
1937 n = m_pullup(n, sizeof(*newmsg));
1939 return key_senderror(so, m, ENOBUFS);
1941 newmsg = mtod(n, struct sadb_msg *);
1942 newmsg->sadb_msg_errno = 0;
1943 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1946 mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1947 sizeof(*xpl), &off);
1948 if (mpolicy == NULL) {
1949 /* n is already freed */
1950 return key_senderror(so, m, ENOBUFS);
1952 xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1953 if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1955 return key_senderror(so, m, EINVAL);
1957 xpl->sadb_x_policy_id = newsp->id;
1960 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
1965 * get new policy id.
1971 key_getnewspid(void)
1973 struct secpolicy *sp;
1975 int count = V_key_spi_trycnt; /* XXX */
1977 SPTREE_WLOCK_ASSERT();
1979 if (V_policy_id == ~0) /* overflowed */
1980 newid = V_policy_id = 1;
1982 newid = ++V_policy_id;
1983 LIST_FOREACH(sp, SPHASH_HASH(newid), idhash) {
1984 if (sp->id == newid)
1990 if (count == 0 || newid == 0) {
1991 ipseclog((LOG_DEBUG, "%s: failed to allocate policy id.\n",
1999 * SADB_SPDDELETE processing
2001 * <base, address(SD), policy(*)>
2002 * from the user(?), and set SADB_SASTATE_DEAD,
2004 * <base, address(SD), policy(*)>
2006 * policy(*) including direction of policy.
2008 * m will always be freed.
2011 key_spddelete(struct socket *so, struct mbuf *m,
2012 const struct sadb_msghdr *mhp)
2014 struct secpolicyindex spidx;
2015 struct sadb_address *src0, *dst0;
2016 struct sadb_x_policy *xpl0;
2017 struct secpolicy *sp;
2019 IPSEC_ASSERT(so != NULL, ("null so"));
2020 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2021 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2022 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2024 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
2025 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
2026 SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY)) {
2027 ipseclog((LOG_DEBUG,
2028 "%s: invalid message: missing required header.\n",
2030 return key_senderror(so, m, EINVAL);
2032 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
2033 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
2034 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2035 ipseclog((LOG_DEBUG,
2036 "%s: invalid message: wrong header size.\n", __func__));
2037 return key_senderror(so, m, EINVAL);
2040 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2041 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2042 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2044 /* check the direciton */
2045 switch (xpl0->sadb_x_policy_dir) {
2046 case IPSEC_DIR_INBOUND:
2047 case IPSEC_DIR_OUTBOUND:
2050 ipseclog((LOG_DEBUG, "%s: invalid SP direction.\n", __func__));
2051 return key_senderror(so, m, EINVAL);
2053 /* Only DISCARD, NONE and IPSEC are allowed */
2054 if (xpl0->sadb_x_policy_type != IPSEC_POLICY_DISCARD &&
2055 xpl0->sadb_x_policy_type != IPSEC_POLICY_NONE &&
2056 xpl0->sadb_x_policy_type != IPSEC_POLICY_IPSEC) {
2057 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
2058 return key_senderror(so, m, EINVAL);
2060 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
2061 (struct sockaddr *)(dst0 + 1)) != 0 ||
2062 src0->sadb_address_proto != dst0->sadb_address_proto) {
2063 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
2064 return key_senderror(so, m, EINVAL);
2067 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2070 src0->sadb_address_prefixlen,
2071 dst0->sadb_address_prefixlen,
2072 src0->sadb_address_proto,
2075 /* Is there SP in SPD ? */
2076 if ((sp = key_getsp(&spidx)) == NULL) {
2077 ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2078 return key_senderror(so, m, EINVAL);
2081 /* save policy id to buffer to be returned. */
2082 xpl0->sadb_x_policy_id = sp->id;
2085 printf("%s: SP(%p)\n", __func__, sp));
2086 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2092 struct sadb_msg *newmsg;
2094 /* create new sadb_msg to reply. */
2095 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2096 SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2098 return key_senderror(so, m, ENOBUFS);
2100 newmsg = mtod(n, struct sadb_msg *);
2101 newmsg->sadb_msg_errno = 0;
2102 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2105 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2110 * SADB_SPDDELETE2 processing
2113 * from the user(?), and set SADB_SASTATE_DEAD,
2117 * policy(*) including direction of policy.
2119 * m will always be freed.
2122 key_spddelete2(struct socket *so, struct mbuf *m,
2123 const struct sadb_msghdr *mhp)
2125 struct secpolicy *sp;
2128 IPSEC_ASSERT(so != NULL, ("null socket"));
2129 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2130 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2131 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2133 if (SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY) ||
2134 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2135 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2137 return key_senderror(so, m, EINVAL);
2140 id = ((struct sadb_x_policy *)
2141 mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2143 /* Is there SP in SPD ? */
2144 if ((sp = key_getspbyid(id)) == NULL) {
2145 ipseclog((LOG_DEBUG, "%s: no SP found for id %u.\n",
2147 return key_senderror(so, m, EINVAL);
2151 printf("%s: SP(%p)\n", __func__, sp));
2152 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2154 if (sp->state != IPSEC_SPSTATE_DEAD) {
2155 ipseclog((LOG_DEBUG, "%s: failed to delete SP with id %u.\n",
2158 return (key_senderror(so, m, EACCES));
2163 struct mbuf *n, *nn;
2164 struct sadb_msg *newmsg;
2167 /* create new sadb_msg to reply. */
2168 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2170 MGETHDR(n, M_NOWAIT, MT_DATA);
2171 if (n && len > MHLEN) {
2172 if (!(MCLGET(n, M_NOWAIT))) {
2178 return key_senderror(so, m, ENOBUFS);
2184 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2185 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2187 IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2190 n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2191 mhp->extlen[SADB_X_EXT_POLICY], M_NOWAIT);
2194 return key_senderror(so, m, ENOBUFS);
2197 n->m_pkthdr.len = 0;
2198 for (nn = n; nn; nn = nn->m_next)
2199 n->m_pkthdr.len += nn->m_len;
2201 newmsg = mtod(n, struct sadb_msg *);
2202 newmsg->sadb_msg_errno = 0;
2203 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2206 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2211 * SADB_X_SPDGET processing
2216 * <base, address(SD), policy>
2218 * policy(*) including direction of policy.
2220 * m will always be freed.
2223 key_spdget(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2225 struct secpolicy *sp;
2229 IPSEC_ASSERT(so != NULL, ("null socket"));
2230 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2231 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2232 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2234 if (SADB_CHECKHDR(mhp, SADB_X_EXT_POLICY) ||
2235 SADB_CHECKLEN(mhp, SADB_X_EXT_POLICY)) {
2236 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2238 return key_senderror(so, m, EINVAL);
2241 id = ((struct sadb_x_policy *)
2242 mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2244 /* Is there SP in SPD ? */
2245 if ((sp = key_getspbyid(id)) == NULL) {
2246 ipseclog((LOG_DEBUG, "%s: no SP found for id %u.\n",
2248 return key_senderror(so, m, ENOENT);
2251 n = key_setdumpsp(sp, SADB_X_SPDGET, mhp->msg->sadb_msg_seq,
2252 mhp->msg->sadb_msg_pid);
2256 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2258 return key_senderror(so, m, ENOBUFS);
2262 * SADB_X_SPDACQUIRE processing.
2263 * Acquire policy and SA(s) for a *OUTBOUND* packet.
2266 * to KMD, and expect to receive
2267 * <base> with SADB_X_SPDACQUIRE if error occurred,
2270 * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2271 * policy(*) is without policy requests.
2274 * others: error number
2277 key_spdacquire(struct secpolicy *sp)
2279 struct mbuf *result = NULL, *m;
2280 struct secspacq *newspacq;
2282 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2283 IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2284 IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2285 ("policy not IPSEC %u", sp->policy));
2287 /* Get an entry to check whether sent message or not. */
2288 newspacq = key_getspacq(&sp->spidx);
2289 if (newspacq != NULL) {
2290 if (V_key_blockacq_count < newspacq->count) {
2291 /* reset counter and do send message. */
2292 newspacq->count = 0;
2294 /* increment counter and do nothing. */
2301 /* make new entry for blocking to send SADB_ACQUIRE. */
2302 newspacq = key_newspacq(&sp->spidx);
2303 if (newspacq == NULL)
2307 /* create new sadb_msg to reply. */
2308 m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2314 result->m_pkthdr.len = 0;
2315 for (m = result; m; m = m->m_next)
2316 result->m_pkthdr.len += m->m_len;
2318 mtod(result, struct sadb_msg *)->sadb_msg_len =
2319 PFKEY_UNIT64(result->m_pkthdr.len);
2321 return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2325 * SADB_SPDFLUSH processing
2328 * from the user, and free all entries in secpctree.
2332 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2334 * m will always be freed.
2337 key_spdflush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2339 struct secpolicy_queue drainq;
2340 struct sadb_msg *newmsg;
2341 struct secpolicy *sp, *nextsp;
2344 IPSEC_ASSERT(so != NULL, ("null socket"));
2345 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2346 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2347 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2349 if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2350 return key_senderror(so, m, EINVAL);
2352 TAILQ_INIT(&drainq);
2354 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2355 TAILQ_CONCAT(&drainq, &V_sptree[dir], chain);
2358 * We need to set state to DEAD for each policy to be sure,
2359 * that another thread won't try to unlink it.
2360 * Also remove SP from sphash.
2362 TAILQ_FOREACH(sp, &drainq, chain) {
2363 sp->state = IPSEC_SPSTATE_DEAD;
2364 LIST_REMOVE(sp, idhash);
2368 sp = TAILQ_FIRST(&drainq);
2369 while (sp != NULL) {
2370 nextsp = TAILQ_NEXT(sp, chain);
2375 if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2376 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2377 return key_senderror(so, m, ENOBUFS);
2383 m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2384 newmsg = mtod(m, struct sadb_msg *);
2385 newmsg->sadb_msg_errno = 0;
2386 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2388 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2392 * SADB_SPDDUMP processing
2395 * from the user, and dump all SP leaves
2400 * m will always be freed.
2403 key_spddump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2405 SPTREE_RLOCK_TRACKER;
2406 struct secpolicy *sp;
2411 IPSEC_ASSERT(so != NULL, ("null socket"));
2412 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2413 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2414 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2416 /* search SPD entry and get buffer size. */
2419 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2420 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
2423 TAILQ_FOREACH(sp, &V_sptree_ifnet[dir], chain) {
2430 return key_senderror(so, m, ENOENT);
2433 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2434 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
2436 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2437 mhp->msg->sadb_msg_pid);
2440 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2442 TAILQ_FOREACH(sp, &V_sptree_ifnet[dir], chain) {
2444 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2445 mhp->msg->sadb_msg_pid);
2448 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2457 static struct mbuf *
2458 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq,
2461 struct mbuf *result = NULL, *m;
2462 struct seclifetime lt;
2464 m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2469 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2470 &sp->spidx.src.sa, sp->spidx.prefs,
2471 sp->spidx.ul_proto);
2476 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2477 &sp->spidx.dst.sa, sp->spidx.prefd,
2478 sp->spidx.ul_proto);
2483 m = key_sp2mbuf(sp);
2489 lt.addtime=sp->created;
2490 lt.usetime= sp->lastused;
2491 m = key_setlifetime(<, SADB_EXT_LIFETIME_CURRENT);
2496 lt.addtime=sp->lifetime;
2497 lt.usetime= sp->validtime;
2498 m = key_setlifetime(<, SADB_EXT_LIFETIME_HARD);
2504 if ((result->m_flags & M_PKTHDR) == 0)
2507 if (result->m_len < sizeof(struct sadb_msg)) {
2508 result = m_pullup(result, sizeof(struct sadb_msg));
2513 result->m_pkthdr.len = 0;
2514 for (m = result; m; m = m->m_next)
2515 result->m_pkthdr.len += m->m_len;
2517 mtod(result, struct sadb_msg *)->sadb_msg_len =
2518 PFKEY_UNIT64(result->m_pkthdr.len);
2527 * get PFKEY message length for security policy and request.
2530 key_getspreqmsglen(struct secpolicy *sp)
2535 tlen = sizeof(struct sadb_x_policy);
2536 /* if is the policy for ipsec ? */
2537 if (sp->policy != IPSEC_POLICY_IPSEC)
2540 /* get length of ipsec requests */
2541 for (i = 0; i < sp->tcount; i++) {
2542 len = sizeof(struct sadb_x_ipsecrequest)
2543 + sp->req[i]->saidx.src.sa.sa_len
2544 + sp->req[i]->saidx.dst.sa.sa_len;
2546 tlen += PFKEY_ALIGN8(len);
2552 * SADB_SPDEXPIRE processing
2554 * <base, address(SD), lifetime(CH), policy>
2558 * others : error number
2561 key_spdexpire(struct secpolicy *sp)
2563 struct sadb_lifetime *lt;
2564 struct mbuf *result = NULL, *m;
2565 int len, error = -1;
2567 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2570 printf("%s: SP(%p)\n", __func__, sp));
2571 KEYDBG(KEY_DATA, kdebug_secpolicy(sp));
2573 /* set msg header */
2574 m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2581 /* create lifetime extension (current and hard) */
2582 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2583 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
2590 bzero(mtod(m, caddr_t), len);
2591 lt = mtod(m, struct sadb_lifetime *);
2592 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2593 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2594 lt->sadb_lifetime_allocations = 0;
2595 lt->sadb_lifetime_bytes = 0;
2596 lt->sadb_lifetime_addtime = sp->created;
2597 lt->sadb_lifetime_usetime = sp->lastused;
2598 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2599 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2600 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2601 lt->sadb_lifetime_allocations = 0;
2602 lt->sadb_lifetime_bytes = 0;
2603 lt->sadb_lifetime_addtime = sp->lifetime;
2604 lt->sadb_lifetime_usetime = sp->validtime;
2607 /* set sadb_address for source */
2608 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2610 sp->spidx.prefs, sp->spidx.ul_proto);
2617 /* set sadb_address for destination */
2618 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2620 sp->spidx.prefd, sp->spidx.ul_proto);
2628 m = key_sp2mbuf(sp);
2635 if ((result->m_flags & M_PKTHDR) == 0) {
2640 if (result->m_len < sizeof(struct sadb_msg)) {
2641 result = m_pullup(result, sizeof(struct sadb_msg));
2642 if (result == NULL) {
2648 result->m_pkthdr.len = 0;
2649 for (m = result; m; m = m->m_next)
2650 result->m_pkthdr.len += m->m_len;
2652 mtod(result, struct sadb_msg *)->sadb_msg_len =
2653 PFKEY_UNIT64(result->m_pkthdr.len);
2655 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2663 /* %%% SAD management */
2665 * allocating and initialize new SA head.
2666 * OUT: NULL : failure due to the lack of memory.
2667 * others : pointer to new SA head.
2669 static struct secashead *
2670 key_newsah(struct secasindex *saidx)
2672 struct secashead *sah;
2674 sah = malloc(sizeof(struct secashead), M_IPSEC_SAH,
2677 PFKEYSTAT_INC(in_nomem);
2680 TAILQ_INIT(&sah->savtree_larval);
2681 TAILQ_INIT(&sah->savtree_alive);
2682 sah->saidx = *saidx;
2683 sah->state = SADB_SASTATE_DEAD;
2687 printf("%s: SAH(%p)\n", __func__, sah));
2688 KEYDBG(KEY_DATA, kdebug_secash(sah, NULL));
2693 key_freesah(struct secashead **psah)
2695 struct secashead *sah = *psah;
2697 if (SAH_DELREF(sah) == 0)
2701 printf("%s: last reference to SAH(%p)\n", __func__, sah));
2702 KEYDBG(KEY_DATA, kdebug_secash(sah, NULL));
2709 key_delsah(struct secashead *sah)
2711 IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2712 IPSEC_ASSERT(sah->state == SADB_SASTATE_DEAD,
2713 ("Attempt to free non DEAD SAH %p", sah));
2714 IPSEC_ASSERT(TAILQ_EMPTY(&sah->savtree_larval),
2715 ("Attempt to free SAH %p with LARVAL SA", sah));
2716 IPSEC_ASSERT(TAILQ_EMPTY(&sah->savtree_alive),
2717 ("Attempt to free SAH %p with ALIVE SA", sah));
2719 free(sah, M_IPSEC_SAH);
2723 * allocating a new SA for key_add() and key_getspi() call,
2724 * and copy the values of mhp into new buffer.
2725 * When SAD message type is SADB_GETSPI set SA state to LARVAL.
2726 * For SADB_ADD create and initialize SA with MATURE state.
2728 * others : pointer to new secasvar.
2730 static struct secasvar *
2731 key_newsav(const struct sadb_msghdr *mhp, struct secasindex *saidx,
2732 uint32_t spi, int *errp)
2734 struct secashead *sah;
2735 struct secasvar *sav;
2738 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2739 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2740 IPSEC_ASSERT(mhp->msg->sadb_msg_type == SADB_GETSPI ||
2741 mhp->msg->sadb_msg_type == SADB_ADD, ("wrong message type"));
2745 /* check SPI value */
2746 switch (saidx->proto) {
2750 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
2751 * 1-255 reserved by IANA for future use,
2752 * 0 for implementation specific, local use.
2754 if (ntohl(spi) <= 255) {
2755 ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
2756 __func__, ntohl(spi)));
2763 sav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT | M_ZERO);
2768 sav->lock = malloc(sizeof(struct mtx), M_IPSEC_MISC,
2770 if (sav->lock == NULL) {
2774 mtx_init(sav->lock, "ipsec association", NULL, MTX_DEF);
2775 sav->lft_c = uma_zalloc(V_key_lft_zone, M_NOWAIT);
2776 if (sav->lft_c == NULL) {
2780 counter_u64_zero(sav->lft_c_allocations);
2781 counter_u64_zero(sav->lft_c_bytes);
2784 sav->seq = mhp->msg->sadb_msg_seq;
2785 sav->state = SADB_SASTATE_LARVAL;
2786 sav->pid = (pid_t)mhp->msg->sadb_msg_pid;
2789 sah = key_getsah(saidx);
2791 /* create a new SA index */
2792 sah = key_newsah(saidx);
2794 ipseclog((LOG_DEBUG,
2795 "%s: No more memory.\n", __func__));
2804 if (mhp->msg->sadb_msg_type == SADB_GETSPI) {
2805 sav->created = time_second;
2806 } else if (sav->state == SADB_SASTATE_LARVAL) {
2808 * Do not call key_setsaval() second time in case
2809 * of `goto again`. We will have MATURE state.
2811 *errp = key_setsaval(sav, mhp);
2814 sav->state = SADB_SASTATE_MATURE;
2819 * Check that existing SAH wasn't unlinked.
2820 * Since we didn't hold the SAHTREE lock, it is possible,
2821 * that callout handler or key_flush() or key_delete() could
2824 if (isnew == 0 && sah->state == SADB_SASTATE_DEAD) {
2826 key_freesah(&sah); /* reference from key_getsah() */
2831 * Add new SAH into SADB.
2833 * XXXAE: we can serialize key_add and key_getspi calls, so
2834 * several threads will not fight in the race.
2835 * Otherwise we should check under SAHTREE lock, that this
2836 * SAH would not added twice.
2838 TAILQ_INSERT_HEAD(&V_sahtree, sah, chain);
2839 /* Add new SAH into hash by addresses */
2840 LIST_INSERT_HEAD(SAHADDRHASH_HASH(saidx), sah, addrhash);
2841 /* Now we are linked in the chain */
2842 sah->state = SADB_SASTATE_MATURE;
2844 * SAV references this new SAH.
2845 * In case of existing SAH we reuse reference
2846 * from key_getsah().
2850 /* Link SAV with SAH */
2851 if (sav->state == SADB_SASTATE_MATURE)
2852 TAILQ_INSERT_HEAD(&sah->savtree_alive, sav, chain);
2854 TAILQ_INSERT_HEAD(&sah->savtree_larval, sav, chain);
2855 /* Add SAV into SPI hash */
2856 LIST_INSERT_HEAD(SAVHASH_HASH(sav->spi), sav, spihash);
2858 *errp = 0; /* success */
2862 if (sav->lock != NULL) {
2863 mtx_destroy(sav->lock);
2864 free(sav->lock, M_IPSEC_MISC);
2866 if (sav->lft_c != NULL)
2867 uma_zfree(V_key_lft_zone, sav->lft_c);
2868 free(sav, M_IPSEC_SA), sav = NULL;
2872 if (*errp == ENOBUFS) {
2873 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
2875 PFKEYSTAT_INC(in_nomem);
2882 * free() SA variable entry.
2885 key_cleansav(struct secasvar *sav)
2888 if (sav->natt != NULL) {
2889 free(sav->natt, M_IPSEC_MISC);
2892 if (sav->flags & SADB_X_EXT_F_CLONED)
2895 * Cleanup xform state. Note that zeroize'ing causes the
2896 * keys to be cleared; otherwise we must do it ourself.
2898 if (sav->tdb_xform != NULL) {
2899 sav->tdb_xform->xf_zeroize(sav);
2900 sav->tdb_xform = NULL;
2902 if (sav->key_auth != NULL)
2903 bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2904 if (sav->key_enc != NULL)
2905 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2907 if (sav->key_auth != NULL) {
2908 if (sav->key_auth->key_data != NULL)
2909 free(sav->key_auth->key_data, M_IPSEC_MISC);
2910 free(sav->key_auth, M_IPSEC_MISC);
2911 sav->key_auth = NULL;
2913 if (sav->key_enc != NULL) {
2914 if (sav->key_enc->key_data != NULL)
2915 free(sav->key_enc->key_data, M_IPSEC_MISC);
2916 free(sav->key_enc, M_IPSEC_MISC);
2917 sav->key_enc = NULL;
2919 if (sav->replay != NULL) {
2920 if (sav->replay->bitmap != NULL)
2921 free(sav->replay->bitmap, M_IPSEC_MISC);
2922 free(sav->replay, M_IPSEC_MISC);
2925 if (sav->lft_h != NULL) {
2926 free(sav->lft_h, M_IPSEC_MISC);
2929 if (sav->lft_s != NULL) {
2930 free(sav->lft_s, M_IPSEC_MISC);
2936 * free() SA variable entry.
2939 key_delsav(struct secasvar *sav)
2941 IPSEC_ASSERT(sav != NULL, ("null sav"));
2942 IPSEC_ASSERT(sav->state == SADB_SASTATE_DEAD,
2943 ("attempt to free non DEAD SA %p", sav));
2944 IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0",
2948 * SA must be unlinked from the chain and hashtbl.
2949 * If SA was cloned, we leave all fields untouched,
2950 * except NAT-T config.
2953 if ((sav->flags & SADB_X_EXT_F_CLONED) == 0) {
2954 mtx_destroy(sav->lock);
2955 free(sav->lock, M_IPSEC_MISC);
2956 uma_zfree(V_key_lft_zone, sav->lft_c);
2958 free(sav, M_IPSEC_SA);
2965 * others : found, referenced pointer to a SAH.
2967 static struct secashead *
2968 key_getsah(struct secasindex *saidx)
2970 SAHTREE_RLOCK_TRACKER;
2971 struct secashead *sah;
2974 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
2975 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID) != 0) {
2985 * Check not to be duplicated SPI.
2988 * 1 : found SA with given SPI.
2991 key_checkspidup(uint32_t spi)
2993 SAHTREE_RLOCK_TRACKER;
2994 struct secasvar *sav;
2996 /* Assume SPI is in network byte order */
2998 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
2999 if (sav->spi == spi)
3003 return (sav != NULL);
3010 * others : found, referenced pointer to a SA.
3012 static struct secasvar *
3013 key_getsavbyspi(uint32_t spi)
3015 SAHTREE_RLOCK_TRACKER;
3016 struct secasvar *sav;
3018 /* Assume SPI is in network byte order */
3020 LIST_FOREACH(sav, SAVHASH_HASH(spi), spihash) {
3021 if (sav->spi != spi)
3031 key_updatelifetimes(struct secasvar *sav, const struct sadb_msghdr *mhp)
3033 struct seclifetime *lft_h, *lft_s, *tmp;
3035 /* Lifetime extension is optional, check that it is present. */
3036 if (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
3037 SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) {
3039 * In case of SADB_UPDATE we may need to change
3040 * existing lifetimes.
3042 if (sav->state == SADB_SASTATE_MATURE) {
3043 lft_h = lft_s = NULL;
3048 /* Both HARD and SOFT extensions must present */
3049 if ((SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
3050 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
3051 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
3052 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
3053 ipseclog((LOG_DEBUG,
3054 "%s: invalid message: missing required header.\n",
3058 if (SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_HARD) ||
3059 SADB_CHECKLEN(mhp, SADB_EXT_LIFETIME_SOFT)) {
3060 ipseclog((LOG_DEBUG,
3061 "%s: invalid message: wrong header size.\n", __func__));
3064 lft_h = key_dup_lifemsg((const struct sadb_lifetime *)
3065 mhp->ext[SADB_EXT_LIFETIME_HARD], M_IPSEC_MISC);
3066 if (lft_h == NULL) {
3067 PFKEYSTAT_INC(in_nomem);
3068 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3071 lft_s = key_dup_lifemsg((const struct sadb_lifetime *)
3072 mhp->ext[SADB_EXT_LIFETIME_SOFT], M_IPSEC_MISC);
3073 if (lft_s == NULL) {
3074 PFKEYSTAT_INC(in_nomem);
3075 free(lft_h, M_IPSEC_MISC);
3076 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3080 if (sav->state != SADB_SASTATE_LARVAL) {
3082 * key_update() holds reference to this SA,
3083 * so it won't be deleted in meanwhile.
3093 SECASVAR_UNLOCK(sav);
3095 free(lft_h, M_IPSEC_MISC);
3097 free(lft_s, M_IPSEC_MISC);
3100 /* We can update lifetime without holding a lock */
3101 IPSEC_ASSERT(sav->lft_h == NULL, ("lft_h is already initialized\n"));
3102 IPSEC_ASSERT(sav->lft_s == NULL, ("lft_s is already initialized\n"));
3109 * copy SA values from PF_KEY message except *SPI, SEQ, PID and TYPE*.
3110 * You must update these if need. Expects only LARVAL SAs.
3115 key_setsaval(struct secasvar *sav, const struct sadb_msghdr *mhp)
3117 const struct sadb_sa *sa0;
3118 const struct sadb_key *key0;
3123 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3124 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3125 IPSEC_ASSERT(sav->state == SADB_SASTATE_LARVAL,
3126 ("Attempt to update non LARVAL SA"));
3129 error = key_setident(sav->sah, mhp);
3134 if (!SADB_CHECKHDR(mhp, SADB_EXT_SA)) {
3135 if (SADB_CHECKLEN(mhp, SADB_EXT_SA)) {
3139 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3140 sav->alg_auth = sa0->sadb_sa_auth;
3141 sav->alg_enc = sa0->sadb_sa_encrypt;
3142 sav->flags = sa0->sadb_sa_flags;
3143 if ((sav->flags & SADB_KEY_FLAGS_MAX) != sav->flags) {
3144 ipseclog((LOG_DEBUG,
3145 "%s: invalid sa_flags 0x%08x.\n", __func__,
3151 /* Optional replay window */
3153 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0)
3154 replay = sa0->sadb_sa_replay;
3155 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_SA_REPLAY)) {
3156 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA_REPLAY)) {
3160 replay = ((const struct sadb_x_sa_replay *)
3161 mhp->ext[SADB_X_EXT_SA_REPLAY])->sadb_x_sa_replay_replay;
3163 if (replay > UINT32_MAX - 32) {
3164 ipseclog((LOG_DEBUG,
3165 "%s: replay window too big.\n", __func__));
3170 replay = (replay + 7) >> 3;
3173 sav->replay = malloc(sizeof(struct secreplay), M_IPSEC_MISC,
3175 if (sav->replay == NULL) {
3176 PFKEYSTAT_INC(in_nomem);
3177 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3184 /* number of 32b blocks to be allocated */
3185 uint32_t bitmap_size;
3188 * - the allocated replay window size must be
3190 * - use an extra 32b block as a redundant window.
3193 while (replay + 4 > bitmap_size)
3195 bitmap_size = bitmap_size / 4;
3197 sav->replay->bitmap = malloc(
3198 bitmap_size * sizeof(uint32_t), M_IPSEC_MISC,
3200 if (sav->replay->bitmap == NULL) {
3201 PFKEYSTAT_INC(in_nomem);
3202 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3207 sav->replay->bitmap_size = bitmap_size;
3208 sav->replay->wsize = replay;
3212 /* Authentication keys */
3213 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH)) {
3214 if (SADB_CHECKLEN(mhp, SADB_EXT_KEY_AUTH)) {
3219 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3220 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3221 switch (mhp->msg->sadb_msg_satype) {
3222 case SADB_SATYPE_AH:
3223 case SADB_SATYPE_ESP:
3224 case SADB_X_SATYPE_TCPSIGNATURE:
3225 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3226 sav->alg_auth != SADB_X_AALG_NULL)
3229 case SADB_X_SATYPE_IPCOMP:
3235 ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3240 sav->key_auth = key_dup_keymsg(key0, len, M_IPSEC_MISC);
3241 if (sav->key_auth == NULL ) {
3242 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3244 PFKEYSTAT_INC(in_nomem);
3250 /* Encryption key */
3251 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT)) {
3252 if (SADB_CHECKLEN(mhp, SADB_EXT_KEY_ENCRYPT)) {
3257 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3258 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3259 switch (mhp->msg->sadb_msg_satype) {
3260 case SADB_SATYPE_ESP:
3261 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3262 sav->alg_enc != SADB_EALG_NULL) {
3266 sav->key_enc = key_dup_keymsg(key0, len, M_IPSEC_MISC);
3267 if (sav->key_enc == NULL) {
3268 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3270 PFKEYSTAT_INC(in_nomem);
3275 case SADB_X_SATYPE_IPCOMP:
3276 if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3278 sav->key_enc = NULL; /*just in case*/
3280 case SADB_SATYPE_AH:
3281 case SADB_X_SATYPE_TCPSIGNATURE:
3287 ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3295 switch (mhp->msg->sadb_msg_satype) {
3296 case SADB_SATYPE_AH:
3297 if (sav->flags & SADB_X_EXT_DERIV) {
3298 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3299 "given to AH SA.\n", __func__));
3303 if (sav->alg_enc != SADB_EALG_NONE) {
3304 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3305 "mismated.\n", __func__));
3309 error = xform_init(sav, XF_AH);
3311 case SADB_SATYPE_ESP:
3312 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_DERIV)) ==
3313 (SADB_X_EXT_OLD | SADB_X_EXT_DERIV)) {
3314 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3315 "given to old-esp.\n", __func__));
3319 error = xform_init(sav, XF_ESP);
3321 case SADB_X_SATYPE_IPCOMP:
3322 if (sav->alg_auth != SADB_AALG_NONE) {
3323 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3324 "mismated.\n", __func__));
3328 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0 &&
3329 ntohl(sav->spi) >= 0x10000) {
3330 ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3335 error = xform_init(sav, XF_IPCOMP);
3337 case SADB_X_SATYPE_TCPSIGNATURE:
3338 if (sav->alg_enc != SADB_EALG_NONE) {
3339 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3340 "mismated.\n", __func__));
3344 error = xform_init(sav, XF_TCPSIGNATURE);
3347 ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3348 error = EPROTONOSUPPORT;
3352 ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3353 __func__, mhp->msg->sadb_msg_satype));
3357 /* Handle NAT-T headers */
3358 error = key_setnatt(sav, mhp);
3362 /* Initialize lifetime for CURRENT */
3364 sav->created = time_second;
3366 /* lifetimes for HARD and SOFT */
3367 error = key_updatelifetimes(sav, mhp);
3376 * subroutine for SADB_GET and SADB_DUMP.
3378 static struct mbuf *
3379 key_setdumpsa(struct secasvar *sav, uint8_t type, uint8_t satype,
3380 uint32_t seq, uint32_t pid)
3382 struct seclifetime lft_c;
3383 struct mbuf *result = NULL, *tres = NULL, *m;
3384 int i, dumporder[] = {
3385 SADB_EXT_SA, SADB_X_EXT_SA2, SADB_X_EXT_SA_REPLAY,
3386 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3387 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3388 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY,
3389 SADB_EXT_KEY_AUTH, SADB_EXT_KEY_ENCRYPT,
3390 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
3391 SADB_EXT_SENSITIVITY,
3392 SADB_X_EXT_NAT_T_TYPE,
3393 SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3394 SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3395 SADB_X_EXT_NAT_T_FRAG,
3397 uint32_t replay_count;
3399 m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3404 for (i = nitems(dumporder) - 1; i >= 0; i--) {
3406 switch (dumporder[i]) {
3408 m = key_setsadbsa(sav);
3413 case SADB_X_EXT_SA2:
3415 replay_count = sav->replay ? sav->replay->count : 0;
3416 SECASVAR_UNLOCK(sav);
3417 m = key_setsadbxsa2(sav->sah->saidx.mode, replay_count,
3418 sav->sah->saidx.reqid);
3423 case SADB_X_EXT_SA_REPLAY:
3424 if (sav->replay == NULL ||
3425 sav->replay->wsize <= UINT8_MAX)
3428 m = key_setsadbxsareplay(sav->replay->wsize);
3433 case SADB_EXT_ADDRESS_SRC:
3434 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3435 &sav->sah->saidx.src.sa,
3436 FULLMASK, IPSEC_ULPROTO_ANY);
3441 case SADB_EXT_ADDRESS_DST:
3442 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3443 &sav->sah->saidx.dst.sa,
3444 FULLMASK, IPSEC_ULPROTO_ANY);
3449 case SADB_EXT_KEY_AUTH:
3452 m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3457 case SADB_EXT_KEY_ENCRYPT:
3460 m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3465 case SADB_EXT_LIFETIME_CURRENT:
3466 lft_c.addtime = sav->created;
3467 lft_c.allocations = (uint32_t)counter_u64_fetch(
3468 sav->lft_c_allocations);
3469 lft_c.bytes = counter_u64_fetch(sav->lft_c_bytes);
3470 lft_c.usetime = sav->firstused;
3471 m = key_setlifetime(&lft_c, SADB_EXT_LIFETIME_CURRENT);
3476 case SADB_EXT_LIFETIME_HARD:
3479 m = key_setlifetime(sav->lft_h,
3480 SADB_EXT_LIFETIME_HARD);
3485 case SADB_EXT_LIFETIME_SOFT:
3488 m = key_setlifetime(sav->lft_s,
3489 SADB_EXT_LIFETIME_SOFT);
3495 case SADB_X_EXT_NAT_T_TYPE:
3496 if (sav->natt == NULL)
3498 m = key_setsadbxtype(UDP_ENCAP_ESPINUDP);
3503 case SADB_X_EXT_NAT_T_DPORT:
3504 if (sav->natt == NULL)
3506 m = key_setsadbxport(sav->natt->dport,
3507 SADB_X_EXT_NAT_T_DPORT);
3512 case SADB_X_EXT_NAT_T_SPORT:
3513 if (sav->natt == NULL)
3515 m = key_setsadbxport(sav->natt->sport,
3516 SADB_X_EXT_NAT_T_SPORT);
3521 case SADB_X_EXT_NAT_T_OAI:
3522 if (sav->natt == NULL ||
3523 (sav->natt->flags & IPSEC_NATT_F_OAI) == 0)
3525 m = key_setsadbaddr(SADB_X_EXT_NAT_T_OAI,
3526 &sav->natt->oai.sa, FULLMASK, IPSEC_ULPROTO_ANY);
3530 case SADB_X_EXT_NAT_T_OAR:
3531 if (sav->natt == NULL ||
3532 (sav->natt->flags & IPSEC_NATT_F_OAR) == 0)
3534 m = key_setsadbaddr(SADB_X_EXT_NAT_T_OAR,
3535 &sav->natt->oar.sa, FULLMASK, IPSEC_ULPROTO_ANY);
3539 case SADB_X_EXT_NAT_T_FRAG:
3540 /* We do not (yet) support those. */
3543 case SADB_EXT_ADDRESS_PROXY:
3544 case SADB_EXT_IDENTITY_SRC:
3545 case SADB_EXT_IDENTITY_DST:
3546 /* XXX: should we brought from SPD ? */
3547 case SADB_EXT_SENSITIVITY:
3559 m_cat(result, tres);
3561 if (result->m_len < sizeof(struct sadb_msg)) {
3562 result = m_pullup(result, sizeof(struct sadb_msg));
3567 result->m_pkthdr.len = 0;
3568 for (m = result; m; m = m->m_next)
3569 result->m_pkthdr.len += m->m_len;
3571 mtod(result, struct sadb_msg *)->sadb_msg_len =
3572 PFKEY_UNIT64(result->m_pkthdr.len);
3583 * set data into sadb_msg.
3585 static struct mbuf *
3586 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3587 pid_t pid, u_int16_t reserved)
3593 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3596 MGETHDR(m, M_NOWAIT, MT_DATA);
3597 if (m && len > MHLEN) {
3598 if (!(MCLGET(m, M_NOWAIT))) {
3605 m->m_pkthdr.len = m->m_len = len;
3608 p = mtod(m, struct sadb_msg *);
3611 p->sadb_msg_version = PF_KEY_V2;
3612 p->sadb_msg_type = type;
3613 p->sadb_msg_errno = 0;
3614 p->sadb_msg_satype = satype;
3615 p->sadb_msg_len = PFKEY_UNIT64(tlen);
3616 p->sadb_msg_reserved = reserved;
3617 p->sadb_msg_seq = seq;
3618 p->sadb_msg_pid = (u_int32_t)pid;
3624 * copy secasvar data into sadb_address.
3626 static struct mbuf *
3627 key_setsadbsa(struct secasvar *sav)
3633 len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3634 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3639 p = mtod(m, struct sadb_sa *);
3641 p->sadb_sa_len = PFKEY_UNIT64(len);
3642 p->sadb_sa_exttype = SADB_EXT_SA;
3643 p->sadb_sa_spi = sav->spi;
3644 p->sadb_sa_replay = sav->replay ?
3645 (sav->replay->wsize > UINT8_MAX ? UINT8_MAX :
3646 sav->replay->wsize): 0;
3647 p->sadb_sa_state = sav->state;
3648 p->sadb_sa_auth = sav->alg_auth;
3649 p->sadb_sa_encrypt = sav->alg_enc;
3650 p->sadb_sa_flags = sav->flags & SADB_KEY_FLAGS_MAX;
3655 * set data into sadb_address.
3657 static struct mbuf *
3658 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
3659 u_int8_t prefixlen, u_int16_t ul_proto)
3662 struct sadb_address *p;
3665 len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3666 PFKEY_ALIGN8(saddr->sa_len);
3667 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3672 p = mtod(m, struct sadb_address *);
3675 p->sadb_address_len = PFKEY_UNIT64(len);
3676 p->sadb_address_exttype = exttype;
3677 p->sadb_address_proto = ul_proto;
3678 if (prefixlen == FULLMASK) {
3679 switch (saddr->sa_family) {
3681 prefixlen = sizeof(struct in_addr) << 3;
3684 prefixlen = sizeof(struct in6_addr) << 3;
3690 p->sadb_address_prefixlen = prefixlen;
3691 p->sadb_address_reserved = 0;
3694 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3701 * set data into sadb_x_sa2.
3703 static struct mbuf *
3704 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3707 struct sadb_x_sa2 *p;
3710 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3711 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3716 p = mtod(m, struct sadb_x_sa2 *);
3719 p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3720 p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3721 p->sadb_x_sa2_mode = mode;
3722 p->sadb_x_sa2_reserved1 = 0;
3723 p->sadb_x_sa2_reserved2 = 0;
3724 p->sadb_x_sa2_sequence = seq;
3725 p->sadb_x_sa2_reqid = reqid;
3731 * Set data into sadb_x_sa_replay.
3733 static struct mbuf *
3734 key_setsadbxsareplay(u_int32_t replay)
3737 struct sadb_x_sa_replay *p;
3740 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa_replay));
3741 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3746 p = mtod(m, struct sadb_x_sa_replay *);
3749 p->sadb_x_sa_replay_len = PFKEY_UNIT64(len);
3750 p->sadb_x_sa_replay_exttype = SADB_X_EXT_SA_REPLAY;
3751 p->sadb_x_sa_replay_replay = (replay << 3);
3757 * Set a type in sadb_x_nat_t_type.
3759 static struct mbuf *
3760 key_setsadbxtype(u_int16_t type)
3764 struct sadb_x_nat_t_type *p;
3766 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3768 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3773 p = mtod(m, struct sadb_x_nat_t_type *);
3776 p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3777 p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3778 p->sadb_x_nat_t_type_type = type;
3783 * Set a port in sadb_x_nat_t_port.
3784 * In contrast to default RFC 2367 behaviour, port is in network byte order.
3786 static struct mbuf *
3787 key_setsadbxport(u_int16_t port, u_int16_t type)
3791 struct sadb_x_nat_t_port *p;
3793 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3795 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3800 p = mtod(m, struct sadb_x_nat_t_port *);
3803 p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3804 p->sadb_x_nat_t_port_exttype = type;
3805 p->sadb_x_nat_t_port_port = port;
3811 * Get port from sockaddr. Port is in network byte order.
3814 key_portfromsaddr(struct sockaddr *sa)
3817 switch (sa->sa_family) {
3820 return ((struct sockaddr_in *)sa)->sin_port;
3824 return ((struct sockaddr_in6 *)sa)->sin6_port;
3831 * Set port in struct sockaddr. Port is in network byte order.
3834 key_porttosaddr(struct sockaddr *sa, uint16_t port)
3837 switch (sa->sa_family) {
3840 ((struct sockaddr_in *)sa)->sin_port = port;
3845 ((struct sockaddr_in6 *)sa)->sin6_port = port;
3849 ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
3850 __func__, sa->sa_family));
3856 * set data into sadb_x_policy
3858 static struct mbuf *
3859 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id, u_int32_t priority)
3862 struct sadb_x_policy *p;
3865 len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3866 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3871 p = mtod(m, struct sadb_x_policy *);
3874 p->sadb_x_policy_len = PFKEY_UNIT64(len);
3875 p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3876 p->sadb_x_policy_type = type;
3877 p->sadb_x_policy_dir = dir;
3878 p->sadb_x_policy_id = id;
3879 p->sadb_x_policy_priority = priority;
3885 /* Take a key message (sadb_key) from the socket and turn it into one
3886 * of the kernel's key structures (seckey).
3888 * IN: pointer to the src
3889 * OUT: NULL no more memory
3892 key_dup_keymsg(const struct sadb_key *src, size_t len,
3893 struct malloc_type *type)
3897 dst = malloc(sizeof(*dst), type, M_NOWAIT);
3899 dst->bits = src->sadb_key_bits;
3900 dst->key_data = malloc(len, type, M_NOWAIT);
3901 if (dst->key_data != NULL) {
3902 bcopy((const char *)(src + 1), dst->key_data, len);
3904 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3910 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3917 /* Take a lifetime message (sadb_lifetime) passed in on a socket and
3918 * turn it into one of the kernel's lifetime structures (seclifetime).
3920 * IN: pointer to the destination, source and malloc type
3921 * OUT: NULL, no more memory
3924 static struct seclifetime *
3925 key_dup_lifemsg(const struct sadb_lifetime *src, struct malloc_type *type)
3927 struct seclifetime *dst;
3929 dst = malloc(sizeof(*dst), type, M_NOWAIT);
3931 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3934 dst->allocations = src->sadb_lifetime_allocations;
3935 dst->bytes = src->sadb_lifetime_bytes;
3936 dst->addtime = src->sadb_lifetime_addtime;
3937 dst->usetime = src->sadb_lifetime_usetime;
3942 * compare two secasindex structure.
3943 * flag can specify to compare 2 saidxes.
3944 * compare two secasindex structure without both mode and reqid.
3945 * don't compare port.
3947 * saidx0: source, it can be in SAD.
3954 key_cmpsaidx(const struct secasindex *saidx0, const struct secasindex *saidx1,
3959 if (saidx0 == NULL && saidx1 == NULL)
3962 if (saidx0 == NULL || saidx1 == NULL)
3965 if (saidx0->proto != saidx1->proto)
3968 if (flag == CMP_EXACTLY) {
3969 if (saidx0->mode != saidx1->mode)
3971 if (saidx0->reqid != saidx1->reqid)
3973 if (bcmp(&saidx0->src, &saidx1->src,
3974 saidx0->src.sa.sa_len) != 0 ||
3975 bcmp(&saidx0->dst, &saidx1->dst,
3976 saidx0->dst.sa.sa_len) != 0)
3980 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3981 if (flag == CMP_MODE_REQID || flag == CMP_REQID) {
3983 * If reqid of SPD is non-zero, unique SA is required.
3984 * The result must be of same reqid in this case.
3986 if (saidx1->reqid != 0 &&
3987 saidx0->reqid != saidx1->reqid)
3991 if (flag == CMP_MODE_REQID) {
3992 if (saidx0->mode != IPSEC_MODE_ANY
3993 && saidx0->mode != saidx1->mode)
3997 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0)
3999 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0)
4007 * compare two secindex structure exactly.
4009 * spidx0: source, it is often in SPD.
4010 * spidx1: object, it is often from PFKEY message.
4016 key_cmpspidx_exactly(struct secpolicyindex *spidx0,
4017 struct secpolicyindex *spidx1)
4020 if (spidx0 == NULL && spidx1 == NULL)
4023 if (spidx0 == NULL || spidx1 == NULL)
4026 if (spidx0->prefs != spidx1->prefs
4027 || spidx0->prefd != spidx1->prefd
4028 || spidx0->ul_proto != spidx1->ul_proto)
4031 return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4032 key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4036 * compare two secindex structure with mask.
4038 * spidx0: source, it is often in SPD.
4039 * spidx1: object, it is often from IP header.
4045 key_cmpspidx_withmask(struct secpolicyindex *spidx0,
4046 struct secpolicyindex *spidx1)
4049 if (spidx0 == NULL && spidx1 == NULL)
4052 if (spidx0 == NULL || spidx1 == NULL)
4055 if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4056 spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4057 spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4058 spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4061 /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4062 if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4063 && spidx0->ul_proto != spidx1->ul_proto)
4066 switch (spidx0->src.sa.sa_family) {
4068 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4069 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4071 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4072 &spidx1->src.sin.sin_addr, spidx0->prefs))
4076 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4077 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4080 * scope_id check. if sin6_scope_id is 0, we regard it
4081 * as a wildcard scope, which matches any scope zone ID.
4083 if (spidx0->src.sin6.sin6_scope_id &&
4084 spidx1->src.sin6.sin6_scope_id &&
4085 spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4087 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4088 &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4093 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4098 switch (spidx0->dst.sa.sa_family) {
4100 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4101 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4103 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4104 &spidx1->dst.sin.sin_addr, spidx0->prefd))
4108 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4109 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4112 * scope_id check. if sin6_scope_id is 0, we regard it
4113 * as a wildcard scope, which matches any scope zone ID.
4115 if (spidx0->dst.sin6.sin6_scope_id &&
4116 spidx1->dst.sin6.sin6_scope_id &&
4117 spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4119 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4120 &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4125 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4130 /* XXX Do we check other field ? e.g. flowinfo */
4138 #define satosin(s) ((const struct sockaddr_in *)s)
4142 #define satosin6(s) ((const struct sockaddr_in6 *)s)
4143 /* returns 0 on match */
4145 key_sockaddrcmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
4148 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4151 switch (sa1->sa_family) {
4154 if (sa1->sa_len != sizeof(struct sockaddr_in))
4156 if (satosin(sa1)->sin_addr.s_addr !=
4157 satosin(sa2)->sin_addr.s_addr) {
4160 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4166 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4167 return 1; /*EINVAL*/
4168 if (satosin6(sa1)->sin6_scope_id !=
4169 satosin6(sa2)->sin6_scope_id) {
4172 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4173 &satosin6(sa2)->sin6_addr)) {
4177 satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4183 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4191 /* returns 0 on match */
4193 key_sockaddrcmp_withmask(const struct sockaddr *sa1,
4194 const struct sockaddr *sa2, size_t mask)
4196 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4199 switch (sa1->sa_family) {
4202 return (!key_bbcmp(&satosin(sa1)->sin_addr,
4203 &satosin(sa2)->sin_addr, mask));
4207 if (satosin6(sa1)->sin6_scope_id !=
4208 satosin6(sa2)->sin6_scope_id)
4210 return (!key_bbcmp(&satosin6(sa1)->sin6_addr,
4211 &satosin6(sa2)->sin6_addr, mask));
4220 * compare two buffers with mask.
4224 * bits: Number of bits to compare
4230 key_bbcmp(const void *a1, const void *a2, u_int bits)
4232 const unsigned char *p1 = a1;
4233 const unsigned char *p2 = a2;
4235 /* XXX: This could be considerably faster if we compare a word
4236 * at a time, but it is complicated on LSB Endian machines */
4238 /* Handle null pointers */
4239 if (p1 == NULL || p2 == NULL)
4249 u_int8_t mask = ~((1<<(8-bits))-1);
4250 if ((*p1 & mask) != (*p2 & mask))
4253 return 1; /* Match! */
4257 key_flush_spd(time_t now)
4259 SPTREE_RLOCK_TRACKER;
4260 struct secpolicy_list drainq;
4261 struct secpolicy *sp, *nextsp;
4266 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4267 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
4268 if (sp->lifetime == 0 && sp->validtime == 0)
4270 if ((sp->lifetime &&
4271 now - sp->created > sp->lifetime) ||
4273 now - sp->lastused > sp->validtime)) {
4274 /* Hold extra reference to send SPDEXPIRE */
4276 LIST_INSERT_HEAD(&drainq, sp, drainq);
4281 if (LIST_EMPTY(&drainq))
4285 sp = LIST_FIRST(&drainq);
4286 while (sp != NULL) {
4287 nextsp = LIST_NEXT(sp, drainq);
4288 /* Check that SP is still linked */
4289 if (sp->state != IPSEC_SPSTATE_ALIVE) {
4290 LIST_REMOVE(sp, drainq);
4291 key_freesp(&sp); /* release extra reference */
4295 TAILQ_REMOVE(&V_sptree[sp->spidx.dir], sp, chain);
4296 LIST_REMOVE(sp, idhash);
4297 sp->state = IPSEC_SPSTATE_DEAD;
4303 sp = LIST_FIRST(&drainq);
4304 while (sp != NULL) {
4305 nextsp = LIST_NEXT(sp, drainq);
4307 key_freesp(&sp); /* release extra reference */
4308 key_freesp(&sp); /* release last reference */
4314 key_flush_sad(time_t now)
4316 SAHTREE_RLOCK_TRACKER;
4317 struct secashead_list emptyq;
4318 struct secasvar_list drainq, hexpireq, sexpireq, freeq;
4319 struct secashead *sah, *nextsah;
4320 struct secasvar *sav, *nextsav;
4323 LIST_INIT(&hexpireq);
4324 LIST_INIT(&sexpireq);
4328 TAILQ_FOREACH(sah, &V_sahtree, chain) {
4329 /* Check for empty SAH */
4330 if (TAILQ_EMPTY(&sah->savtree_larval) &&
4331 TAILQ_EMPTY(&sah->savtree_alive)) {
4333 LIST_INSERT_HEAD(&emptyq, sah, drainq);
4336 /* Add all stale LARVAL SAs into drainq */
4337 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
4338 if (now - sav->created < V_key_larval_lifetime)
4341 LIST_INSERT_HEAD(&drainq, sav, drainq);
4343 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
4344 /* lifetimes aren't specified */
4345 if (sav->lft_h == NULL)
4349 * Check again with lock held, because it may
4350 * be updated by SADB_UPDATE.
4352 if (sav->lft_h == NULL) {
4353 SECASVAR_UNLOCK(sav);
4358 * HARD lifetimes MUST take precedence over SOFT
4359 * lifetimes, meaning if the HARD and SOFT lifetimes
4360 * are the same, the HARD lifetime will appear on the
4363 /* check HARD lifetime */
4364 if ((sav->lft_h->addtime != 0 &&
4365 now - sav->created > sav->lft_h->addtime) ||
4366 (sav->lft_h->usetime != 0 && sav->firstused &&
4367 now - sav->firstused > sav->lft_h->usetime) ||
4368 (sav->lft_h->bytes != 0 && counter_u64_fetch(
4369 sav->lft_c_bytes) > sav->lft_h->bytes)) {
4370 SECASVAR_UNLOCK(sav);
4372 LIST_INSERT_HEAD(&hexpireq, sav, drainq);
4375 /* check SOFT lifetime (only for MATURE SAs) */
4376 if (sav->state == SADB_SASTATE_MATURE && (
4377 (sav->lft_s->addtime != 0 &&
4378 now - sav->created > sav->lft_s->addtime) ||
4379 (sav->lft_s->usetime != 0 && sav->firstused &&
4380 now - sav->firstused > sav->lft_s->usetime) ||
4381 (sav->lft_s->bytes != 0 && counter_u64_fetch(
4382 sav->lft_c_bytes) > sav->lft_s->bytes))) {
4383 SECASVAR_UNLOCK(sav);
4385 LIST_INSERT_HEAD(&sexpireq, sav, drainq);
4388 SECASVAR_UNLOCK(sav);
4393 if (LIST_EMPTY(&emptyq) && LIST_EMPTY(&drainq) &&
4394 LIST_EMPTY(&hexpireq) && LIST_EMPTY(&sexpireq))
4399 /* Unlink stale LARVAL SAs */
4400 sav = LIST_FIRST(&drainq);
4401 while (sav != NULL) {
4402 nextsav = LIST_NEXT(sav, drainq);
4403 /* Check that SA is still LARVAL */
4404 if (sav->state != SADB_SASTATE_LARVAL) {
4405 LIST_REMOVE(sav, drainq);
4406 LIST_INSERT_HEAD(&freeq, sav, drainq);
4410 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
4411 LIST_REMOVE(sav, spihash);
4412 sav->state = SADB_SASTATE_DEAD;
4415 /* Unlink all SAs with expired HARD lifetime */
4416 sav = LIST_FIRST(&hexpireq);
4417 while (sav != NULL) {
4418 nextsav = LIST_NEXT(sav, drainq);
4419 /* Check that SA is not unlinked */
4420 if (sav->state == SADB_SASTATE_DEAD) {
4421 LIST_REMOVE(sav, drainq);
4422 LIST_INSERT_HEAD(&freeq, sav, drainq);
4426 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
4427 LIST_REMOVE(sav, spihash);
4428 sav->state = SADB_SASTATE_DEAD;
4431 /* Mark all SAs with expired SOFT lifetime as DYING */
4432 sav = LIST_FIRST(&sexpireq);
4433 while (sav != NULL) {
4434 nextsav = LIST_NEXT(sav, drainq);
4435 /* Check that SA is not unlinked */
4436 if (sav->state == SADB_SASTATE_DEAD) {
4437 LIST_REMOVE(sav, drainq);
4438 LIST_INSERT_HEAD(&freeq, sav, drainq);
4443 * NOTE: this doesn't change SA order in the chain.
4445 sav->state = SADB_SASTATE_DYING;
4448 /* Unlink empty SAHs */
4449 sah = LIST_FIRST(&emptyq);
4450 while (sah != NULL) {
4451 nextsah = LIST_NEXT(sah, drainq);
4452 /* Check that SAH is still empty and not unlinked */
4453 if (sah->state == SADB_SASTATE_DEAD ||
4454 !TAILQ_EMPTY(&sah->savtree_larval) ||
4455 !TAILQ_EMPTY(&sah->savtree_alive)) {
4456 LIST_REMOVE(sah, drainq);
4457 key_freesah(&sah); /* release extra reference */
4461 TAILQ_REMOVE(&V_sahtree, sah, chain);
4462 LIST_REMOVE(sah, addrhash);
4463 sah->state = SADB_SASTATE_DEAD;
4468 /* Send SPDEXPIRE messages */
4469 sav = LIST_FIRST(&hexpireq);
4470 while (sav != NULL) {
4471 nextsav = LIST_NEXT(sav, drainq);
4473 key_freesah(&sav->sah); /* release reference from SAV */
4474 key_freesav(&sav); /* release extra reference */
4475 key_freesav(&sav); /* release last reference */
4478 sav = LIST_FIRST(&sexpireq);
4479 while (sav != NULL) {
4480 nextsav = LIST_NEXT(sav, drainq);
4482 key_freesav(&sav); /* release extra reference */
4485 /* Free stale LARVAL SAs */
4486 sav = LIST_FIRST(&drainq);
4487 while (sav != NULL) {
4488 nextsav = LIST_NEXT(sav, drainq);
4489 key_freesah(&sav->sah); /* release reference from SAV */
4490 key_freesav(&sav); /* release extra reference */
4491 key_freesav(&sav); /* release last reference */
4494 /* Free SAs that were unlinked/changed by someone else */
4495 sav = LIST_FIRST(&freeq);
4496 while (sav != NULL) {
4497 nextsav = LIST_NEXT(sav, drainq);
4498 key_freesav(&sav); /* release extra reference */
4501 /* Free empty SAH */
4502 sah = LIST_FIRST(&emptyq);
4503 while (sah != NULL) {
4504 nextsah = LIST_NEXT(sah, drainq);
4505 key_freesah(&sah); /* release extra reference */
4506 key_freesah(&sah); /* release last reference */
4512 key_flush_acq(time_t now)
4514 struct secacq *acq, *nextacq;
4518 acq = LIST_FIRST(&V_acqtree);
4519 while (acq != NULL) {
4520 nextacq = LIST_NEXT(acq, chain);
4521 if (now - acq->created > V_key_blockacq_lifetime) {
4522 LIST_REMOVE(acq, chain);
4523 LIST_REMOVE(acq, addrhash);
4524 LIST_REMOVE(acq, seqhash);
4525 free(acq, M_IPSEC_SAQ);
4533 key_flush_spacq(time_t now)
4535 struct secspacq *acq, *nextacq;
4539 for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4540 nextacq = LIST_NEXT(acq, chain);
4541 if (now - acq->created > V_key_blockacq_lifetime
4542 && __LIST_CHAINED(acq)) {
4543 LIST_REMOVE(acq, chain);
4544 free(acq, M_IPSEC_SAQ);
4552 * scanning SPD and SAD to check status for each entries,
4553 * and do to remove or to expire.
4554 * XXX: year 2038 problem may remain.
4557 key_timehandler(void *arg)
4559 VNET_ITERATOR_DECL(vnet_iter);
4560 time_t now = time_second;
4562 VNET_LIST_RLOCK_NOSLEEP();
4563 VNET_FOREACH(vnet_iter) {
4564 CURVNET_SET(vnet_iter);
4568 key_flush_spacq(now);
4571 VNET_LIST_RUNLOCK_NOSLEEP();
4573 #ifndef IPSEC_DEBUG2
4574 /* do exchange to tick time !! */
4575 callout_schedule(&key_timer, hz);
4576 #endif /* IPSEC_DEBUG2 */
4584 key_randomfill(&value, sizeof(value));
4589 key_randomfill(void *p, size_t l)
4593 static int warn = 1;
4596 n = (size_t)read_random(p, (u_int)l);
4600 bcopy(&v, (u_int8_t *)p + n,
4601 l - n < sizeof(v) ? l - n : sizeof(v));
4605 printf("WARNING: pseudo-random number generator "
4606 "used for IPsec processing\n");
4613 * map SADB_SATYPE_* to IPPROTO_*.
4614 * if satype == SADB_SATYPE then satype is mapped to ~0.
4616 * 0: invalid satype.
4619 key_satype2proto(uint8_t satype)
4622 case SADB_SATYPE_UNSPEC:
4623 return IPSEC_PROTO_ANY;
4624 case SADB_SATYPE_AH:
4626 case SADB_SATYPE_ESP:
4628 case SADB_X_SATYPE_IPCOMP:
4629 return IPPROTO_IPCOMP;
4630 case SADB_X_SATYPE_TCPSIGNATURE:
4639 * map IPPROTO_* to SADB_SATYPE_*
4641 * 0: invalid protocol type.
4644 key_proto2satype(uint8_t proto)
4648 return SADB_SATYPE_AH;
4650 return SADB_SATYPE_ESP;
4651 case IPPROTO_IPCOMP:
4652 return SADB_X_SATYPE_IPCOMP;
4654 return SADB_X_SATYPE_TCPSIGNATURE;
4663 * SADB_GETSPI processing is to receive
4664 * <base, (SA2), src address, dst address, (SPI range)>
4665 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4666 * tree with the status of LARVAL, and send
4667 * <base, SA(*), address(SD)>
4670 * IN: mhp: pointer to the pointer to each header.
4671 * OUT: NULL if fail.
4672 * other if success, return pointer to the message to send.
4675 key_getspi(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4677 struct secasindex saidx;
4678 struct sadb_address *src0, *dst0;
4679 struct secasvar *sav;
4680 uint32_t reqid, spi;
4682 uint8_t mode, proto;
4684 IPSEC_ASSERT(so != NULL, ("null socket"));
4685 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4686 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4687 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4689 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
4690 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST)
4691 #ifdef PFKEY_STRICT_CHECKS
4692 || SADB_CHECKHDR(mhp, SADB_EXT_SPIRANGE)
4695 ipseclog((LOG_DEBUG,
4696 "%s: invalid message: missing required header.\n",
4701 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
4702 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)
4703 #ifdef PFKEY_STRICT_CHECKS
4704 || SADB_CHECKLEN(mhp, SADB_EXT_SPIRANGE)
4707 ipseclog((LOG_DEBUG,
4708 "%s: invalid message: wrong header size.\n", __func__));
4712 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
4713 mode = IPSEC_MODE_ANY;
4716 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
4717 ipseclog((LOG_DEBUG,
4718 "%s: invalid message: wrong header size.\n",
4723 mode = ((struct sadb_x_sa2 *)
4724 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4725 reqid = ((struct sadb_x_sa2 *)
4726 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4729 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4730 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4732 /* map satype to proto */
4733 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4734 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4739 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
4740 (struct sockaddr *)(dst0 + 1));
4742 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
4746 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4748 /* SPI allocation */
4749 spi = key_do_getnewspi(
4750 (struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE], &saidx);
4753 * Requested SPI or SPI range is not available or
4759 sav = key_newsav(mhp, &saidx, spi, &error);
4763 if (sav->seq != 0) {
4766 * If the SADB_GETSPI message is in response to a
4767 * kernel-generated SADB_ACQUIRE, the sadb_msg_seq
4768 * MUST be the same as the SADB_ACQUIRE message.
4770 * XXXAE: However it doesn't definethe behaviour how to
4771 * check this and what to do if it doesn't match.
4772 * Also what we should do if it matches?
4774 * We can compare saidx used in SADB_ACQUIRE with saidx
4775 * used in SADB_GETSPI, but this probably can break
4776 * existing software. For now just warn if it doesn't match.
4778 * XXXAE: anyway it looks useless.
4780 key_acqdone(&saidx, sav->seq);
4783 printf("%s: SA(%p)\n", __func__, sav));
4784 KEYDBG(KEY_DATA, kdebug_secasv(sav));
4787 struct mbuf *n, *nn;
4788 struct sadb_sa *m_sa;
4789 struct sadb_msg *newmsg;
4792 /* create new sadb_msg to reply. */
4793 len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4794 PFKEY_ALIGN8(sizeof(struct sadb_sa));
4796 MGETHDR(n, M_NOWAIT, MT_DATA);
4798 if (!(MCLGET(n, M_NOWAIT))) {
4812 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4813 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4815 m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4816 m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4817 m_sa->sadb_sa_exttype = SADB_EXT_SA;
4818 m_sa->sadb_sa_spi = spi; /* SPI is already in network byte order */
4819 off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4821 IPSEC_ASSERT(off == len,
4822 ("length inconsistency (off %u len %u)", off, len));
4824 n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4825 SADB_EXT_ADDRESS_DST);
4832 if (n->m_len < sizeof(struct sadb_msg)) {
4833 n = m_pullup(n, sizeof(struct sadb_msg));
4835 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4838 n->m_pkthdr.len = 0;
4839 for (nn = n; nn; nn = nn->m_next)
4840 n->m_pkthdr.len += nn->m_len;
4842 newmsg = mtod(n, struct sadb_msg *);
4843 newmsg->sadb_msg_seq = sav->seq;
4844 newmsg->sadb_msg_errno = 0;
4845 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4848 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4852 return (key_senderror(so, m, error));
4856 * allocating new SPI
4857 * called by key_getspi().
4860 * others: success, SPI in network byte order.
4863 key_do_getnewspi(struct sadb_spirange *spirange, struct secasindex *saidx)
4865 uint32_t min, max, newspi, t;
4866 int count = V_key_spi_trycnt;
4868 /* set spi range to allocate */
4869 if (spirange != NULL) {
4870 min = spirange->sadb_spirange_min;
4871 max = spirange->sadb_spirange_max;
4873 min = V_key_spi_minval;
4874 max = V_key_spi_maxval;
4876 /* IPCOMP needs 2-byte SPI */
4877 if (saidx->proto == IPPROTO_IPCOMP) {
4883 t = min; min = max; max = t;
4888 if (!key_checkspidup(htonl(min))) {
4889 ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4894 count--; /* taking one cost. */
4901 /* when requesting to allocate spi ranged */
4903 /* generate pseudo-random SPI value ranged. */
4904 newspi = min + (key_random() % (max - min + 1));
4905 if (!key_checkspidup(htonl(newspi)))
4909 if (count == 0 || newspi == 0) {
4910 ipseclog((LOG_DEBUG,
4911 "%s: failed to allocate SPI.\n", __func__));
4917 keystat.getspi_count =
4918 (keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4920 return (htonl(newspi));
4924 * Find TCP-MD5 SA with corresponding secasindex.
4925 * If not found, return NULL and fill SPI with usable value if needed.
4927 static struct secasvar *
4928 key_getsav_tcpmd5(struct secasindex *saidx, uint32_t *spi)
4930 SAHTREE_RLOCK_TRACKER;
4931 struct secashead *sah;
4932 struct secasvar *sav;
4934 IPSEC_ASSERT(saidx->proto == IPPROTO_TCP, ("wrong proto"));
4936 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
4937 if (sah->saidx.proto != IPPROTO_TCP)
4939 if (!key_sockaddrcmp(&saidx->dst.sa, &sah->saidx.dst.sa, 0))
4943 if (V_key_preferred_oldsa)
4944 sav = TAILQ_LAST(&sah->savtree_alive, secasvar_queue);
4946 sav = TAILQ_FIRST(&sah->savtree_alive);
4954 /* No SPI required */
4958 /* Check that SPI is unique */
4959 LIST_FOREACH(sav, SAVHASH_HASH(*spi), spihash) {
4960 if (sav->spi == *spi)
4965 /* SPI is already unique */
4969 /* XXX: not optimal */
4970 *spi = key_do_getnewspi(NULL, saidx);
4975 key_updateaddresses(struct socket *so, struct mbuf *m,
4976 const struct sadb_msghdr *mhp, struct secasvar *sav,
4977 struct secasindex *saidx)
4979 struct sockaddr *newaddr;
4980 struct secashead *sah;
4981 struct secasvar *newsav, *tmp;
4985 /* Check that we need to change SAH */
4986 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC)) {
4987 newaddr = (struct sockaddr *)(
4988 ((struct sadb_address *)
4989 mhp->ext[SADB_X_EXT_NEW_ADDRESS_SRC]) + 1);
4990 bcopy(newaddr, &saidx->src, newaddr->sa_len);
4991 key_porttosaddr(&saidx->src.sa, 0);
4993 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST)) {
4994 newaddr = (struct sockaddr *)(
4995 ((struct sadb_address *)
4996 mhp->ext[SADB_X_EXT_NEW_ADDRESS_DST]) + 1);
4997 bcopy(newaddr, &saidx->dst, newaddr->sa_len);
4998 key_porttosaddr(&saidx->dst.sa, 0);
5000 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC) ||
5001 !SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST)) {
5002 error = key_checksockaddrs(&saidx->src.sa, &saidx->dst.sa);
5004 ipseclog((LOG_DEBUG, "%s: invalid new sockaddr.\n",
5009 sah = key_getsah(saidx);
5011 /* create a new SA index */
5012 sah = key_newsah(saidx);
5014 ipseclog((LOG_DEBUG,
5015 "%s: No more memory.\n", __func__));
5018 isnew = 2; /* SAH is new */
5020 isnew = 1; /* existing SAH is referenced */
5023 * src and dst addresses are still the same.
5024 * Do we want to change NAT-T config?
5026 if (sav->sah->saidx.proto != IPPROTO_ESP ||
5027 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5028 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_SPORT) ||
5029 SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5030 ipseclog((LOG_DEBUG,
5031 "%s: invalid message: missing required header.\n",
5035 /* We hold reference to SA, thus SAH will be referenced too. */
5040 newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA,
5042 if (newsav == NULL) {
5043 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5048 /* Clone SA's content into newsav */
5049 SAV_INITREF(newsav);
5050 bcopy(sav, newsav, offsetof(struct secasvar, chain));
5052 * We create new NAT-T config if it is needed.
5053 * Old NAT-T config will be freed by key_cleansav() when
5054 * last reference to SA will be released.
5056 newsav->natt = NULL;
5058 newsav->state = SADB_SASTATE_MATURE;
5059 error = key_setnatt(sav, mhp);
5064 /* Check that SA is still alive */
5065 if (sav->state == SADB_SASTATE_DEAD) {
5066 /* SA was unlinked */
5072 /* Unlink SA from SAH and SPI hash */
5073 IPSEC_ASSERT((sav->flags & SADB_X_EXT_F_CLONED) == 0,
5074 ("SA is already cloned"));
5075 IPSEC_ASSERT(sav->state == SADB_SASTATE_MATURE ||
5076 sav->state == SADB_SASTATE_DYING,
5077 ("Wrong SA state %u\n", sav->state));
5078 TAILQ_REMOVE(&sav->sah->savtree_alive, sav, chain);
5079 LIST_REMOVE(sav, spihash);
5080 sav->state = SADB_SASTATE_DEAD;
5083 * Link new SA with SAH. Keep SAs ordered by
5084 * create time (newer are first).
5086 TAILQ_FOREACH(tmp, &sah->savtree_alive, chain) {
5087 if (newsav->created > tmp->created) {
5088 TAILQ_INSERT_BEFORE(tmp, newsav, chain);
5093 TAILQ_INSERT_TAIL(&sah->savtree_alive, newsav, chain);
5095 /* Add new SA into SPI hash. */
5096 LIST_INSERT_HEAD(SAVHASH_HASH(newsav->spi), newsav, spihash);
5098 /* Add new SAH into SADB. */
5100 TAILQ_INSERT_HEAD(&V_sahtree, sah, chain);
5101 LIST_INSERT_HEAD(SAHADDRHASH_HASH(saidx), sah, addrhash);
5102 sah->state = SADB_SASTATE_MATURE;
5103 SAH_ADDREF(sah); /* newsav references new SAH */
5106 * isnew == 1 -> @sah was referenced by key_getsah().
5107 * isnew == 0 -> we use the same @sah, that was used by @sav,
5108 * and we use its reference for @newsav.
5111 /* XXX: replace cntr with pointer? */
5112 newsav->cntr = sav->cntr;
5113 sav->flags |= SADB_X_EXT_F_CLONED;
5114 SECASVAR_UNLOCK(sav);
5119 printf("%s: SA(%p) cloned into SA(%p)\n",
5120 __func__, sav, newsav));
5121 KEYDBG(KEY_DATA, kdebug_secasv(newsav));
5123 key_freesav(&sav); /* release last reference */
5125 /* set msg buf from mhp */
5126 n = key_getmsgbuf_x1(m, mhp);
5128 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5132 key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5137 if (newsav != NULL) {
5138 if (newsav->natt != NULL)
5139 free(newsav->natt, M_IPSEC_MISC);
5140 free(newsav, M_IPSEC_SA);
5146 * SADB_UPDATE processing
5148 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5149 * key(AE), (identity(SD),) (sensitivity)>
5150 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
5152 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5153 * (identity(SD),) (sensitivity)>
5156 * m will always be freed.
5159 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5161 struct secasindex saidx;
5162 struct sadb_address *src0, *dst0;
5163 struct sadb_sa *sa0;
5164 struct secasvar *sav;
5167 uint8_t mode, proto;
5169 IPSEC_ASSERT(so != NULL, ("null socket"));
5170 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5171 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5172 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5174 /* map satype to proto */
5175 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5176 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5178 return key_senderror(so, m, EINVAL);
5181 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
5182 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5183 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5184 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
5185 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
5186 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
5187 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
5188 ipseclog((LOG_DEBUG,
5189 "%s: invalid message: missing required header.\n",
5191 return key_senderror(so, m, EINVAL);
5193 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
5194 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5195 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5196 ipseclog((LOG_DEBUG,
5197 "%s: invalid message: wrong header size.\n", __func__));
5198 return key_senderror(so, m, EINVAL);
5200 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
5201 mode = IPSEC_MODE_ANY;
5204 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
5205 ipseclog((LOG_DEBUG,
5206 "%s: invalid message: wrong header size.\n",
5208 return key_senderror(so, m, EINVAL);
5210 mode = ((struct sadb_x_sa2 *)
5211 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5212 reqid = ((struct sadb_x_sa2 *)
5213 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5216 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5217 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5218 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5221 * Only SADB_SASTATE_MATURE SAs may be submitted in an
5222 * SADB_UPDATE message.
5224 if (sa0->sadb_sa_state != SADB_SASTATE_MATURE) {
5225 ipseclog((LOG_DEBUG, "%s: invalid state.\n", __func__));
5226 #ifdef PFKEY_STRICT_CHECKS
5227 return key_senderror(so, m, EINVAL);
5230 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
5231 (struct sockaddr *)(dst0 + 1));
5233 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5234 return key_senderror(so, m, error);
5236 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5237 sav = key_getsavbyspi(sa0->sadb_sa_spi);
5239 ipseclog((LOG_DEBUG, "%s: no SA found for SPI %u\n",
5240 __func__, ntohl(sa0->sadb_sa_spi)));
5241 return key_senderror(so, m, EINVAL);
5244 * Check that SADB_UPDATE issued by the same process that did
5245 * SADB_GETSPI or SADB_ADD.
5247 if (sav->pid != mhp->msg->sadb_msg_pid) {
5248 ipseclog((LOG_DEBUG,
5249 "%s: pid mismatched (SPI %u, pid %u vs. %u)\n", __func__,
5250 ntohl(sav->spi), sav->pid, mhp->msg->sadb_msg_pid));
5252 return key_senderror(so, m, EINVAL);
5254 /* saidx should match with SA. */
5255 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_MODE_REQID) == 0) {
5256 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u",
5257 __func__, ntohl(sav->spi)));
5259 return key_senderror(so, m, ESRCH);
5262 if (sav->state == SADB_SASTATE_LARVAL) {
5263 if ((mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5264 SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT)) ||
5265 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5266 SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH))) {
5267 ipseclog((LOG_DEBUG,
5268 "%s: invalid message: missing required header.\n",
5271 return key_senderror(so, m, EINVAL);
5274 * We can set any values except src, dst and SPI.
5276 error = key_setsaval(sav, mhp);
5279 return (key_senderror(so, m, error));
5281 /* Change SA state to MATURE */
5283 if (sav->state != SADB_SASTATE_LARVAL) {
5284 /* SA was deleted or another thread made it MATURE. */
5287 return (key_senderror(so, m, ESRCH));
5290 * NOTE: we keep SAs in savtree_alive ordered by created
5291 * time. When SA's state changed from LARVAL to MATURE,
5292 * we update its created time in key_setsaval() and move
5293 * it into head of savtree_alive.
5295 TAILQ_REMOVE(&sav->sah->savtree_larval, sav, chain);
5296 TAILQ_INSERT_HEAD(&sav->sah->savtree_alive, sav, chain);
5297 sav->state = SADB_SASTATE_MATURE;
5301 * For DYING and MATURE SA we can change only state
5302 * and lifetimes. Report EINVAL if something else attempted
5305 if (!SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT) ||
5306 !SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH)) {
5308 return (key_senderror(so, m, EINVAL));
5310 error = key_updatelifetimes(sav, mhp);
5313 return (key_senderror(so, m, error));
5316 * This is FreeBSD extension to RFC2367.
5317 * IKEd can specify SADB_X_EXT_NEW_ADDRESS_SRC and/or
5318 * SADB_X_EXT_NEW_ADDRESS_DST when it wants to change
5319 * SA addresses (for example to implement MOBIKE protocol
5320 * as described in RFC4555). Also we allow to change
5323 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_SRC) ||
5324 !SADB_CHECKHDR(mhp, SADB_X_EXT_NEW_ADDRESS_DST) ||
5325 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5326 sav->natt != NULL) {
5327 error = key_updateaddresses(so, m, mhp, sav, &saidx);
5330 return (key_senderror(so, m, error));
5333 /* Check that SA is still alive */
5335 if (sav->state == SADB_SASTATE_DEAD) {
5336 /* SA was unlinked */
5339 return (key_senderror(so, m, ESRCH));
5342 * NOTE: there is possible state moving from DYING to MATURE,
5343 * but this doesn't change created time, so we won't reorder
5346 sav->state = SADB_SASTATE_MATURE;
5350 printf("%s: SA(%p)\n", __func__, sav));
5351 KEYDBG(KEY_DATA, kdebug_secasv(sav));
5357 /* set msg buf from mhp */
5358 n = key_getmsgbuf_x1(m, mhp);
5360 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5361 return key_senderror(so, m, ENOBUFS);
5365 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5370 * SADB_ADD processing
5371 * add an entry to SA database, when received
5372 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5373 * key(AE), (identity(SD),) (sensitivity)>
5376 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5377 * (identity(SD),) (sensitivity)>
5380 * IGNORE identity and sensitivity messages.
5382 * m will always be freed.
5385 key_add(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5387 struct secasindex saidx;
5388 struct sadb_address *src0, *dst0;
5389 struct sadb_sa *sa0;
5390 struct secasvar *sav;
5391 uint32_t reqid, spi;
5392 uint8_t mode, proto;
5395 IPSEC_ASSERT(so != NULL, ("null socket"));
5396 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5397 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5398 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5400 /* map satype to proto */
5401 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5402 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5404 return key_senderror(so, m, EINVAL);
5407 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
5408 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5409 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5410 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP && (
5411 SADB_CHECKHDR(mhp, SADB_EXT_KEY_ENCRYPT) ||
5412 SADB_CHECKLEN(mhp, SADB_EXT_KEY_ENCRYPT))) ||
5413 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH && (
5414 SADB_CHECKHDR(mhp, SADB_EXT_KEY_AUTH) ||
5415 SADB_CHECKLEN(mhp, SADB_EXT_KEY_AUTH))) ||
5416 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD) &&
5417 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT)) ||
5418 (SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_SOFT) &&
5419 !SADB_CHECKHDR(mhp, SADB_EXT_LIFETIME_HARD))) {
5420 ipseclog((LOG_DEBUG,
5421 "%s: invalid message: missing required header.\n",
5423 return key_senderror(so, m, EINVAL);
5425 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
5426 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5427 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5428 ipseclog((LOG_DEBUG,
5429 "%s: invalid message: wrong header size.\n", __func__));
5430 return key_senderror(so, m, EINVAL);
5432 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
5433 mode = IPSEC_MODE_ANY;
5436 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
5437 ipseclog((LOG_DEBUG,
5438 "%s: invalid message: wrong header size.\n",
5440 return key_senderror(so, m, EINVAL);
5442 mode = ((struct sadb_x_sa2 *)
5443 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5444 reqid = ((struct sadb_x_sa2 *)
5445 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5448 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5449 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5450 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5453 * Only SADB_SASTATE_MATURE SAs may be submitted in an
5456 if (sa0->sadb_sa_state != SADB_SASTATE_MATURE) {
5457 ipseclog((LOG_DEBUG, "%s: invalid state.\n", __func__));
5458 #ifdef PFKEY_STRICT_CHECKS
5459 return key_senderror(so, m, EINVAL);
5462 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
5463 (struct sockaddr *)(dst0 + 1));
5465 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5466 return key_senderror(so, m, error);
5468 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5469 spi = sa0->sadb_sa_spi;
5471 * For TCP-MD5 SAs we don't use SPI. Check the uniqueness using
5473 * XXXAE: IPComp seems also doesn't use SPI.
5475 if (proto == IPPROTO_TCP) {
5476 sav = key_getsav_tcpmd5(&saidx, &spi);
5477 if (sav == NULL && spi == 0) {
5478 /* Failed to allocate SPI */
5479 ipseclog((LOG_DEBUG, "%s: SA already exists.\n",
5481 return key_senderror(so, m, EEXIST);
5483 /* XXX: SPI that we report back can have another value */
5485 /* We can create new SA only if SPI is different. */
5486 sav = key_getsavbyspi(spi);
5490 ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5491 return key_senderror(so, m, EEXIST);
5494 sav = key_newsav(mhp, &saidx, spi, &error);
5496 return key_senderror(so, m, error);
5498 printf("%s: return SA(%p)\n", __func__, sav));
5499 KEYDBG(KEY_DATA, kdebug_secasv(sav));
5501 * If SADB_ADD was in response to SADB_ACQUIRE, we need to schedule
5505 key_acqdone(&saidx, sav->seq);
5509 * Don't call key_freesav() on error here, as we would like to
5510 * keep the SA in the database.
5514 /* set msg buf from mhp */
5515 n = key_getmsgbuf_x1(m, mhp);
5517 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5518 return key_senderror(so, m, ENOBUFS);
5522 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5528 * IKEd may request the use ESP in UDP encapsulation when it detects the
5529 * presence of NAT. It uses NAT-T extension headers for such SAs to specify
5530 * parameters needed for encapsulation and decapsulation. These PF_KEY
5531 * extension headers are not standardized, so this comment addresses our
5533 * SADB_X_EXT_NAT_T_TYPE specifies type of encapsulation, we support only
5534 * UDP_ENCAP_ESPINUDP as described in RFC3948.
5535 * SADB_X_EXT_NAT_T_SPORT/DPORT specifies source and destination ports for
5536 * UDP header. We use these ports in UDP encapsulation procedure, also we
5537 * can check them in UDP decapsulation procedure.
5538 * SADB_X_EXT_NAT_T_OA[IR] specifies original address of initiator or
5539 * responder. These addresses can be used for transport mode to adjust
5540 * checksum after decapsulation and decryption. Since original IP addresses
5541 * used by peer usually different (we detected presence of NAT), TCP/UDP
5542 * pseudo header checksum and IP header checksum was calculated using original
5543 * addresses. After decapsulation and decryption we need to adjust checksum
5544 * to have correct datagram.
5546 * We expect presence of NAT-T extension headers only in SADB_ADD and
5547 * SADB_UPDATE messages. We report NAT-T extension headers in replies
5548 * to SADB_ADD, SADB_UPDATE, SADB_GET, and SADB_DUMP messages.
5551 key_setnatt(struct secasvar *sav, const struct sadb_msghdr *mhp)
5553 struct sadb_x_nat_t_port *port;
5554 struct sadb_x_nat_t_type *type;
5555 struct sadb_address *oai, *oar;
5556 struct sockaddr *sa;
5560 IPSEC_ASSERT(sav->natt == NULL, ("natt is already initialized"));
5562 * Ignore NAT-T headers if sproto isn't ESP.
5564 if (sav->sah->saidx.proto != IPPROTO_ESP)
5567 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_TYPE) &&
5568 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_SPORT) &&
5569 !SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5570 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_TYPE) ||
5571 SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_SPORT) ||
5572 SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_DPORT)) {
5573 ipseclog((LOG_DEBUG,
5574 "%s: invalid message: wrong header size.\n",
5581 type = (struct sadb_x_nat_t_type *)mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5582 if (type->sadb_x_nat_t_type_type != UDP_ENCAP_ESPINUDP) {
5583 ipseclog((LOG_DEBUG, "%s: unsupported NAT-T type %u.\n",
5584 __func__, type->sadb_x_nat_t_type_type));
5588 * Allocate storage for NAT-T config.
5589 * On error it will be released by key_cleansav().
5591 sav->natt = malloc(sizeof(struct secnatt), M_IPSEC_MISC,
5593 if (sav->natt == NULL) {
5594 PFKEYSTAT_INC(in_nomem);
5595 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5598 port = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5599 if (port->sadb_x_nat_t_port_port == 0) {
5600 ipseclog((LOG_DEBUG, "%s: invalid NAT-T sport specified.\n",
5604 sav->natt->sport = port->sadb_x_nat_t_port_port;
5605 port = (struct sadb_x_nat_t_port *)mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5606 if (port->sadb_x_nat_t_port_port == 0) {
5607 ipseclog((LOG_DEBUG, "%s: invalid NAT-T dport specified.\n",
5611 sav->natt->dport = port->sadb_x_nat_t_port_port;
5614 * SADB_X_EXT_NAT_T_OAI and SADB_X_EXT_NAT_T_OAR are optional
5615 * and needed only for transport mode IPsec.
5616 * Usually NAT translates only one address, but it is possible,
5617 * that both addresses could be translated.
5618 * NOTE: Value of SADB_X_EXT_NAT_T_OAI is equal to SADB_X_EXT_NAT_T_OA.
5620 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_OAI)) {
5621 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_OAI)) {
5622 ipseclog((LOG_DEBUG,
5623 "%s: invalid message: wrong header size.\n",
5627 oai = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5630 if (!SADB_CHECKHDR(mhp, SADB_X_EXT_NAT_T_OAR)) {
5631 if (SADB_CHECKLEN(mhp, SADB_X_EXT_NAT_T_OAR)) {
5632 ipseclog((LOG_DEBUG,
5633 "%s: invalid message: wrong header size.\n",
5637 oar = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5641 /* Initialize addresses only for transport mode */
5642 if (sav->sah->saidx.mode != IPSEC_MODE_TUNNEL) {
5645 /* Currently we support only AF_INET */
5646 sa = (struct sockaddr *)(oai + 1);
5647 if (sa->sa_family != AF_INET ||
5648 sa->sa_len != sizeof(struct sockaddr_in)) {
5649 ipseclog((LOG_DEBUG,
5650 "%s: wrong NAT-OAi header.\n",
5654 /* Ignore address if it the same */
5655 if (((struct sockaddr_in *)sa)->sin_addr.s_addr !=
5656 sav->sah->saidx.src.sin.sin_addr.s_addr) {
5657 bcopy(sa, &sav->natt->oai.sa, sa->sa_len);
5658 sav->natt->flags |= IPSEC_NATT_F_OAI;
5659 /* Calculate checksum delta */
5660 addr = sav->sah->saidx.src.sin.sin_addr.s_addr;
5661 cksum = in_addword(cksum, ~addr >> 16);
5662 cksum = in_addword(cksum, ~addr & 0xffff);
5663 addr = sav->natt->oai.sin.sin_addr.s_addr;
5664 cksum = in_addword(cksum, addr >> 16);
5665 cksum = in_addword(cksum, addr & 0xffff);
5669 /* Currently we support only AF_INET */
5670 sa = (struct sockaddr *)(oar + 1);
5671 if (sa->sa_family != AF_INET ||
5672 sa->sa_len != sizeof(struct sockaddr_in)) {
5673 ipseclog((LOG_DEBUG,
5674 "%s: wrong NAT-OAr header.\n",
5678 /* Ignore address if it the same */
5679 if (((struct sockaddr_in *)sa)->sin_addr.s_addr !=
5680 sav->sah->saidx.dst.sin.sin_addr.s_addr) {
5681 bcopy(sa, &sav->natt->oar.sa, sa->sa_len);
5682 sav->natt->flags |= IPSEC_NATT_F_OAR;
5683 /* Calculate checksum delta */
5684 addr = sav->sah->saidx.dst.sin.sin_addr.s_addr;
5685 cksum = in_addword(cksum, ~addr >> 16);
5686 cksum = in_addword(cksum, ~addr & 0xffff);
5687 addr = sav->natt->oar.sin.sin_addr.s_addr;
5688 cksum = in_addword(cksum, addr >> 16);
5689 cksum = in_addword(cksum, addr & 0xffff);
5692 sav->natt->cksum = cksum;
5698 key_setident(struct secashead *sah, const struct sadb_msghdr *mhp)
5700 const struct sadb_ident *idsrc, *iddst;
5701 int idsrclen, iddstlen;
5703 IPSEC_ASSERT(sah != NULL, ("null secashead"));
5704 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5705 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5707 /* don't make buffer if not there */
5708 if (SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_SRC) &&
5709 SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_DST)) {
5715 if (SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_SRC) ||
5716 SADB_CHECKHDR(mhp, SADB_EXT_IDENTITY_DST)) {
5717 ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5721 idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5722 iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5723 idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5724 iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5726 /* validity check */
5727 if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5728 ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5732 switch (idsrc->sadb_ident_type) {
5733 case SADB_IDENTTYPE_PREFIX:
5734 case SADB_IDENTTYPE_FQDN:
5735 case SADB_IDENTTYPE_USERFQDN:
5737 /* XXX do nothing */
5743 /* make structure */
5744 sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5745 if (sah->idents == NULL) {
5746 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5749 sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5750 if (sah->identd == NULL) {
5751 free(sah->idents, M_IPSEC_MISC);
5753 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5756 sah->idents->type = idsrc->sadb_ident_type;
5757 sah->idents->id = idsrc->sadb_ident_id;
5759 sah->identd->type = iddst->sadb_ident_type;
5760 sah->identd->id = iddst->sadb_ident_id;
5766 * m will not be freed on return.
5767 * it is caller's responsibility to free the result.
5769 * Called from SADB_ADD and SADB_UPDATE. Reply will contain headers
5770 * from the request in defined order.
5772 static struct mbuf *
5773 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
5777 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5778 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5779 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5781 /* create new sadb_msg to reply. */
5782 n = key_gather_mbuf(m, mhp, 1, 16, SADB_EXT_RESERVED,
5783 SADB_EXT_SA, SADB_X_EXT_SA2,
5784 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5785 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5786 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST,
5787 SADB_X_EXT_NAT_T_TYPE, SADB_X_EXT_NAT_T_SPORT,
5788 SADB_X_EXT_NAT_T_DPORT, SADB_X_EXT_NAT_T_OAI,
5789 SADB_X_EXT_NAT_T_OAR, SADB_X_EXT_NEW_ADDRESS_SRC,
5790 SADB_X_EXT_NEW_ADDRESS_DST);
5794 if (n->m_len < sizeof(struct sadb_msg)) {
5795 n = m_pullup(n, sizeof(struct sadb_msg));
5799 mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5800 mtod(n, struct sadb_msg *)->sadb_msg_len =
5801 PFKEY_UNIT64(n->m_pkthdr.len);
5807 * SADB_DELETE processing
5809 * <base, SA(*), address(SD)>
5810 * from the ikmpd, and set SADB_SASTATE_DEAD,
5812 * <base, SA(*), address(SD)>
5815 * m will always be freed.
5818 key_delete(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5820 struct secasindex saidx;
5821 struct sadb_address *src0, *dst0;
5822 struct secasvar *sav;
5823 struct sadb_sa *sa0;
5826 IPSEC_ASSERT(so != NULL, ("null socket"));
5827 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5828 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5829 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5831 /* map satype to proto */
5832 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5833 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5835 return key_senderror(so, m, EINVAL);
5838 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
5839 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
5840 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
5841 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
5842 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5844 return key_senderror(so, m, EINVAL);
5847 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5848 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5850 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
5851 (struct sockaddr *)(dst0 + 1)) != 0) {
5852 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
5853 return (key_senderror(so, m, EINVAL));
5855 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5856 if (SADB_CHECKHDR(mhp, SADB_EXT_SA)) {
5858 * Caller wants us to delete all non-LARVAL SAs
5859 * that match the src/dst. This is used during
5860 * IKE INITIAL-CONTACT.
5861 * XXXAE: this looks like some extension to RFC2367.
5863 ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5864 return (key_delete_all(so, m, mhp, &saidx));
5866 if (SADB_CHECKLEN(mhp, SADB_EXT_SA)) {
5867 ipseclog((LOG_DEBUG,
5868 "%s: invalid message: wrong header size.\n", __func__));
5869 return (key_senderror(so, m, EINVAL));
5871 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5872 if (proto == IPPROTO_TCP)
5873 sav = key_getsav_tcpmd5(&saidx, NULL);
5875 sav = key_getsavbyspi(sa0->sadb_sa_spi);
5877 ipseclog((LOG_DEBUG, "%s: no SA found for SPI %u.\n",
5878 __func__, ntohl(sa0->sadb_sa_spi)));
5879 return (key_senderror(so, m, ESRCH));
5881 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_HEAD) == 0) {
5882 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u.\n",
5883 __func__, ntohl(sav->spi)));
5885 return (key_senderror(so, m, ESRCH));
5888 printf("%s: SA(%p)\n", __func__, sav));
5889 KEYDBG(KEY_DATA, kdebug_secasv(sav));
5895 struct sadb_msg *newmsg;
5897 /* create new sadb_msg to reply. */
5898 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5899 SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5901 return key_senderror(so, m, ENOBUFS);
5903 if (n->m_len < sizeof(struct sadb_msg)) {
5904 n = m_pullup(n, sizeof(struct sadb_msg));
5906 return key_senderror(so, m, ENOBUFS);
5908 newmsg = mtod(n, struct sadb_msg *);
5909 newmsg->sadb_msg_errno = 0;
5910 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5913 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5918 * delete all SAs for src/dst. Called from key_delete().
5921 key_delete_all(struct socket *so, struct mbuf *m,
5922 const struct sadb_msghdr *mhp, struct secasindex *saidx)
5924 struct secasvar_queue drainq;
5925 struct secashead *sah;
5926 struct secasvar *sav, *nextsav;
5928 TAILQ_INIT(&drainq);
5930 LIST_FOREACH(sah, SAHADDRHASH_HASH(saidx), addrhash) {
5931 if (key_cmpsaidx(&sah->saidx, saidx, CMP_HEAD) == 0)
5933 /* Move all ALIVE SAs into drainq */
5934 TAILQ_CONCAT(&drainq, &sah->savtree_alive, chain);
5936 /* Unlink all queued SAs from SPI hash */
5937 TAILQ_FOREACH(sav, &drainq, chain) {
5938 sav->state = SADB_SASTATE_DEAD;
5939 LIST_REMOVE(sav, spihash);
5942 /* Now we can release reference for all SAs in drainq */
5943 sav = TAILQ_FIRST(&drainq);
5944 while (sav != NULL) {
5946 printf("%s: SA(%p)\n", __func__, sav));
5947 KEYDBG(KEY_DATA, kdebug_secasv(sav));
5948 nextsav = TAILQ_NEXT(sav, chain);
5949 key_freesah(&sav->sah); /* release reference from SAV */
5950 key_freesav(&sav); /* release last reference */
5956 struct sadb_msg *newmsg;
5958 /* create new sadb_msg to reply. */
5959 n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5960 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5962 return key_senderror(so, m, ENOBUFS);
5964 if (n->m_len < sizeof(struct sadb_msg)) {
5965 n = m_pullup(n, sizeof(struct sadb_msg));
5967 return key_senderror(so, m, ENOBUFS);
5969 newmsg = mtod(n, struct sadb_msg *);
5970 newmsg->sadb_msg_errno = 0;
5971 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5974 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5979 * Delete all alive SAs for corresponding xform.
5980 * Larval SAs have not initialized tdb_xform, so it is safe to leave them
5981 * here when xform disappears.
5984 key_delete_xform(const struct xformsw *xsp)
5986 struct secasvar_queue drainq;
5987 struct secashead *sah;
5988 struct secasvar *sav, *nextsav;
5990 TAILQ_INIT(&drainq);
5992 TAILQ_FOREACH(sah, &V_sahtree, chain) {
5993 sav = TAILQ_FIRST(&sah->savtree_alive);
5996 if (sav->tdb_xform != xsp)
5999 * It is supposed that all SAs in the chain are related to
6002 TAILQ_CONCAT(&drainq, &sah->savtree_alive, chain);
6004 /* Unlink all queued SAs from SPI hash */
6005 TAILQ_FOREACH(sav, &drainq, chain) {
6006 sav->state = SADB_SASTATE_DEAD;
6007 LIST_REMOVE(sav, spihash);
6011 /* Now we can release reference for all SAs in drainq */
6012 sav = TAILQ_FIRST(&drainq);
6013 while (sav != NULL) {
6015 printf("%s: SA(%p)\n", __func__, sav));
6016 KEYDBG(KEY_DATA, kdebug_secasv(sav));
6017 nextsav = TAILQ_NEXT(sav, chain);
6018 key_freesah(&sav->sah); /* release reference from SAV */
6019 key_freesav(&sav); /* release last reference */
6025 * SADB_GET processing
6027 * <base, SA(*), address(SD)>
6028 * from the ikmpd, and get a SP and a SA to respond,
6030 * <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
6031 * (identity(SD),) (sensitivity)>
6034 * m will always be freed.
6037 key_get(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6039 struct secasindex saidx;
6040 struct sadb_address *src0, *dst0;
6041 struct sadb_sa *sa0;
6042 struct secasvar *sav;
6045 IPSEC_ASSERT(so != NULL, ("null socket"));
6046 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6047 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6048 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6050 /* map satype to proto */
6051 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6052 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6054 return key_senderror(so, m, EINVAL);
6057 if (SADB_CHECKHDR(mhp, SADB_EXT_SA) ||
6058 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
6059 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST)) {
6060 ipseclog((LOG_DEBUG,
6061 "%s: invalid message: missing required header.\n",
6063 return key_senderror(so, m, EINVAL);
6065 if (SADB_CHECKLEN(mhp, SADB_EXT_SA) ||
6066 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
6067 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST)) {
6068 ipseclog((LOG_DEBUG,
6069 "%s: invalid message: wrong header size.\n", __func__));
6070 return key_senderror(so, m, EINVAL);
6073 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
6074 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6075 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6077 if (key_checksockaddrs((struct sockaddr *)(src0 + 1),
6078 (struct sockaddr *)(dst0 + 1)) != 0) {
6079 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
6080 return key_senderror(so, m, EINVAL);
6082 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6084 if (proto == IPPROTO_TCP)
6085 sav = key_getsav_tcpmd5(&saidx, NULL);
6087 sav = key_getsavbyspi(sa0->sadb_sa_spi);
6089 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
6090 return key_senderror(so, m, ESRCH);
6092 if (key_cmpsaidx(&sav->sah->saidx, &saidx, CMP_HEAD) == 0) {
6093 ipseclog((LOG_DEBUG, "%s: saidx mismatched for SPI %u.\n",
6094 __func__, ntohl(sa0->sadb_sa_spi)));
6096 return (key_senderror(so, m, ESRCH));
6103 /* map proto to satype */
6104 if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0) {
6105 ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
6108 return key_senderror(so, m, EINVAL);
6111 /* create new sadb_msg to reply. */
6112 n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
6113 mhp->msg->sadb_msg_pid);
6117 return key_senderror(so, m, ENOBUFS);
6120 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6124 /* XXX make it sysctl-configurable? */
6126 key_getcomb_setlifetime(struct sadb_comb *comb)
6129 comb->sadb_comb_soft_allocations = 1;
6130 comb->sadb_comb_hard_allocations = 1;
6131 comb->sadb_comb_soft_bytes = 0;
6132 comb->sadb_comb_hard_bytes = 0;
6133 comb->sadb_comb_hard_addtime = 86400; /* 1 day */
6134 comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
6135 comb->sadb_comb_soft_usetime = 28800; /* 8 hours */
6136 comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
6140 * XXX reorder combinations by preference
6141 * XXX no idea if the user wants ESP authentication or not
6143 static struct mbuf *
6144 key_getcomb_ealg(void)
6146 struct sadb_comb *comb;
6147 const struct enc_xform *algo;
6148 struct mbuf *result = NULL, *m, *n;
6152 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6155 for (i = 1; i <= SADB_EALG_MAX; i++) {
6156 algo = enc_algorithm_lookup(i);
6160 /* discard algorithms with key size smaller than system min */
6161 if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
6163 if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
6164 encmin = V_ipsec_esp_keymin;
6166 encmin = _BITS(algo->minkey);
6168 if (V_ipsec_esp_auth)
6169 m = key_getcomb_ah();
6171 IPSEC_ASSERT(l <= MLEN,
6172 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6173 MGET(m, M_NOWAIT, MT_DATA);
6178 bzero(mtod(m, caddr_t), m->m_len);
6185 for (n = m; n; n = n->m_next)
6187 IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
6189 for (off = 0; off < totlen; off += l) {
6190 n = m_pulldown(m, off, l, &o);
6192 /* m is already freed */
6195 comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
6196 bzero(comb, sizeof(*comb));
6197 key_getcomb_setlifetime(comb);
6198 comb->sadb_comb_encrypt = i;
6199 comb->sadb_comb_encrypt_minbits = encmin;
6200 comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
6218 key_getsizes_ah(const struct auth_hash *ah, int alg, u_int16_t* min,
6222 *min = *max = ah->keysize;
6223 if (ah->keysize == 0) {
6225 * Transform takes arbitrary key size but algorithm
6226 * key size is restricted. Enforce this here.
6229 case SADB_X_AALG_MD5: *min = *max = 16; break;
6230 case SADB_X_AALG_SHA: *min = *max = 20; break;
6231 case SADB_X_AALG_NULL: *min = 1; *max = 256; break;
6232 case SADB_X_AALG_SHA2_256: *min = *max = 32; break;
6233 case SADB_X_AALG_SHA2_384: *min = *max = 48; break;
6234 case SADB_X_AALG_SHA2_512: *min = *max = 64; break;
6236 DPRINTF(("%s: unknown AH algorithm %u\n",
6244 * XXX reorder combinations by preference
6246 static struct mbuf *
6249 const struct auth_hash *algo;
6250 struct sadb_comb *comb;
6252 u_int16_t minkeysize, maxkeysize;
6254 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6257 for (i = 1; i <= SADB_AALG_MAX; i++) {
6259 /* we prefer HMAC algorithms, not old algorithms */
6260 if (i != SADB_AALG_SHA1HMAC &&
6261 i != SADB_AALG_MD5HMAC &&
6262 i != SADB_X_AALG_SHA2_256 &&
6263 i != SADB_X_AALG_SHA2_384 &&
6264 i != SADB_X_AALG_SHA2_512)
6267 algo = auth_algorithm_lookup(i);
6270 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
6271 /* discard algorithms with key size smaller than system min */
6272 if (_BITS(minkeysize) < V_ipsec_ah_keymin)
6276 IPSEC_ASSERT(l <= MLEN,
6277 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6278 MGET(m, M_NOWAIT, MT_DATA);
6285 M_PREPEND(m, l, M_NOWAIT);
6289 comb = mtod(m, struct sadb_comb *);
6290 bzero(comb, sizeof(*comb));
6291 key_getcomb_setlifetime(comb);
6292 comb->sadb_comb_auth = i;
6293 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6294 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6301 * not really an official behavior. discussed in pf_key@inner.net in Sep2000.
6302 * XXX reorder combinations by preference
6304 static struct mbuf *
6305 key_getcomb_ipcomp()
6307 const struct comp_algo *algo;
6308 struct sadb_comb *comb;
6311 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6314 for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6315 algo = comp_algorithm_lookup(i);
6320 IPSEC_ASSERT(l <= MLEN,
6321 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6322 MGET(m, M_NOWAIT, MT_DATA);
6329 M_PREPEND(m, l, M_NOWAIT);
6333 comb = mtod(m, struct sadb_comb *);
6334 bzero(comb, sizeof(*comb));
6335 key_getcomb_setlifetime(comb);
6336 comb->sadb_comb_encrypt = i;
6337 /* what should we set into sadb_comb_*_{min,max}bits? */
6344 * XXX no way to pass mode (transport/tunnel) to userland
6345 * XXX replay checking?
6346 * XXX sysctl interface to ipsec_{ah,esp}_keymin
6348 static struct mbuf *
6349 key_getprop(const struct secasindex *saidx)
6351 struct sadb_prop *prop;
6353 const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6356 switch (saidx->proto) {
6358 m = key_getcomb_ealg();
6361 m = key_getcomb_ah();
6363 case IPPROTO_IPCOMP:
6364 m = key_getcomb_ipcomp();
6372 M_PREPEND(m, l, M_NOWAIT);
6377 for (n = m; n; n = n->m_next)
6380 prop = mtod(m, struct sadb_prop *);
6381 bzero(prop, sizeof(*prop));
6382 prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6383 prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6384 prop->sadb_prop_replay = 32; /* XXX */
6390 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6392 * <base, SA, address(SD), (address(P)), x_policy,
6393 * (identity(SD),) (sensitivity,) proposal>
6394 * to KMD, and expect to receive
6395 * <base> with SADB_ACQUIRE if error occurred,
6397 * <base, src address, dst address, (SPI range)> with SADB_GETSPI
6398 * from KMD by PF_KEY.
6400 * XXX x_policy is outside of RFC2367 (KAME extension).
6401 * XXX sensitivity is not supported.
6402 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6403 * see comment for key_getcomb_ipcomp().
6407 * others: error number
6410 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6412 union sockaddr_union addr;
6413 struct mbuf *result, *m;
6417 uint8_t mask, satype;
6419 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6420 satype = key_proto2satype(saidx->proto);
6421 IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6425 ul_proto = IPSEC_ULPROTO_ANY;
6427 /* Get seq number to check whether sending message or not. */
6428 seq = key_getacq(saidx, &error);
6432 m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6440 * set sadb_address for saidx's.
6442 * Note that if sp is supplied, then we're being called from
6443 * key_allocsa_policy() and should supply port and protocol
6445 * XXXAE: why only TCP and UDP? ICMP and SCTP looks applicable too.
6446 * XXXAE: probably we can handle this in the ipsec[46]_allocsa().
6447 * XXXAE: it looks like we should save this info in the ACQ entry.
6449 if (sp != NULL && (sp->spidx.ul_proto == IPPROTO_TCP ||
6450 sp->spidx.ul_proto == IPPROTO_UDP))
6451 ul_proto = sp->spidx.ul_proto;
6455 if (ul_proto != IPSEC_ULPROTO_ANY) {
6456 switch (sp->spidx.src.sa.sa_family) {
6458 if (sp->spidx.src.sin.sin_port != IPSEC_PORT_ANY) {
6459 addr.sin.sin_port = sp->spidx.src.sin.sin_port;
6460 mask = sp->spidx.prefs;
6464 if (sp->spidx.src.sin6.sin6_port != IPSEC_PORT_ANY) {
6465 addr.sin6.sin6_port =
6466 sp->spidx.src.sin6.sin6_port;
6467 mask = sp->spidx.prefs;
6474 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC, &addr.sa, mask, ul_proto);
6483 if (ul_proto != IPSEC_ULPROTO_ANY) {
6484 switch (sp->spidx.dst.sa.sa_family) {
6486 if (sp->spidx.dst.sin.sin_port != IPSEC_PORT_ANY) {
6487 addr.sin.sin_port = sp->spidx.dst.sin.sin_port;
6488 mask = sp->spidx.prefd;
6492 if (sp->spidx.dst.sin6.sin6_port != IPSEC_PORT_ANY) {
6493 addr.sin6.sin6_port =
6494 sp->spidx.dst.sin6.sin6_port;
6495 mask = sp->spidx.prefd;
6502 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST, &addr.sa, mask, ul_proto);
6509 /* XXX proxy address (optional) */
6511 /* set sadb_x_policy */
6513 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id,
6522 /* XXX identity (optional) */
6524 if (idexttype && fqdn) {
6525 /* create identity extension (FQDN) */
6526 struct sadb_ident *id;
6529 fqdnlen = strlen(fqdn) + 1; /* +1 for terminating-NUL */
6530 id = (struct sadb_ident *)p;
6531 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6532 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6533 id->sadb_ident_exttype = idexttype;
6534 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6535 bcopy(fqdn, id + 1, fqdnlen);
6536 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6540 /* create identity extension (USERFQDN) */
6541 struct sadb_ident *id;
6545 /* +1 for terminating-NUL */
6546 userfqdnlen = strlen(userfqdn) + 1;
6549 id = (struct sadb_ident *)p;
6550 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6551 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6552 id->sadb_ident_exttype = idexttype;
6553 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6554 /* XXX is it correct? */
6555 if (curproc && curproc->p_cred)
6556 id->sadb_ident_id = curproc->p_cred->p_ruid;
6557 if (userfqdn && userfqdnlen)
6558 bcopy(userfqdn, id + 1, userfqdnlen);
6559 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6563 /* XXX sensitivity (optional) */
6565 /* create proposal/combination extension */
6566 m = key_getprop(saidx);
6569 * spec conformant: always attach proposal/combination extension,
6570 * the problem is that we have no way to attach it for ipcomp,
6571 * due to the way sadb_comb is declared in RFC2367.
6580 * outside of spec; make proposal/combination extension optional.
6586 if ((result->m_flags & M_PKTHDR) == 0) {
6591 if (result->m_len < sizeof(struct sadb_msg)) {
6592 result = m_pullup(result, sizeof(struct sadb_msg));
6593 if (result == NULL) {
6599 result->m_pkthdr.len = 0;
6600 for (m = result; m; m = m->m_next)
6601 result->m_pkthdr.len += m->m_len;
6603 mtod(result, struct sadb_msg *)->sadb_msg_len =
6604 PFKEY_UNIT64(result->m_pkthdr.len);
6607 printf("%s: SP(%p)\n", __func__, sp));
6608 KEYDBG(KEY_DATA, kdebug_secasindex(saidx, NULL));
6610 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6619 key_newacq(const struct secasindex *saidx, int *perror)
6624 acq = malloc(sizeof(*acq), M_IPSEC_SAQ, M_NOWAIT | M_ZERO);
6626 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6632 bcopy(saidx, &acq->saidx, sizeof(acq->saidx));
6633 acq->created = time_second;
6636 /* add to acqtree */
6638 seq = acq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6639 LIST_INSERT_HEAD(&V_acqtree, acq, chain);
6640 LIST_INSERT_HEAD(ACQADDRHASH_HASH(saidx), acq, addrhash);
6641 LIST_INSERT_HEAD(ACQSEQHASH_HASH(seq), acq, seqhash);
6648 key_getacq(const struct secasindex *saidx, int *perror)
6654 LIST_FOREACH(acq, ACQADDRHASH_HASH(saidx), addrhash) {
6655 if (key_cmpsaidx(&acq->saidx, saidx, CMP_EXACTLY)) {
6656 if (acq->count > V_key_blockacq_count) {
6658 * Reset counter and send message.
6659 * Also reset created time to keep ACQ for
6662 acq->created = time_second;
6667 * Increment counter and do nothing.
6668 * We send SADB_ACQUIRE message only
6669 * for each V_key_blockacq_count packet.
6682 /* allocate new entry */
6683 return (key_newacq(saidx, perror));
6687 key_acqreset(uint32_t seq)
6692 LIST_FOREACH(acq, ACQSEQHASH_HASH(seq), seqhash) {
6693 if (acq->seq == seq) {
6695 acq->created = time_second;
6705 * Mark ACQ entry as stale to remove it in key_flush_acq().
6706 * Called after successful SADB_GETSPI message.
6709 key_acqdone(const struct secasindex *saidx, uint32_t seq)
6714 LIST_FOREACH(acq, ACQSEQHASH_HASH(seq), seqhash) {
6715 if (acq->seq == seq)
6719 if (key_cmpsaidx(&acq->saidx, saidx, CMP_EXACTLY) == 0) {
6720 ipseclog((LOG_DEBUG,
6721 "%s: Mismatched saidx for ACQ %u", __func__, seq));
6727 ipseclog((LOG_DEBUG,
6728 "%s: ACQ %u is not found.", __func__, seq));
6736 static struct secspacq *
6737 key_newspacq(struct secpolicyindex *spidx)
6739 struct secspacq *acq;
6742 acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6744 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6749 bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6750 acq->created = time_second;
6753 /* add to spacqtree */
6755 LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6761 static struct secspacq *
6762 key_getspacq(struct secpolicyindex *spidx)
6764 struct secspacq *acq;
6767 LIST_FOREACH(acq, &V_spacqtree, chain) {
6768 if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6769 /* NB: return holding spacq_lock */
6779 * SADB_ACQUIRE processing,
6780 * in first situation, is receiving
6782 * from the ikmpd, and clear sequence of its secasvar entry.
6784 * In second situation, is receiving
6785 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6786 * from a user land process, and return
6787 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6790 * m will always be freed.
6793 key_acquire2(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6795 SAHTREE_RLOCK_TRACKER;
6796 struct sadb_address *src0, *dst0;
6797 struct secasindex saidx;
6798 struct secashead *sah;
6801 uint8_t mode, proto;
6803 IPSEC_ASSERT(so != NULL, ("null socket"));
6804 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6805 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6806 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6809 * Error message from KMd.
6810 * We assume that if error was occurred in IKEd, the length of PFKEY
6811 * message is equal to the size of sadb_msg structure.
6812 * We do not raise error even if error occurred in this function.
6814 if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6815 /* check sequence number */
6816 if (mhp->msg->sadb_msg_seq == 0 ||
6817 mhp->msg->sadb_msg_errno == 0) {
6818 ipseclog((LOG_DEBUG, "%s: must specify sequence "
6819 "number and errno.\n", __func__));
6822 * IKEd reported that error occurred.
6823 * XXXAE: what it expects from the kernel?
6824 * Probably we should send SADB_ACQUIRE again?
6825 * If so, reset ACQ's state.
6826 * XXXAE: it looks useless.
6828 key_acqreset(mhp->msg->sadb_msg_seq);
6835 * This message is from user land.
6838 /* map satype to proto */
6839 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6840 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6842 return key_senderror(so, m, EINVAL);
6845 if (SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_SRC) ||
6846 SADB_CHECKHDR(mhp, SADB_EXT_ADDRESS_DST) ||
6847 SADB_CHECKHDR(mhp, SADB_EXT_PROPOSAL)) {
6848 ipseclog((LOG_DEBUG,
6849 "%s: invalid message: missing required header.\n",
6851 return key_senderror(so, m, EINVAL);
6853 if (SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_SRC) ||
6854 SADB_CHECKLEN(mhp, SADB_EXT_ADDRESS_DST) ||
6855 SADB_CHECKLEN(mhp, SADB_EXT_PROPOSAL)) {
6856 ipseclog((LOG_DEBUG,
6857 "%s: invalid message: wrong header size.\n", __func__));
6858 return key_senderror(so, m, EINVAL);
6861 if (SADB_CHECKHDR(mhp, SADB_X_EXT_SA2)) {
6862 mode = IPSEC_MODE_ANY;
6865 if (SADB_CHECKLEN(mhp, SADB_X_EXT_SA2)) {
6866 ipseclog((LOG_DEBUG,
6867 "%s: invalid message: wrong header size.\n",
6869 return key_senderror(so, m, EINVAL);
6871 mode = ((struct sadb_x_sa2 *)
6872 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
6873 reqid = ((struct sadb_x_sa2 *)
6874 mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
6877 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6878 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6880 error = key_checksockaddrs((struct sockaddr *)(src0 + 1),
6881 (struct sockaddr *)(dst0 + 1));
6883 ipseclog((LOG_DEBUG, "%s: invalid sockaddr.\n", __func__));
6884 return key_senderror(so, m, EINVAL);
6886 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
6888 /* get a SA index */
6890 LIST_FOREACH(sah, SAHADDRHASH_HASH(&saidx), addrhash) {
6891 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6896 ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6897 return key_senderror(so, m, EEXIST);
6900 error = key_acquire(&saidx, NULL);
6902 ipseclog((LOG_DEBUG,
6903 "%s: error %d returned from key_acquire()\n",
6905 return key_senderror(so, m, error);
6912 * SADB_REGISTER processing.
6913 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6916 * from the ikmpd, and register a socket to send PF_KEY messages,
6920 * If socket is detached, must free from regnode.
6922 * m will always be freed.
6925 key_register(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6927 struct secreg *reg, *newreg = NULL;
6929 IPSEC_ASSERT(so != NULL, ("null socket"));
6930 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6931 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6932 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6934 /* check for invalid register message */
6935 if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6936 return key_senderror(so, m, EINVAL);
6938 /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6939 if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6942 /* check whether existing or not */
6944 LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6945 if (reg->so == so) {
6947 ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6949 return key_senderror(so, m, EEXIST);
6953 /* create regnode */
6954 newreg = malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6955 if (newreg == NULL) {
6957 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6958 return key_senderror(so, m, ENOBUFS);
6962 ((struct keycb *)sotorawcb(so))->kp_registered++;
6964 /* add regnode to regtree. */
6965 LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6971 struct sadb_msg *newmsg;
6972 struct sadb_supported *sup;
6973 u_int len, alen, elen;
6976 struct sadb_alg *alg;
6978 /* create new sadb_msg to reply. */
6980 for (i = 1; i <= SADB_AALG_MAX; i++) {
6981 if (auth_algorithm_lookup(i))
6982 alen += sizeof(struct sadb_alg);
6985 alen += sizeof(struct sadb_supported);
6987 for (i = 1; i <= SADB_EALG_MAX; i++) {
6988 if (enc_algorithm_lookup(i))
6989 elen += sizeof(struct sadb_alg);
6992 elen += sizeof(struct sadb_supported);
6994 len = sizeof(struct sadb_msg) + alen + elen;
6997 return key_senderror(so, m, ENOBUFS);
6999 MGETHDR(n, M_NOWAIT, MT_DATA);
7001 if (!(MCLGET(n, M_NOWAIT))) {
7007 return key_senderror(so, m, ENOBUFS);
7009 n->m_pkthdr.len = n->m_len = len;
7013 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
7014 newmsg = mtod(n, struct sadb_msg *);
7015 newmsg->sadb_msg_errno = 0;
7016 newmsg->sadb_msg_len = PFKEY_UNIT64(len);
7017 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
7019 /* for authentication algorithm */
7021 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
7022 sup->sadb_supported_len = PFKEY_UNIT64(alen);
7023 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
7024 off += PFKEY_ALIGN8(sizeof(*sup));
7026 for (i = 1; i <= SADB_AALG_MAX; i++) {
7027 const struct auth_hash *aalgo;
7028 u_int16_t minkeysize, maxkeysize;
7030 aalgo = auth_algorithm_lookup(i);
7033 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
7034 alg->sadb_alg_id = i;
7035 alg->sadb_alg_ivlen = 0;
7036 key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
7037 alg->sadb_alg_minbits = _BITS(minkeysize);
7038 alg->sadb_alg_maxbits = _BITS(maxkeysize);
7039 off += PFKEY_ALIGN8(sizeof(*alg));
7043 /* for encryption algorithm */
7045 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
7046 sup->sadb_supported_len = PFKEY_UNIT64(elen);
7047 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
7048 off += PFKEY_ALIGN8(sizeof(*sup));
7050 for (i = 1; i <= SADB_EALG_MAX; i++) {
7051 const struct enc_xform *ealgo;
7053 ealgo = enc_algorithm_lookup(i);
7056 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
7057 alg->sadb_alg_id = i;
7058 alg->sadb_alg_ivlen = ealgo->ivsize;
7059 alg->sadb_alg_minbits = _BITS(ealgo->minkey);
7060 alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
7061 off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
7065 IPSEC_ASSERT(off == len,
7066 ("length assumption failed (off %u len %u)", off, len));
7069 return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
7074 * free secreg entry registered.
7075 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
7078 key_freereg(struct socket *so)
7083 IPSEC_ASSERT(so != NULL, ("NULL so"));
7086 * check whether existing or not.
7087 * check all type of SA, because there is a potential that
7088 * one socket is registered to multiple type of SA.
7091 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7092 LIST_FOREACH(reg, &V_regtree[i], chain) {
7093 if (reg->so == so && __LIST_CHAINED(reg)) {
7094 LIST_REMOVE(reg, chain);
7095 free(reg, M_IPSEC_SAR);
7104 * SADB_EXPIRE processing
7106 * <base, SA, SA2, lifetime(C and one of HS), address(SD)>
7108 * NOTE: We send only soft lifetime extension.
7111 * others : error number
7114 key_expire(struct secasvar *sav, int hard)
7116 struct mbuf *result = NULL, *m;
7117 struct sadb_lifetime *lt;
7118 uint32_t replay_count;
7122 IPSEC_ASSERT (sav != NULL, ("null sav"));
7123 IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
7126 printf("%s: SA(%p) expired %s lifetime\n", __func__,
7127 sav, hard ? "hard": "soft"));
7128 KEYDBG(KEY_DATA, kdebug_secasv(sav));
7129 /* set msg header */
7130 satype = key_proto2satype(sav->sah->saidx.proto);
7131 IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
7132 m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
7139 /* create SA extension */
7140 m = key_setsadbsa(sav);
7147 /* create SA extension */
7149 replay_count = sav->replay ? sav->replay->count : 0;
7150 SECASVAR_UNLOCK(sav);
7152 m = key_setsadbxsa2(sav->sah->saidx.mode, replay_count,
7153 sav->sah->saidx.reqid);
7160 if (sav->replay && sav->replay->wsize > UINT8_MAX) {
7161 m = key_setsadbxsareplay(sav->replay->wsize);
7169 /* create lifetime extension (current and soft) */
7170 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
7171 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
7178 bzero(mtod(m, caddr_t), len);
7179 lt = mtod(m, struct sadb_lifetime *);
7180 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7181 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
7182 lt->sadb_lifetime_allocations =
7183 (uint32_t)counter_u64_fetch(sav->lft_c_allocations);
7184 lt->sadb_lifetime_bytes =
7185 counter_u64_fetch(sav->lft_c_bytes);
7186 lt->sadb_lifetime_addtime = sav->created;
7187 lt->sadb_lifetime_usetime = sav->firstused;
7188 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
7189 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7191 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
7192 lt->sadb_lifetime_allocations = sav->lft_h->allocations;
7193 lt->sadb_lifetime_bytes = sav->lft_h->bytes;
7194 lt->sadb_lifetime_addtime = sav->lft_h->addtime;
7195 lt->sadb_lifetime_usetime = sav->lft_h->usetime;
7197 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
7198 lt->sadb_lifetime_allocations = sav->lft_s->allocations;
7199 lt->sadb_lifetime_bytes = sav->lft_s->bytes;
7200 lt->sadb_lifetime_addtime = sav->lft_s->addtime;
7201 lt->sadb_lifetime_usetime = sav->lft_s->usetime;
7205 /* set sadb_address for source */
7206 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
7207 &sav->sah->saidx.src.sa,
7208 FULLMASK, IPSEC_ULPROTO_ANY);
7215 /* set sadb_address for destination */
7216 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
7217 &sav->sah->saidx.dst.sa,
7218 FULLMASK, IPSEC_ULPROTO_ANY);
7226 * XXX-BZ Handle NAT-T extensions here.
7227 * XXXAE: it doesn't seem quite useful. IKEs should not depend on
7228 * this information, we report only significant SA fields.
7231 if ((result->m_flags & M_PKTHDR) == 0) {
7236 if (result->m_len < sizeof(struct sadb_msg)) {
7237 result = m_pullup(result, sizeof(struct sadb_msg));
7238 if (result == NULL) {
7244 result->m_pkthdr.len = 0;
7245 for (m = result; m; m = m->m_next)
7246 result->m_pkthdr.len += m->m_len;
7248 mtod(result, struct sadb_msg *)->sadb_msg_len =
7249 PFKEY_UNIT64(result->m_pkthdr.len);
7251 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7260 key_freesah_flushed(struct secashead_queue *flushq)
7262 struct secashead *sah, *nextsah;
7263 struct secasvar *sav, *nextsav;
7265 sah = TAILQ_FIRST(flushq);
7266 while (sah != NULL) {
7267 sav = TAILQ_FIRST(&sah->savtree_larval);
7268 while (sav != NULL) {
7269 nextsav = TAILQ_NEXT(sav, chain);
7270 TAILQ_REMOVE(&sah->savtree_larval, sav, chain);
7271 key_freesav(&sav); /* release last reference */
7272 key_freesah(&sah); /* release reference from SAV */
7275 sav = TAILQ_FIRST(&sah->savtree_alive);
7276 while (sav != NULL) {
7277 nextsav = TAILQ_NEXT(sav, chain);
7278 TAILQ_REMOVE(&sah->savtree_alive, sav, chain);
7279 key_freesav(&sav); /* release last reference */
7280 key_freesah(&sah); /* release reference from SAV */
7283 nextsah = TAILQ_NEXT(sah, chain);
7284 key_freesah(&sah); /* release last reference */
7290 * SADB_FLUSH processing
7293 * from the ikmpd, and free all entries in secastree.
7297 * NOTE: to do is only marking SADB_SASTATE_DEAD.
7299 * m will always be freed.
7302 key_flush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7304 struct secashead_queue flushq;
7305 struct sadb_msg *newmsg;
7306 struct secashead *sah, *nextsah;
7307 struct secasvar *sav;
7311 IPSEC_ASSERT(so != NULL, ("null socket"));
7312 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7313 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7315 /* map satype to proto */
7316 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7317 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7319 return key_senderror(so, m, EINVAL);
7322 printf("%s: proto %u\n", __func__, proto));
7324 TAILQ_INIT(&flushq);
7325 if (proto == IPSEC_PROTO_ANY) {
7326 /* no SATYPE specified, i.e. flushing all SA. */
7328 /* Move all SAHs into flushq */
7329 TAILQ_CONCAT(&flushq, &V_sahtree, chain);
7330 /* Flush all buckets in SPI hash */
7331 for (i = 0; i < V_savhash_mask + 1; i++)
7332 LIST_INIT(&V_savhashtbl[i]);
7333 /* Flush all buckets in SAHADDRHASH */
7334 for (i = 0; i < V_sahaddrhash_mask + 1; i++)
7335 LIST_INIT(&V_sahaddrhashtbl[i]);
7336 /* Mark all SAHs as unlinked */
7337 TAILQ_FOREACH(sah, &flushq, chain) {
7338 sah->state = SADB_SASTATE_DEAD;
7340 * Callout handler makes its job using
7341 * RLOCK and drain queues. In case, when this
7342 * function will be called just before it
7343 * acquires WLOCK, we need to mark SAs as
7344 * unlinked to prevent second unlink.
7346 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7347 sav->state = SADB_SASTATE_DEAD;
7349 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7350 sav->state = SADB_SASTATE_DEAD;
7356 sah = TAILQ_FIRST(&V_sahtree);
7357 while (sah != NULL) {
7358 IPSEC_ASSERT(sah->state != SADB_SASTATE_DEAD,
7359 ("DEAD SAH %p in SADB_FLUSH", sah));
7360 nextsah = TAILQ_NEXT(sah, chain);
7361 if (sah->saidx.proto != proto) {
7365 sah->state = SADB_SASTATE_DEAD;
7366 TAILQ_REMOVE(&V_sahtree, sah, chain);
7367 LIST_REMOVE(sah, addrhash);
7368 /* Unlink all SAs from SPI hash */
7369 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7370 LIST_REMOVE(sav, spihash);
7371 sav->state = SADB_SASTATE_DEAD;
7373 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7374 LIST_REMOVE(sav, spihash);
7375 sav->state = SADB_SASTATE_DEAD;
7377 /* Add SAH into flushq */
7378 TAILQ_INSERT_HEAD(&flushq, sah, chain);
7384 key_freesah_flushed(&flushq);
7385 /* Free all queued SAs and SAHs */
7386 if (m->m_len < sizeof(struct sadb_msg) ||
7387 sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
7388 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
7389 return key_senderror(so, m, ENOBUFS);
7395 m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
7396 newmsg = mtod(m, struct sadb_msg *);
7397 newmsg->sadb_msg_errno = 0;
7398 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
7400 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7404 * SADB_DUMP processing
7405 * dump all entries including status of DEAD in SAD.
7408 * from the ikmpd, and dump all secasvar leaves
7413 * m will always be freed.
7416 key_dump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7418 SAHTREE_RLOCK_TRACKER;
7419 struct secashead *sah;
7420 struct secasvar *sav;
7421 struct sadb_msg *newmsg;
7424 uint8_t proto, satype;
7426 IPSEC_ASSERT(so != NULL, ("null socket"));
7427 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7428 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7429 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7431 /* map satype to proto */
7432 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7433 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
7435 return key_senderror(so, m, EINVAL);
7438 /* count sav entries to be sent to the userland. */
7441 TAILQ_FOREACH(sah, &V_sahtree, chain) {
7442 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
7443 proto != sah->saidx.proto)
7446 TAILQ_FOREACH(sav, &sah->savtree_larval, chain)
7448 TAILQ_FOREACH(sav, &sah->savtree_alive, chain)
7454 return key_senderror(so, m, ENOENT);
7457 /* send this to the userland, one at a time. */
7459 TAILQ_FOREACH(sah, &V_sahtree, chain) {
7460 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC &&
7461 proto != sah->saidx.proto)
7464 /* map proto to satype */
7465 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7467 ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7468 "SAD.\n", __func__));
7469 return key_senderror(so, m, EINVAL);
7471 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
7472 n = key_setdumpsa(sav, SADB_DUMP, satype,
7473 --cnt, mhp->msg->sadb_msg_pid);
7476 return key_senderror(so, m, ENOBUFS);
7478 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7480 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
7481 n = key_setdumpsa(sav, SADB_DUMP, satype,
7482 --cnt, mhp->msg->sadb_msg_pid);
7485 return key_senderror(so, m, ENOBUFS);
7487 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7495 * SADB_X_PROMISC processing
7497 * m will always be freed.
7500 key_promisc(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7504 IPSEC_ASSERT(so != NULL, ("null socket"));
7505 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7506 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7507 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7509 olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7511 if (olen < sizeof(struct sadb_msg)) {
7513 return key_senderror(so, m, EINVAL);
7518 } else if (olen == sizeof(struct sadb_msg)) {
7519 /* enable/disable promisc mode */
7522 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7523 return key_senderror(so, m, EINVAL);
7524 mhp->msg->sadb_msg_errno = 0;
7525 switch (mhp->msg->sadb_msg_satype) {
7528 kp->kp_promisc = mhp->msg->sadb_msg_satype;
7531 return key_senderror(so, m, EINVAL);
7534 /* send the original message back to everyone */
7535 mhp->msg->sadb_msg_errno = 0;
7536 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7538 /* send packet as is */
7540 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7542 /* TODO: if sadb_msg_seq is specified, send to specific pid */
7543 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7547 static int (*key_typesw[])(struct socket *, struct mbuf *,
7548 const struct sadb_msghdr *) = {
7549 NULL, /* SADB_RESERVED */
7550 key_getspi, /* SADB_GETSPI */
7551 key_update, /* SADB_UPDATE */
7552 key_add, /* SADB_ADD */
7553 key_delete, /* SADB_DELETE */
7554 key_get, /* SADB_GET */
7555 key_acquire2, /* SADB_ACQUIRE */
7556 key_register, /* SADB_REGISTER */
7557 NULL, /* SADB_EXPIRE */
7558 key_flush, /* SADB_FLUSH */
7559 key_dump, /* SADB_DUMP */
7560 key_promisc, /* SADB_X_PROMISC */
7561 NULL, /* SADB_X_PCHANGE */
7562 key_spdadd, /* SADB_X_SPDUPDATE */
7563 key_spdadd, /* SADB_X_SPDADD */
7564 key_spddelete, /* SADB_X_SPDDELETE */
7565 key_spdget, /* SADB_X_SPDGET */
7566 NULL, /* SADB_X_SPDACQUIRE */
7567 key_spddump, /* SADB_X_SPDDUMP */
7568 key_spdflush, /* SADB_X_SPDFLUSH */
7569 key_spdadd, /* SADB_X_SPDSETIDX */
7570 NULL, /* SADB_X_SPDEXPIRE */
7571 key_spddelete2, /* SADB_X_SPDDELETE2 */
7575 * parse sadb_msg buffer to process PFKEYv2,
7576 * and create a data to response if needed.
7577 * I think to be dealed with mbuf directly.
7579 * msgp : pointer to pointer to a received buffer pulluped.
7580 * This is rewrited to response.
7581 * so : pointer to socket.
7583 * length for buffer to send to user process.
7586 key_parse(struct mbuf *m, struct socket *so)
7588 struct sadb_msg *msg;
7589 struct sadb_msghdr mh;
7594 IPSEC_ASSERT(so != NULL, ("null socket"));
7595 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7597 if (m->m_len < sizeof(struct sadb_msg)) {
7598 m = m_pullup(m, sizeof(struct sadb_msg));
7602 msg = mtod(m, struct sadb_msg *);
7603 orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7604 target = KEY_SENDUP_ONE;
7606 if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len != orglen) {
7607 ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7608 PFKEYSTAT_INC(out_invlen);
7613 if (msg->sadb_msg_version != PF_KEY_V2) {
7614 ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7615 __func__, msg->sadb_msg_version));
7616 PFKEYSTAT_INC(out_invver);
7621 if (msg->sadb_msg_type > SADB_MAX) {
7622 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7623 __func__, msg->sadb_msg_type));
7624 PFKEYSTAT_INC(out_invmsgtype);
7629 /* for old-fashioned code - should be nuked */
7630 if (m->m_pkthdr.len > MCLBYTES) {
7637 MGETHDR(n, M_NOWAIT, MT_DATA);
7638 if (n && m->m_pkthdr.len > MHLEN) {
7639 if (!(MCLGET(n, M_NOWAIT))) {
7648 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7649 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7655 /* align the mbuf chain so that extensions are in contiguous region. */
7656 error = key_align(m, &mh);
7663 switch (msg->sadb_msg_satype) {
7664 case SADB_SATYPE_UNSPEC:
7665 switch (msg->sadb_msg_type) {
7673 ipseclog((LOG_DEBUG, "%s: must specify satype "
7674 "when msg type=%u.\n", __func__,
7675 msg->sadb_msg_type));
7676 PFKEYSTAT_INC(out_invsatype);
7681 case SADB_SATYPE_AH:
7682 case SADB_SATYPE_ESP:
7683 case SADB_X_SATYPE_IPCOMP:
7684 case SADB_X_SATYPE_TCPSIGNATURE:
7685 switch (msg->sadb_msg_type) {
7687 case SADB_X_SPDDELETE:
7689 case SADB_X_SPDDUMP:
7690 case SADB_X_SPDFLUSH:
7691 case SADB_X_SPDSETIDX:
7692 case SADB_X_SPDUPDATE:
7693 case SADB_X_SPDDELETE2:
7694 ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7695 __func__, msg->sadb_msg_type));
7696 PFKEYSTAT_INC(out_invsatype);
7701 case SADB_SATYPE_RSVP:
7702 case SADB_SATYPE_OSPFV2:
7703 case SADB_SATYPE_RIPV2:
7704 case SADB_SATYPE_MIP:
7705 ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7706 __func__, msg->sadb_msg_satype));
7707 PFKEYSTAT_INC(out_invsatype);
7710 case 1: /* XXX: What does it do? */
7711 if (msg->sadb_msg_type == SADB_X_PROMISC)
7715 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7716 __func__, msg->sadb_msg_satype));
7717 PFKEYSTAT_INC(out_invsatype);
7722 /* check field of upper layer protocol and address family */
7723 if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7724 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7725 struct sadb_address *src0, *dst0;
7728 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7729 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7731 /* check upper layer protocol */
7732 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7733 ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7734 "mismatched.\n", __func__));
7735 PFKEYSTAT_INC(out_invaddr);
7741 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7742 PFKEY_ADDR_SADDR(dst0)->sa_family) {
7743 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7745 PFKEYSTAT_INC(out_invaddr);
7749 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7750 PFKEY_ADDR_SADDR(dst0)->sa_len) {
7751 ipseclog((LOG_DEBUG, "%s: address struct size "
7752 "mismatched.\n", __func__));
7753 PFKEYSTAT_INC(out_invaddr);
7758 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7760 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7761 sizeof(struct sockaddr_in)) {
7762 PFKEYSTAT_INC(out_invaddr);
7768 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7769 sizeof(struct sockaddr_in6)) {
7770 PFKEYSTAT_INC(out_invaddr);
7776 ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7778 PFKEYSTAT_INC(out_invaddr);
7779 error = EAFNOSUPPORT;
7783 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7785 plen = sizeof(struct in_addr) << 3;
7788 plen = sizeof(struct in6_addr) << 3;
7791 plen = 0; /*fool gcc*/
7795 /* check max prefix length */
7796 if (src0->sadb_address_prefixlen > plen ||
7797 dst0->sadb_address_prefixlen > plen) {
7798 ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7800 PFKEYSTAT_INC(out_invaddr);
7806 * prefixlen == 0 is valid because there can be a case when
7807 * all addresses are matched.
7811 if (msg->sadb_msg_type >= nitems(key_typesw) ||
7812 key_typesw[msg->sadb_msg_type] == NULL) {
7813 PFKEYSTAT_INC(out_invmsgtype);
7818 return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7821 msg->sadb_msg_errno = error;
7822 return key_sendup_mbuf(so, m, target);
7826 key_senderror(struct socket *so, struct mbuf *m, int code)
7828 struct sadb_msg *msg;
7830 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7831 ("mbuf too small, len %u", m->m_len));
7833 msg = mtod(m, struct sadb_msg *);
7834 msg->sadb_msg_errno = code;
7835 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7839 * set the pointer to each header into message buffer.
7840 * m will be freed on error.
7841 * XXX larger-than-MCLBYTES extension?
7844 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
7847 struct sadb_ext *ext;
7852 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7853 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7854 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7855 ("mbuf too small, len %u", m->m_len));
7858 bzero(mhp, sizeof(*mhp));
7860 mhp->msg = mtod(m, struct sadb_msg *);
7861 mhp->ext[0] = (struct sadb_ext *)mhp->msg; /*XXX backward compat */
7863 end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7864 extlen = end; /*just in case extlen is not updated*/
7865 for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7866 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7868 /* m is already freed */
7871 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7874 switch (ext->sadb_ext_type) {
7876 case SADB_EXT_ADDRESS_SRC:
7877 case SADB_EXT_ADDRESS_DST:
7878 case SADB_EXT_ADDRESS_PROXY:
7879 case SADB_EXT_LIFETIME_CURRENT:
7880 case SADB_EXT_LIFETIME_HARD:
7881 case SADB_EXT_LIFETIME_SOFT:
7882 case SADB_EXT_KEY_AUTH:
7883 case SADB_EXT_KEY_ENCRYPT:
7884 case SADB_EXT_IDENTITY_SRC:
7885 case SADB_EXT_IDENTITY_DST:
7886 case SADB_EXT_SENSITIVITY:
7887 case SADB_EXT_PROPOSAL:
7888 case SADB_EXT_SUPPORTED_AUTH:
7889 case SADB_EXT_SUPPORTED_ENCRYPT:
7890 case SADB_EXT_SPIRANGE:
7891 case SADB_X_EXT_POLICY:
7892 case SADB_X_EXT_SA2:
7893 case SADB_X_EXT_NAT_T_TYPE:
7894 case SADB_X_EXT_NAT_T_SPORT:
7895 case SADB_X_EXT_NAT_T_DPORT:
7896 case SADB_X_EXT_NAT_T_OAI:
7897 case SADB_X_EXT_NAT_T_OAR:
7898 case SADB_X_EXT_NAT_T_FRAG:
7899 case SADB_X_EXT_SA_REPLAY:
7900 case SADB_X_EXT_NEW_ADDRESS_SRC:
7901 case SADB_X_EXT_NEW_ADDRESS_DST:
7902 /* duplicate check */
7904 * XXX Are there duplication payloads of either
7905 * KEY_AUTH or KEY_ENCRYPT ?
7907 if (mhp->ext[ext->sadb_ext_type] != NULL) {
7908 ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7909 "%u\n", __func__, ext->sadb_ext_type));
7911 PFKEYSTAT_INC(out_dupext);
7916 ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7917 __func__, ext->sadb_ext_type));
7919 PFKEYSTAT_INC(out_invexttype);
7923 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7925 if (key_validate_ext(ext, extlen)) {
7927 PFKEYSTAT_INC(out_invlen);
7931 n = m_pulldown(m, off, extlen, &toff);
7933 /* m is already freed */
7936 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7938 mhp->ext[ext->sadb_ext_type] = ext;
7939 mhp->extoff[ext->sadb_ext_type] = off;
7940 mhp->extlen[ext->sadb_ext_type] = extlen;
7945 PFKEYSTAT_INC(out_invlen);
7953 key_validate_ext(const struct sadb_ext *ext, int len)
7955 const struct sockaddr *sa;
7956 enum { NONE, ADDR } checktype = NONE;
7958 const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7960 if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7963 /* if it does not match minimum/maximum length, bail */
7964 if (ext->sadb_ext_type >= nitems(minsize) ||
7965 ext->sadb_ext_type >= nitems(maxsize))
7967 if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7969 if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7972 /* more checks based on sadb_ext_type XXX need more */
7973 switch (ext->sadb_ext_type) {
7974 case SADB_EXT_ADDRESS_SRC:
7975 case SADB_EXT_ADDRESS_DST:
7976 case SADB_EXT_ADDRESS_PROXY:
7977 case SADB_X_EXT_NAT_T_OAI:
7978 case SADB_X_EXT_NAT_T_OAR:
7979 case SADB_X_EXT_NEW_ADDRESS_SRC:
7980 case SADB_X_EXT_NEW_ADDRESS_DST:
7981 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7984 case SADB_EXT_IDENTITY_SRC:
7985 case SADB_EXT_IDENTITY_DST:
7986 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7987 SADB_X_IDENTTYPE_ADDR) {
7988 baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7998 switch (checktype) {
8002 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
8003 if (len < baselen + sal)
8005 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
8018 for (i = 0; i < IPSEC_DIR_MAX; i++) {
8019 TAILQ_INIT(&V_sptree[i]);
8020 TAILQ_INIT(&V_sptree_ifnet[i]);
8023 V_key_lft_zone = uma_zcreate("IPsec SA lft_c",
8024 sizeof(uint64_t) * 2, NULL, NULL, NULL, NULL,
8025 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
8027 TAILQ_INIT(&V_sahtree);
8028 V_sphashtbl = hashinit(SPHASH_NHASH, M_IPSEC_SP, &V_sphash_mask);
8029 V_savhashtbl = hashinit(SAVHASH_NHASH, M_IPSEC_SA, &V_savhash_mask);
8030 V_sahaddrhashtbl = hashinit(SAHHASH_NHASH, M_IPSEC_SAH,
8031 &V_sahaddrhash_mask);
8032 V_acqaddrhashtbl = hashinit(ACQHASH_NHASH, M_IPSEC_SAQ,
8033 &V_acqaddrhash_mask);
8034 V_acqseqhashtbl = hashinit(ACQHASH_NHASH, M_IPSEC_SAQ,
8035 &V_acqseqhash_mask);
8037 for (i = 0; i <= SADB_SATYPE_MAX; i++)
8038 LIST_INIT(&V_regtree[i]);
8040 LIST_INIT(&V_acqtree);
8041 LIST_INIT(&V_spacqtree);
8043 if (!IS_DEFAULT_VNET(curvnet))
8048 REGTREE_LOCK_INIT();
8049 SAHTREE_LOCK_INIT();
8053 #ifndef IPSEC_DEBUG2
8054 callout_init(&key_timer, 1);
8055 callout_reset(&key_timer, hz, key_timehandler, NULL);
8056 #endif /*IPSEC_DEBUG2*/
8058 /* initialize key statistics */
8059 keystat.getspi_count = 1;
8062 printf("IPsec: Initialized Security Association Processing.\n");
8069 struct secashead_queue sahdrainq;
8070 struct secpolicy_queue drainq;
8071 struct secpolicy *sp, *nextsp;
8072 struct secacq *acq, *nextacq;
8073 struct secspacq *spacq, *nextspacq;
8074 struct secashead *sah;
8075 struct secasvar *sav;
8080 * XXX: can we just call free() for each object without
8081 * walking through safe way with releasing references?
8083 TAILQ_INIT(&drainq);
8085 for (i = 0; i < IPSEC_DIR_MAX; i++) {
8086 TAILQ_CONCAT(&drainq, &V_sptree[i], chain);
8087 TAILQ_CONCAT(&drainq, &V_sptree_ifnet[i], chain);
8090 sp = TAILQ_FIRST(&drainq);
8091 while (sp != NULL) {
8092 nextsp = TAILQ_NEXT(sp, chain);
8097 TAILQ_INIT(&sahdrainq);
8099 TAILQ_CONCAT(&sahdrainq, &V_sahtree, chain);
8100 for (i = 0; i < V_savhash_mask + 1; i++)
8101 LIST_INIT(&V_savhashtbl[i]);
8102 for (i = 0; i < V_sahaddrhash_mask + 1; i++)
8103 LIST_INIT(&V_sahaddrhashtbl[i]);
8104 TAILQ_FOREACH(sah, &sahdrainq, chain) {
8105 sah->state = SADB_SASTATE_DEAD;
8106 TAILQ_FOREACH(sav, &sah->savtree_larval, chain) {
8107 sav->state = SADB_SASTATE_DEAD;
8109 TAILQ_FOREACH(sav, &sah->savtree_alive, chain) {
8110 sav->state = SADB_SASTATE_DEAD;
8115 key_freesah_flushed(&sahdrainq);
8116 hashdestroy(V_sphashtbl, M_IPSEC_SP, V_sphash_mask);
8117 hashdestroy(V_savhashtbl, M_IPSEC_SA, V_savhash_mask);
8118 hashdestroy(V_sahaddrhashtbl, M_IPSEC_SAH, V_sahaddrhash_mask);
8121 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
8122 LIST_FOREACH(reg, &V_regtree[i], chain) {
8123 if (__LIST_CHAINED(reg)) {
8124 LIST_REMOVE(reg, chain);
8125 free(reg, M_IPSEC_SAR);
8133 acq = LIST_FIRST(&V_acqtree);
8134 while (acq != NULL) {
8135 nextacq = LIST_NEXT(acq, chain);
8136 LIST_REMOVE(acq, chain);
8137 free(acq, M_IPSEC_SAQ);
8143 for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
8144 spacq = nextspacq) {
8145 nextspacq = LIST_NEXT(spacq, chain);
8146 if (__LIST_CHAINED(spacq)) {
8147 LIST_REMOVE(spacq, chain);
8148 free(spacq, M_IPSEC_SAQ);
8152 hashdestroy(V_acqaddrhashtbl, M_IPSEC_SAQ, V_acqaddrhash_mask);
8153 hashdestroy(V_acqseqhashtbl, M_IPSEC_SAQ, V_acqseqhash_mask);
8154 uma_zdestroy(V_key_lft_zone);
8158 /* record data transfer on SA, and update timestamps */
8160 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
8162 IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
8163 IPSEC_ASSERT(m != NULL, ("Null mbuf"));
8166 * XXX Currently, there is a difference of bytes size
8167 * between inbound and outbound processing.
8169 counter_u64_add(sav->lft_c_bytes, m->m_pkthdr.len);
8172 * We use the number of packets as the unit of
8173 * allocations. We increment the variable
8174 * whenever {esp,ah}_{in,out}put is called.
8176 counter_u64_add(sav->lft_c_allocations, 1);
8179 * NOTE: We record CURRENT usetime by using wall clock,
8180 * in seconds. HARD and SOFT lifetime are measured by the time
8181 * difference (again in seconds) from usetime.
8185 * -----+-----+--------+---> t
8186 * <--------------> HARD
8189 if (sav->firstused == 0)
8190 sav->firstused = time_second;
8194 * Take one of the kernel's security keys and convert it into a PF_KEY
8195 * structure within an mbuf, suitable for sending up to a waiting
8196 * application in user land.
8199 * src: A pointer to a kernel security key.
8200 * exttype: Which type of key this is. Refer to the PF_KEY data structures.
8202 * a valid mbuf or NULL indicating an error
8206 static struct mbuf *
8207 key_setkey(struct seckey *src, uint16_t exttype)
8216 len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
8217 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
8222 p = mtod(m, struct sadb_key *);
8224 p->sadb_key_len = PFKEY_UNIT64(len);
8225 p->sadb_key_exttype = exttype;
8226 p->sadb_key_bits = src->bits;
8227 bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
8233 * Take one of the kernel's lifetime data structures and convert it
8234 * into a PF_KEY structure within an mbuf, suitable for sending up to
8235 * a waiting application in user land.
8238 * src: A pointer to a kernel lifetime structure.
8239 * exttype: Which type of lifetime this is. Refer to the PF_KEY
8240 * data structures for more information.
8242 * a valid mbuf or NULL indicating an error
8246 static struct mbuf *
8247 key_setlifetime(struct seclifetime *src, uint16_t exttype)
8249 struct mbuf *m = NULL;
8250 struct sadb_lifetime *p;
8251 int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
8256 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
8261 p = mtod(m, struct sadb_lifetime *);
8264 p->sadb_lifetime_len = PFKEY_UNIT64(len);
8265 p->sadb_lifetime_exttype = exttype;
8266 p->sadb_lifetime_allocations = src->allocations;
8267 p->sadb_lifetime_bytes = src->bytes;
8268 p->sadb_lifetime_addtime = src->addtime;
8269 p->sadb_lifetime_usetime = src->usetime;
8275 const struct enc_xform *
8276 enc_algorithm_lookup(int alg)
8280 for (i = 0; i < nitems(supported_ealgs); i++)
8281 if (alg == supported_ealgs[i].sadb_alg)
8282 return (supported_ealgs[i].xform);
8286 const struct auth_hash *
8287 auth_algorithm_lookup(int alg)
8291 for (i = 0; i < nitems(supported_aalgs); i++)
8292 if (alg == supported_aalgs[i].sadb_alg)
8293 return (supported_aalgs[i].xform);
8297 const struct comp_algo *
8298 comp_algorithm_lookup(int alg)
8302 for (i = 0; i < nitems(supported_calgs); i++)
8303 if (alg == supported_calgs[i].sadb_alg)
8304 return (supported_calgs[i].xform);
8309 * Register a transform.
8312 xform_register(struct xformsw* xsp)
8314 struct xformsw *entry;
8317 LIST_FOREACH(entry, &xforms, chain) {
8318 if (entry->xf_type == xsp->xf_type) {
8323 LIST_INSERT_HEAD(&xforms, xsp, chain);
8329 xform_attach(void *data)
8331 struct xformsw *xsp = (struct xformsw *)data;
8333 if (xform_register(xsp) != 0)
8334 printf("%s: failed to register %s xform\n", __func__,
8339 xform_detach(void *data)
8341 struct xformsw *xsp = (struct xformsw *)data;
8344 LIST_REMOVE(xsp, chain);
8347 /* Delete all SAs related to this xform. */
8348 key_delete_xform(xsp);
8352 * Initialize transform support in an sav.
8355 xform_init(struct secasvar *sav, u_short xftype)
8357 struct xformsw *entry;
8360 IPSEC_ASSERT(sav->tdb_xform == NULL,
8361 ("tdb_xform is already initialized"));
8365 LIST_FOREACH(entry, &xforms, chain) {
8366 if (entry->xf_type == xftype) {
8367 ret = (*entry->xf_init)(sav, entry);