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>
46 #include <sys/mutex.h>
48 #include <sys/domain.h>
49 #include <sys/protosw.h>
50 #include <sys/malloc.h>
51 #include <sys/rmlock.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/sysctl.h>
55 #include <sys/errno.h>
57 #include <sys/queue.h>
58 #include <sys/refcount.h>
59 #include <sys/syslog.h>
62 #include <net/if_var.h>
64 #include <net/raw_cb.h>
66 #include <netinet/in.h>
67 #include <netinet/in_systm.h>
68 #include <netinet/ip.h>
69 #include <netinet/in_var.h>
72 #include <netinet/ip6.h>
73 #include <netinet6/in6_var.h>
74 #include <netinet6/ip6_var.h>
77 #if defined(INET) || defined(INET6)
78 #include <netinet/in_pcb.h>
81 #include <netinet6/in6_pcb.h>
84 #include <net/pfkeyv2.h>
85 #include <netipsec/keydb.h>
86 #include <netipsec/key.h>
87 #include <netipsec/keysock.h>
88 #include <netipsec/key_debug.h>
90 #include <netipsec/ipsec.h>
92 #include <netipsec/ipsec6.h>
95 #include <netipsec/xform.h>
97 #include <machine/stdarg.h>
100 #include <sys/random.h>
102 #define FULLMASK 0xff
103 #define _BITS(bytes) ((bytes) << 3)
106 * Note on SA reference counting:
107 * - SAs that are not in DEAD state will have (total external reference + 1)
108 * following value in reference count field. they cannot be freed and are
109 * referenced from SA header.
110 * - SAs that are in DEAD state will have (total external reference)
111 * in reference count field. they are ready to be freed. reference from
112 * SA header will be removed in key_delsav(), when the reference count
113 * field hits 0 (= no external reference other than from SA header.
116 VNET_DEFINE(u_int32_t, key_debug_level) = 0;
117 static VNET_DEFINE(u_int, key_spi_trycnt) = 1000;
118 static VNET_DEFINE(u_int32_t, key_spi_minval) = 0x100;
119 static VNET_DEFINE(u_int32_t, key_spi_maxval) = 0x0fffffff; /* XXX */
120 static VNET_DEFINE(u_int32_t, policy_id) = 0;
121 /*interval to initialize randseed,1(m)*/
122 static VNET_DEFINE(u_int, key_int_random) = 60;
123 /* interval to expire acquiring, 30(s)*/
124 static VNET_DEFINE(u_int, key_larval_lifetime) = 30;
125 /* counter for blocking SADB_ACQUIRE.*/
126 static VNET_DEFINE(int, key_blockacq_count) = 10;
127 /* lifetime for blocking SADB_ACQUIRE.*/
128 static VNET_DEFINE(int, key_blockacq_lifetime) = 20;
129 /* preferred old sa rather than new sa.*/
130 static VNET_DEFINE(int, key_preferred_oldsa) = 1;
131 #define V_key_spi_trycnt VNET(key_spi_trycnt)
132 #define V_key_spi_minval VNET(key_spi_minval)
133 #define V_key_spi_maxval VNET(key_spi_maxval)
134 #define V_policy_id VNET(policy_id)
135 #define V_key_int_random VNET(key_int_random)
136 #define V_key_larval_lifetime VNET(key_larval_lifetime)
137 #define V_key_blockacq_count VNET(key_blockacq_count)
138 #define V_key_blockacq_lifetime VNET(key_blockacq_lifetime)
139 #define V_key_preferred_oldsa VNET(key_preferred_oldsa)
141 static VNET_DEFINE(u_int32_t, acq_seq) = 0;
142 #define V_acq_seq VNET(acq_seq)
145 static VNET_DEFINE(TAILQ_HEAD(_sptree, secpolicy), sptree[IPSEC_DIR_MAX]);
146 static struct rmlock sptree_lock;
147 #define V_sptree VNET(sptree)
148 #define SPTREE_LOCK_INIT() rm_init(&sptree_lock, "sptree")
149 #define SPTREE_LOCK_DESTROY() rm_destroy(&sptree_lock)
150 #define SPTREE_RLOCK_TRACKER struct rm_priotracker sptree_tracker
151 #define SPTREE_RLOCK() rm_rlock(&sptree_lock, &sptree_tracker)
152 #define SPTREE_RUNLOCK() rm_runlock(&sptree_lock, &sptree_tracker)
153 #define SPTREE_RLOCK_ASSERT() rm_assert(&sptree_lock, RA_RLOCKED)
154 #define SPTREE_WLOCK() rm_wlock(&sptree_lock)
155 #define SPTREE_WUNLOCK() rm_wunlock(&sptree_lock)
156 #define SPTREE_WLOCK_ASSERT() rm_assert(&sptree_lock, RA_WLOCKED)
157 #define SPTREE_UNLOCK_ASSERT() rm_assert(&sptree_lock, RA_UNLOCKED)
159 static VNET_DEFINE(LIST_HEAD(_sahtree, secashead), sahtree); /* SAD */
160 #define V_sahtree VNET(sahtree)
161 static struct mtx sahtree_lock;
162 #define SAHTREE_LOCK_INIT() \
163 mtx_init(&sahtree_lock, "sahtree", \
164 "fast ipsec security association database", MTX_DEF)
165 #define SAHTREE_LOCK_DESTROY() mtx_destroy(&sahtree_lock)
166 #define SAHTREE_LOCK() mtx_lock(&sahtree_lock)
167 #define SAHTREE_UNLOCK() mtx_unlock(&sahtree_lock)
168 #define SAHTREE_LOCK_ASSERT() mtx_assert(&sahtree_lock, MA_OWNED)
171 static VNET_DEFINE(LIST_HEAD(_regtree, secreg), regtree[SADB_SATYPE_MAX + 1]);
172 #define V_regtree VNET(regtree)
173 static struct mtx regtree_lock;
174 #define REGTREE_LOCK_INIT() \
175 mtx_init(®tree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
176 #define REGTREE_LOCK_DESTROY() mtx_destroy(®tree_lock)
177 #define REGTREE_LOCK() mtx_lock(®tree_lock)
178 #define REGTREE_UNLOCK() mtx_unlock(®tree_lock)
179 #define REGTREE_LOCK_ASSERT() mtx_assert(®tree_lock, MA_OWNED)
181 static VNET_DEFINE(LIST_HEAD(_acqtree, secacq), acqtree); /* acquiring list */
182 #define V_acqtree VNET(acqtree)
183 static struct mtx acq_lock;
184 #define ACQ_LOCK_INIT() \
185 mtx_init(&acq_lock, "acqtree", "fast ipsec acquire list", MTX_DEF)
186 #define ACQ_LOCK_DESTROY() mtx_destroy(&acq_lock)
187 #define ACQ_LOCK() mtx_lock(&acq_lock)
188 #define ACQ_UNLOCK() mtx_unlock(&acq_lock)
189 #define ACQ_LOCK_ASSERT() mtx_assert(&acq_lock, MA_OWNED)
191 /* SP acquiring list */
192 static VNET_DEFINE(LIST_HEAD(_spacqtree, secspacq), spacqtree);
193 #define V_spacqtree VNET(spacqtree)
194 static struct mtx spacq_lock;
195 #define SPACQ_LOCK_INIT() \
196 mtx_init(&spacq_lock, "spacqtree", \
197 "fast ipsec security policy acquire list", MTX_DEF)
198 #define SPACQ_LOCK_DESTROY() mtx_destroy(&spacq_lock)
199 #define SPACQ_LOCK() mtx_lock(&spacq_lock)
200 #define SPACQ_UNLOCK() mtx_unlock(&spacq_lock)
201 #define SPACQ_LOCK_ASSERT() mtx_assert(&spacq_lock, MA_OWNED)
203 /* search order for SAs */
204 static const u_int saorder_state_valid_prefer_old[] = {
205 SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
207 static const u_int saorder_state_valid_prefer_new[] = {
208 SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
210 static const u_int saorder_state_alive[] = {
212 SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
214 static const u_int saorder_state_any[] = {
215 SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
216 SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
219 static const int minsize[] = {
220 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
221 sizeof(struct sadb_sa), /* SADB_EXT_SA */
222 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
223 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
224 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
225 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_SRC */
226 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_DST */
227 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_PROXY */
228 sizeof(struct sadb_key), /* SADB_EXT_KEY_AUTH */
229 sizeof(struct sadb_key), /* SADB_EXT_KEY_ENCRYPT */
230 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_SRC */
231 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_DST */
232 sizeof(struct sadb_sens), /* SADB_EXT_SENSITIVITY */
233 sizeof(struct sadb_prop), /* SADB_EXT_PROPOSAL */
234 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_AUTH */
235 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_ENCRYPT */
236 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
237 0, /* SADB_X_EXT_KMPRIVATE */
238 sizeof(struct sadb_x_policy), /* SADB_X_EXT_POLICY */
239 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
240 sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
241 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
242 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
243 sizeof(struct sadb_address), /* SADB_X_EXT_NAT_T_OAI */
244 sizeof(struct sadb_address), /* SADB_X_EXT_NAT_T_OAR */
245 sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
247 static const int maxsize[] = {
248 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
249 sizeof(struct sadb_sa), /* SADB_EXT_SA */
250 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
251 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
252 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
253 0, /* SADB_EXT_ADDRESS_SRC */
254 0, /* SADB_EXT_ADDRESS_DST */
255 0, /* SADB_EXT_ADDRESS_PROXY */
256 0, /* SADB_EXT_KEY_AUTH */
257 0, /* SADB_EXT_KEY_ENCRYPT */
258 0, /* SADB_EXT_IDENTITY_SRC */
259 0, /* SADB_EXT_IDENTITY_DST */
260 0, /* SADB_EXT_SENSITIVITY */
261 0, /* SADB_EXT_PROPOSAL */
262 0, /* SADB_EXT_SUPPORTED_AUTH */
263 0, /* SADB_EXT_SUPPORTED_ENCRYPT */
264 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
265 0, /* SADB_X_EXT_KMPRIVATE */
266 0, /* SADB_X_EXT_POLICY */
267 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
268 sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
269 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
270 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
271 0, /* SADB_X_EXT_NAT_T_OAI */
272 0, /* SADB_X_EXT_NAT_T_OAR */
273 sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
276 static VNET_DEFINE(int, ipsec_esp_keymin) = 256;
277 static VNET_DEFINE(int, ipsec_esp_auth) = 0;
278 static VNET_DEFINE(int, ipsec_ah_keymin) = 128;
280 #define V_ipsec_esp_keymin VNET(ipsec_esp_keymin)
281 #define V_ipsec_esp_auth VNET(ipsec_esp_auth)
282 #define V_ipsec_ah_keymin VNET(ipsec_ah_keymin)
285 SYSCTL_DECL(_net_key);
288 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL, debug,
289 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_debug_level), 0, "");
291 /* max count of trial for the decision of spi value */
292 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt,
293 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_trycnt), 0, "");
295 /* minimum spi value to allocate automatically. */
296 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE, spi_minval,
297 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_minval), 0, "");
299 /* maximun spi value to allocate automatically. */
300 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE, spi_maxval,
301 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_maxval), 0, "");
303 /* interval to initialize randseed */
304 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random,
305 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_int_random), 0, "");
307 /* lifetime for larval SA */
308 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME, larval_lifetime,
309 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_larval_lifetime), 0, "");
311 /* counter for blocking to send SADB_ACQUIRE to IKEd */
312 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT, blockacq_count,
313 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_blockacq_count), 0, "");
315 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
316 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME, blockacq_lifetime,
317 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_blockacq_lifetime), 0, "");
320 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH, esp_auth,
321 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_esp_auth), 0, "");
323 /* minimum ESP key length */
324 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin,
325 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_esp_keymin), 0, "");
327 /* minimum AH key length */
328 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN, ah_keymin,
329 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_ah_keymin), 0, "");
331 /* perfered old SA rather than new SA */
332 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA, preferred_oldsa,
333 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_preferred_oldsa), 0, "");
335 #define __LIST_CHAINED(elm) \
336 (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
337 #define LIST_INSERT_TAIL(head, elm, type, field) \
339 struct type *curelm = LIST_FIRST(head); \
340 if (curelm == NULL) {\
341 LIST_INSERT_HEAD(head, elm, field); \
343 while (LIST_NEXT(curelm, field)) \
344 curelm = LIST_NEXT(curelm, field);\
345 LIST_INSERT_AFTER(curelm, elm, field);\
349 #define KEY_CHKSASTATE(head, sav, name) \
351 if ((head) != (sav)) { \
352 ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
353 (name), (head), (sav))); \
358 #define KEY_CHKSPDIR(head, sp, name) \
360 if ((head) != (sp)) { \
361 ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
362 "anyway continue.\n", \
363 (name), (head), (sp))); \
367 MALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
368 MALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
369 MALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
370 MALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
371 MALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
372 MALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
373 MALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
376 * set parameters into secpolicyindex buffer.
377 * Must allocate secpolicyindex buffer passed to this function.
379 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
381 bzero((idx), sizeof(struct secpolicyindex)); \
382 (idx)->dir = (_dir); \
383 (idx)->prefs = (ps); \
384 (idx)->prefd = (pd); \
385 (idx)->ul_proto = (ulp); \
386 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
387 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
391 * set parameters into secasindex buffer.
392 * Must allocate secasindex buffer before calling this function.
394 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
396 bzero((idx), sizeof(struct secasindex)); \
397 (idx)->proto = (p); \
399 (idx)->reqid = (r); \
400 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
401 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
406 u_long getspi_count; /* the avarage of count to try to get new SPI */
410 struct sadb_msg *msg;
411 struct sadb_ext *ext[SADB_EXT_MAX + 1];
412 int extoff[SADB_EXT_MAX + 1];
413 int extlen[SADB_EXT_MAX + 1];
417 static struct callout key_timer;
420 static struct secasvar *key_allocsa_policy(const struct secasindex *);
421 static void key_freesp_so(struct secpolicy **);
422 static struct secasvar *key_do_allocsa_policy(struct secashead *, u_int);
423 static void key_unlink(struct secpolicy *);
424 static struct secpolicy *key_getsp(struct secpolicyindex *);
425 static struct secpolicy *key_getspbyid(u_int32_t);
426 static u_int32_t key_newreqid(void);
427 static struct mbuf *key_gather_mbuf(struct mbuf *,
428 const struct sadb_msghdr *, int, int, ...);
429 static int key_spdadd(struct socket *, struct mbuf *,
430 const struct sadb_msghdr *);
431 static u_int32_t key_getnewspid(void);
432 static int key_spddelete(struct socket *, struct mbuf *,
433 const struct sadb_msghdr *);
434 static int key_spddelete2(struct socket *, struct mbuf *,
435 const struct sadb_msghdr *);
436 static int key_spdget(struct socket *, struct mbuf *,
437 const struct sadb_msghdr *);
438 static int key_spdflush(struct socket *, struct mbuf *,
439 const struct sadb_msghdr *);
440 static int key_spddump(struct socket *, struct mbuf *,
441 const struct sadb_msghdr *);
442 static struct mbuf *key_setdumpsp(struct secpolicy *,
443 u_int8_t, u_int32_t, u_int32_t);
444 static u_int key_getspreqmsglen(struct secpolicy *);
445 static int key_spdexpire(struct secpolicy *);
446 static struct secashead *key_newsah(struct secasindex *);
447 static void key_delsah(struct secashead *);
448 static struct secasvar *key_newsav(struct mbuf *,
449 const struct sadb_msghdr *, struct secashead *, int *,
451 #define KEY_NEWSAV(m, sadb, sah, e) \
452 key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
453 static void key_delsav(struct secasvar *);
454 static struct secashead *key_getsah(struct secasindex *);
455 static struct secasvar *key_checkspidup(struct secasindex *, u_int32_t);
456 static struct secasvar *key_getsavbyspi(struct secashead *, u_int32_t);
457 static int key_setsaval(struct secasvar *, struct mbuf *,
458 const struct sadb_msghdr *);
459 static int key_mature(struct secasvar *);
460 static struct mbuf *key_setdumpsa(struct secasvar *, u_int8_t,
461 u_int8_t, u_int32_t, u_int32_t);
462 static struct mbuf *key_setsadbmsg(u_int8_t, u_int16_t, u_int8_t,
463 u_int32_t, pid_t, u_int16_t);
464 static struct mbuf *key_setsadbsa(struct secasvar *);
465 static struct mbuf *key_setsadbaddr(u_int16_t,
466 const struct sockaddr *, u_int8_t, u_int16_t);
468 static struct mbuf *key_setsadbxport(u_int16_t, u_int16_t);
469 static struct mbuf *key_setsadbxtype(u_int16_t);
471 static void key_porttosaddr(struct sockaddr *, u_int16_t);
472 #define KEY_PORTTOSADDR(saddr, port) \
473 key_porttosaddr((struct sockaddr *)(saddr), (port))
474 static struct mbuf *key_setsadbxsa2(u_int8_t, u_int32_t, u_int32_t);
475 static struct mbuf *key_setsadbxpolicy(u_int16_t, u_int8_t,
477 static struct seckey *key_dup_keymsg(const struct sadb_key *, u_int,
478 struct malloc_type *);
479 static struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
480 struct malloc_type *type);
482 static int key_ismyaddr6(struct sockaddr_in6 *);
485 /* flags for key_cmpsaidx() */
486 #define CMP_HEAD 1 /* protocol, addresses. */
487 #define CMP_MODE_REQID 2 /* additionally HEAD, reqid, mode. */
488 #define CMP_REQID 3 /* additionally HEAD, reaid. */
489 #define CMP_EXACTLY 4 /* all elements. */
490 static int key_cmpsaidx(const struct secasindex *,
491 const struct secasindex *, int);
492 static int key_cmpspidx_exactly(struct secpolicyindex *,
493 struct secpolicyindex *);
494 static int key_cmpspidx_withmask(struct secpolicyindex *,
495 struct secpolicyindex *);
496 static int key_sockaddrcmp(const struct sockaddr *,
497 const struct sockaddr *, int);
498 static int key_bbcmp(const void *, const void *, u_int);
499 static u_int16_t key_satype2proto(u_int8_t);
500 static u_int8_t key_proto2satype(u_int16_t);
502 static int key_getspi(struct socket *, struct mbuf *,
503 const struct sadb_msghdr *);
504 static u_int32_t key_do_getnewspi(struct sadb_spirange *,
505 struct secasindex *);
506 static int key_update(struct socket *, struct mbuf *,
507 const struct sadb_msghdr *);
508 #ifdef IPSEC_DOSEQCHECK
509 static struct secasvar *key_getsavbyseq(struct secashead *, u_int32_t);
511 static int key_add(struct socket *, struct mbuf *,
512 const struct sadb_msghdr *);
513 static int key_setident(struct secashead *, struct mbuf *,
514 const struct sadb_msghdr *);
515 static struct mbuf *key_getmsgbuf_x1(struct mbuf *,
516 const struct sadb_msghdr *);
517 static int key_delete(struct socket *, struct mbuf *,
518 const struct sadb_msghdr *);
519 static int key_delete_all(struct socket *, struct mbuf *,
520 const struct sadb_msghdr *, u_int16_t);
521 static int key_get(struct socket *, struct mbuf *,
522 const struct sadb_msghdr *);
524 static void key_getcomb_setlifetime(struct sadb_comb *);
525 static struct mbuf *key_getcomb_esp(void);
526 static struct mbuf *key_getcomb_ah(void);
527 static struct mbuf *key_getcomb_ipcomp(void);
528 static struct mbuf *key_getprop(const struct secasindex *);
530 static int key_acquire(const struct secasindex *, struct secpolicy *);
531 static struct secacq *key_newacq(const struct secasindex *);
532 static struct secacq *key_getacq(const struct secasindex *);
533 static struct secacq *key_getacqbyseq(u_int32_t);
534 static struct secspacq *key_newspacq(struct secpolicyindex *);
535 static struct secspacq *key_getspacq(struct secpolicyindex *);
536 static int key_acquire2(struct socket *, struct mbuf *,
537 const struct sadb_msghdr *);
538 static int key_register(struct socket *, struct mbuf *,
539 const struct sadb_msghdr *);
540 static int key_expire(struct secasvar *);
541 static int key_flush(struct socket *, struct mbuf *,
542 const struct sadb_msghdr *);
543 static int key_dump(struct socket *, struct mbuf *,
544 const struct sadb_msghdr *);
545 static int key_promisc(struct socket *, struct mbuf *,
546 const struct sadb_msghdr *);
547 static int key_senderror(struct socket *, struct mbuf *, int);
548 static int key_validate_ext(const struct sadb_ext *, int);
549 static int key_align(struct mbuf *, struct sadb_msghdr *);
550 static struct mbuf *key_setlifetime(struct seclifetime *src,
552 static struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
555 static const char *key_getfqdn(void);
556 static const char *key_getuserfqdn(void);
558 static void key_sa_chgstate(struct secasvar *, u_int8_t);
561 sa_initref(struct secasvar *sav)
564 refcount_init(&sav->refcnt, 1);
567 sa_addref(struct secasvar *sav)
570 refcount_acquire(&sav->refcnt);
571 IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
574 sa_delref(struct secasvar *sav)
577 IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
578 return (refcount_release(&sav->refcnt));
581 #define SP_ADDREF(p) refcount_acquire(&(p)->refcnt)
582 #define SP_DELREF(p) refcount_release(&(p)->refcnt)
585 * Update the refcnt while holding the SPTREE lock.
588 key_addref(struct secpolicy *sp)
595 * Return 0 when there are known to be no SP's for the specified
596 * direction. Otherwise return 1. This is used by IPsec code
597 * to optimize performance.
600 key_havesp(u_int dir)
603 return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
604 TAILQ_FIRST(&V_sptree[dir]) != NULL : 1);
607 /* %%% IPsec policy management */
609 * allocating a SP for OUTBOUND or INBOUND packet.
610 * Must call key_freesp() later.
611 * OUT: NULL: not found
612 * others: found and return the pointer.
615 key_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where,
618 SPTREE_RLOCK_TRACKER;
619 struct secpolicy *sp;
621 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
622 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
623 ("invalid direction %u", dir));
625 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
626 printf("DP %s from %s:%u\n", __func__, where, tag));
629 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
630 printf("*** objects\n");
631 kdebug_secpolicyindex(spidx));
634 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
635 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
636 printf("*** in SPD\n");
637 kdebug_secpolicyindex(&sp->spidx));
638 if (key_cmpspidx_withmask(&sp->spidx, spidx))
645 KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
647 /* found a SPD entry */
648 sp->lastused = time_second;
653 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
654 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
655 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
660 * allocating a SP for OUTBOUND or INBOUND packet.
661 * Must call key_freesp() later.
662 * OUT: NULL: not found
663 * others: found and return the pointer.
666 key_allocsp2(u_int32_t spi, union sockaddr_union *dst, u_int8_t proto,
667 u_int dir, const char* where, int tag)
669 SPTREE_RLOCK_TRACKER;
670 struct secpolicy *sp;
672 IPSEC_ASSERT(dst != NULL, ("null dst"));
673 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
674 ("invalid direction %u", dir));
676 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
677 printf("DP %s from %s:%u\n", __func__, where, tag));
680 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
681 printf("*** objects\n");
682 printf("spi %u proto %u dir %u\n", spi, proto, dir);
683 kdebug_sockaddr(&dst->sa));
686 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
687 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
688 printf("*** in SPD\n");
689 kdebug_secpolicyindex(&sp->spidx));
690 /* compare simple values, then dst address */
691 if (sp->spidx.ul_proto != proto)
693 /* NB: spi's must exist and match */
694 if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
696 if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
703 KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
705 /* found a SPD entry */
706 sp->lastused = time_second;
711 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
712 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
713 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
719 * return a policy that matches this particular inbound packet.
723 key_gettunnel(const struct sockaddr *osrc,
724 const struct sockaddr *odst,
725 const struct sockaddr *isrc,
726 const struct sockaddr *idst,
727 const char* where, int tag)
729 struct secpolicy *sp;
730 const int dir = IPSEC_DIR_INBOUND;
731 struct ipsecrequest *r1, *r2, *p;
732 struct secpolicyindex spidx;
734 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
735 printf("DP %s from %s:%u\n", __func__, where, tag));
737 if (isrc->sa_family != idst->sa_family) {
738 ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
739 __func__, isrc->sa_family, idst->sa_family));
745 LIST_FOREACH(sp, &V_sptree[dir], chain) {
746 if (sp->state == IPSEC_SPSTATE_DEAD)
750 for (p = sp->req; p; p = p->next) {
751 if (p->saidx.mode != IPSEC_MODE_TUNNEL)
758 /* here we look at address matches only */
760 if (isrc->sa_len > sizeof(spidx.src) ||
761 idst->sa_len > sizeof(spidx.dst))
763 bcopy(isrc, &spidx.src, isrc->sa_len);
764 bcopy(idst, &spidx.dst, idst->sa_len);
765 if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
768 if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
769 key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
773 if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
774 key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
783 sp->lastused = time_second;
788 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
789 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
790 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
796 * allocating an SA entry for an *OUTBOUND* packet.
797 * checking each request entries in SP, and acquire an SA if need.
798 * OUT: 0: there are valid requests.
799 * ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
802 key_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
806 struct secasvar *sav;
808 IPSEC_ASSERT(isr != NULL, ("null isr"));
809 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
810 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
811 saidx->mode == IPSEC_MODE_TUNNEL,
812 ("unexpected policy %u", saidx->mode));
815 * XXX guard against protocol callbacks from the crypto
816 * thread as they reference ipsecrequest.sav which we
817 * temporarily null out below. Need to rethink how we
818 * handle bundled SA's in the callback thread.
820 IPSECREQUEST_LOCK_ASSERT(isr);
822 /* get current level */
823 level = ipsec_get_reqlevel(isr);
826 * We check new SA in the IPsec request because a different
827 * SA may be involved each time this request is checked, either
828 * because new SAs are being configured, or this request is
829 * associated with an unconnected datagram socket, or this request
830 * is associated with a system default policy.
832 * key_allocsa_policy should allocate the oldest SA available.
833 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
835 sav = key_allocsa_policy(saidx);
836 if (sav != isr->sav) {
837 /* SA need to be updated. */
838 if (!IPSECREQUEST_UPGRADE(isr)) {
839 /* Kick everyone off. */
840 IPSECREQUEST_UNLOCK(isr);
841 IPSECREQUEST_WLOCK(isr);
843 if (isr->sav != NULL)
844 KEY_FREESAV(&isr->sav);
846 IPSECREQUEST_DOWNGRADE(isr);
847 } else if (sav != NULL)
850 /* When there is SA. */
851 if (isr->sav != NULL) {
852 if (isr->sav->state != SADB_SASTATE_MATURE &&
853 isr->sav->state != SADB_SASTATE_DYING)
859 error = key_acquire(saidx, isr->sp);
861 /* XXX What should I do ? */
862 ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
867 if (level != IPSEC_LEVEL_REQUIRE) {
868 /* XXX sigh, the interface to this routine is botched */
869 IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
877 * allocating a SA for policy entry from SAD.
878 * NOTE: searching SAD of aliving state.
879 * OUT: NULL: not found.
880 * others: found and return the pointer.
882 static struct secasvar *
883 key_allocsa_policy(const struct secasindex *saidx)
885 #define N(a) _ARRAYLEN(a)
886 struct secashead *sah;
887 struct secasvar *sav;
888 u_int stateidx, arraysize;
889 const u_int *state_valid;
891 state_valid = NULL; /* silence gcc */
892 arraysize = 0; /* silence gcc */
895 LIST_FOREACH(sah, &V_sahtree, chain) {
896 if (sah->state == SADB_SASTATE_DEAD)
898 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
899 if (V_key_preferred_oldsa) {
900 state_valid = saorder_state_valid_prefer_old;
901 arraysize = N(saorder_state_valid_prefer_old);
903 state_valid = saorder_state_valid_prefer_new;
904 arraysize = N(saorder_state_valid_prefer_new);
913 /* search valid state */
914 for (stateidx = 0; stateidx < arraysize; stateidx++) {
915 sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
925 * searching SAD with direction, protocol, mode and state.
926 * called by key_allocsa_policy().
929 * others : found, pointer to a SA.
931 static struct secasvar *
932 key_do_allocsa_policy(struct secashead *sah, u_int state)
934 struct secasvar *sav, *nextsav, *candidate, *d;
940 for (sav = LIST_FIRST(&sah->savtree[state]);
944 nextsav = LIST_NEXT(sav, chain);
947 KEY_CHKSASTATE(sav->state, state, __func__);
950 if (candidate == NULL) {
955 /* Which SA is the better ? */
957 IPSEC_ASSERT(candidate->lft_c != NULL,
958 ("null candidate lifetime"));
959 IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
961 /* What the best method is to compare ? */
962 if (V_key_preferred_oldsa) {
963 if (candidate->lft_c->addtime >
964 sav->lft_c->addtime) {
971 /* preferred new sa rather than old sa */
972 if (candidate->lft_c->addtime <
973 sav->lft_c->addtime) {
980 * prepared to delete the SA when there is more
981 * suitable candidate and the lifetime of the SA is not
984 if (d->lft_h->addtime != 0) {
985 struct mbuf *m, *result;
988 key_sa_chgstate(d, SADB_SASTATE_DEAD);
990 IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
992 satype = key_proto2satype(d->sah->saidx.proto);
996 m = key_setsadbmsg(SADB_DELETE, 0,
997 satype, 0, 0, d->refcnt - 1);
1002 /* set sadb_address for saidx's. */
1003 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
1004 &d->sah->saidx.src.sa,
1005 d->sah->saidx.src.sa.sa_len << 3,
1011 /* set sadb_address for saidx's. */
1012 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
1013 &d->sah->saidx.dst.sa,
1014 d->sah->saidx.dst.sa.sa_len << 3,
1020 /* create SA extension */
1021 m = key_setsadbsa(d);
1026 if (result->m_len < sizeof(struct sadb_msg)) {
1027 result = m_pullup(result,
1028 sizeof(struct sadb_msg));
1033 result->m_pkthdr.len = 0;
1034 for (m = result; m; m = m->m_next)
1035 result->m_pkthdr.len += m->m_len;
1036 mtod(result, struct sadb_msg *)->sadb_msg_len =
1037 PFKEY_UNIT64(result->m_pkthdr.len);
1039 if (key_sendup_mbuf(NULL, result,
1040 KEY_SENDUP_REGISTERED))
1047 sa_addref(candidate);
1048 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1049 printf("DP %s cause refcnt++:%d SA:%p\n",
1050 __func__, candidate->refcnt, candidate));
1058 * allocating a usable SA entry for a *INBOUND* packet.
1059 * Must call key_freesav() later.
1060 * OUT: positive: pointer to a usable sav (i.e. MATURE or DYING state).
1061 * NULL: not found, or error occured.
1063 * In the comparison, no source address is used--for RFC2401 conformance.
1064 * To quote, from section 4.1:
1065 * A security association is uniquely identified by a triple consisting
1066 * of a Security Parameter Index (SPI), an IP Destination Address, and a
1067 * security protocol (AH or ESP) identifier.
1068 * Note that, however, we do need to keep source address in IPsec SA.
1069 * IKE specification and PF_KEY specification do assume that we
1070 * keep source address in IPsec SA. We see a tricky situation here.
1073 key_allocsa(union sockaddr_union *dst, u_int proto, u_int32_t spi,
1074 const char* where, int tag)
1076 struct secashead *sah;
1077 struct secasvar *sav;
1078 u_int stateidx, arraysize, state;
1079 const u_int *saorder_state_valid;
1084 IPSEC_ASSERT(dst != NULL, ("null dst address"));
1086 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1087 printf("DP %s from %s:%u\n", __func__, where, tag));
1090 natt_chkport = (dst->sa.sa_family == AF_INET &&
1091 dst->sa.sa_len == sizeof(struct sockaddr_in) &&
1092 dst->sin.sin_port != 0);
1097 * XXX: to be checked internal IP header somewhere. Also when
1098 * IPsec tunnel packet is received. But ESP tunnel mode is
1099 * encrypted so we can't check internal IP header.
1102 if (V_key_preferred_oldsa) {
1103 saorder_state_valid = saorder_state_valid_prefer_old;
1104 arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1106 saorder_state_valid = saorder_state_valid_prefer_new;
1107 arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1109 LIST_FOREACH(sah, &V_sahtree, chain) {
1112 /* search valid state */
1113 for (stateidx = 0; stateidx < arraysize; stateidx++) {
1114 state = saorder_state_valid[stateidx];
1115 LIST_FOREACH(sav, &sah->savtree[state], chain) {
1117 KEY_CHKSASTATE(sav->state, state, __func__);
1118 /* do not return entries w/ unusable state */
1119 if (sav->state != SADB_SASTATE_MATURE &&
1120 sav->state != SADB_SASTATE_DYING)
1122 if (proto != sav->sah->saidx.proto)
1124 if (spi != sav->spi)
1129 * Really only check ports when this is a NAT-T
1130 * SA. Otherwise other lookups providing ports
1133 if (sav->natt_type && natt_chkport)
1136 #if 0 /* don't check src */
1137 /* check src address */
1138 if (key_sockaddrcmp(&src->sa,
1139 &sav->sah->saidx.src.sa, checkport) != 0)
1142 /* check dst address */
1143 if (key_sockaddrcmp(&dst->sa,
1144 &sav->sah->saidx.dst.sa, checkport) != 0)
1155 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1156 printf("DP %s return SA:%p; refcnt %u\n", __func__,
1157 sav, sav ? sav->refcnt : 0));
1162 * Must be called after calling key_allocsp().
1163 * For both the packet without socket and key_freeso().
1166 _key_freesp(struct secpolicy **spp, const char* where, int tag)
1168 struct ipsecrequest *isr, *nextisr;
1169 struct secpolicy *sp = *spp;
1171 IPSEC_ASSERT(sp != NULL, ("null sp"));
1172 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1173 printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1174 __func__, sp, sp->id, where, tag, sp->refcnt));
1176 if (SP_DELREF(sp) == 0)
1179 for (isr = sp->req; isr != NULL; isr = nextisr) {
1180 if (isr->sav != NULL) {
1181 KEY_FREESAV(&isr->sav);
1184 nextisr = isr->next;
1187 free(sp, M_IPSEC_SP);
1191 key_unlink(struct secpolicy *sp)
1194 IPSEC_ASSERT(sp != NULL, ("null sp"));
1195 IPSEC_ASSERT(sp->spidx.dir == IPSEC_DIR_INBOUND ||
1196 sp->spidx.dir == IPSEC_DIR_OUTBOUND,
1197 ("invalid direction %u", sp->spidx.dir));
1198 SPTREE_UNLOCK_ASSERT();
1201 if (sp->state == IPSEC_SPSTATE_DEAD) {
1205 sp->state = IPSEC_SPSTATE_DEAD;
1206 TAILQ_REMOVE(&V_sptree[sp->spidx.dir], sp, chain);
1212 * Must be called after calling key_allocsp().
1213 * For the packet with socket.
1216 key_freeso(struct socket *so)
1218 IPSEC_ASSERT(so != NULL, ("null so"));
1220 switch (so->so_proto->pr_domain->dom_family) {
1221 #if defined(INET) || defined(INET6)
1229 struct inpcb *pcb = sotoinpcb(so);
1231 /* Does it have a PCB ? */
1234 key_freesp_so(&pcb->inp_sp->sp_in);
1235 key_freesp_so(&pcb->inp_sp->sp_out);
1238 #endif /* INET || INET6 */
1240 ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
1241 __func__, so->so_proto->pr_domain->dom_family));
1247 key_freesp_so(struct secpolicy **sp)
1249 IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
1251 if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1252 (*sp)->policy == IPSEC_POLICY_BYPASS)
1255 IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1256 ("invalid policy %u", (*sp)->policy));
1261 key_addrefsa(struct secasvar *sav, const char* where, int tag)
1264 IPSEC_ASSERT(sav != NULL, ("null sav"));
1265 IPSEC_ASSERT(sav->refcnt > 0, ("refcount must exist"));
1271 * Must be called after calling key_allocsa().
1272 * This function is called by key_freesp() to free some SA allocated
1276 key_freesav(struct secasvar **psav, const char* where, int tag)
1278 struct secasvar *sav = *psav;
1280 IPSEC_ASSERT(sav != NULL, ("null sav"));
1282 if (sa_delref(sav)) {
1283 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1284 printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1285 __func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1289 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1290 printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1291 __func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1295 /* %%% SPD management */
1298 * OUT: NULL : not found
1299 * others : found, pointer to a SP.
1301 static struct secpolicy *
1302 key_getsp(struct secpolicyindex *spidx)
1304 SPTREE_RLOCK_TRACKER;
1305 struct secpolicy *sp;
1307 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1310 TAILQ_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1311 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1323 * OUT: NULL : not found
1324 * others : found, pointer to a SP.
1326 static struct secpolicy *
1327 key_getspbyid(u_int32_t id)
1329 SPTREE_RLOCK_TRACKER;
1330 struct secpolicy *sp;
1333 TAILQ_FOREACH(sp, &V_sptree[IPSEC_DIR_INBOUND], chain) {
1340 TAILQ_FOREACH(sp, &V_sptree[IPSEC_DIR_OUTBOUND], chain) {
1353 key_newsp(const char* where, int tag)
1355 struct secpolicy *newsp = NULL;
1357 newsp = (struct secpolicy *)
1358 malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
1360 refcount_init(&newsp->refcnt, 1);
1362 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1363 printf("DP %s from %s:%u return SP:%p\n", __func__,
1364 where, tag, newsp));
1369 * create secpolicy structure from sadb_x_policy structure.
1370 * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1371 * so must be set properly later.
1374 key_msg2sp(struct sadb_x_policy *xpl0, size_t len, int *error)
1376 struct secpolicy *newsp;
1378 IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1379 IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1381 if (len != PFKEY_EXTLEN(xpl0)) {
1382 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1387 if ((newsp = KEY_NEWSP()) == NULL) {
1392 newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1393 newsp->policy = xpl0->sadb_x_policy_type;
1396 switch (xpl0->sadb_x_policy_type) {
1397 case IPSEC_POLICY_DISCARD:
1398 case IPSEC_POLICY_NONE:
1399 case IPSEC_POLICY_ENTRUST:
1400 case IPSEC_POLICY_BYPASS:
1404 case IPSEC_POLICY_IPSEC:
1407 struct sadb_x_ipsecrequest *xisr;
1408 struct ipsecrequest **p_isr = &newsp->req;
1410 /* validity check */
1411 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1412 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1419 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1420 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1424 if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1425 ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1426 "length.\n", __func__));
1432 /* allocate request buffer */
1433 /* NB: data structure is zero'd */
1434 *p_isr = ipsec_newisr();
1435 if ((*p_isr) == NULL) {
1436 ipseclog((LOG_DEBUG,
1437 "%s: No more memory.\n", __func__));
1444 switch (xisr->sadb_x_ipsecrequest_proto) {
1447 case IPPROTO_IPCOMP:
1450 ipseclog((LOG_DEBUG,
1451 "%s: invalid proto type=%u\n", __func__,
1452 xisr->sadb_x_ipsecrequest_proto));
1454 *error = EPROTONOSUPPORT;
1457 (*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1459 switch (xisr->sadb_x_ipsecrequest_mode) {
1460 case IPSEC_MODE_TRANSPORT:
1461 case IPSEC_MODE_TUNNEL:
1463 case IPSEC_MODE_ANY:
1465 ipseclog((LOG_DEBUG,
1466 "%s: invalid mode=%u\n", __func__,
1467 xisr->sadb_x_ipsecrequest_mode));
1472 (*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1474 switch (xisr->sadb_x_ipsecrequest_level) {
1475 case IPSEC_LEVEL_DEFAULT:
1476 case IPSEC_LEVEL_USE:
1477 case IPSEC_LEVEL_REQUIRE:
1479 case IPSEC_LEVEL_UNIQUE:
1480 /* validity check */
1482 * If range violation of reqid, kernel will
1483 * update it, don't refuse it.
1485 if (xisr->sadb_x_ipsecrequest_reqid
1486 > IPSEC_MANUAL_REQID_MAX) {
1487 ipseclog((LOG_DEBUG,
1488 "%s: reqid=%d range "
1489 "violation, updated by kernel.\n",
1491 xisr->sadb_x_ipsecrequest_reqid));
1492 xisr->sadb_x_ipsecrequest_reqid = 0;
1495 /* allocate new reqid id if reqid is zero. */
1496 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1498 if ((reqid = key_newreqid()) == 0) {
1503 (*p_isr)->saidx.reqid = reqid;
1504 xisr->sadb_x_ipsecrequest_reqid = reqid;
1506 /* set it for manual keying. */
1507 (*p_isr)->saidx.reqid =
1508 xisr->sadb_x_ipsecrequest_reqid;
1513 ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1515 xisr->sadb_x_ipsecrequest_level));
1520 (*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1522 /* set IP addresses if there */
1523 if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1524 struct sockaddr *paddr;
1526 paddr = (struct sockaddr *)(xisr + 1);
1528 /* validity check */
1530 > sizeof((*p_isr)->saidx.src)) {
1531 ipseclog((LOG_DEBUG, "%s: invalid "
1532 "request address length.\n",
1538 bcopy(paddr, &(*p_isr)->saidx.src,
1541 paddr = (struct sockaddr *)((caddr_t)paddr
1544 /* validity check */
1546 > sizeof((*p_isr)->saidx.dst)) {
1547 ipseclog((LOG_DEBUG, "%s: invalid "
1548 "request address length.\n",
1554 bcopy(paddr, &(*p_isr)->saidx.dst,
1558 (*p_isr)->sp = newsp;
1560 /* initialization for the next. */
1561 p_isr = &(*p_isr)->next;
1562 tlen -= xisr->sadb_x_ipsecrequest_len;
1564 /* validity check */
1566 ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1573 xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1574 + xisr->sadb_x_ipsecrequest_len);
1579 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1592 static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1594 auto_reqid = (auto_reqid == ~0
1595 ? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1597 /* XXX should be unique check */
1603 * copy secpolicy struct to sadb_x_policy structure indicated.
1606 key_sp2msg(struct secpolicy *sp)
1608 struct sadb_x_policy *xpl;
1613 IPSEC_ASSERT(sp != NULL, ("null policy"));
1615 tlen = key_getspreqmsglen(sp);
1617 m = m_get2(tlen, M_NOWAIT, MT_DATA, 0);
1622 xpl = mtod(m, struct sadb_x_policy *);
1625 xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1626 xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1627 xpl->sadb_x_policy_type = sp->policy;
1628 xpl->sadb_x_policy_dir = sp->spidx.dir;
1629 xpl->sadb_x_policy_id = sp->id;
1630 p = (caddr_t)xpl + sizeof(*xpl);
1632 /* if is the policy for ipsec ? */
1633 if (sp->policy == IPSEC_POLICY_IPSEC) {
1634 struct sadb_x_ipsecrequest *xisr;
1635 struct ipsecrequest *isr;
1637 for (isr = sp->req; isr != NULL; isr = isr->next) {
1639 xisr = (struct sadb_x_ipsecrequest *)p;
1641 xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1642 xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1643 xisr->sadb_x_ipsecrequest_level = isr->level;
1644 xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1647 bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1648 p += isr->saidx.src.sa.sa_len;
1649 bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1650 p += isr->saidx.src.sa.sa_len;
1652 xisr->sadb_x_ipsecrequest_len =
1653 PFKEY_ALIGN8(sizeof(*xisr)
1654 + isr->saidx.src.sa.sa_len
1655 + isr->saidx.dst.sa.sa_len);
1662 /* m will not be freed nor modified */
1663 static struct mbuf *
1664 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1665 int ndeep, int nitem, ...)
1670 struct mbuf *result = NULL, *n;
1673 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1674 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1676 va_start(ap, nitem);
1677 for (i = 0; i < nitem; i++) {
1678 idx = va_arg(ap, int);
1679 if (idx < 0 || idx > SADB_EXT_MAX)
1681 /* don't attempt to pull empty extension */
1682 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1684 if (idx != SADB_EXT_RESERVED &&
1685 (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1688 if (idx == SADB_EXT_RESERVED) {
1689 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1691 IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1693 MGETHDR(n, M_NOWAIT, MT_DATA);
1698 m_copydata(m, 0, sizeof(struct sadb_msg),
1700 } else if (i < ndeep) {
1701 len = mhp->extlen[idx];
1702 n = m_get2(len, M_NOWAIT, MT_DATA, 0);
1707 m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1710 n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1723 if ((result->m_flags & M_PKTHDR) != 0) {
1724 result->m_pkthdr.len = 0;
1725 for (n = result; n; n = n->m_next)
1726 result->m_pkthdr.len += n->m_len;
1738 * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1739 * add an entry to SP database, when received
1740 * <base, address(SD), (lifetime(H),) policy>
1742 * Adding to SP database,
1744 * <base, address(SD), (lifetime(H),) policy>
1745 * to the socket which was send.
1747 * SPDADD set a unique policy entry.
1748 * SPDSETIDX like SPDADD without a part of policy requests.
1749 * SPDUPDATE replace a unique policy entry.
1751 * m will always be freed.
1754 key_spdadd(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
1756 struct sadb_address *src0, *dst0;
1757 struct sadb_x_policy *xpl0, *xpl;
1758 struct sadb_lifetime *lft = NULL;
1759 struct secpolicyindex spidx;
1760 struct secpolicy *newsp;
1763 IPSEC_ASSERT(so != NULL, ("null socket"));
1764 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1765 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1766 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1768 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1769 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1770 mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1771 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1772 return key_senderror(so, m, EINVAL);
1774 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1775 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1776 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1777 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1779 return key_senderror(so, m, EINVAL);
1781 if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1782 if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1783 < sizeof(struct sadb_lifetime)) {
1784 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1786 return key_senderror(so, m, EINVAL);
1788 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1791 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1792 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1793 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1796 * Note: do not parse SADB_X_EXT_NAT_T_* here:
1797 * we are processing traffic endpoints.
1801 /* XXX boundary check against sa_len */
1802 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1805 src0->sadb_address_prefixlen,
1806 dst0->sadb_address_prefixlen,
1807 src0->sadb_address_proto,
1810 /* checking the direciton. */
1811 switch (xpl0->sadb_x_policy_dir) {
1812 case IPSEC_DIR_INBOUND:
1813 case IPSEC_DIR_OUTBOUND:
1816 ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
1817 mhp->msg->sadb_msg_errno = EINVAL;
1822 /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1823 if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1824 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1825 ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
1826 return key_senderror(so, m, EINVAL);
1829 /* policy requests are mandatory when action is ipsec. */
1830 if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1831 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1832 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1833 ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
1835 return key_senderror(so, m, EINVAL);
1839 * checking there is SP already or not.
1840 * SPDUPDATE doesn't depend on whether there is a SP or not.
1841 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1844 newsp = key_getsp(&spidx);
1845 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1851 if (newsp != NULL) {
1853 ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1855 return key_senderror(so, m, EEXIST);
1859 /* XXX: there is race between key_getsp and key_msg2sp. */
1861 /* allocation new SP entry */
1862 if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1863 return key_senderror(so, m, error);
1866 if ((newsp->id = key_getnewspid()) == 0) {
1868 return key_senderror(so, m, ENOBUFS);
1871 /* XXX boundary check against sa_len */
1872 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1875 src0->sadb_address_prefixlen,
1876 dst0->sadb_address_prefixlen,
1877 src0->sadb_address_proto,
1880 /* sanity check on addr pair */
1881 if (((struct sockaddr *)(src0 + 1))->sa_family !=
1882 ((struct sockaddr *)(dst0+ 1))->sa_family) {
1884 return key_senderror(so, m, EINVAL);
1886 if (((struct sockaddr *)(src0 + 1))->sa_len !=
1887 ((struct sockaddr *)(dst0+ 1))->sa_len) {
1889 return key_senderror(so, m, EINVAL);
1892 if (newsp->req && newsp->req->saidx.src.sa.sa_family &&
1893 newsp->req->saidx.dst.sa.sa_family) {
1894 if (newsp->req->saidx.src.sa.sa_family !=
1895 newsp->req->saidx.dst.sa.sa_family) {
1897 return key_senderror(so, m, EINVAL);
1902 newsp->created = time_second;
1903 newsp->lastused = newsp->created;
1904 newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1905 newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1908 TAILQ_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, chain);
1909 newsp->state = IPSEC_SPSTATE_ALIVE;
1912 /* delete the entry in spacqtree */
1913 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1914 struct secspacq *spacq = key_getspacq(&spidx);
1915 if (spacq != NULL) {
1916 /* reset counter in order to deletion by timehandler. */
1917 spacq->created = time_second;
1924 struct mbuf *n, *mpolicy;
1925 struct sadb_msg *newmsg;
1929 * Note: do not send SADB_X_EXT_NAT_T_* here:
1930 * we are sending traffic endpoints.
1933 /* create new sadb_msg to reply. */
1935 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1936 SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1937 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1939 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1941 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1944 return key_senderror(so, m, ENOBUFS);
1946 if (n->m_len < sizeof(*newmsg)) {
1947 n = m_pullup(n, sizeof(*newmsg));
1949 return key_senderror(so, m, ENOBUFS);
1951 newmsg = mtod(n, struct sadb_msg *);
1952 newmsg->sadb_msg_errno = 0;
1953 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1956 mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1957 sizeof(*xpl), &off);
1958 if (mpolicy == NULL) {
1959 /* n is already freed */
1960 return key_senderror(so, m, ENOBUFS);
1962 xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1963 if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1965 return key_senderror(so, m, EINVAL);
1967 xpl->sadb_x_policy_id = newsp->id;
1970 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
1975 * get new policy id.
1983 u_int32_t newid = 0;
1984 int count = V_key_spi_trycnt; /* XXX */
1985 struct secpolicy *sp;
1987 /* when requesting to allocate spi ranged */
1989 newid = (V_policy_id = (V_policy_id == ~0 ? 1 : V_policy_id + 1));
1991 if ((sp = key_getspbyid(newid)) == NULL)
1997 if (count == 0 || newid == 0) {
1998 ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
2007 * SADB_SPDDELETE processing
2009 * <base, address(SD), policy(*)>
2010 * from the user(?), and set SADB_SASTATE_DEAD,
2012 * <base, address(SD), policy(*)>
2014 * policy(*) including direction of policy.
2016 * m will always be freed.
2019 key_spddelete(struct socket *so, struct mbuf *m,
2020 const struct sadb_msghdr *mhp)
2022 struct sadb_address *src0, *dst0;
2023 struct sadb_x_policy *xpl0;
2024 struct secpolicyindex spidx;
2025 struct secpolicy *sp;
2027 IPSEC_ASSERT(so != NULL, ("null so"));
2028 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2029 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2030 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2032 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2033 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2034 mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2035 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2037 return key_senderror(so, m, EINVAL);
2039 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2040 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2041 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2042 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2044 return key_senderror(so, m, EINVAL);
2047 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2048 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2049 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2052 * Note: do not parse SADB_X_EXT_NAT_T_* here:
2053 * we are processing traffic endpoints.
2057 /* XXX boundary check against sa_len */
2058 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2061 src0->sadb_address_prefixlen,
2062 dst0->sadb_address_prefixlen,
2063 src0->sadb_address_proto,
2066 /* checking the direciton. */
2067 switch (xpl0->sadb_x_policy_dir) {
2068 case IPSEC_DIR_INBOUND:
2069 case IPSEC_DIR_OUTBOUND:
2072 ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2073 return key_senderror(so, m, EINVAL);
2076 /* Is there SP in SPD ? */
2077 if ((sp = key_getsp(&spidx)) == NULL) {
2078 ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2079 return key_senderror(so, m, EINVAL);
2082 /* save policy id to buffer to be returned. */
2083 xpl0->sadb_x_policy_id = sp->id;
2090 struct sadb_msg *newmsg;
2093 * Note: do not send SADB_X_EXT_NAT_T_* here:
2094 * we are sending traffic endpoints.
2097 /* create new sadb_msg to reply. */
2098 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2099 SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2101 return key_senderror(so, m, ENOBUFS);
2103 newmsg = mtod(n, struct sadb_msg *);
2104 newmsg->sadb_msg_errno = 0;
2105 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2108 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2113 * SADB_SPDDELETE2 processing
2116 * from the user(?), and set SADB_SASTATE_DEAD,
2120 * policy(*) including direction of policy.
2122 * m will always be freed.
2125 key_spddelete2(struct socket *so, struct mbuf *m,
2126 const struct sadb_msghdr *mhp)
2129 struct secpolicy *sp;
2131 IPSEC_ASSERT(so != NULL, ("null socket"));
2132 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2133 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2134 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2136 if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2137 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2138 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2139 return key_senderror(so, m, EINVAL);
2142 id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2144 /* Is there SP in SPD ? */
2145 if ((sp = key_getspbyid(id)) == NULL) {
2146 ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2147 return key_senderror(so, m, EINVAL);
2154 struct mbuf *n, *nn;
2155 struct sadb_msg *newmsg;
2158 /* create new sadb_msg to reply. */
2159 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2161 MGETHDR(n, M_NOWAIT, MT_DATA);
2162 if (n && len > MHLEN) {
2163 if (!(MCLGET(n, M_NOWAIT))) {
2169 return key_senderror(so, m, ENOBUFS);
2175 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2176 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2178 IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2181 n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2182 mhp->extlen[SADB_X_EXT_POLICY], M_NOWAIT);
2185 return key_senderror(so, m, ENOBUFS);
2188 n->m_pkthdr.len = 0;
2189 for (nn = n; nn; nn = nn->m_next)
2190 n->m_pkthdr.len += nn->m_len;
2192 newmsg = mtod(n, struct sadb_msg *);
2193 newmsg->sadb_msg_errno = 0;
2194 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2197 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2202 * SADB_X_GET processing
2207 * <base, address(SD), policy>
2209 * policy(*) including direction of policy.
2211 * m will always be freed.
2214 key_spdget(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2217 struct secpolicy *sp;
2220 IPSEC_ASSERT(so != NULL, ("null socket"));
2221 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2222 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2223 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2225 if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2226 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2227 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2229 return key_senderror(so, m, EINVAL);
2232 id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2234 /* Is there SP in SPD ? */
2235 if ((sp = key_getspbyid(id)) == NULL) {
2236 ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2237 return key_senderror(so, m, ENOENT);
2240 n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2244 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2246 return key_senderror(so, m, ENOBUFS);
2250 * SADB_X_SPDACQUIRE processing.
2251 * Acquire policy and SA(s) for a *OUTBOUND* packet.
2254 * to KMD, and expect to receive
2255 * <base> with SADB_X_SPDACQUIRE if error occured,
2258 * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2259 * policy(*) is without policy requests.
2262 * others: error number
2265 key_spdacquire(struct secpolicy *sp)
2267 struct mbuf *result = NULL, *m;
2268 struct secspacq *newspacq;
2270 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2271 IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2272 IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2273 ("policy not IPSEC %u", sp->policy));
2275 /* Get an entry to check whether sent message or not. */
2276 newspacq = key_getspacq(&sp->spidx);
2277 if (newspacq != NULL) {
2278 if (V_key_blockacq_count < newspacq->count) {
2279 /* reset counter and do send message. */
2280 newspacq->count = 0;
2282 /* increment counter and do nothing. */
2289 /* make new entry for blocking to send SADB_ACQUIRE. */
2290 newspacq = key_newspacq(&sp->spidx);
2291 if (newspacq == NULL)
2295 /* create new sadb_msg to reply. */
2296 m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2302 result->m_pkthdr.len = 0;
2303 for (m = result; m; m = m->m_next)
2304 result->m_pkthdr.len += m->m_len;
2306 mtod(result, struct sadb_msg *)->sadb_msg_len =
2307 PFKEY_UNIT64(result->m_pkthdr.len);
2309 return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2313 * SADB_SPDFLUSH processing
2316 * from the user, and free all entries in secpctree.
2320 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2322 * m will always be freed.
2325 key_spdflush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2327 TAILQ_HEAD(, secpolicy) drainq;
2328 struct sadb_msg *newmsg;
2329 struct secpolicy *sp, *nextsp;
2332 IPSEC_ASSERT(so != NULL, ("null socket"));
2333 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2334 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2335 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2337 if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2338 return key_senderror(so, m, EINVAL);
2340 TAILQ_INIT(&drainq);
2342 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2343 TAILQ_CONCAT(&drainq, &V_sptree[dir], chain);
2346 * We need to set state to DEAD for each policy to be sure,
2347 * that another thread won't try to unlink it.
2349 TAILQ_FOREACH(sp, &drainq, chain)
2350 sp->state = IPSEC_SPSTATE_DEAD;
2352 sp = TAILQ_FIRST(&drainq);
2353 while (sp != NULL) {
2354 nextsp = TAILQ_NEXT(sp, chain);
2359 if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2360 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2361 return key_senderror(so, m, ENOBUFS);
2367 m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2368 newmsg = mtod(m, struct sadb_msg *);
2369 newmsg->sadb_msg_errno = 0;
2370 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2372 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2376 * SADB_SPDDUMP processing
2379 * from the user, and dump all SP leaves
2384 * m will always be freed.
2387 key_spddump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2389 SPTREE_RLOCK_TRACKER;
2390 struct secpolicy *sp;
2395 IPSEC_ASSERT(so != NULL, ("null socket"));
2396 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2397 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2398 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2400 /* search SPD entry and get buffer size. */
2403 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2404 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
2411 return key_senderror(so, m, ENOENT);
2414 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2415 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
2417 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2418 mhp->msg->sadb_msg_pid);
2421 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2430 static struct mbuf *
2431 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq,
2434 struct mbuf *result = NULL, *m;
2435 struct seclifetime lt;
2437 m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2443 * Note: do not send SADB_X_EXT_NAT_T_* here:
2444 * we are sending traffic endpoints.
2446 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2447 &sp->spidx.src.sa, sp->spidx.prefs,
2448 sp->spidx.ul_proto);
2453 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2454 &sp->spidx.dst.sa, sp->spidx.prefd,
2455 sp->spidx.ul_proto);
2466 lt.addtime=sp->created;
2467 lt.usetime= sp->lastused;
2468 m = key_setlifetime(<, SADB_EXT_LIFETIME_CURRENT);
2473 lt.addtime=sp->lifetime;
2474 lt.usetime= sp->validtime;
2475 m = key_setlifetime(<, SADB_EXT_LIFETIME_HARD);
2481 if ((result->m_flags & M_PKTHDR) == 0)
2484 if (result->m_len < sizeof(struct sadb_msg)) {
2485 result = m_pullup(result, sizeof(struct sadb_msg));
2490 result->m_pkthdr.len = 0;
2491 for (m = result; m; m = m->m_next)
2492 result->m_pkthdr.len += m->m_len;
2494 mtod(result, struct sadb_msg *)->sadb_msg_len =
2495 PFKEY_UNIT64(result->m_pkthdr.len);
2505 * get PFKEY message length for security policy and request.
2508 key_getspreqmsglen(struct secpolicy *sp)
2512 tlen = sizeof(struct sadb_x_policy);
2514 /* if is the policy for ipsec ? */
2515 if (sp->policy != IPSEC_POLICY_IPSEC)
2518 /* get length of ipsec requests */
2520 struct ipsecrequest *isr;
2523 for (isr = sp->req; isr != NULL; isr = isr->next) {
2524 len = sizeof(struct sadb_x_ipsecrequest)
2525 + isr->saidx.src.sa.sa_len
2526 + isr->saidx.dst.sa.sa_len;
2528 tlen += PFKEY_ALIGN8(len);
2536 * SADB_SPDEXPIRE processing
2538 * <base, address(SD), lifetime(CH), policy>
2542 * others : error number
2545 key_spdexpire(struct secpolicy *sp)
2547 struct mbuf *result = NULL, *m;
2550 struct sadb_lifetime *lt;
2552 /* XXX: Why do we lock ? */
2554 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2556 /* set msg header */
2557 m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2564 /* create lifetime extension (current and hard) */
2565 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2566 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
2573 bzero(mtod(m, caddr_t), len);
2574 lt = mtod(m, struct sadb_lifetime *);
2575 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2576 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2577 lt->sadb_lifetime_allocations = 0;
2578 lt->sadb_lifetime_bytes = 0;
2579 lt->sadb_lifetime_addtime = sp->created;
2580 lt->sadb_lifetime_usetime = sp->lastused;
2581 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2582 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2583 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2584 lt->sadb_lifetime_allocations = 0;
2585 lt->sadb_lifetime_bytes = 0;
2586 lt->sadb_lifetime_addtime = sp->lifetime;
2587 lt->sadb_lifetime_usetime = sp->validtime;
2591 * Note: do not send SADB_X_EXT_NAT_T_* here:
2592 * we are sending traffic endpoints.
2595 /* set sadb_address for source */
2596 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2598 sp->spidx.prefs, sp->spidx.ul_proto);
2605 /* set sadb_address for destination */
2606 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2608 sp->spidx.prefd, sp->spidx.ul_proto);
2623 if ((result->m_flags & M_PKTHDR) == 0) {
2628 if (result->m_len < sizeof(struct sadb_msg)) {
2629 result = m_pullup(result, sizeof(struct sadb_msg));
2630 if (result == NULL) {
2636 result->m_pkthdr.len = 0;
2637 for (m = result; m; m = m->m_next)
2638 result->m_pkthdr.len += m->m_len;
2640 mtod(result, struct sadb_msg *)->sadb_msg_len =
2641 PFKEY_UNIT64(result->m_pkthdr.len);
2643 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2651 /* %%% SAD management */
2653 * allocating a memory for new SA head, and copy from the values of mhp.
2654 * OUT: NULL : failure due to the lack of memory.
2655 * others : pointer to new SA head.
2657 static struct secashead *
2658 key_newsah(struct secasindex *saidx)
2660 struct secashead *newsah;
2662 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2664 newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2665 if (newsah != NULL) {
2667 for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2668 LIST_INIT(&newsah->savtree[i]);
2669 newsah->saidx = *saidx;
2671 /* add to saidxtree */
2672 newsah->state = SADB_SASTATE_MATURE;
2675 LIST_INSERT_HEAD(&V_sahtree, newsah, chain);
2682 * delete SA index and all SA registerd.
2685 key_delsah(struct secashead *sah)
2687 struct secasvar *sav, *nextsav;
2691 IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2692 SAHTREE_LOCK_ASSERT();
2694 /* searching all SA registerd in the secindex. */
2696 stateidx < _ARRAYLEN(saorder_state_any);
2698 u_int state = saorder_state_any[stateidx];
2699 LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2700 if (sav->refcnt == 0) {
2702 KEY_CHKSASTATE(state, sav->state, __func__);
2704 * do NOT call KEY_FREESAV here:
2705 * it will only delete the sav if refcnt == 1,
2706 * where we already know that refcnt == 0
2710 /* give up to delete this sa */
2715 if (!zombie) { /* delete only if there are savs */
2716 /* remove from tree of SA index */
2717 if (__LIST_CHAINED(sah))
2718 LIST_REMOVE(sah, chain);
2719 free(sah, M_IPSEC_SAH);
2724 * allocating a new SA with LARVAL state. key_add() and key_getspi() call,
2725 * and copy the values of mhp into new buffer.
2726 * When SAD message type is GETSPI:
2727 * to set sequence number from acq_seq++,
2728 * to set zero to SPI.
2729 * not to call key_setsava().
2731 * others : pointer to new secasvar.
2733 * does not modify mbuf. does not free mbuf on error.
2735 static struct secasvar *
2736 key_newsav(struct mbuf *m, const struct sadb_msghdr *mhp,
2737 struct secashead *sah, int *errp, const char *where, int tag)
2739 struct secasvar *newsav;
2740 const struct sadb_sa *xsa;
2742 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2743 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2744 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2745 IPSEC_ASSERT(sah != NULL, ("null secashead"));
2747 newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2748 if (newsav == NULL) {
2749 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2754 switch (mhp->msg->sadb_msg_type) {
2758 #ifdef IPSEC_DOSEQCHECK
2759 /* sync sequence number */
2760 if (mhp->msg->sadb_msg_seq == 0)
2762 (V_acq_seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq));
2765 newsav->seq = mhp->msg->sadb_msg_seq;
2770 if (mhp->ext[SADB_EXT_SA] == NULL) {
2771 free(newsav, M_IPSEC_SA);
2773 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2778 xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2779 newsav->spi = xsa->sadb_sa_spi;
2780 newsav->seq = mhp->msg->sadb_msg_seq;
2783 free(newsav, M_IPSEC_SA);
2790 /* copy sav values */
2791 if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2792 *errp = key_setsaval(newsav, m, mhp);
2794 free(newsav, M_IPSEC_SA);
2800 SECASVAR_LOCK_INIT(newsav);
2803 newsav->created = time_second;
2804 newsav->pid = mhp->msg->sadb_msg_pid;
2809 newsav->state = SADB_SASTATE_LARVAL;
2812 LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2816 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2817 printf("DP %s from %s:%u return SP:%p\n", __func__,
2818 where, tag, newsav));
2824 * free() SA variable entry.
2827 key_cleansav(struct secasvar *sav)
2830 * Cleanup xform state. Note that zeroize'ing causes the
2831 * keys to be cleared; otherwise we must do it ourself.
2833 if (sav->tdb_xform != NULL) {
2834 sav->tdb_xform->xf_zeroize(sav);
2835 sav->tdb_xform = NULL;
2837 KASSERT(sav->iv == NULL, ("iv but no xform"));
2838 if (sav->key_auth != NULL)
2839 bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2840 if (sav->key_enc != NULL)
2841 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2843 if (sav->key_auth != NULL) {
2844 if (sav->key_auth->key_data != NULL)
2845 free(sav->key_auth->key_data, M_IPSEC_MISC);
2846 free(sav->key_auth, M_IPSEC_MISC);
2847 sav->key_auth = NULL;
2849 if (sav->key_enc != NULL) {
2850 if (sav->key_enc->key_data != NULL)
2851 free(sav->key_enc->key_data, M_IPSEC_MISC);
2852 free(sav->key_enc, M_IPSEC_MISC);
2853 sav->key_enc = NULL;
2856 bzero(sav->sched, sav->schedlen);
2857 free(sav->sched, M_IPSEC_MISC);
2860 if (sav->replay != NULL) {
2861 free(sav->replay, M_IPSEC_MISC);
2864 if (sav->lft_c != NULL) {
2865 free(sav->lft_c, M_IPSEC_MISC);
2868 if (sav->lft_h != NULL) {
2869 free(sav->lft_h, M_IPSEC_MISC);
2872 if (sav->lft_s != NULL) {
2873 free(sav->lft_s, M_IPSEC_MISC);
2879 * free() SA variable entry.
2882 key_delsav(struct secasvar *sav)
2884 IPSEC_ASSERT(sav != NULL, ("null sav"));
2885 IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2887 /* remove from SA header */
2888 if (__LIST_CHAINED(sav))
2889 LIST_REMOVE(sav, chain);
2891 SECASVAR_LOCK_DESTROY(sav);
2892 free(sav, M_IPSEC_SA);
2899 * others : found, pointer to a SA.
2901 static struct secashead *
2902 key_getsah(struct secasindex *saidx)
2904 struct secashead *sah;
2907 LIST_FOREACH(sah, &V_sahtree, chain) {
2908 if (sah->state == SADB_SASTATE_DEAD)
2910 if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2919 * check not to be duplicated SPI.
2920 * NOTE: this function is too slow due to searching all SAD.
2923 * others : found, pointer to a SA.
2925 static struct secasvar *
2926 key_checkspidup(struct secasindex *saidx, u_int32_t spi)
2928 struct secashead *sah;
2929 struct secasvar *sav;
2931 /* check address family */
2932 if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2933 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2941 LIST_FOREACH(sah, &V_sahtree, chain) {
2942 if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2944 sav = key_getsavbyspi(sah, spi);
2954 * search SAD litmited alive SA, protocol, SPI.
2957 * others : found, pointer to a SA.
2959 static struct secasvar *
2960 key_getsavbyspi(struct secashead *sah, u_int32_t spi)
2962 struct secasvar *sav;
2963 u_int stateidx, state;
2966 SAHTREE_LOCK_ASSERT();
2967 /* search all status */
2969 stateidx < _ARRAYLEN(saorder_state_alive);
2972 state = saorder_state_alive[stateidx];
2973 LIST_FOREACH(sav, &sah->savtree[state], chain) {
2976 if (sav->state != state) {
2977 ipseclog((LOG_DEBUG, "%s: "
2978 "invalid sav->state (queue: %d SA: %d)\n",
2979 __func__, state, sav->state));
2983 if (sav->spi == spi)
2992 * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
2993 * You must update these if need.
2997 * does not modify mbuf. does not free mbuf on error.
3000 key_setsaval(struct secasvar *sav, struct mbuf *m,
3001 const struct sadb_msghdr *mhp)
3005 IPSEC_ASSERT(m != NULL, ("null mbuf"));
3006 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3007 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3009 /* initialization */
3011 sav->key_auth = NULL;
3012 sav->key_enc = NULL;
3019 sav->tdb_xform = NULL; /* transform */
3020 sav->tdb_encalgxform = NULL; /* encoding algorithm */
3021 sav->tdb_authalgxform = NULL; /* authentication algorithm */
3022 sav->tdb_compalgxform = NULL; /* compression algorithm */
3023 /* Initialize even if NAT-T not compiled in: */
3025 sav->natt_esp_frag_len = 0;
3028 if (mhp->ext[SADB_EXT_SA] != NULL) {
3029 const struct sadb_sa *sa0;
3031 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3032 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3037 sav->alg_auth = sa0->sadb_sa_auth;
3038 sav->alg_enc = sa0->sadb_sa_encrypt;
3039 sav->flags = sa0->sadb_sa_flags;
3042 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3043 sav->replay = (struct secreplay *)
3044 malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
3045 if (sav->replay == NULL) {
3046 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3051 if (sa0->sadb_sa_replay != 0)
3052 sav->replay->bitmap = (caddr_t)(sav->replay+1);
3053 sav->replay->wsize = sa0->sadb_sa_replay;
3057 /* Authentication keys */
3058 if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3059 const struct sadb_key *key0;
3062 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3063 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3066 if (len < sizeof(*key0)) {
3070 switch (mhp->msg->sadb_msg_satype) {
3071 case SADB_SATYPE_AH:
3072 case SADB_SATYPE_ESP:
3073 case SADB_X_SATYPE_TCPSIGNATURE:
3074 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3075 sav->alg_auth != SADB_X_AALG_NULL)
3078 case SADB_X_SATYPE_IPCOMP:
3084 ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3089 sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
3091 if (sav->key_auth == NULL ) {
3092 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3099 /* Encryption key */
3100 if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3101 const struct sadb_key *key0;
3104 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3105 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3108 if (len < sizeof(*key0)) {
3112 switch (mhp->msg->sadb_msg_satype) {
3113 case SADB_SATYPE_ESP:
3114 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3115 sav->alg_enc != SADB_EALG_NULL) {
3119 sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
3122 if (sav->key_enc == NULL) {
3123 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3129 case SADB_X_SATYPE_IPCOMP:
3130 if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3132 sav->key_enc = NULL; /*just in case*/
3134 case SADB_SATYPE_AH:
3135 case SADB_X_SATYPE_TCPSIGNATURE:
3141 ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3150 switch (mhp->msg->sadb_msg_satype) {
3151 case SADB_SATYPE_AH:
3152 error = xform_init(sav, XF_AH);
3154 case SADB_SATYPE_ESP:
3155 error = xform_init(sav, XF_ESP);
3157 case SADB_X_SATYPE_IPCOMP:
3158 error = xform_init(sav, XF_IPCOMP);
3160 case SADB_X_SATYPE_TCPSIGNATURE:
3161 error = xform_init(sav, XF_TCPSIGNATURE);
3165 ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3166 __func__, mhp->msg->sadb_msg_satype));
3171 sav->created = time_second;
3173 /* make lifetime for CURRENT */
3174 sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
3175 if (sav->lft_c == NULL) {
3176 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3181 sav->lft_c->allocations = 0;
3182 sav->lft_c->bytes = 0;
3183 sav->lft_c->addtime = time_second;
3184 sav->lft_c->usetime = 0;
3186 /* lifetimes for HARD and SOFT */
3188 const struct sadb_lifetime *lft0;
3190 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3192 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3196 sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3197 if (sav->lft_h == NULL) {
3198 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3202 /* to be initialize ? */
3205 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3207 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3211 sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3212 if (sav->lft_s == NULL) {
3213 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3217 /* to be initialize ? */
3224 /* initialization */
3231 * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3236 key_mature(struct secasvar *sav)
3240 /* check SPI value */
3241 switch (sav->sah->saidx.proto) {
3245 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
3246 * 1-255 reserved by IANA for future use,
3247 * 0 for implementation specific, local use.
3249 if (ntohl(sav->spi) <= 255) {
3250 ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3251 __func__, (u_int32_t)ntohl(sav->spi)));
3258 switch (sav->sah->saidx.proto) {
3261 if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3262 (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3263 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3264 "given to old-esp.\n", __func__));
3267 error = xform_init(sav, XF_ESP);
3271 if (sav->flags & SADB_X_EXT_DERIV) {
3272 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3273 "given to AH SA.\n", __func__));
3276 if (sav->alg_enc != SADB_EALG_NONE) {
3277 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3278 "mismated.\n", __func__));
3281 error = xform_init(sav, XF_AH);
3283 case IPPROTO_IPCOMP:
3284 if (sav->alg_auth != SADB_AALG_NONE) {
3285 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3286 "mismated.\n", __func__));
3289 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3290 && ntohl(sav->spi) >= 0x10000) {
3291 ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3295 error = xform_init(sav, XF_IPCOMP);
3298 if (sav->alg_enc != SADB_EALG_NONE) {
3299 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3300 "mismated.\n", __func__));
3303 error = xform_init(sav, XF_TCPSIGNATURE);
3306 ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3307 error = EPROTONOSUPPORT;
3312 key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3319 * subroutine for SADB_GET and SADB_DUMP.
3321 static struct mbuf *
3322 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3323 u_int32_t seq, u_int32_t pid)
3325 struct mbuf *result = NULL, *tres = NULL, *m;
3328 SADB_EXT_SA, SADB_X_EXT_SA2,
3329 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3330 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3331 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3332 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3333 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3335 SADB_X_EXT_NAT_T_TYPE,
3336 SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3337 SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3338 SADB_X_EXT_NAT_T_FRAG,
3342 m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3347 for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3349 switch (dumporder[i]) {
3351 m = key_setsadbsa(sav);
3356 case SADB_X_EXT_SA2:
3357 m = key_setsadbxsa2(sav->sah->saidx.mode,
3358 sav->replay ? sav->replay->count : 0,
3359 sav->sah->saidx.reqid);
3364 case SADB_EXT_ADDRESS_SRC:
3365 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3366 &sav->sah->saidx.src.sa,
3367 FULLMASK, IPSEC_ULPROTO_ANY);
3372 case SADB_EXT_ADDRESS_DST:
3373 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3374 &sav->sah->saidx.dst.sa,
3375 FULLMASK, IPSEC_ULPROTO_ANY);
3380 case SADB_EXT_KEY_AUTH:
3383 m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3388 case SADB_EXT_KEY_ENCRYPT:
3391 m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3396 case SADB_EXT_LIFETIME_CURRENT:
3399 m = key_setlifetime(sav->lft_c,
3400 SADB_EXT_LIFETIME_CURRENT);
3405 case SADB_EXT_LIFETIME_HARD:
3408 m = key_setlifetime(sav->lft_h,
3409 SADB_EXT_LIFETIME_HARD);
3414 case SADB_EXT_LIFETIME_SOFT:
3417 m = key_setlifetime(sav->lft_s,
3418 SADB_EXT_LIFETIME_SOFT);
3425 case SADB_X_EXT_NAT_T_TYPE:
3426 m = key_setsadbxtype(sav->natt_type);
3431 case SADB_X_EXT_NAT_T_DPORT:
3432 m = key_setsadbxport(
3433 KEY_PORTFROMSADDR(&sav->sah->saidx.dst),
3434 SADB_X_EXT_NAT_T_DPORT);
3439 case SADB_X_EXT_NAT_T_SPORT:
3440 m = key_setsadbxport(
3441 KEY_PORTFROMSADDR(&sav->sah->saidx.src),
3442 SADB_X_EXT_NAT_T_SPORT);
3447 case SADB_X_EXT_NAT_T_OAI:
3448 case SADB_X_EXT_NAT_T_OAR:
3449 case SADB_X_EXT_NAT_T_FRAG:
3450 /* We do not (yet) support those. */
3454 case SADB_EXT_ADDRESS_PROXY:
3455 case SADB_EXT_IDENTITY_SRC:
3456 case SADB_EXT_IDENTITY_DST:
3457 /* XXX: should we brought from SPD ? */
3458 case SADB_EXT_SENSITIVITY:
3471 m_cat(result, tres);
3472 if (result->m_len < sizeof(struct sadb_msg)) {
3473 result = m_pullup(result, sizeof(struct sadb_msg));
3478 result->m_pkthdr.len = 0;
3479 for (m = result; m; m = m->m_next)
3480 result->m_pkthdr.len += m->m_len;
3482 mtod(result, struct sadb_msg *)->sadb_msg_len =
3483 PFKEY_UNIT64(result->m_pkthdr.len);
3494 * set data into sadb_msg.
3496 static struct mbuf *
3497 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3498 pid_t pid, u_int16_t reserved)
3504 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3507 MGETHDR(m, M_NOWAIT, MT_DATA);
3508 if (m && len > MHLEN) {
3509 if (!(MCLGET(m, M_NOWAIT))) {
3516 m->m_pkthdr.len = m->m_len = len;
3519 p = mtod(m, struct sadb_msg *);
3522 p->sadb_msg_version = PF_KEY_V2;
3523 p->sadb_msg_type = type;
3524 p->sadb_msg_errno = 0;
3525 p->sadb_msg_satype = satype;
3526 p->sadb_msg_len = PFKEY_UNIT64(tlen);
3527 p->sadb_msg_reserved = reserved;
3528 p->sadb_msg_seq = seq;
3529 p->sadb_msg_pid = (u_int32_t)pid;
3535 * copy secasvar data into sadb_address.
3537 static struct mbuf *
3538 key_setsadbsa(struct secasvar *sav)
3544 len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3545 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3550 p = mtod(m, struct sadb_sa *);
3552 p->sadb_sa_len = PFKEY_UNIT64(len);
3553 p->sadb_sa_exttype = SADB_EXT_SA;
3554 p->sadb_sa_spi = sav->spi;
3555 p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3556 p->sadb_sa_state = sav->state;
3557 p->sadb_sa_auth = sav->alg_auth;
3558 p->sadb_sa_encrypt = sav->alg_enc;
3559 p->sadb_sa_flags = sav->flags;
3565 * set data into sadb_address.
3567 static struct mbuf *
3568 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
3569 u_int8_t prefixlen, u_int16_t ul_proto)
3572 struct sadb_address *p;
3575 len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3576 PFKEY_ALIGN8(saddr->sa_len);
3577 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3582 p = mtod(m, struct sadb_address *);
3585 p->sadb_address_len = PFKEY_UNIT64(len);
3586 p->sadb_address_exttype = exttype;
3587 p->sadb_address_proto = ul_proto;
3588 if (prefixlen == FULLMASK) {
3589 switch (saddr->sa_family) {
3591 prefixlen = sizeof(struct in_addr) << 3;
3594 prefixlen = sizeof(struct in6_addr) << 3;
3600 p->sadb_address_prefixlen = prefixlen;
3601 p->sadb_address_reserved = 0;
3604 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3611 * set data into sadb_x_sa2.
3613 static struct mbuf *
3614 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3617 struct sadb_x_sa2 *p;
3620 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3621 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3626 p = mtod(m, struct sadb_x_sa2 *);
3629 p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3630 p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3631 p->sadb_x_sa2_mode = mode;
3632 p->sadb_x_sa2_reserved1 = 0;
3633 p->sadb_x_sa2_reserved2 = 0;
3634 p->sadb_x_sa2_sequence = seq;
3635 p->sadb_x_sa2_reqid = reqid;
3642 * Set a type in sadb_x_nat_t_type.
3644 static struct mbuf *
3645 key_setsadbxtype(u_int16_t type)
3649 struct sadb_x_nat_t_type *p;
3651 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3653 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3658 p = mtod(m, struct sadb_x_nat_t_type *);
3661 p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3662 p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3663 p->sadb_x_nat_t_type_type = type;
3668 * Set a port in sadb_x_nat_t_port.
3669 * In contrast to default RFC 2367 behaviour, port is in network byte order.
3671 static struct mbuf *
3672 key_setsadbxport(u_int16_t port, u_int16_t type)
3676 struct sadb_x_nat_t_port *p;
3678 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3680 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3685 p = mtod(m, struct sadb_x_nat_t_port *);
3688 p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3689 p->sadb_x_nat_t_port_exttype = type;
3690 p->sadb_x_nat_t_port_port = port;
3696 * Get port from sockaddr. Port is in network byte order.
3699 key_portfromsaddr(struct sockaddr *sa)
3702 switch (sa->sa_family) {
3705 return ((struct sockaddr_in *)sa)->sin_port;
3709 return ((struct sockaddr_in6 *)sa)->sin6_port;
3712 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
3713 printf("DP %s unexpected address family %d\n",
3714 __func__, sa->sa_family));
3717 #endif /* IPSEC_NAT_T */
3720 * Set port in struct sockaddr. Port is in network byte order.
3723 key_porttosaddr(struct sockaddr *sa, u_int16_t port)
3726 switch (sa->sa_family) {
3729 ((struct sockaddr_in *)sa)->sin_port = port;
3734 ((struct sockaddr_in6 *)sa)->sin6_port = port;
3738 ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
3739 __func__, sa->sa_family));
3745 * set data into sadb_x_policy
3747 static struct mbuf *
3748 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3751 struct sadb_x_policy *p;
3754 len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3755 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3760 p = mtod(m, struct sadb_x_policy *);
3763 p->sadb_x_policy_len = PFKEY_UNIT64(len);
3764 p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3765 p->sadb_x_policy_type = type;
3766 p->sadb_x_policy_dir = dir;
3767 p->sadb_x_policy_id = id;
3773 /* Take a key message (sadb_key) from the socket and turn it into one
3774 * of the kernel's key structures (seckey).
3776 * IN: pointer to the src
3777 * OUT: NULL no more memory
3780 key_dup_keymsg(const struct sadb_key *src, u_int len,
3781 struct malloc_type *type)
3784 dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
3786 dst->bits = src->sadb_key_bits;
3787 dst->key_data = (char *)malloc(len, type, M_NOWAIT);
3788 if (dst->key_data != NULL) {
3789 bcopy((const char *)src + sizeof(struct sadb_key),
3790 dst->key_data, len);
3792 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3798 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3805 /* Take a lifetime message (sadb_lifetime) passed in on a socket and
3806 * turn it into one of the kernel's lifetime structures (seclifetime).
3808 * IN: pointer to the destination, source and malloc type
3809 * OUT: NULL, no more memory
3812 static struct seclifetime *
3813 key_dup_lifemsg(const struct sadb_lifetime *src, struct malloc_type *type)
3815 struct seclifetime *dst = NULL;
3817 dst = (struct seclifetime *)malloc(sizeof(struct seclifetime),
3821 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3823 dst->allocations = src->sadb_lifetime_allocations;
3824 dst->bytes = src->sadb_lifetime_bytes;
3825 dst->addtime = src->sadb_lifetime_addtime;
3826 dst->usetime = src->sadb_lifetime_usetime;
3831 /* compare my own address
3832 * OUT: 1: true, i.e. my address.
3836 key_ismyaddr(struct sockaddr *sa)
3839 IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3840 switch (sa->sa_family) {
3843 return (in_localip(satosin(sa)->sin_addr));
3847 return key_ismyaddr6((struct sockaddr_in6 *)sa);
3856 * compare my own address for IPv6.
3859 * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3861 #include <netinet6/in6_var.h>
3864 key_ismyaddr6(struct sockaddr_in6 *sin6)
3866 struct in6_ifaddr *ia;
3868 struct in6_multi *in6m;
3872 TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
3873 if (key_sockaddrcmp((struct sockaddr *)&sin6,
3874 (struct sockaddr *)&ia->ia_addr, 0) == 0) {
3875 IN6_IFADDR_RUNLOCK();
3882 * XXX why do we care about multlicast here while we don't care
3883 * about IPv4 multicast??
3887 IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3889 IN6_IFADDR_RUNLOCK();
3894 IN6_IFADDR_RUNLOCK();
3896 /* loopback, just for safety */
3897 if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3905 * compare two secasindex structure.
3906 * flag can specify to compare 2 saidxes.
3907 * compare two secasindex structure without both mode and reqid.
3908 * don't compare port.
3910 * saidx0: source, it can be in SAD.
3917 key_cmpsaidx(const struct secasindex *saidx0, const struct secasindex *saidx1,
3923 if (saidx0 == NULL && saidx1 == NULL)
3926 if (saidx0 == NULL || saidx1 == NULL)
3929 if (saidx0->proto != saidx1->proto)
3932 if (flag == CMP_EXACTLY) {
3933 if (saidx0->mode != saidx1->mode)
3935 if (saidx0->reqid != saidx1->reqid)
3937 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
3938 bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
3942 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3943 if (flag == CMP_MODE_REQID
3944 ||flag == CMP_REQID) {
3946 * If reqid of SPD is non-zero, unique SA is required.
3947 * The result must be of same reqid in this case.
3949 if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3953 if (flag == CMP_MODE_REQID) {
3954 if (saidx0->mode != IPSEC_MODE_ANY
3955 && saidx0->mode != saidx1->mode)
3961 * If NAT-T is enabled, check ports for tunnel mode.
3962 * Do not check ports if they are set to zero in the SPD.
3963 * Also do not do it for native transport mode, as there
3964 * is no port information available in the SP.
3966 if ((saidx1->mode == IPSEC_MODE_TUNNEL ||
3967 (saidx1->mode == IPSEC_MODE_TRANSPORT &&
3968 saidx1->proto == IPPROTO_ESP)) &&
3969 saidx1->src.sa.sa_family == AF_INET &&
3970 saidx1->dst.sa.sa_family == AF_INET &&
3971 ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
3972 ((const struct sockaddr_in *)(&saidx1->dst))->sin_port)
3974 #endif /* IPSEC_NAT_T */
3976 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
3979 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
3988 * compare two secindex structure exactly.
3990 * spidx0: source, it is often in SPD.
3991 * spidx1: object, it is often from PFKEY message.
3997 key_cmpspidx_exactly(struct secpolicyindex *spidx0,
3998 struct secpolicyindex *spidx1)
4001 if (spidx0 == NULL && spidx1 == NULL)
4004 if (spidx0 == NULL || spidx1 == NULL)
4007 if (spidx0->prefs != spidx1->prefs
4008 || spidx0->prefd != spidx1->prefd
4009 || spidx0->ul_proto != spidx1->ul_proto)
4012 return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
4013 key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
4017 * compare two secindex structure with mask.
4019 * spidx0: source, it is often in SPD.
4020 * spidx1: object, it is often from IP header.
4026 key_cmpspidx_withmask(struct secpolicyindex *spidx0,
4027 struct secpolicyindex *spidx1)
4030 if (spidx0 == NULL && spidx1 == NULL)
4033 if (spidx0 == NULL || spidx1 == NULL)
4036 if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4037 spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4038 spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4039 spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4042 /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4043 if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4044 && spidx0->ul_proto != spidx1->ul_proto)
4047 switch (spidx0->src.sa.sa_family) {
4049 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4050 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4052 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4053 &spidx1->src.sin.sin_addr, spidx0->prefs))
4057 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4058 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4061 * scope_id check. if sin6_scope_id is 0, we regard it
4062 * as a wildcard scope, which matches any scope zone ID.
4064 if (spidx0->src.sin6.sin6_scope_id &&
4065 spidx1->src.sin6.sin6_scope_id &&
4066 spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4068 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4069 &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4074 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4079 switch (spidx0->dst.sa.sa_family) {
4081 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4082 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4084 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4085 &spidx1->dst.sin.sin_addr, spidx0->prefd))
4089 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4090 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4093 * scope_id check. if sin6_scope_id is 0, we regard it
4094 * as a wildcard scope, which matches any scope zone ID.
4096 if (spidx0->dst.sin6.sin6_scope_id &&
4097 spidx1->dst.sin6.sin6_scope_id &&
4098 spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4100 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4101 &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4106 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4111 /* XXX Do we check other field ? e.g. flowinfo */
4116 /* returns 0 on match */
4118 key_sockaddrcmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
4124 #define satosin(s) ((const struct sockaddr_in *)s)
4128 #define satosin6(s) ((const struct sockaddr_in6 *)s)
4129 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4132 switch (sa1->sa_family) {
4134 if (sa1->sa_len != sizeof(struct sockaddr_in))
4136 if (satosin(sa1)->sin_addr.s_addr !=
4137 satosin(sa2)->sin_addr.s_addr) {
4140 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4144 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4145 return 1; /*EINVAL*/
4146 if (satosin6(sa1)->sin6_scope_id !=
4147 satosin6(sa2)->sin6_scope_id) {
4150 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4151 &satosin6(sa2)->sin6_addr)) {
4155 satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4160 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4171 * compare two buffers with mask.
4175 * bits: Number of bits to compare
4181 key_bbcmp(const void *a1, const void *a2, u_int bits)
4183 const unsigned char *p1 = a1;
4184 const unsigned char *p2 = a2;
4186 /* XXX: This could be considerably faster if we compare a word
4187 * at a time, but it is complicated on LSB Endian machines */
4189 /* Handle null pointers */
4190 if (p1 == NULL || p2 == NULL)
4200 u_int8_t mask = ~((1<<(8-bits))-1);
4201 if ((*p1 & mask) != (*p2 & mask))
4204 return 1; /* Match! */
4208 key_flush_spd(time_t now)
4210 SPTREE_RLOCK_TRACKER;
4211 struct secpolicy *sp;
4215 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4218 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
4219 if (sp->lifetime == 0 && sp->validtime == 0)
4221 if ((sp->lifetime &&
4222 now - sp->created > sp->lifetime) ||
4224 now - sp->lastused > sp->validtime)) {
4238 key_flush_sad(time_t now)
4240 struct secashead *sah, *nextsah;
4241 struct secasvar *sav, *nextsav;
4245 LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4246 /* if sah has been dead, then delete it and process next sah. */
4247 if (sah->state == SADB_SASTATE_DEAD) {
4252 /* if LARVAL entry doesn't become MATURE, delete it. */
4253 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4254 /* Need to also check refcnt for a larval SA ??? */
4255 if (now - sav->created > V_key_larval_lifetime)
4260 * check MATURE entry to start to send expire message
4263 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4264 /* we don't need to check. */
4265 if (sav->lft_s == NULL)
4269 if (sav->lft_c == NULL) {
4270 ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4271 "time, why?\n", __func__));
4275 /* check SOFT lifetime */
4276 if (sav->lft_s->addtime != 0 &&
4277 now - sav->created > sav->lft_s->addtime) {
4278 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4280 * Actually, only send expire message if
4281 * SA has been used, as it was done before,
4282 * but should we always send such message,
4283 * and let IKE daemon decide if it should be
4284 * renegotiated or not ?
4285 * XXX expire message will actually NOT be
4286 * sent if SA is only used after soft
4287 * lifetime has been reached, see below
4290 if (sav->lft_c->usetime != 0)
4293 /* check SOFT lifetime by bytes */
4295 * XXX I don't know the way to delete this SA
4296 * when new SA is installed. Caution when it's
4297 * installed too big lifetime by time.
4299 else if (sav->lft_s->bytes != 0 &&
4300 sav->lft_s->bytes < sav->lft_c->bytes) {
4302 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4304 * XXX If we keep to send expire
4305 * message in the status of
4306 * DYING. Do remove below code.
4312 /* check DYING entry to change status to DEAD. */
4313 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4314 /* we don't need to check. */
4315 if (sav->lft_h == NULL)
4319 if (sav->lft_c == NULL) {
4320 ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4321 "time, why?\n", __func__));
4325 if (sav->lft_h->addtime != 0 &&
4326 now - sav->created > sav->lft_h->addtime) {
4327 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4330 #if 0 /* XXX Should we keep to send expire message until HARD lifetime ? */
4331 else if (sav->lft_s != NULL
4332 && sav->lft_s->addtime != 0
4333 && now - sav->created > sav->lft_s->addtime) {
4335 * XXX: should be checked to be
4336 * installed the valid SA.
4340 * If there is no SA then sending
4346 /* check HARD lifetime by bytes */
4347 else if (sav->lft_h->bytes != 0 &&
4348 sav->lft_h->bytes < sav->lft_c->bytes) {
4349 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4354 /* delete entry in DEAD */
4355 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4357 if (sav->state != SADB_SASTATE_DEAD) {
4358 ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4359 "(queue: %d SA: %d): kill it anyway\n",
4361 SADB_SASTATE_DEAD, sav->state));
4364 * do not call key_freesav() here.
4365 * sav should already be freed, and sav->refcnt
4366 * shows other references to sav
4367 * (such as from SPD).
4375 key_flush_acq(time_t now)
4377 struct secacq *acq, *nextacq;
4381 for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4382 nextacq = LIST_NEXT(acq, chain);
4383 if (now - acq->created > V_key_blockacq_lifetime
4384 && __LIST_CHAINED(acq)) {
4385 LIST_REMOVE(acq, chain);
4386 free(acq, M_IPSEC_SAQ);
4393 key_flush_spacq(time_t now)
4395 struct secspacq *acq, *nextacq;
4399 for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4400 nextacq = LIST_NEXT(acq, chain);
4401 if (now - acq->created > V_key_blockacq_lifetime
4402 && __LIST_CHAINED(acq)) {
4403 LIST_REMOVE(acq, chain);
4404 free(acq, M_IPSEC_SAQ);
4412 * scanning SPD and SAD to check status for each entries,
4413 * and do to remove or to expire.
4414 * XXX: year 2038 problem may remain.
4417 key_timehandler(void *arg)
4419 VNET_ITERATOR_DECL(vnet_iter);
4420 time_t now = time_second;
4422 VNET_LIST_RLOCK_NOSLEEP();
4423 VNET_FOREACH(vnet_iter) {
4424 CURVNET_SET(vnet_iter);
4428 key_flush_spacq(now);
4431 VNET_LIST_RUNLOCK_NOSLEEP();
4433 #ifndef IPSEC_DEBUG2
4434 /* do exchange to tick time !! */
4435 callout_schedule(&key_timer, hz);
4436 #endif /* IPSEC_DEBUG2 */
4444 key_randomfill(&value, sizeof(value));
4449 key_randomfill(void *p, size_t l)
4453 static int warn = 1;
4456 n = (size_t)read_random(p, (u_int)l);
4460 bcopy(&v, (u_int8_t *)p + n,
4461 l - n < sizeof(v) ? l - n : sizeof(v));
4465 printf("WARNING: pseudo-random number generator "
4466 "used for IPsec processing\n");
4473 * map SADB_SATYPE_* to IPPROTO_*.
4474 * if satype == SADB_SATYPE then satype is mapped to ~0.
4476 * 0: invalid satype.
4479 key_satype2proto(u_int8_t satype)
4482 case SADB_SATYPE_UNSPEC:
4483 return IPSEC_PROTO_ANY;
4484 case SADB_SATYPE_AH:
4486 case SADB_SATYPE_ESP:
4488 case SADB_X_SATYPE_IPCOMP:
4489 return IPPROTO_IPCOMP;
4490 case SADB_X_SATYPE_TCPSIGNATURE:
4499 * map IPPROTO_* to SADB_SATYPE_*
4501 * 0: invalid protocol type.
4504 key_proto2satype(u_int16_t proto)
4508 return SADB_SATYPE_AH;
4510 return SADB_SATYPE_ESP;
4511 case IPPROTO_IPCOMP:
4512 return SADB_X_SATYPE_IPCOMP;
4514 return SADB_X_SATYPE_TCPSIGNATURE;
4523 * SADB_GETSPI processing is to receive
4524 * <base, (SA2), src address, dst address, (SPI range)>
4525 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4526 * tree with the status of LARVAL, and send
4527 * <base, SA(*), address(SD)>
4530 * IN: mhp: pointer to the pointer to each header.
4531 * OUT: NULL if fail.
4532 * other if success, return pointer to the message to send.
4535 key_getspi(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4537 struct sadb_address *src0, *dst0;
4538 struct secasindex saidx;
4539 struct secashead *newsah;
4540 struct secasvar *newsav;
4547 IPSEC_ASSERT(so != NULL, ("null socket"));
4548 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4549 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4550 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4552 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4553 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4554 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4556 return key_senderror(so, m, EINVAL);
4558 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4559 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4560 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4562 return key_senderror(so, m, EINVAL);
4564 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4565 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4566 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4568 mode = IPSEC_MODE_ANY;
4572 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4573 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4575 /* map satype to proto */
4576 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4577 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4579 return key_senderror(so, m, EINVAL);
4583 * Make sure the port numbers are zero.
4584 * In case of NAT-T we will update them later if needed.
4586 switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4588 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4589 sizeof(struct sockaddr_in))
4590 return key_senderror(so, m, EINVAL);
4591 ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4594 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4595 sizeof(struct sockaddr_in6))
4596 return key_senderror(so, m, EINVAL);
4597 ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4602 switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4604 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4605 sizeof(struct sockaddr_in))
4606 return key_senderror(so, m, EINVAL);
4607 ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4610 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4611 sizeof(struct sockaddr_in6))
4612 return key_senderror(so, m, EINVAL);
4613 ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4619 /* XXX boundary check against sa_len */
4620 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4624 * Handle NAT-T info if present.
4625 * We made sure the port numbers are zero above, so we do
4626 * not have to worry in case we do not update them.
4628 if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
4629 ipseclog((LOG_DEBUG, "%s: NAT-T OAi present\n", __func__));
4630 if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
4631 ipseclog((LOG_DEBUG, "%s: NAT-T OAr present\n", __func__));
4633 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4634 mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4635 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4636 struct sadb_x_nat_t_type *type;
4637 struct sadb_x_nat_t_port *sport, *dport;
4639 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4640 mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4641 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4642 ipseclog((LOG_DEBUG, "%s: invalid nat-t message "
4643 "passed.\n", __func__));
4644 return key_senderror(so, m, EINVAL);
4647 sport = (struct sadb_x_nat_t_port *)
4648 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4649 dport = (struct sadb_x_nat_t_port *)
4650 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4653 KEY_PORTTOSADDR(&saidx.src, sport->sadb_x_nat_t_port_port);
4655 KEY_PORTTOSADDR(&saidx.dst, dport->sadb_x_nat_t_port_port);
4659 /* SPI allocation */
4660 spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4663 return key_senderror(so, m, EINVAL);
4665 /* get a SA index */
4666 if ((newsah = key_getsah(&saidx)) == NULL) {
4667 /* create a new SA index */
4668 if ((newsah = key_newsah(&saidx)) == NULL) {
4669 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4670 return key_senderror(so, m, ENOBUFS);
4676 newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4677 if (newsav == NULL) {
4678 /* XXX don't free new SA index allocated in above. */
4679 return key_senderror(so, m, error);
4683 newsav->spi = htonl(spi);
4685 /* delete the entry in acqtree */
4686 if (mhp->msg->sadb_msg_seq != 0) {
4688 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4689 /* reset counter in order to deletion by timehandler. */
4690 acq->created = time_second;
4696 struct mbuf *n, *nn;
4697 struct sadb_sa *m_sa;
4698 struct sadb_msg *newmsg;
4701 /* create new sadb_msg to reply. */
4702 len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4703 PFKEY_ALIGN8(sizeof(struct sadb_sa));
4705 MGETHDR(n, M_NOWAIT, MT_DATA);
4707 if (!(MCLGET(n, M_NOWAIT))) {
4713 return key_senderror(so, m, ENOBUFS);
4719 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4720 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4722 m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4723 m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4724 m_sa->sadb_sa_exttype = SADB_EXT_SA;
4725 m_sa->sadb_sa_spi = htonl(spi);
4726 off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4728 IPSEC_ASSERT(off == len,
4729 ("length inconsistency (off %u len %u)", off, len));
4731 n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4732 SADB_EXT_ADDRESS_DST);
4735 return key_senderror(so, m, ENOBUFS);
4738 if (n->m_len < sizeof(struct sadb_msg)) {
4739 n = m_pullup(n, sizeof(struct sadb_msg));
4741 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4744 n->m_pkthdr.len = 0;
4745 for (nn = n; nn; nn = nn->m_next)
4746 n->m_pkthdr.len += nn->m_len;
4748 newmsg = mtod(n, struct sadb_msg *);
4749 newmsg->sadb_msg_seq = newsav->seq;
4750 newmsg->sadb_msg_errno = 0;
4751 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4754 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4759 * allocating new SPI
4760 * called by key_getspi().
4766 key_do_getnewspi(struct sadb_spirange *spirange, struct secasindex *saidx)
4770 int count = V_key_spi_trycnt;
4772 /* set spi range to allocate */
4773 if (spirange != NULL) {
4774 min = spirange->sadb_spirange_min;
4775 max = spirange->sadb_spirange_max;
4777 min = V_key_spi_minval;
4778 max = V_key_spi_maxval;
4780 /* IPCOMP needs 2-byte SPI */
4781 if (saidx->proto == IPPROTO_IPCOMP) {
4788 t = min; min = max; max = t;
4793 if (key_checkspidup(saidx, min) != NULL) {
4794 ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4799 count--; /* taking one cost. */
4807 /* when requesting to allocate spi ranged */
4809 /* generate pseudo-random SPI value ranged. */
4810 newspi = min + (key_random() % (max - min + 1));
4812 if (key_checkspidup(saidx, newspi) == NULL)
4816 if (count == 0 || newspi == 0) {
4817 ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4824 keystat.getspi_count =
4825 (keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4831 * SADB_UPDATE processing
4833 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4834 * key(AE), (identity(SD),) (sensitivity)>
4835 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4837 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4838 * (identity(SD),) (sensitivity)>
4841 * m will always be freed.
4844 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4846 struct sadb_sa *sa0;
4847 struct sadb_address *src0, *dst0;
4849 struct sadb_x_nat_t_type *type;
4850 struct sadb_x_nat_t_port *sport, *dport;
4851 struct sadb_address *iaddr, *raddr;
4852 struct sadb_x_nat_t_frag *frag;
4854 struct secasindex saidx;
4855 struct secashead *sah;
4856 struct secasvar *sav;
4862 IPSEC_ASSERT(so != NULL, ("null socket"));
4863 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4864 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4865 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4867 /* map satype to proto */
4868 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4869 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4871 return key_senderror(so, m, EINVAL);
4874 if (mhp->ext[SADB_EXT_SA] == NULL ||
4875 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4876 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4877 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4878 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4879 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4880 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4881 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4882 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4883 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4884 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4885 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4887 return key_senderror(so, m, EINVAL);
4889 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4890 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4891 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4892 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4894 return key_senderror(so, m, EINVAL);
4896 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4897 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4898 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4900 mode = IPSEC_MODE_ANY;
4903 /* XXX boundary checking for other extensions */
4905 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4906 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4907 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4909 /* XXX boundary check against sa_len */
4910 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4913 * Make sure the port numbers are zero.
4914 * In case of NAT-T we will update them later if needed.
4916 KEY_PORTTOSADDR(&saidx.src, 0);
4917 KEY_PORTTOSADDR(&saidx.dst, 0);
4921 * Handle NAT-T info if present.
4923 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4924 mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4925 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4927 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4928 mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4929 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4930 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
4932 return key_senderror(so, m, EINVAL);
4935 type = (struct sadb_x_nat_t_type *)
4936 mhp->ext[SADB_X_EXT_NAT_T_TYPE];
4937 sport = (struct sadb_x_nat_t_port *)
4938 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4939 dport = (struct sadb_x_nat_t_port *)
4940 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4945 if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
4946 mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
4947 if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
4948 mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
4949 ipseclog((LOG_DEBUG, "%s: invalid message\n",
4951 return key_senderror(so, m, EINVAL);
4953 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
4954 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
4955 ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
4957 iaddr = raddr = NULL;
4959 if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
4960 if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
4961 ipseclog((LOG_DEBUG, "%s: invalid message\n",
4963 return key_senderror(so, m, EINVAL);
4965 frag = (struct sadb_x_nat_t_frag *)
4966 mhp->ext[SADB_X_EXT_NAT_T_FRAG];
4972 /* get a SA header */
4973 if ((sah = key_getsah(&saidx)) == NULL) {
4974 ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
4975 return key_senderror(so, m, ENOENT);
4978 /* set spidx if there */
4980 error = key_setident(sah, m, mhp);
4982 return key_senderror(so, m, error);
4984 /* find a SA with sequence number. */
4985 #ifdef IPSEC_DOSEQCHECK
4986 if (mhp->msg->sadb_msg_seq != 0
4987 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4988 ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
4989 "exists.\n", __func__, mhp->msg->sadb_msg_seq));
4990 return key_senderror(so, m, ENOENT);
4994 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
4997 ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
4998 __func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4999 return key_senderror(so, m, EINVAL);
5003 /* validity check */
5004 if (sav->sah->saidx.proto != proto) {
5005 ipseclog((LOG_DEBUG, "%s: protocol mismatched "
5006 "(DB=%u param=%u)\n", __func__,
5007 sav->sah->saidx.proto, proto));
5008 return key_senderror(so, m, EINVAL);
5010 #ifdef IPSEC_DOSEQCHECK
5011 if (sav->spi != sa0->sadb_sa_spi) {
5012 ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
5014 (u_int32_t)ntohl(sav->spi),
5015 (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5016 return key_senderror(so, m, EINVAL);
5019 if (sav->pid != mhp->msg->sadb_msg_pid) {
5020 ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
5021 __func__, sav->pid, mhp->msg->sadb_msg_pid));
5022 return key_senderror(so, m, EINVAL);
5025 /* copy sav values */
5026 error = key_setsaval(sav, m, mhp);
5029 return key_senderror(so, m, error);
5034 * Handle more NAT-T info if present,
5035 * now that we have a sav to fill.
5038 sav->natt_type = type->sadb_x_nat_t_type_type;
5041 KEY_PORTTOSADDR(&sav->sah->saidx.src,
5042 sport->sadb_x_nat_t_port_port);
5044 KEY_PORTTOSADDR(&sav->sah->saidx.dst,
5045 dport->sadb_x_nat_t_port_port);
5049 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5050 * We should actually check for a minimum MTU here, if we
5051 * want to support it in ip_output.
5054 sav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5058 /* check SA values to be mature. */
5059 if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
5061 return key_senderror(so, m, 0);
5067 /* set msg buf from mhp */
5068 n = key_getmsgbuf_x1(m, mhp);
5070 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5071 return key_senderror(so, m, ENOBUFS);
5075 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5080 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5081 * only called by key_update().
5084 * others : found, pointer to a SA.
5086 #ifdef IPSEC_DOSEQCHECK
5087 static struct secasvar *
5088 key_getsavbyseq(struct secashead *sah, u_int32_t seq)
5090 struct secasvar *sav;
5093 state = SADB_SASTATE_LARVAL;
5095 /* search SAD with sequence number ? */
5096 LIST_FOREACH(sav, &sah->savtree[state], chain) {
5098 KEY_CHKSASTATE(state, sav->state, __func__);
5100 if (sav->seq == seq) {
5102 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
5103 printf("DP %s cause refcnt++:%d SA:%p\n",
5104 __func__, sav->refcnt, sav));
5114 * SADB_ADD processing
5115 * add an entry to SA database, when received
5116 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5117 * key(AE), (identity(SD),) (sensitivity)>
5120 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5121 * (identity(SD),) (sensitivity)>
5124 * IGNORE identity and sensitivity messages.
5126 * m will always be freed.
5129 key_add(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5131 struct sadb_sa *sa0;
5132 struct sadb_address *src0, *dst0;
5134 struct sadb_x_nat_t_type *type;
5135 struct sadb_address *iaddr, *raddr;
5136 struct sadb_x_nat_t_frag *frag;
5138 struct secasindex saidx;
5139 struct secashead *newsah;
5140 struct secasvar *newsav;
5146 IPSEC_ASSERT(so != NULL, ("null socket"));
5147 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5148 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5149 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5151 /* map satype to proto */
5152 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5153 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5155 return key_senderror(so, m, EINVAL);
5158 if (mhp->ext[SADB_EXT_SA] == NULL ||
5159 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5160 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5161 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5162 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5163 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5164 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5165 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5166 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5167 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5168 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5169 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5171 return key_senderror(so, m, EINVAL);
5173 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5174 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5175 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5177 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5179 return key_senderror(so, m, EINVAL);
5181 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5182 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5183 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5185 mode = IPSEC_MODE_ANY;
5189 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5190 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5191 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5193 /* XXX boundary check against sa_len */
5194 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5197 * Make sure the port numbers are zero.
5198 * In case of NAT-T we will update them later if needed.
5200 KEY_PORTTOSADDR(&saidx.src, 0);
5201 KEY_PORTTOSADDR(&saidx.dst, 0);
5205 * Handle NAT-T info if present.
5207 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5208 mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5209 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5210 struct sadb_x_nat_t_port *sport, *dport;
5212 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5213 mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5214 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5215 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5217 return key_senderror(so, m, EINVAL);
5220 type = (struct sadb_x_nat_t_type *)
5221 mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5222 sport = (struct sadb_x_nat_t_port *)
5223 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5224 dport = (struct sadb_x_nat_t_port *)
5225 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5228 KEY_PORTTOSADDR(&saidx.src,
5229 sport->sadb_x_nat_t_port_port);
5231 KEY_PORTTOSADDR(&saidx.dst,
5232 dport->sadb_x_nat_t_port_port);
5236 if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5237 mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5238 if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5239 mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5240 ipseclog((LOG_DEBUG, "%s: invalid message\n",
5242 return key_senderror(so, m, EINVAL);
5244 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5245 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5246 ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5248 iaddr = raddr = NULL;
5250 if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5251 if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5252 ipseclog((LOG_DEBUG, "%s: invalid message\n",
5254 return key_senderror(so, m, EINVAL);
5256 frag = (struct sadb_x_nat_t_frag *)
5257 mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5263 /* get a SA header */
5264 if ((newsah = key_getsah(&saidx)) == NULL) {
5265 /* create a new SA header */
5266 if ((newsah = key_newsah(&saidx)) == NULL) {
5267 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
5268 return key_senderror(so, m, ENOBUFS);
5272 /* set spidx if there */
5274 error = key_setident(newsah, m, mhp);
5276 return key_senderror(so, m, error);
5279 /* create new SA entry. */
5280 /* We can create new SA only if SPI is differenct. */
5282 newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5284 if (newsav != NULL) {
5285 ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5286 return key_senderror(so, m, EEXIST);
5288 newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5289 if (newsav == NULL) {
5290 return key_senderror(so, m, error);
5295 * Handle more NAT-T info if present,
5296 * now that we have a sav to fill.
5299 newsav->natt_type = type->sadb_x_nat_t_type_type;
5303 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5304 * We should actually check for a minimum MTU here, if we
5305 * want to support it in ip_output.
5308 newsav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5312 /* check SA values to be mature. */
5313 if ((error = key_mature(newsav)) != 0) {
5314 KEY_FREESAV(&newsav);
5315 return key_senderror(so, m, error);
5319 * don't call key_freesav() here, as we would like to keep the SA
5320 * in the database on success.
5326 /* set msg buf from mhp */
5327 n = key_getmsgbuf_x1(m, mhp);
5329 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5330 return key_senderror(so, m, ENOBUFS);
5334 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5340 key_setident(struct secashead *sah, struct mbuf *m,
5341 const struct sadb_msghdr *mhp)
5343 const struct sadb_ident *idsrc, *iddst;
5344 int idsrclen, iddstlen;
5346 IPSEC_ASSERT(sah != NULL, ("null secashead"));
5347 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5348 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5349 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5351 /* don't make buffer if not there */
5352 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5353 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5359 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5360 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5361 ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5365 idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5366 iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5367 idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5368 iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5370 /* validity check */
5371 if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5372 ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5376 switch (idsrc->sadb_ident_type) {
5377 case SADB_IDENTTYPE_PREFIX:
5378 case SADB_IDENTTYPE_FQDN:
5379 case SADB_IDENTTYPE_USERFQDN:
5381 /* XXX do nothing */
5387 /* make structure */
5388 sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5389 if (sah->idents == NULL) {
5390 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5393 sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5394 if (sah->identd == NULL) {
5395 free(sah->idents, M_IPSEC_MISC);
5397 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5400 sah->idents->type = idsrc->sadb_ident_type;
5401 sah->idents->id = idsrc->sadb_ident_id;
5403 sah->identd->type = iddst->sadb_ident_type;
5404 sah->identd->id = iddst->sadb_ident_id;
5410 * m will not be freed on return.
5411 * it is caller's responsibility to free the result.
5413 static struct mbuf *
5414 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
5418 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5419 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5420 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5422 /* create new sadb_msg to reply. */
5423 n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5424 SADB_EXT_SA, SADB_X_EXT_SA2,
5425 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5426 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5427 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5431 if (n->m_len < sizeof(struct sadb_msg)) {
5432 n = m_pullup(n, sizeof(struct sadb_msg));
5436 mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5437 mtod(n, struct sadb_msg *)->sadb_msg_len =
5438 PFKEY_UNIT64(n->m_pkthdr.len);
5444 * SADB_DELETE processing
5446 * <base, SA(*), address(SD)>
5447 * from the ikmpd, and set SADB_SASTATE_DEAD,
5449 * <base, SA(*), address(SD)>
5452 * m will always be freed.
5455 key_delete(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5457 struct sadb_sa *sa0;
5458 struct sadb_address *src0, *dst0;
5459 struct secasindex saidx;
5460 struct secashead *sah;
5461 struct secasvar *sav = NULL;
5464 IPSEC_ASSERT(so != NULL, ("null socket"));
5465 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5466 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5467 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5469 /* map satype to proto */
5470 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5471 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5473 return key_senderror(so, m, EINVAL);
5476 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5477 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5478 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5480 return key_senderror(so, m, EINVAL);
5483 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5484 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5485 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5487 return key_senderror(so, m, EINVAL);
5490 if (mhp->ext[SADB_EXT_SA] == NULL) {
5492 * Caller wants us to delete all non-LARVAL SAs
5493 * that match the src/dst. This is used during
5494 * IKE INITIAL-CONTACT.
5496 ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5497 return key_delete_all(so, m, mhp, proto);
5498 } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5499 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5501 return key_senderror(so, m, EINVAL);
5504 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5505 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5506 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5508 /* XXX boundary check against sa_len */
5509 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5512 * Make sure the port numbers are zero.
5513 * In case of NAT-T we will update them later if needed.
5515 KEY_PORTTOSADDR(&saidx.src, 0);
5516 KEY_PORTTOSADDR(&saidx.dst, 0);
5520 * Handle NAT-T info if present.
5522 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5523 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5524 struct sadb_x_nat_t_port *sport, *dport;
5526 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5527 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5528 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5530 return key_senderror(so, m, EINVAL);
5533 sport = (struct sadb_x_nat_t_port *)
5534 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5535 dport = (struct sadb_x_nat_t_port *)
5536 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5539 KEY_PORTTOSADDR(&saidx.src,
5540 sport->sadb_x_nat_t_port_port);
5542 KEY_PORTTOSADDR(&saidx.dst,
5543 dport->sadb_x_nat_t_port_port);
5547 /* get a SA header */
5549 LIST_FOREACH(sah, &V_sahtree, chain) {
5550 if (sah->state == SADB_SASTATE_DEAD)
5552 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5555 /* get a SA with SPI. */
5556 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5562 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5563 return key_senderror(so, m, ENOENT);
5566 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5572 struct sadb_msg *newmsg;
5574 /* create new sadb_msg to reply. */
5575 /* XXX-BZ NAT-T extensions? */
5576 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5577 SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5579 return key_senderror(so, m, ENOBUFS);
5581 if (n->m_len < sizeof(struct sadb_msg)) {
5582 n = m_pullup(n, sizeof(struct sadb_msg));
5584 return key_senderror(so, m, ENOBUFS);
5586 newmsg = mtod(n, struct sadb_msg *);
5587 newmsg->sadb_msg_errno = 0;
5588 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5591 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5596 * delete all SAs for src/dst. Called from key_delete().
5599 key_delete_all(struct socket *so, struct mbuf *m,
5600 const struct sadb_msghdr *mhp, u_int16_t proto)
5602 struct sadb_address *src0, *dst0;
5603 struct secasindex saidx;
5604 struct secashead *sah;
5605 struct secasvar *sav, *nextsav;
5606 u_int stateidx, state;
5608 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5609 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5611 /* XXX boundary check against sa_len */
5612 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5615 * Make sure the port numbers are zero.
5616 * In case of NAT-T we will update them later if needed.
5618 KEY_PORTTOSADDR(&saidx.src, 0);
5619 KEY_PORTTOSADDR(&saidx.dst, 0);
5623 * Handle NAT-T info if present.
5626 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5627 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5628 struct sadb_x_nat_t_port *sport, *dport;
5630 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5631 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5632 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5634 return key_senderror(so, m, EINVAL);
5637 sport = (struct sadb_x_nat_t_port *)
5638 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5639 dport = (struct sadb_x_nat_t_port *)
5640 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5643 KEY_PORTTOSADDR(&saidx.src,
5644 sport->sadb_x_nat_t_port_port);
5646 KEY_PORTTOSADDR(&saidx.dst,
5647 dport->sadb_x_nat_t_port_port);
5652 LIST_FOREACH(sah, &V_sahtree, chain) {
5653 if (sah->state == SADB_SASTATE_DEAD)
5655 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5658 /* Delete all non-LARVAL SAs. */
5660 stateidx < _ARRAYLEN(saorder_state_alive);
5662 state = saorder_state_alive[stateidx];
5663 if (state == SADB_SASTATE_LARVAL)
5665 for (sav = LIST_FIRST(&sah->savtree[state]);
5666 sav != NULL; sav = nextsav) {
5667 nextsav = LIST_NEXT(sav, chain);
5669 if (sav->state != state) {
5670 ipseclog((LOG_DEBUG, "%s: invalid "
5671 "sav->state (queue %d SA %d)\n",
5672 __func__, state, sav->state));
5676 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5684 struct sadb_msg *newmsg;
5686 /* create new sadb_msg to reply. */
5687 /* XXX-BZ NAT-T extensions? */
5688 n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5689 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5691 return key_senderror(so, m, ENOBUFS);
5693 if (n->m_len < sizeof(struct sadb_msg)) {
5694 n = m_pullup(n, sizeof(struct sadb_msg));
5696 return key_senderror(so, m, ENOBUFS);
5698 newmsg = mtod(n, struct sadb_msg *);
5699 newmsg->sadb_msg_errno = 0;
5700 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5703 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5708 * SADB_GET processing
5710 * <base, SA(*), address(SD)>
5711 * from the ikmpd, and get a SP and a SA to respond,
5713 * <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5714 * (identity(SD),) (sensitivity)>
5717 * m will always be freed.
5720 key_get(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5722 struct sadb_sa *sa0;
5723 struct sadb_address *src0, *dst0;
5724 struct secasindex saidx;
5725 struct secashead *sah;
5726 struct secasvar *sav = NULL;
5729 IPSEC_ASSERT(so != NULL, ("null socket"));
5730 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5731 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5732 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5734 /* map satype to proto */
5735 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5736 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5738 return key_senderror(so, m, EINVAL);
5741 if (mhp->ext[SADB_EXT_SA] == NULL ||
5742 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5743 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5744 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5746 return key_senderror(so, m, EINVAL);
5748 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5749 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5750 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5751 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5753 return key_senderror(so, m, EINVAL);
5756 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5757 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5758 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5760 /* XXX boundary check against sa_len */
5761 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5764 * Make sure the port numbers are zero.
5765 * In case of NAT-T we will update them later if needed.
5767 KEY_PORTTOSADDR(&saidx.src, 0);
5768 KEY_PORTTOSADDR(&saidx.dst, 0);
5772 * Handle NAT-T info if present.
5775 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5776 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5777 struct sadb_x_nat_t_port *sport, *dport;
5779 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5780 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5781 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5783 return key_senderror(so, m, EINVAL);
5786 sport = (struct sadb_x_nat_t_port *)
5787 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5788 dport = (struct sadb_x_nat_t_port *)
5789 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5792 KEY_PORTTOSADDR(&saidx.src,
5793 sport->sadb_x_nat_t_port_port);
5795 KEY_PORTTOSADDR(&saidx.dst,
5796 dport->sadb_x_nat_t_port_port);
5800 /* get a SA header */
5802 LIST_FOREACH(sah, &V_sahtree, chain) {
5803 if (sah->state == SADB_SASTATE_DEAD)
5805 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5808 /* get a SA with SPI. */
5809 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5815 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5816 return key_senderror(so, m, ENOENT);
5823 /* map proto to satype */
5824 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5825 ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5827 return key_senderror(so, m, EINVAL);
5830 /* create new sadb_msg to reply. */
5831 n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5832 mhp->msg->sadb_msg_pid);
5834 return key_senderror(so, m, ENOBUFS);
5837 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5841 /* XXX make it sysctl-configurable? */
5843 key_getcomb_setlifetime(struct sadb_comb *comb)
5846 comb->sadb_comb_soft_allocations = 1;
5847 comb->sadb_comb_hard_allocations = 1;
5848 comb->sadb_comb_soft_bytes = 0;
5849 comb->sadb_comb_hard_bytes = 0;
5850 comb->sadb_comb_hard_addtime = 86400; /* 1 day */
5851 comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5852 comb->sadb_comb_soft_usetime = 28800; /* 8 hours */
5853 comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5857 * XXX reorder combinations by preference
5858 * XXX no idea if the user wants ESP authentication or not
5860 static struct mbuf *
5863 struct sadb_comb *comb;
5864 struct enc_xform *algo;
5865 struct mbuf *result = NULL, *m, *n;
5869 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5872 for (i = 1; i <= SADB_EALG_MAX; i++) {
5873 algo = esp_algorithm_lookup(i);
5877 /* discard algorithms with key size smaller than system min */
5878 if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
5880 if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
5881 encmin = V_ipsec_esp_keymin;
5883 encmin = _BITS(algo->minkey);
5885 if (V_ipsec_esp_auth)
5886 m = key_getcomb_ah();
5888 IPSEC_ASSERT(l <= MLEN,
5889 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
5890 MGET(m, M_NOWAIT, MT_DATA);
5895 bzero(mtod(m, caddr_t), m->m_len);
5902 for (n = m; n; n = n->m_next)
5904 IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
5906 for (off = 0; off < totlen; off += l) {
5907 n = m_pulldown(m, off, l, &o);
5909 /* m is already freed */
5912 comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5913 bzero(comb, sizeof(*comb));
5914 key_getcomb_setlifetime(comb);
5915 comb->sadb_comb_encrypt = i;
5916 comb->sadb_comb_encrypt_minbits = encmin;
5917 comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5935 key_getsizes_ah(const struct auth_hash *ah, int alg, u_int16_t* min,
5939 *min = *max = ah->keysize;
5940 if (ah->keysize == 0) {
5942 * Transform takes arbitrary key size but algorithm
5943 * key size is restricted. Enforce this here.
5946 case SADB_X_AALG_MD5: *min = *max = 16; break;
5947 case SADB_X_AALG_SHA: *min = *max = 20; break;
5948 case SADB_X_AALG_NULL: *min = 1; *max = 256; break;
5949 case SADB_X_AALG_SHA2_256: *min = *max = 32; break;
5950 case SADB_X_AALG_SHA2_384: *min = *max = 48; break;
5951 case SADB_X_AALG_SHA2_512: *min = *max = 64; break;
5953 DPRINTF(("%s: unknown AH algorithm %u\n",
5961 * XXX reorder combinations by preference
5963 static struct mbuf *
5966 struct sadb_comb *comb;
5967 struct auth_hash *algo;
5969 u_int16_t minkeysize, maxkeysize;
5971 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5974 for (i = 1; i <= SADB_AALG_MAX; i++) {
5976 /* we prefer HMAC algorithms, not old algorithms */
5977 if (i != SADB_AALG_SHA1HMAC &&
5978 i != SADB_AALG_MD5HMAC &&
5979 i != SADB_X_AALG_SHA2_256 &&
5980 i != SADB_X_AALG_SHA2_384 &&
5981 i != SADB_X_AALG_SHA2_512)
5984 algo = ah_algorithm_lookup(i);
5987 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5988 /* discard algorithms with key size smaller than system min */
5989 if (_BITS(minkeysize) < V_ipsec_ah_keymin)
5993 IPSEC_ASSERT(l <= MLEN,
5994 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
5995 MGET(m, M_NOWAIT, MT_DATA);
6002 M_PREPEND(m, l, M_NOWAIT);
6006 comb = mtod(m, struct sadb_comb *);
6007 bzero(comb, sizeof(*comb));
6008 key_getcomb_setlifetime(comb);
6009 comb->sadb_comb_auth = i;
6010 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
6011 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
6018 * not really an official behavior. discussed in pf_key@inner.net in Sep2000.
6019 * XXX reorder combinations by preference
6021 static struct mbuf *
6022 key_getcomb_ipcomp()
6024 struct sadb_comb *comb;
6025 struct comp_algo *algo;
6028 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6031 for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6032 algo = ipcomp_algorithm_lookup(i);
6037 IPSEC_ASSERT(l <= MLEN,
6038 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6039 MGET(m, M_NOWAIT, MT_DATA);
6046 M_PREPEND(m, l, M_NOWAIT);
6050 comb = mtod(m, struct sadb_comb *);
6051 bzero(comb, sizeof(*comb));
6052 key_getcomb_setlifetime(comb);
6053 comb->sadb_comb_encrypt = i;
6054 /* what should we set into sadb_comb_*_{min,max}bits? */
6061 * XXX no way to pass mode (transport/tunnel) to userland
6062 * XXX replay checking?
6063 * XXX sysctl interface to ipsec_{ah,esp}_keymin
6065 static struct mbuf *
6066 key_getprop(const struct secasindex *saidx)
6068 struct sadb_prop *prop;
6070 const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6073 switch (saidx->proto) {
6075 m = key_getcomb_esp();
6078 m = key_getcomb_ah();
6080 case IPPROTO_IPCOMP:
6081 m = key_getcomb_ipcomp();
6089 M_PREPEND(m, l, M_NOWAIT);
6094 for (n = m; n; n = n->m_next)
6097 prop = mtod(m, struct sadb_prop *);
6098 bzero(prop, sizeof(*prop));
6099 prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6100 prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6101 prop->sadb_prop_replay = 32; /* XXX */
6107 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6109 * <base, SA, address(SD), (address(P)), x_policy,
6110 * (identity(SD),) (sensitivity,) proposal>
6111 * to KMD, and expect to receive
6112 * <base> with SADB_ACQUIRE if error occured,
6114 * <base, src address, dst address, (SPI range)> with SADB_GETSPI
6115 * from KMD by PF_KEY.
6117 * XXX x_policy is outside of RFC2367 (KAME extension).
6118 * XXX sensitivity is not supported.
6119 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6120 * see comment for key_getcomb_ipcomp().
6124 * others: error number
6127 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6129 struct mbuf *result = NULL, *m;
6130 struct secacq *newacq;
6135 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6136 satype = key_proto2satype(saidx->proto);
6137 IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6140 * We never do anything about acquirng SA. There is anather
6141 * solution that kernel blocks to send SADB_ACQUIRE message until
6142 * getting something message from IKEd. In later case, to be
6143 * managed with ACQUIRING list.
6145 /* Get an entry to check whether sending message or not. */
6146 if ((newacq = key_getacq(saidx)) != NULL) {
6147 if (V_key_blockacq_count < newacq->count) {
6148 /* reset counter and do send message. */
6151 /* increment counter and do nothing. */
6156 /* make new entry for blocking to send SADB_ACQUIRE. */
6157 if ((newacq = key_newacq(saidx)) == NULL)
6163 m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6171 * No SADB_X_EXT_NAT_T_* here: we do not know
6172 * anything related to NAT-T at this time.
6175 /* set sadb_address for saidx's. */
6176 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6177 &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6184 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6185 &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6192 /* XXX proxy address (optional) */
6194 /* set sadb_x_policy */
6196 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6204 /* XXX identity (optional) */
6206 if (idexttype && fqdn) {
6207 /* create identity extension (FQDN) */
6208 struct sadb_ident *id;
6211 fqdnlen = strlen(fqdn) + 1; /* +1 for terminating-NUL */
6212 id = (struct sadb_ident *)p;
6213 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6214 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6215 id->sadb_ident_exttype = idexttype;
6216 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6217 bcopy(fqdn, id + 1, fqdnlen);
6218 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6222 /* create identity extension (USERFQDN) */
6223 struct sadb_ident *id;
6227 /* +1 for terminating-NUL */
6228 userfqdnlen = strlen(userfqdn) + 1;
6231 id = (struct sadb_ident *)p;
6232 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6233 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6234 id->sadb_ident_exttype = idexttype;
6235 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6236 /* XXX is it correct? */
6237 if (curproc && curproc->p_cred)
6238 id->sadb_ident_id = curproc->p_cred->p_ruid;
6239 if (userfqdn && userfqdnlen)
6240 bcopy(userfqdn, id + 1, userfqdnlen);
6241 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6245 /* XXX sensitivity (optional) */
6247 /* create proposal/combination extension */
6248 m = key_getprop(saidx);
6251 * spec conformant: always attach proposal/combination extension,
6252 * the problem is that we have no way to attach it for ipcomp,
6253 * due to the way sadb_comb is declared in RFC2367.
6262 * outside of spec; make proposal/combination extension optional.
6268 if ((result->m_flags & M_PKTHDR) == 0) {
6273 if (result->m_len < sizeof(struct sadb_msg)) {
6274 result = m_pullup(result, sizeof(struct sadb_msg));
6275 if (result == NULL) {
6281 result->m_pkthdr.len = 0;
6282 for (m = result; m; m = m->m_next)
6283 result->m_pkthdr.len += m->m_len;
6285 mtod(result, struct sadb_msg *)->sadb_msg_len =
6286 PFKEY_UNIT64(result->m_pkthdr.len);
6288 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6296 static struct secacq *
6297 key_newacq(const struct secasindex *saidx)
6299 struct secacq *newacq;
6302 newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6303 if (newacq == NULL) {
6304 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6309 bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
6310 newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6311 newacq->created = time_second;
6314 /* add to acqtree */
6316 LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
6322 static struct secacq *
6323 key_getacq(const struct secasindex *saidx)
6328 LIST_FOREACH(acq, &V_acqtree, chain) {
6329 if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6337 static struct secacq *
6338 key_getacqbyseq(u_int32_t seq)
6343 LIST_FOREACH(acq, &V_acqtree, chain) {
6344 if (acq->seq == seq)
6352 static struct secspacq *
6353 key_newspacq(struct secpolicyindex *spidx)
6355 struct secspacq *acq;
6358 acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6360 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6365 bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6366 acq->created = time_second;
6369 /* add to spacqtree */
6371 LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6377 static struct secspacq *
6378 key_getspacq(struct secpolicyindex *spidx)
6380 struct secspacq *acq;
6383 LIST_FOREACH(acq, &V_spacqtree, chain) {
6384 if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6385 /* NB: return holding spacq_lock */
6395 * SADB_ACQUIRE processing,
6396 * in first situation, is receiving
6398 * from the ikmpd, and clear sequence of its secasvar entry.
6400 * In second situation, is receiving
6401 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6402 * from a user land process, and return
6403 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6406 * m will always be freed.
6409 key_acquire2(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6411 const struct sadb_address *src0, *dst0;
6412 struct secasindex saidx;
6413 struct secashead *sah;
6417 IPSEC_ASSERT(so != NULL, ("null socket"));
6418 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6419 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6420 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6423 * Error message from KMd.
6424 * We assume that if error was occured in IKEd, the length of PFKEY
6425 * message is equal to the size of sadb_msg structure.
6426 * We do not raise error even if error occured in this function.
6428 if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6431 /* check sequence number */
6432 if (mhp->msg->sadb_msg_seq == 0) {
6433 ipseclog((LOG_DEBUG, "%s: must specify sequence "
6434 "number.\n", __func__));
6439 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6441 * the specified larval SA is already gone, or we got
6442 * a bogus sequence number. we can silently ignore it.
6448 /* reset acq counter in order to deletion by timehander. */
6449 acq->created = time_second;
6456 * This message is from user land.
6459 /* map satype to proto */
6460 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6461 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6463 return key_senderror(so, m, EINVAL);
6466 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6467 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6468 mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6470 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6472 return key_senderror(so, m, EINVAL);
6474 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6475 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6476 mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6478 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6480 return key_senderror(so, m, EINVAL);
6483 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6484 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6486 /* XXX boundary check against sa_len */
6487 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6490 * Make sure the port numbers are zero.
6491 * In case of NAT-T we will update them later if needed.
6493 KEY_PORTTOSADDR(&saidx.src, 0);
6494 KEY_PORTTOSADDR(&saidx.dst, 0);
6498 * Handle NAT-T info if present.
6501 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
6502 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
6503 struct sadb_x_nat_t_port *sport, *dport;
6505 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
6506 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
6507 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
6509 return key_senderror(so, m, EINVAL);
6512 sport = (struct sadb_x_nat_t_port *)
6513 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
6514 dport = (struct sadb_x_nat_t_port *)
6515 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
6518 KEY_PORTTOSADDR(&saidx.src,
6519 sport->sadb_x_nat_t_port_port);
6521 KEY_PORTTOSADDR(&saidx.dst,
6522 dport->sadb_x_nat_t_port_port);
6526 /* get a SA index */
6528 LIST_FOREACH(sah, &V_sahtree, chain) {
6529 if (sah->state == SADB_SASTATE_DEAD)
6531 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6536 ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6537 return key_senderror(so, m, EEXIST);
6540 error = key_acquire(&saidx, NULL);
6542 ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6543 __func__, mhp->msg->sadb_msg_errno));
6544 return key_senderror(so, m, error);
6547 return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6551 * SADB_REGISTER processing.
6552 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6555 * from the ikmpd, and register a socket to send PF_KEY messages,
6559 * If socket is detached, must free from regnode.
6561 * m will always be freed.
6564 key_register(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6566 struct secreg *reg, *newreg = 0;
6568 IPSEC_ASSERT(so != NULL, ("null socket"));
6569 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6570 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6571 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6573 /* check for invalid register message */
6574 if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6575 return key_senderror(so, m, EINVAL);
6577 /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6578 if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6581 /* check whether existing or not */
6583 LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6584 if (reg->so == so) {
6586 ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6588 return key_senderror(so, m, EEXIST);
6592 /* create regnode */
6593 newreg = malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6594 if (newreg == NULL) {
6596 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6597 return key_senderror(so, m, ENOBUFS);
6601 ((struct keycb *)sotorawcb(so))->kp_registered++;
6603 /* add regnode to regtree. */
6604 LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6610 struct sadb_msg *newmsg;
6611 struct sadb_supported *sup;
6612 u_int len, alen, elen;
6615 struct sadb_alg *alg;
6617 /* create new sadb_msg to reply. */
6619 for (i = 1; i <= SADB_AALG_MAX; i++) {
6620 if (ah_algorithm_lookup(i))
6621 alen += sizeof(struct sadb_alg);
6624 alen += sizeof(struct sadb_supported);
6626 for (i = 1; i <= SADB_EALG_MAX; i++) {
6627 if (esp_algorithm_lookup(i))
6628 elen += sizeof(struct sadb_alg);
6631 elen += sizeof(struct sadb_supported);
6633 len = sizeof(struct sadb_msg) + alen + elen;
6636 return key_senderror(so, m, ENOBUFS);
6638 MGETHDR(n, M_NOWAIT, MT_DATA);
6640 if (!(MCLGET(n, M_NOWAIT))) {
6646 return key_senderror(so, m, ENOBUFS);
6648 n->m_pkthdr.len = n->m_len = len;
6652 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6653 newmsg = mtod(n, struct sadb_msg *);
6654 newmsg->sadb_msg_errno = 0;
6655 newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6656 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6658 /* for authentication algorithm */
6660 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6661 sup->sadb_supported_len = PFKEY_UNIT64(alen);
6662 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6663 off += PFKEY_ALIGN8(sizeof(*sup));
6665 for (i = 1; i <= SADB_AALG_MAX; i++) {
6666 struct auth_hash *aalgo;
6667 u_int16_t minkeysize, maxkeysize;
6669 aalgo = ah_algorithm_lookup(i);
6672 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6673 alg->sadb_alg_id = i;
6674 alg->sadb_alg_ivlen = 0;
6675 key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6676 alg->sadb_alg_minbits = _BITS(minkeysize);
6677 alg->sadb_alg_maxbits = _BITS(maxkeysize);
6678 off += PFKEY_ALIGN8(sizeof(*alg));
6682 /* for encryption algorithm */
6684 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6685 sup->sadb_supported_len = PFKEY_UNIT64(elen);
6686 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6687 off += PFKEY_ALIGN8(sizeof(*sup));
6689 for (i = 1; i <= SADB_EALG_MAX; i++) {
6690 struct enc_xform *ealgo;
6692 ealgo = esp_algorithm_lookup(i);
6695 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6696 alg->sadb_alg_id = i;
6697 alg->sadb_alg_ivlen = ealgo->blocksize;
6698 alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6699 alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6700 off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6704 IPSEC_ASSERT(off == len,
6705 ("length assumption failed (off %u len %u)", off, len));
6708 return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6713 * free secreg entry registered.
6714 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6717 key_freereg(struct socket *so)
6722 IPSEC_ASSERT(so != NULL, ("NULL so"));
6725 * check whether existing or not.
6726 * check all type of SA, because there is a potential that
6727 * one socket is registered to multiple type of SA.
6730 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6731 LIST_FOREACH(reg, &V_regtree[i], chain) {
6732 if (reg->so == so && __LIST_CHAINED(reg)) {
6733 LIST_REMOVE(reg, chain);
6734 free(reg, M_IPSEC_SAR);
6743 * SADB_EXPIRE processing
6745 * <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6747 * NOTE: We send only soft lifetime extension.
6750 * others : error number
6753 key_expire(struct secasvar *sav)
6756 struct mbuf *result = NULL, *m;
6759 struct sadb_lifetime *lt;
6761 IPSEC_ASSERT (sav != NULL, ("null sav"));
6762 IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6764 /* set msg header */
6765 satype = key_proto2satype(sav->sah->saidx.proto);
6766 IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6767 m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6774 /* create SA extension */
6775 m = key_setsadbsa(sav);
6782 /* create SA extension */
6783 m = key_setsadbxsa2(sav->sah->saidx.mode,
6784 sav->replay ? sav->replay->count : 0,
6785 sav->sah->saidx.reqid);
6792 /* create lifetime extension (current and soft) */
6793 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6794 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
6801 bzero(mtod(m, caddr_t), len);
6802 lt = mtod(m, struct sadb_lifetime *);
6803 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6804 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6805 lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6806 lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6807 lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6808 lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6809 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6810 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6811 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6812 lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6813 lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6814 lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6815 lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6818 /* set sadb_address for source */
6819 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6820 &sav->sah->saidx.src.sa,
6821 FULLMASK, IPSEC_ULPROTO_ANY);
6828 /* set sadb_address for destination */
6829 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6830 &sav->sah->saidx.dst.sa,
6831 FULLMASK, IPSEC_ULPROTO_ANY);
6839 * XXX-BZ Handle NAT-T extensions here.
6842 if ((result->m_flags & M_PKTHDR) == 0) {
6847 if (result->m_len < sizeof(struct sadb_msg)) {
6848 result = m_pullup(result, sizeof(struct sadb_msg));
6849 if (result == NULL) {
6855 result->m_pkthdr.len = 0;
6856 for (m = result; m; m = m->m_next)
6857 result->m_pkthdr.len += m->m_len;
6859 mtod(result, struct sadb_msg *)->sadb_msg_len =
6860 PFKEY_UNIT64(result->m_pkthdr.len);
6862 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6871 * SADB_FLUSH processing
6874 * from the ikmpd, and free all entries in secastree.
6878 * NOTE: to do is only marking SADB_SASTATE_DEAD.
6880 * m will always be freed.
6883 key_flush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6885 struct sadb_msg *newmsg;
6886 struct secashead *sah, *nextsah;
6887 struct secasvar *sav, *nextsav;
6892 IPSEC_ASSERT(so != NULL, ("null socket"));
6893 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6894 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6896 /* map satype to proto */
6897 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6898 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6900 return key_senderror(so, m, EINVAL);
6903 /* no SATYPE specified, i.e. flushing all SA. */
6905 for (sah = LIST_FIRST(&V_sahtree);
6908 nextsah = LIST_NEXT(sah, chain);
6910 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6911 && proto != sah->saidx.proto)
6915 stateidx < _ARRAYLEN(saorder_state_alive);
6917 state = saorder_state_any[stateidx];
6918 for (sav = LIST_FIRST(&sah->savtree[state]);
6922 nextsav = LIST_NEXT(sav, chain);
6924 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6929 sah->state = SADB_SASTATE_DEAD;
6933 if (m->m_len < sizeof(struct sadb_msg) ||
6934 sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6935 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6936 return key_senderror(so, m, ENOBUFS);
6942 m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6943 newmsg = mtod(m, struct sadb_msg *);
6944 newmsg->sadb_msg_errno = 0;
6945 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6947 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6951 * SADB_DUMP processing
6952 * dump all entries including status of DEAD in SAD.
6955 * from the ikmpd, and dump all secasvar leaves
6960 * m will always be freed.
6963 key_dump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6965 struct secashead *sah;
6966 struct secasvar *sav;
6972 struct sadb_msg *newmsg;
6975 IPSEC_ASSERT(so != NULL, ("null socket"));
6976 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6977 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6978 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6980 /* map satype to proto */
6981 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6982 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6984 return key_senderror(so, m, EINVAL);
6987 /* count sav entries to be sent to the userland. */
6990 LIST_FOREACH(sah, &V_sahtree, chain) {
6991 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6992 && proto != sah->saidx.proto)
6996 stateidx < _ARRAYLEN(saorder_state_any);
6998 state = saorder_state_any[stateidx];
6999 LIST_FOREACH(sav, &sah->savtree[state], chain) {
7007 return key_senderror(so, m, ENOENT);
7010 /* send this to the userland, one at a time. */
7012 LIST_FOREACH(sah, &V_sahtree, chain) {
7013 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
7014 && proto != sah->saidx.proto)
7017 /* map proto to satype */
7018 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
7020 ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
7021 "SAD.\n", __func__));
7022 return key_senderror(so, m, EINVAL);
7026 stateidx < _ARRAYLEN(saorder_state_any);
7028 state = saorder_state_any[stateidx];
7029 LIST_FOREACH(sav, &sah->savtree[state], chain) {
7030 n = key_setdumpsa(sav, SADB_DUMP, satype,
7031 --cnt, mhp->msg->sadb_msg_pid);
7034 return key_senderror(so, m, ENOBUFS);
7036 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7047 * SADB_X_PROMISC processing
7049 * m will always be freed.
7052 key_promisc(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7056 IPSEC_ASSERT(so != NULL, ("null socket"));
7057 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7058 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7059 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7061 olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7063 if (olen < sizeof(struct sadb_msg)) {
7065 return key_senderror(so, m, EINVAL);
7070 } else if (olen == sizeof(struct sadb_msg)) {
7071 /* enable/disable promisc mode */
7074 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7075 return key_senderror(so, m, EINVAL);
7076 mhp->msg->sadb_msg_errno = 0;
7077 switch (mhp->msg->sadb_msg_satype) {
7080 kp->kp_promisc = mhp->msg->sadb_msg_satype;
7083 return key_senderror(so, m, EINVAL);
7086 /* send the original message back to everyone */
7087 mhp->msg->sadb_msg_errno = 0;
7088 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7090 /* send packet as is */
7092 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7094 /* TODO: if sadb_msg_seq is specified, send to specific pid */
7095 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7099 static int (*key_typesw[])(struct socket *, struct mbuf *,
7100 const struct sadb_msghdr *) = {
7101 NULL, /* SADB_RESERVED */
7102 key_getspi, /* SADB_GETSPI */
7103 key_update, /* SADB_UPDATE */
7104 key_add, /* SADB_ADD */
7105 key_delete, /* SADB_DELETE */
7106 key_get, /* SADB_GET */
7107 key_acquire2, /* SADB_ACQUIRE */
7108 key_register, /* SADB_REGISTER */
7109 NULL, /* SADB_EXPIRE */
7110 key_flush, /* SADB_FLUSH */
7111 key_dump, /* SADB_DUMP */
7112 key_promisc, /* SADB_X_PROMISC */
7113 NULL, /* SADB_X_PCHANGE */
7114 key_spdadd, /* SADB_X_SPDUPDATE */
7115 key_spdadd, /* SADB_X_SPDADD */
7116 key_spddelete, /* SADB_X_SPDDELETE */
7117 key_spdget, /* SADB_X_SPDGET */
7118 NULL, /* SADB_X_SPDACQUIRE */
7119 key_spddump, /* SADB_X_SPDDUMP */
7120 key_spdflush, /* SADB_X_SPDFLUSH */
7121 key_spdadd, /* SADB_X_SPDSETIDX */
7122 NULL, /* SADB_X_SPDEXPIRE */
7123 key_spddelete2, /* SADB_X_SPDDELETE2 */
7127 * parse sadb_msg buffer to process PFKEYv2,
7128 * and create a data to response if needed.
7129 * I think to be dealed with mbuf directly.
7131 * msgp : pointer to pointer to a received buffer pulluped.
7132 * This is rewrited to response.
7133 * so : pointer to socket.
7135 * length for buffer to send to user process.
7138 key_parse(struct mbuf *m, struct socket *so)
7140 struct sadb_msg *msg;
7141 struct sadb_msghdr mh;
7146 IPSEC_ASSERT(so != NULL, ("null socket"));
7147 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7149 #if 0 /*kdebug_sadb assumes msg in linear buffer*/
7150 KEYDEBUG(KEYDEBUG_KEY_DUMP,
7151 ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
7155 if (m->m_len < sizeof(struct sadb_msg)) {
7156 m = m_pullup(m, sizeof(struct sadb_msg));
7160 msg = mtod(m, struct sadb_msg *);
7161 orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7162 target = KEY_SENDUP_ONE;
7164 if ((m->m_flags & M_PKTHDR) == 0 ||
7165 m->m_pkthdr.len != m->m_pkthdr.len) {
7166 ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7167 PFKEYSTAT_INC(out_invlen);
7172 if (msg->sadb_msg_version != PF_KEY_V2) {
7173 ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7174 __func__, msg->sadb_msg_version));
7175 PFKEYSTAT_INC(out_invver);
7180 if (msg->sadb_msg_type > SADB_MAX) {
7181 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7182 __func__, msg->sadb_msg_type));
7183 PFKEYSTAT_INC(out_invmsgtype);
7188 /* for old-fashioned code - should be nuked */
7189 if (m->m_pkthdr.len > MCLBYTES) {
7196 MGETHDR(n, M_NOWAIT, MT_DATA);
7197 if (n && m->m_pkthdr.len > MHLEN) {
7198 if (!(MCLGET(n, M_NOWAIT))) {
7207 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7208 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7214 /* align the mbuf chain so that extensions are in contiguous region. */
7215 error = key_align(m, &mh);
7222 switch (msg->sadb_msg_satype) {
7223 case SADB_SATYPE_UNSPEC:
7224 switch (msg->sadb_msg_type) {
7232 ipseclog((LOG_DEBUG, "%s: must specify satype "
7233 "when msg type=%u.\n", __func__,
7234 msg->sadb_msg_type));
7235 PFKEYSTAT_INC(out_invsatype);
7240 case SADB_SATYPE_AH:
7241 case SADB_SATYPE_ESP:
7242 case SADB_X_SATYPE_IPCOMP:
7243 case SADB_X_SATYPE_TCPSIGNATURE:
7244 switch (msg->sadb_msg_type) {
7246 case SADB_X_SPDDELETE:
7248 case SADB_X_SPDDUMP:
7249 case SADB_X_SPDFLUSH:
7250 case SADB_X_SPDSETIDX:
7251 case SADB_X_SPDUPDATE:
7252 case SADB_X_SPDDELETE2:
7253 ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7254 __func__, msg->sadb_msg_type));
7255 PFKEYSTAT_INC(out_invsatype);
7260 case SADB_SATYPE_RSVP:
7261 case SADB_SATYPE_OSPFV2:
7262 case SADB_SATYPE_RIPV2:
7263 case SADB_SATYPE_MIP:
7264 ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7265 __func__, msg->sadb_msg_satype));
7266 PFKEYSTAT_INC(out_invsatype);
7269 case 1: /* XXX: What does it do? */
7270 if (msg->sadb_msg_type == SADB_X_PROMISC)
7274 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7275 __func__, msg->sadb_msg_satype));
7276 PFKEYSTAT_INC(out_invsatype);
7281 /* check field of upper layer protocol and address family */
7282 if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7283 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7284 struct sadb_address *src0, *dst0;
7287 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7288 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7290 /* check upper layer protocol */
7291 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7292 ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7293 "mismatched.\n", __func__));
7294 PFKEYSTAT_INC(out_invaddr);
7300 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7301 PFKEY_ADDR_SADDR(dst0)->sa_family) {
7302 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7304 PFKEYSTAT_INC(out_invaddr);
7308 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7309 PFKEY_ADDR_SADDR(dst0)->sa_len) {
7310 ipseclog((LOG_DEBUG, "%s: address struct size "
7311 "mismatched.\n", __func__));
7312 PFKEYSTAT_INC(out_invaddr);
7317 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7319 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7320 sizeof(struct sockaddr_in)) {
7321 PFKEYSTAT_INC(out_invaddr);
7327 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7328 sizeof(struct sockaddr_in6)) {
7329 PFKEYSTAT_INC(out_invaddr);
7335 ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7337 PFKEYSTAT_INC(out_invaddr);
7338 error = EAFNOSUPPORT;
7342 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7344 plen = sizeof(struct in_addr) << 3;
7347 plen = sizeof(struct in6_addr) << 3;
7350 plen = 0; /*fool gcc*/
7354 /* check max prefix length */
7355 if (src0->sadb_address_prefixlen > plen ||
7356 dst0->sadb_address_prefixlen > plen) {
7357 ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7359 PFKEYSTAT_INC(out_invaddr);
7365 * prefixlen == 0 is valid because there can be a case when
7366 * all addresses are matched.
7370 if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7371 key_typesw[msg->sadb_msg_type] == NULL) {
7372 PFKEYSTAT_INC(out_invmsgtype);
7377 return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7380 msg->sadb_msg_errno = error;
7381 return key_sendup_mbuf(so, m, target);
7385 key_senderror(struct socket *so, struct mbuf *m, int code)
7387 struct sadb_msg *msg;
7389 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7390 ("mbuf too small, len %u", m->m_len));
7392 msg = mtod(m, struct sadb_msg *);
7393 msg->sadb_msg_errno = code;
7394 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7398 * set the pointer to each header into message buffer.
7399 * m will be freed on error.
7400 * XXX larger-than-MCLBYTES extension?
7403 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
7406 struct sadb_ext *ext;
7411 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7412 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7413 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7414 ("mbuf too small, len %u", m->m_len));
7417 bzero(mhp, sizeof(*mhp));
7419 mhp->msg = mtod(m, struct sadb_msg *);
7420 mhp->ext[0] = (struct sadb_ext *)mhp->msg; /*XXX backward compat */
7422 end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7423 extlen = end; /*just in case extlen is not updated*/
7424 for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7425 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7427 /* m is already freed */
7430 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7433 switch (ext->sadb_ext_type) {
7435 case SADB_EXT_ADDRESS_SRC:
7436 case SADB_EXT_ADDRESS_DST:
7437 case SADB_EXT_ADDRESS_PROXY:
7438 case SADB_EXT_LIFETIME_CURRENT:
7439 case SADB_EXT_LIFETIME_HARD:
7440 case SADB_EXT_LIFETIME_SOFT:
7441 case SADB_EXT_KEY_AUTH:
7442 case SADB_EXT_KEY_ENCRYPT:
7443 case SADB_EXT_IDENTITY_SRC:
7444 case SADB_EXT_IDENTITY_DST:
7445 case SADB_EXT_SENSITIVITY:
7446 case SADB_EXT_PROPOSAL:
7447 case SADB_EXT_SUPPORTED_AUTH:
7448 case SADB_EXT_SUPPORTED_ENCRYPT:
7449 case SADB_EXT_SPIRANGE:
7450 case SADB_X_EXT_POLICY:
7451 case SADB_X_EXT_SA2:
7453 case SADB_X_EXT_NAT_T_TYPE:
7454 case SADB_X_EXT_NAT_T_SPORT:
7455 case SADB_X_EXT_NAT_T_DPORT:
7456 case SADB_X_EXT_NAT_T_OAI:
7457 case SADB_X_EXT_NAT_T_OAR:
7458 case SADB_X_EXT_NAT_T_FRAG:
7460 /* duplicate check */
7462 * XXX Are there duplication payloads of either
7463 * KEY_AUTH or KEY_ENCRYPT ?
7465 if (mhp->ext[ext->sadb_ext_type] != NULL) {
7466 ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7467 "%u\n", __func__, ext->sadb_ext_type));
7469 PFKEYSTAT_INC(out_dupext);
7474 ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7475 __func__, ext->sadb_ext_type));
7477 PFKEYSTAT_INC(out_invexttype);
7481 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7483 if (key_validate_ext(ext, extlen)) {
7485 PFKEYSTAT_INC(out_invlen);
7489 n = m_pulldown(m, off, extlen, &toff);
7491 /* m is already freed */
7494 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7496 mhp->ext[ext->sadb_ext_type] = ext;
7497 mhp->extoff[ext->sadb_ext_type] = off;
7498 mhp->extlen[ext->sadb_ext_type] = extlen;
7503 PFKEYSTAT_INC(out_invlen);
7511 key_validate_ext(const struct sadb_ext *ext, int len)
7513 const struct sockaddr *sa;
7514 enum { NONE, ADDR } checktype = NONE;
7516 const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7518 if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7521 /* if it does not match minimum/maximum length, bail */
7522 if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7523 ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7525 if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7527 if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7530 /* more checks based on sadb_ext_type XXX need more */
7531 switch (ext->sadb_ext_type) {
7532 case SADB_EXT_ADDRESS_SRC:
7533 case SADB_EXT_ADDRESS_DST:
7534 case SADB_EXT_ADDRESS_PROXY:
7535 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7538 case SADB_EXT_IDENTITY_SRC:
7539 case SADB_EXT_IDENTITY_DST:
7540 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7541 SADB_X_IDENTTYPE_ADDR) {
7542 baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7552 switch (checktype) {
7556 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7557 if (len < baselen + sal)
7559 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7572 for (i = 0; i < IPSEC_DIR_MAX; i++)
7573 TAILQ_INIT(&V_sptree[i]);
7575 LIST_INIT(&V_sahtree);
7577 for (i = 0; i <= SADB_SATYPE_MAX; i++)
7578 LIST_INIT(&V_regtree[i]);
7580 LIST_INIT(&V_acqtree);
7581 LIST_INIT(&V_spacqtree);
7583 if (!IS_DEFAULT_VNET(curvnet))
7587 REGTREE_LOCK_INIT();
7588 SAHTREE_LOCK_INIT();
7592 #ifndef IPSEC_DEBUG2
7593 callout_init(&key_timer, CALLOUT_MPSAFE);
7594 callout_reset(&key_timer, hz, key_timehandler, NULL);
7595 #endif /*IPSEC_DEBUG2*/
7597 /* initialize key statistics */
7598 keystat.getspi_count = 1;
7600 printf("IPsec: Initialized Security Association Processing.\n");
7607 TAILQ_HEAD(, secpolicy) drainq;
7608 struct secpolicy *sp, *nextsp;
7609 struct secacq *acq, *nextacq;
7610 struct secspacq *spacq, *nextspacq;
7611 struct secashead *sah, *nextsah;
7615 TAILQ_INIT(&drainq);
7617 for (i = 0; i < IPSEC_DIR_MAX; i++) {
7618 TAILQ_CONCAT(&drainq, &V_sptree[i], chain);
7621 sp = TAILQ_FIRST(&drainq);
7622 while (sp != NULL) {
7623 nextsp = TAILQ_NEXT(sp, chain);
7629 for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
7630 nextsah = LIST_NEXT(sah, chain);
7631 if (__LIST_CHAINED(sah)) {
7632 LIST_REMOVE(sah, chain);
7633 free(sah, M_IPSEC_SAH);
7639 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7640 LIST_FOREACH(reg, &V_regtree[i], chain) {
7641 if (__LIST_CHAINED(reg)) {
7642 LIST_REMOVE(reg, chain);
7643 free(reg, M_IPSEC_SAR);
7651 for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
7652 nextacq = LIST_NEXT(acq, chain);
7653 if (__LIST_CHAINED(acq)) {
7654 LIST_REMOVE(acq, chain);
7655 free(acq, M_IPSEC_SAQ);
7661 for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
7662 spacq = nextspacq) {
7663 nextspacq = LIST_NEXT(spacq, chain);
7664 if (__LIST_CHAINED(spacq)) {
7665 LIST_REMOVE(spacq, chain);
7666 free(spacq, M_IPSEC_SAQ);
7674 * XXX: maybe This function is called after INBOUND IPsec processing.
7676 * Special check for tunnel-mode packets.
7677 * We must make some checks for consistency between inner and outer IP header.
7679 * xxx more checks to be provided
7682 key_checktunnelsanity(struct secasvar *sav, u_int family, caddr_t src,
7685 IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7687 /* XXX: check inner IP header */
7692 /* record data transfer on SA, and update timestamps */
7694 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
7696 IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7697 IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7702 * XXX Currently, there is a difference of bytes size
7703 * between inbound and outbound processing.
7705 sav->lft_c->bytes += m->m_pkthdr.len;
7706 /* to check bytes lifetime is done in key_timehandler(). */
7709 * We use the number of packets as the unit of
7710 * allocations. We increment the variable
7711 * whenever {esp,ah}_{in,out}put is called.
7713 sav->lft_c->allocations++;
7714 /* XXX check for expires? */
7717 * NOTE: We record CURRENT usetime by using wall clock,
7718 * in seconds. HARD and SOFT lifetime are measured by the time
7719 * difference (again in seconds) from usetime.
7723 * -----+-----+--------+---> t
7724 * <--------------> HARD
7727 sav->lft_c->usetime = time_second;
7728 /* XXX check for expires? */
7734 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7736 IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7737 SAHTREE_LOCK_ASSERT();
7739 if (sav->state != state) {
7740 if (__LIST_CHAINED(sav))
7741 LIST_REMOVE(sav, chain);
7743 LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7748 key_sa_stir_iv(struct secasvar *sav)
7751 IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7752 key_randomfill(sav->iv, sav->ivlen);
7756 * Take one of the kernel's security keys and convert it into a PF_KEY
7757 * structure within an mbuf, suitable for sending up to a waiting
7758 * application in user land.
7761 * src: A pointer to a kernel security key.
7762 * exttype: Which type of key this is. Refer to the PF_KEY data structures.
7764 * a valid mbuf or NULL indicating an error
7768 static struct mbuf *
7769 key_setkey(struct seckey *src, u_int16_t exttype)
7778 len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
7779 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
7784 p = mtod(m, struct sadb_key *);
7786 p->sadb_key_len = PFKEY_UNIT64(len);
7787 p->sadb_key_exttype = exttype;
7788 p->sadb_key_bits = src->bits;
7789 bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
7795 * Take one of the kernel's lifetime data structures and convert it
7796 * into a PF_KEY structure within an mbuf, suitable for sending up to
7797 * a waiting application in user land.
7800 * src: A pointer to a kernel lifetime structure.
7801 * exttype: Which type of lifetime this is. Refer to the PF_KEY
7802 * data structures for more information.
7804 * a valid mbuf or NULL indicating an error
7808 static struct mbuf *
7809 key_setlifetime(struct seclifetime *src, u_int16_t exttype)
7811 struct mbuf *m = NULL;
7812 struct sadb_lifetime *p;
7813 int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
7818 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
7823 p = mtod(m, struct sadb_lifetime *);
7826 p->sadb_lifetime_len = PFKEY_UNIT64(len);
7827 p->sadb_lifetime_exttype = exttype;
7828 p->sadb_lifetime_allocations = src->allocations;
7829 p->sadb_lifetime_bytes = src->bytes;
7830 p->sadb_lifetime_addtime = src->addtime;
7831 p->sadb_lifetime_usetime = src->usetime;