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 *, int);
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_SPDGET 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, mhp->msg->sadb_msg_seq,
2241 mhp->msg->sadb_msg_pid);
2245 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2247 return key_senderror(so, m, ENOBUFS);
2251 * SADB_X_SPDACQUIRE processing.
2252 * Acquire policy and SA(s) for a *OUTBOUND* packet.
2255 * to KMD, and expect to receive
2256 * <base> with SADB_X_SPDACQUIRE if error occured,
2259 * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2260 * policy(*) is without policy requests.
2263 * others: error number
2266 key_spdacquire(struct secpolicy *sp)
2268 struct mbuf *result = NULL, *m;
2269 struct secspacq *newspacq;
2271 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2272 IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2273 IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2274 ("policy not IPSEC %u", sp->policy));
2276 /* Get an entry to check whether sent message or not. */
2277 newspacq = key_getspacq(&sp->spidx);
2278 if (newspacq != NULL) {
2279 if (V_key_blockacq_count < newspacq->count) {
2280 /* reset counter and do send message. */
2281 newspacq->count = 0;
2283 /* increment counter and do nothing. */
2290 /* make new entry for blocking to send SADB_ACQUIRE. */
2291 newspacq = key_newspacq(&sp->spidx);
2292 if (newspacq == NULL)
2296 /* create new sadb_msg to reply. */
2297 m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2303 result->m_pkthdr.len = 0;
2304 for (m = result; m; m = m->m_next)
2305 result->m_pkthdr.len += m->m_len;
2307 mtod(result, struct sadb_msg *)->sadb_msg_len =
2308 PFKEY_UNIT64(result->m_pkthdr.len);
2310 return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2314 * SADB_SPDFLUSH processing
2317 * from the user, and free all entries in secpctree.
2321 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2323 * m will always be freed.
2326 key_spdflush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2328 TAILQ_HEAD(, secpolicy) drainq;
2329 struct sadb_msg *newmsg;
2330 struct secpolicy *sp, *nextsp;
2333 IPSEC_ASSERT(so != NULL, ("null socket"));
2334 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2335 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2336 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2338 if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2339 return key_senderror(so, m, EINVAL);
2341 TAILQ_INIT(&drainq);
2343 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2344 TAILQ_CONCAT(&drainq, &V_sptree[dir], chain);
2347 * We need to set state to DEAD for each policy to be sure,
2348 * that another thread won't try to unlink it.
2350 TAILQ_FOREACH(sp, &drainq, chain)
2351 sp->state = IPSEC_SPSTATE_DEAD;
2353 sp = TAILQ_FIRST(&drainq);
2354 while (sp != NULL) {
2355 nextsp = TAILQ_NEXT(sp, chain);
2360 if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2361 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2362 return key_senderror(so, m, ENOBUFS);
2368 m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2369 newmsg = mtod(m, struct sadb_msg *);
2370 newmsg->sadb_msg_errno = 0;
2371 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2373 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2377 * SADB_SPDDUMP processing
2380 * from the user, and dump all SP leaves
2385 * m will always be freed.
2388 key_spddump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2390 SPTREE_RLOCK_TRACKER;
2391 struct secpolicy *sp;
2396 IPSEC_ASSERT(so != NULL, ("null socket"));
2397 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2398 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2399 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2401 /* search SPD entry and get buffer size. */
2404 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2405 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
2412 return key_senderror(so, m, ENOENT);
2415 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2416 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
2418 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2419 mhp->msg->sadb_msg_pid);
2422 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2431 static struct mbuf *
2432 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq,
2435 struct mbuf *result = NULL, *m;
2436 struct seclifetime lt;
2438 m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2444 * Note: do not send SADB_X_EXT_NAT_T_* here:
2445 * we are sending traffic endpoints.
2447 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2448 &sp->spidx.src.sa, sp->spidx.prefs,
2449 sp->spidx.ul_proto);
2454 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2455 &sp->spidx.dst.sa, sp->spidx.prefd,
2456 sp->spidx.ul_proto);
2467 lt.addtime=sp->created;
2468 lt.usetime= sp->lastused;
2469 m = key_setlifetime(<, SADB_EXT_LIFETIME_CURRENT);
2474 lt.addtime=sp->lifetime;
2475 lt.usetime= sp->validtime;
2476 m = key_setlifetime(<, SADB_EXT_LIFETIME_HARD);
2482 if ((result->m_flags & M_PKTHDR) == 0)
2485 if (result->m_len < sizeof(struct sadb_msg)) {
2486 result = m_pullup(result, sizeof(struct sadb_msg));
2491 result->m_pkthdr.len = 0;
2492 for (m = result; m; m = m->m_next)
2493 result->m_pkthdr.len += m->m_len;
2495 mtod(result, struct sadb_msg *)->sadb_msg_len =
2496 PFKEY_UNIT64(result->m_pkthdr.len);
2506 * get PFKEY message length for security policy and request.
2509 key_getspreqmsglen(struct secpolicy *sp)
2513 tlen = sizeof(struct sadb_x_policy);
2515 /* if is the policy for ipsec ? */
2516 if (sp->policy != IPSEC_POLICY_IPSEC)
2519 /* get length of ipsec requests */
2521 struct ipsecrequest *isr;
2524 for (isr = sp->req; isr != NULL; isr = isr->next) {
2525 len = sizeof(struct sadb_x_ipsecrequest)
2526 + isr->saidx.src.sa.sa_len
2527 + isr->saidx.dst.sa.sa_len;
2529 tlen += PFKEY_ALIGN8(len);
2537 * SADB_SPDEXPIRE processing
2539 * <base, address(SD), lifetime(CH), policy>
2543 * others : error number
2546 key_spdexpire(struct secpolicy *sp)
2548 struct mbuf *result = NULL, *m;
2551 struct sadb_lifetime *lt;
2553 /* XXX: Why do we lock ? */
2555 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2557 /* set msg header */
2558 m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2565 /* create lifetime extension (current and hard) */
2566 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2567 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
2574 bzero(mtod(m, caddr_t), len);
2575 lt = mtod(m, struct sadb_lifetime *);
2576 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2577 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2578 lt->sadb_lifetime_allocations = 0;
2579 lt->sadb_lifetime_bytes = 0;
2580 lt->sadb_lifetime_addtime = sp->created;
2581 lt->sadb_lifetime_usetime = sp->lastused;
2582 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2583 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2584 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2585 lt->sadb_lifetime_allocations = 0;
2586 lt->sadb_lifetime_bytes = 0;
2587 lt->sadb_lifetime_addtime = sp->lifetime;
2588 lt->sadb_lifetime_usetime = sp->validtime;
2592 * Note: do not send SADB_X_EXT_NAT_T_* here:
2593 * we are sending traffic endpoints.
2596 /* set sadb_address for source */
2597 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2599 sp->spidx.prefs, sp->spidx.ul_proto);
2606 /* set sadb_address for destination */
2607 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2609 sp->spidx.prefd, sp->spidx.ul_proto);
2624 if ((result->m_flags & M_PKTHDR) == 0) {
2629 if (result->m_len < sizeof(struct sadb_msg)) {
2630 result = m_pullup(result, sizeof(struct sadb_msg));
2631 if (result == NULL) {
2637 result->m_pkthdr.len = 0;
2638 for (m = result; m; m = m->m_next)
2639 result->m_pkthdr.len += m->m_len;
2641 mtod(result, struct sadb_msg *)->sadb_msg_len =
2642 PFKEY_UNIT64(result->m_pkthdr.len);
2644 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2652 /* %%% SAD management */
2654 * allocating a memory for new SA head, and copy from the values of mhp.
2655 * OUT: NULL : failure due to the lack of memory.
2656 * others : pointer to new SA head.
2658 static struct secashead *
2659 key_newsah(struct secasindex *saidx)
2661 struct secashead *newsah;
2663 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2665 newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2666 if (newsah != NULL) {
2668 for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2669 LIST_INIT(&newsah->savtree[i]);
2670 newsah->saidx = *saidx;
2672 /* add to saidxtree */
2673 newsah->state = SADB_SASTATE_MATURE;
2676 LIST_INSERT_HEAD(&V_sahtree, newsah, chain);
2683 * delete SA index and all SA registerd.
2686 key_delsah(struct secashead *sah)
2688 struct secasvar *sav, *nextsav;
2692 IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2693 SAHTREE_LOCK_ASSERT();
2695 /* searching all SA registerd in the secindex. */
2697 stateidx < _ARRAYLEN(saorder_state_any);
2699 u_int state = saorder_state_any[stateidx];
2700 LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2701 if (sav->refcnt == 0) {
2703 KEY_CHKSASTATE(state, sav->state, __func__);
2705 * do NOT call KEY_FREESAV here:
2706 * it will only delete the sav if refcnt == 1,
2707 * where we already know that refcnt == 0
2711 /* give up to delete this sa */
2716 if (!zombie) { /* delete only if there are savs */
2717 /* remove from tree of SA index */
2718 if (__LIST_CHAINED(sah))
2719 LIST_REMOVE(sah, chain);
2720 free(sah, M_IPSEC_SAH);
2725 * allocating a new SA with LARVAL state. key_add() and key_getspi() call,
2726 * and copy the values of mhp into new buffer.
2727 * When SAD message type is GETSPI:
2728 * to set sequence number from acq_seq++,
2729 * to set zero to SPI.
2730 * not to call key_setsava().
2732 * others : pointer to new secasvar.
2734 * does not modify mbuf. does not free mbuf on error.
2736 static struct secasvar *
2737 key_newsav(struct mbuf *m, const struct sadb_msghdr *mhp,
2738 struct secashead *sah, int *errp, const char *where, int tag)
2740 struct secasvar *newsav;
2741 const struct sadb_sa *xsa;
2743 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2744 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2745 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2746 IPSEC_ASSERT(sah != NULL, ("null secashead"));
2748 newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2749 if (newsav == NULL) {
2750 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2755 switch (mhp->msg->sadb_msg_type) {
2759 #ifdef IPSEC_DOSEQCHECK
2760 /* sync sequence number */
2761 if (mhp->msg->sadb_msg_seq == 0)
2763 (V_acq_seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq));
2766 newsav->seq = mhp->msg->sadb_msg_seq;
2771 if (mhp->ext[SADB_EXT_SA] == NULL) {
2772 free(newsav, M_IPSEC_SA);
2774 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2779 xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2780 newsav->spi = xsa->sadb_sa_spi;
2781 newsav->seq = mhp->msg->sadb_msg_seq;
2784 free(newsav, M_IPSEC_SA);
2791 /* copy sav values */
2792 if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2793 *errp = key_setsaval(newsav, m, mhp);
2795 free(newsav, M_IPSEC_SA);
2801 SECASVAR_LOCK_INIT(newsav);
2804 newsav->created = time_second;
2805 newsav->pid = mhp->msg->sadb_msg_pid;
2810 newsav->state = SADB_SASTATE_LARVAL;
2813 LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2817 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2818 printf("DP %s from %s:%u return SP:%p\n", __func__,
2819 where, tag, newsav));
2825 * free() SA variable entry.
2828 key_cleansav(struct secasvar *sav)
2831 * Cleanup xform state. Note that zeroize'ing causes the
2832 * keys to be cleared; otherwise we must do it ourself.
2834 if (sav->tdb_xform != NULL) {
2835 sav->tdb_xform->xf_zeroize(sav);
2836 sav->tdb_xform = NULL;
2838 KASSERT(sav->iv == NULL, ("iv but no xform"));
2839 if (sav->key_auth != NULL)
2840 bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2841 if (sav->key_enc != NULL)
2842 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2844 if (sav->key_auth != NULL) {
2845 if (sav->key_auth->key_data != NULL)
2846 free(sav->key_auth->key_data, M_IPSEC_MISC);
2847 free(sav->key_auth, M_IPSEC_MISC);
2848 sav->key_auth = NULL;
2850 if (sav->key_enc != NULL) {
2851 if (sav->key_enc->key_data != NULL)
2852 free(sav->key_enc->key_data, M_IPSEC_MISC);
2853 free(sav->key_enc, M_IPSEC_MISC);
2854 sav->key_enc = NULL;
2857 bzero(sav->sched, sav->schedlen);
2858 free(sav->sched, M_IPSEC_MISC);
2861 if (sav->replay != NULL) {
2862 free(sav->replay, M_IPSEC_MISC);
2865 if (sav->lft_c != NULL) {
2866 free(sav->lft_c, M_IPSEC_MISC);
2869 if (sav->lft_h != NULL) {
2870 free(sav->lft_h, M_IPSEC_MISC);
2873 if (sav->lft_s != NULL) {
2874 free(sav->lft_s, M_IPSEC_MISC);
2880 * free() SA variable entry.
2883 key_delsav(struct secasvar *sav)
2885 IPSEC_ASSERT(sav != NULL, ("null sav"));
2886 IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2888 /* remove from SA header */
2889 if (__LIST_CHAINED(sav))
2890 LIST_REMOVE(sav, chain);
2892 SECASVAR_LOCK_DESTROY(sav);
2893 free(sav, M_IPSEC_SA);
2900 * others : found, pointer to a SA.
2902 static struct secashead *
2903 key_getsah(struct secasindex *saidx)
2905 struct secashead *sah;
2908 LIST_FOREACH(sah, &V_sahtree, chain) {
2909 if (sah->state == SADB_SASTATE_DEAD)
2911 if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2920 * check not to be duplicated SPI.
2921 * NOTE: this function is too slow due to searching all SAD.
2924 * others : found, pointer to a SA.
2926 static struct secasvar *
2927 key_checkspidup(struct secasindex *saidx, u_int32_t spi)
2929 struct secashead *sah;
2930 struct secasvar *sav;
2932 /* check address family */
2933 if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2934 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2942 LIST_FOREACH(sah, &V_sahtree, chain) {
2943 if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2945 sav = key_getsavbyspi(sah, spi);
2955 * search SAD litmited alive SA, protocol, SPI.
2958 * others : found, pointer to a SA.
2960 static struct secasvar *
2961 key_getsavbyspi(struct secashead *sah, u_int32_t spi)
2963 struct secasvar *sav;
2964 u_int stateidx, state;
2967 SAHTREE_LOCK_ASSERT();
2968 /* search all status */
2970 stateidx < _ARRAYLEN(saorder_state_alive);
2973 state = saorder_state_alive[stateidx];
2974 LIST_FOREACH(sav, &sah->savtree[state], chain) {
2977 if (sav->state != state) {
2978 ipseclog((LOG_DEBUG, "%s: "
2979 "invalid sav->state (queue: %d SA: %d)\n",
2980 __func__, state, sav->state));
2984 if (sav->spi == spi)
2993 * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
2994 * You must update these if need.
2998 * does not modify mbuf. does not free mbuf on error.
3001 key_setsaval(struct secasvar *sav, struct mbuf *m,
3002 const struct sadb_msghdr *mhp)
3006 IPSEC_ASSERT(m != NULL, ("null mbuf"));
3007 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3008 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3010 /* initialization */
3012 sav->key_auth = NULL;
3013 sav->key_enc = NULL;
3020 sav->tdb_xform = NULL; /* transform */
3021 sav->tdb_encalgxform = NULL; /* encoding algorithm */
3022 sav->tdb_authalgxform = NULL; /* authentication algorithm */
3023 sav->tdb_compalgxform = NULL; /* compression algorithm */
3024 /* Initialize even if NAT-T not compiled in: */
3026 sav->natt_esp_frag_len = 0;
3029 if (mhp->ext[SADB_EXT_SA] != NULL) {
3030 const struct sadb_sa *sa0;
3032 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3033 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3038 sav->alg_auth = sa0->sadb_sa_auth;
3039 sav->alg_enc = sa0->sadb_sa_encrypt;
3040 sav->flags = sa0->sadb_sa_flags;
3043 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3044 sav->replay = (struct secreplay *)
3045 malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
3046 if (sav->replay == NULL) {
3047 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3052 if (sa0->sadb_sa_replay != 0)
3053 sav->replay->bitmap = (caddr_t)(sav->replay+1);
3054 sav->replay->wsize = sa0->sadb_sa_replay;
3058 /* Authentication keys */
3059 if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3060 const struct sadb_key *key0;
3063 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3064 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3067 if (len < sizeof(*key0)) {
3071 switch (mhp->msg->sadb_msg_satype) {
3072 case SADB_SATYPE_AH:
3073 case SADB_SATYPE_ESP:
3074 case SADB_X_SATYPE_TCPSIGNATURE:
3075 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3076 sav->alg_auth != SADB_X_AALG_NULL)
3079 case SADB_X_SATYPE_IPCOMP:
3085 ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3090 sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
3092 if (sav->key_auth == NULL ) {
3093 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3100 /* Encryption key */
3101 if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3102 const struct sadb_key *key0;
3105 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3106 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3109 if (len < sizeof(*key0)) {
3113 switch (mhp->msg->sadb_msg_satype) {
3114 case SADB_SATYPE_ESP:
3115 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3116 sav->alg_enc != SADB_EALG_NULL) {
3120 sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
3123 if (sav->key_enc == NULL) {
3124 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3130 case SADB_X_SATYPE_IPCOMP:
3131 if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3133 sav->key_enc = NULL; /*just in case*/
3135 case SADB_SATYPE_AH:
3136 case SADB_X_SATYPE_TCPSIGNATURE:
3142 ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3151 switch (mhp->msg->sadb_msg_satype) {
3152 case SADB_SATYPE_AH:
3153 error = xform_init(sav, XF_AH);
3155 case SADB_SATYPE_ESP:
3156 error = xform_init(sav, XF_ESP);
3158 case SADB_X_SATYPE_IPCOMP:
3159 error = xform_init(sav, XF_IPCOMP);
3161 case SADB_X_SATYPE_TCPSIGNATURE:
3162 error = xform_init(sav, XF_TCPSIGNATURE);
3166 ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3167 __func__, mhp->msg->sadb_msg_satype));
3172 sav->created = time_second;
3174 /* make lifetime for CURRENT */
3175 sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
3176 if (sav->lft_c == NULL) {
3177 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3182 sav->lft_c->allocations = 0;
3183 sav->lft_c->bytes = 0;
3184 sav->lft_c->addtime = time_second;
3185 sav->lft_c->usetime = 0;
3187 /* lifetimes for HARD and SOFT */
3189 const struct sadb_lifetime *lft0;
3191 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3193 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3197 sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3198 if (sav->lft_h == NULL) {
3199 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3203 /* to be initialize ? */
3206 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3208 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3212 sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3213 if (sav->lft_s == NULL) {
3214 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3218 /* to be initialize ? */
3225 /* initialization */
3232 * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3237 key_mature(struct secasvar *sav)
3241 /* check SPI value */
3242 switch (sav->sah->saidx.proto) {
3246 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
3247 * 1-255 reserved by IANA for future use,
3248 * 0 for implementation specific, local use.
3250 if (ntohl(sav->spi) <= 255) {
3251 ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3252 __func__, (u_int32_t)ntohl(sav->spi)));
3259 switch (sav->sah->saidx.proto) {
3262 if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3263 (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3264 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3265 "given to old-esp.\n", __func__));
3268 error = xform_init(sav, XF_ESP);
3272 if (sav->flags & SADB_X_EXT_DERIV) {
3273 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3274 "given to AH SA.\n", __func__));
3277 if (sav->alg_enc != SADB_EALG_NONE) {
3278 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3279 "mismated.\n", __func__));
3282 error = xform_init(sav, XF_AH);
3284 case IPPROTO_IPCOMP:
3285 if (sav->alg_auth != SADB_AALG_NONE) {
3286 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3287 "mismated.\n", __func__));
3290 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3291 && ntohl(sav->spi) >= 0x10000) {
3292 ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3296 error = xform_init(sav, XF_IPCOMP);
3299 if (sav->alg_enc != SADB_EALG_NONE) {
3300 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3301 "mismated.\n", __func__));
3304 error = xform_init(sav, XF_TCPSIGNATURE);
3307 ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3308 error = EPROTONOSUPPORT;
3313 key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3320 * subroutine for SADB_GET and SADB_DUMP.
3322 static struct mbuf *
3323 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3324 u_int32_t seq, u_int32_t pid)
3326 struct mbuf *result = NULL, *tres = NULL, *m;
3329 SADB_EXT_SA, SADB_X_EXT_SA2,
3330 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3331 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3332 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3333 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3334 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3336 SADB_X_EXT_NAT_T_TYPE,
3337 SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3338 SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3339 SADB_X_EXT_NAT_T_FRAG,
3343 m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3348 for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3350 switch (dumporder[i]) {
3352 m = key_setsadbsa(sav);
3357 case SADB_X_EXT_SA2:
3358 m = key_setsadbxsa2(sav->sah->saidx.mode,
3359 sav->replay ? sav->replay->count : 0,
3360 sav->sah->saidx.reqid);
3365 case SADB_EXT_ADDRESS_SRC:
3366 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3367 &sav->sah->saidx.src.sa,
3368 FULLMASK, IPSEC_ULPROTO_ANY);
3373 case SADB_EXT_ADDRESS_DST:
3374 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3375 &sav->sah->saidx.dst.sa,
3376 FULLMASK, IPSEC_ULPROTO_ANY);
3381 case SADB_EXT_KEY_AUTH:
3384 m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3389 case SADB_EXT_KEY_ENCRYPT:
3392 m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3397 case SADB_EXT_LIFETIME_CURRENT:
3400 m = key_setlifetime(sav->lft_c,
3401 SADB_EXT_LIFETIME_CURRENT);
3406 case SADB_EXT_LIFETIME_HARD:
3409 m = key_setlifetime(sav->lft_h,
3410 SADB_EXT_LIFETIME_HARD);
3415 case SADB_EXT_LIFETIME_SOFT:
3418 m = key_setlifetime(sav->lft_s,
3419 SADB_EXT_LIFETIME_SOFT);
3426 case SADB_X_EXT_NAT_T_TYPE:
3427 m = key_setsadbxtype(sav->natt_type);
3432 case SADB_X_EXT_NAT_T_DPORT:
3433 m = key_setsadbxport(
3434 KEY_PORTFROMSADDR(&sav->sah->saidx.dst),
3435 SADB_X_EXT_NAT_T_DPORT);
3440 case SADB_X_EXT_NAT_T_SPORT:
3441 m = key_setsadbxport(
3442 KEY_PORTFROMSADDR(&sav->sah->saidx.src),
3443 SADB_X_EXT_NAT_T_SPORT);
3448 case SADB_X_EXT_NAT_T_OAI:
3449 case SADB_X_EXT_NAT_T_OAR:
3450 case SADB_X_EXT_NAT_T_FRAG:
3451 /* We do not (yet) support those. */
3455 case SADB_EXT_ADDRESS_PROXY:
3456 case SADB_EXT_IDENTITY_SRC:
3457 case SADB_EXT_IDENTITY_DST:
3458 /* XXX: should we brought from SPD ? */
3459 case SADB_EXT_SENSITIVITY:
3472 m_cat(result, tres);
3473 if (result->m_len < sizeof(struct sadb_msg)) {
3474 result = m_pullup(result, sizeof(struct sadb_msg));
3479 result->m_pkthdr.len = 0;
3480 for (m = result; m; m = m->m_next)
3481 result->m_pkthdr.len += m->m_len;
3483 mtod(result, struct sadb_msg *)->sadb_msg_len =
3484 PFKEY_UNIT64(result->m_pkthdr.len);
3495 * set data into sadb_msg.
3497 static struct mbuf *
3498 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3499 pid_t pid, u_int16_t reserved)
3505 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3508 MGETHDR(m, M_NOWAIT, MT_DATA);
3509 if (m && len > MHLEN) {
3510 if (!(MCLGET(m, M_NOWAIT))) {
3517 m->m_pkthdr.len = m->m_len = len;
3520 p = mtod(m, struct sadb_msg *);
3523 p->sadb_msg_version = PF_KEY_V2;
3524 p->sadb_msg_type = type;
3525 p->sadb_msg_errno = 0;
3526 p->sadb_msg_satype = satype;
3527 p->sadb_msg_len = PFKEY_UNIT64(tlen);
3528 p->sadb_msg_reserved = reserved;
3529 p->sadb_msg_seq = seq;
3530 p->sadb_msg_pid = (u_int32_t)pid;
3536 * copy secasvar data into sadb_address.
3538 static struct mbuf *
3539 key_setsadbsa(struct secasvar *sav)
3545 len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3546 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3551 p = mtod(m, struct sadb_sa *);
3553 p->sadb_sa_len = PFKEY_UNIT64(len);
3554 p->sadb_sa_exttype = SADB_EXT_SA;
3555 p->sadb_sa_spi = sav->spi;
3556 p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3557 p->sadb_sa_state = sav->state;
3558 p->sadb_sa_auth = sav->alg_auth;
3559 p->sadb_sa_encrypt = sav->alg_enc;
3560 p->sadb_sa_flags = sav->flags;
3566 * set data into sadb_address.
3568 static struct mbuf *
3569 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
3570 u_int8_t prefixlen, u_int16_t ul_proto)
3573 struct sadb_address *p;
3576 len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3577 PFKEY_ALIGN8(saddr->sa_len);
3578 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3583 p = mtod(m, struct sadb_address *);
3586 p->sadb_address_len = PFKEY_UNIT64(len);
3587 p->sadb_address_exttype = exttype;
3588 p->sadb_address_proto = ul_proto;
3589 if (prefixlen == FULLMASK) {
3590 switch (saddr->sa_family) {
3592 prefixlen = sizeof(struct in_addr) << 3;
3595 prefixlen = sizeof(struct in6_addr) << 3;
3601 p->sadb_address_prefixlen = prefixlen;
3602 p->sadb_address_reserved = 0;
3605 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3612 * set data into sadb_x_sa2.
3614 static struct mbuf *
3615 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3618 struct sadb_x_sa2 *p;
3621 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3622 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3627 p = mtod(m, struct sadb_x_sa2 *);
3630 p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3631 p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3632 p->sadb_x_sa2_mode = mode;
3633 p->sadb_x_sa2_reserved1 = 0;
3634 p->sadb_x_sa2_reserved2 = 0;
3635 p->sadb_x_sa2_sequence = seq;
3636 p->sadb_x_sa2_reqid = reqid;
3643 * Set a type in sadb_x_nat_t_type.
3645 static struct mbuf *
3646 key_setsadbxtype(u_int16_t type)
3650 struct sadb_x_nat_t_type *p;
3652 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3654 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3659 p = mtod(m, struct sadb_x_nat_t_type *);
3662 p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3663 p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3664 p->sadb_x_nat_t_type_type = type;
3669 * Set a port in sadb_x_nat_t_port.
3670 * In contrast to default RFC 2367 behaviour, port is in network byte order.
3672 static struct mbuf *
3673 key_setsadbxport(u_int16_t port, u_int16_t type)
3677 struct sadb_x_nat_t_port *p;
3679 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3681 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3686 p = mtod(m, struct sadb_x_nat_t_port *);
3689 p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3690 p->sadb_x_nat_t_port_exttype = type;
3691 p->sadb_x_nat_t_port_port = port;
3697 * Get port from sockaddr. Port is in network byte order.
3700 key_portfromsaddr(struct sockaddr *sa)
3703 switch (sa->sa_family) {
3706 return ((struct sockaddr_in *)sa)->sin_port;
3710 return ((struct sockaddr_in6 *)sa)->sin6_port;
3713 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
3714 printf("DP %s unexpected address family %d\n",
3715 __func__, sa->sa_family));
3718 #endif /* IPSEC_NAT_T */
3721 * Set port in struct sockaddr. Port is in network byte order.
3724 key_porttosaddr(struct sockaddr *sa, u_int16_t port)
3727 switch (sa->sa_family) {
3730 ((struct sockaddr_in *)sa)->sin_port = port;
3735 ((struct sockaddr_in6 *)sa)->sin6_port = port;
3739 ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
3740 __func__, sa->sa_family));
3746 * set data into sadb_x_policy
3748 static struct mbuf *
3749 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3752 struct sadb_x_policy *p;
3755 len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3756 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3761 p = mtod(m, struct sadb_x_policy *);
3764 p->sadb_x_policy_len = PFKEY_UNIT64(len);
3765 p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3766 p->sadb_x_policy_type = type;
3767 p->sadb_x_policy_dir = dir;
3768 p->sadb_x_policy_id = id;
3774 /* Take a key message (sadb_key) from the socket and turn it into one
3775 * of the kernel's key structures (seckey).
3777 * IN: pointer to the src
3778 * OUT: NULL no more memory
3781 key_dup_keymsg(const struct sadb_key *src, u_int len,
3782 struct malloc_type *type)
3785 dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
3787 dst->bits = src->sadb_key_bits;
3788 dst->key_data = (char *)malloc(len, type, M_NOWAIT);
3789 if (dst->key_data != NULL) {
3790 bcopy((const char *)src + sizeof(struct sadb_key),
3791 dst->key_data, len);
3793 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3799 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3806 /* Take a lifetime message (sadb_lifetime) passed in on a socket and
3807 * turn it into one of the kernel's lifetime structures (seclifetime).
3809 * IN: pointer to the destination, source and malloc type
3810 * OUT: NULL, no more memory
3813 static struct seclifetime *
3814 key_dup_lifemsg(const struct sadb_lifetime *src, struct malloc_type *type)
3816 struct seclifetime *dst = NULL;
3818 dst = (struct seclifetime *)malloc(sizeof(struct seclifetime),
3822 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3824 dst->allocations = src->sadb_lifetime_allocations;
3825 dst->bytes = src->sadb_lifetime_bytes;
3826 dst->addtime = src->sadb_lifetime_addtime;
3827 dst->usetime = src->sadb_lifetime_usetime;
3832 /* compare my own address
3833 * OUT: 1: true, i.e. my address.
3837 key_ismyaddr(struct sockaddr *sa)
3840 IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3841 switch (sa->sa_family) {
3844 return (in_localip(satosin(sa)->sin_addr));
3848 return key_ismyaddr6((struct sockaddr_in6 *)sa);
3857 * compare my own address for IPv6.
3862 key_ismyaddr6(struct sockaddr_in6 *sin6)
3864 struct in6_addr in6;
3866 if (!IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr))
3867 return (in6_localip(&sin6->sin6_addr));
3869 /* Convert address into kernel-internal form */
3870 in6 = sin6->sin6_addr;
3871 in6.s6_addr16[1] = htons(sin6->sin6_scope_id & 0xffff);
3872 return (in6_localip(&in6));
3877 * compare two secasindex structure.
3878 * flag can specify to compare 2 saidxes.
3879 * compare two secasindex structure without both mode and reqid.
3880 * don't compare port.
3882 * saidx0: source, it can be in SAD.
3889 key_cmpsaidx(const struct secasindex *saidx0, const struct secasindex *saidx1,
3895 if (saidx0 == NULL && saidx1 == NULL)
3898 if (saidx0 == NULL || saidx1 == NULL)
3901 if (saidx0->proto != saidx1->proto)
3904 if (flag == CMP_EXACTLY) {
3905 if (saidx0->mode != saidx1->mode)
3907 if (saidx0->reqid != saidx1->reqid)
3909 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
3910 bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
3914 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3915 if (flag == CMP_MODE_REQID
3916 ||flag == CMP_REQID) {
3918 * If reqid of SPD is non-zero, unique SA is required.
3919 * The result must be of same reqid in this case.
3921 if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3925 if (flag == CMP_MODE_REQID) {
3926 if (saidx0->mode != IPSEC_MODE_ANY
3927 && saidx0->mode != saidx1->mode)
3933 * If NAT-T is enabled, check ports for tunnel mode.
3934 * Do not check ports if they are set to zero in the SPD.
3935 * Also do not do it for native transport mode, as there
3936 * is no port information available in the SP.
3938 if ((saidx1->mode == IPSEC_MODE_TUNNEL ||
3939 (saidx1->mode == IPSEC_MODE_TRANSPORT &&
3940 saidx1->proto == IPPROTO_ESP)) &&
3941 saidx1->src.sa.sa_family == AF_INET &&
3942 saidx1->dst.sa.sa_family == AF_INET &&
3943 ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
3944 ((const struct sockaddr_in *)(&saidx1->dst))->sin_port)
3946 #endif /* IPSEC_NAT_T */
3948 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
3951 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
3960 * compare two secindex structure exactly.
3962 * spidx0: source, it is often in SPD.
3963 * spidx1: object, it is often from PFKEY message.
3969 key_cmpspidx_exactly(struct secpolicyindex *spidx0,
3970 struct secpolicyindex *spidx1)
3973 if (spidx0 == NULL && spidx1 == NULL)
3976 if (spidx0 == NULL || spidx1 == NULL)
3979 if (spidx0->prefs != spidx1->prefs
3980 || spidx0->prefd != spidx1->prefd
3981 || spidx0->ul_proto != spidx1->ul_proto)
3984 return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
3985 key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
3989 * compare two secindex structure with mask.
3991 * spidx0: source, it is often in SPD.
3992 * spidx1: object, it is often from IP header.
3998 key_cmpspidx_withmask(struct secpolicyindex *spidx0,
3999 struct secpolicyindex *spidx1)
4002 if (spidx0 == NULL && spidx1 == NULL)
4005 if (spidx0 == NULL || spidx1 == NULL)
4008 if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4009 spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4010 spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4011 spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4014 /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4015 if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4016 && spidx0->ul_proto != spidx1->ul_proto)
4019 switch (spidx0->src.sa.sa_family) {
4021 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4022 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4024 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4025 &spidx1->src.sin.sin_addr, spidx0->prefs))
4029 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4030 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4033 * scope_id check. if sin6_scope_id is 0, we regard it
4034 * as a wildcard scope, which matches any scope zone ID.
4036 if (spidx0->src.sin6.sin6_scope_id &&
4037 spidx1->src.sin6.sin6_scope_id &&
4038 spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4040 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4041 &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4046 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4051 switch (spidx0->dst.sa.sa_family) {
4053 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4054 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4056 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4057 &spidx1->dst.sin.sin_addr, spidx0->prefd))
4061 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4062 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4065 * scope_id check. if sin6_scope_id is 0, we regard it
4066 * as a wildcard scope, which matches any scope zone ID.
4068 if (spidx0->dst.sin6.sin6_scope_id &&
4069 spidx1->dst.sin6.sin6_scope_id &&
4070 spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4072 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4073 &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4078 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4083 /* XXX Do we check other field ? e.g. flowinfo */
4088 /* returns 0 on match */
4090 key_sockaddrcmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
4096 #define satosin(s) ((const struct sockaddr_in *)s)
4100 #define satosin6(s) ((const struct sockaddr_in6 *)s)
4101 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4104 switch (sa1->sa_family) {
4106 if (sa1->sa_len != sizeof(struct sockaddr_in))
4108 if (satosin(sa1)->sin_addr.s_addr !=
4109 satosin(sa2)->sin_addr.s_addr) {
4112 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4116 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4117 return 1; /*EINVAL*/
4118 if (satosin6(sa1)->sin6_scope_id !=
4119 satosin6(sa2)->sin6_scope_id) {
4122 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4123 &satosin6(sa2)->sin6_addr)) {
4127 satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4132 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4143 * compare two buffers with mask.
4147 * bits: Number of bits to compare
4153 key_bbcmp(const void *a1, const void *a2, u_int bits)
4155 const unsigned char *p1 = a1;
4156 const unsigned char *p2 = a2;
4158 /* XXX: This could be considerably faster if we compare a word
4159 * at a time, but it is complicated on LSB Endian machines */
4161 /* Handle null pointers */
4162 if (p1 == NULL || p2 == NULL)
4172 u_int8_t mask = ~((1<<(8-bits))-1);
4173 if ((*p1 & mask) != (*p2 & mask))
4176 return 1; /* Match! */
4180 key_flush_spd(time_t now)
4182 SPTREE_RLOCK_TRACKER;
4183 struct secpolicy *sp;
4187 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4190 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
4191 if (sp->lifetime == 0 && sp->validtime == 0)
4193 if ((sp->lifetime &&
4194 now - sp->created > sp->lifetime) ||
4196 now - sp->lastused > sp->validtime)) {
4210 key_flush_sad(time_t now)
4212 struct secashead *sah, *nextsah;
4213 struct secasvar *sav, *nextsav;
4217 LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4218 /* if sah has been dead, then delete it and process next sah. */
4219 if (sah->state == SADB_SASTATE_DEAD) {
4224 /* if LARVAL entry doesn't become MATURE, delete it. */
4225 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4226 /* Need to also check refcnt for a larval SA ??? */
4227 if (now - sav->created > V_key_larval_lifetime)
4232 * check MATURE entry to start to send expire message
4235 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4236 /* we don't need to check. */
4237 if (sav->lft_s == NULL)
4241 if (sav->lft_c == NULL) {
4242 ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4243 "time, why?\n", __func__));
4248 * HARD lifetimes MUST take precedence over SOFT
4249 * lifetimes, meaning if the HARD and SOFT lifetimes
4250 * are the same, the HARD lifetime will appear on the
4253 /* check HARD lifetime */
4254 if ((sav->lft_h->addtime != 0 &&
4255 now - sav->created > sav->lft_h->addtime) ||
4256 (sav->lft_h->bytes != 0 &&
4257 sav->lft_h->bytes < sav->lft_c->bytes)) {
4258 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4262 /* check SOFT lifetime */
4263 else if ((sav->lft_s->addtime != 0 &&
4264 now - sav->created > sav->lft_s->addtime) ||
4265 (sav->lft_s->bytes != 0 &&
4266 sav->lft_s->bytes < sav->lft_c->bytes)) {
4267 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4272 /* check DYING entry to change status to DEAD. */
4273 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4274 /* we don't need to check. */
4275 if (sav->lft_h == NULL)
4279 if (sav->lft_c == NULL) {
4280 ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4281 "time, why?\n", __func__));
4285 if (sav->lft_h->addtime != 0 &&
4286 now - sav->created > sav->lft_h->addtime) {
4287 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4291 #if 0 /* XXX Should we keep to send expire message until HARD lifetime ? */
4292 else if (sav->lft_s != NULL
4293 && sav->lft_s->addtime != 0
4294 && now - sav->created > sav->lft_s->addtime) {
4296 * XXX: should be checked to be
4297 * installed the valid SA.
4301 * If there is no SA then sending
4307 /* check HARD lifetime by bytes */
4308 else if (sav->lft_h->bytes != 0 &&
4309 sav->lft_h->bytes < sav->lft_c->bytes) {
4310 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4316 /* delete entry in DEAD */
4317 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4319 if (sav->state != SADB_SASTATE_DEAD) {
4320 ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4321 "(queue: %d SA: %d): kill it anyway\n",
4323 SADB_SASTATE_DEAD, sav->state));
4326 * do not call key_freesav() here.
4327 * sav should already be freed, and sav->refcnt
4328 * shows other references to sav
4329 * (such as from SPD).
4337 key_flush_acq(time_t now)
4339 struct secacq *acq, *nextacq;
4343 for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4344 nextacq = LIST_NEXT(acq, chain);
4345 if (now - acq->created > V_key_blockacq_lifetime
4346 && __LIST_CHAINED(acq)) {
4347 LIST_REMOVE(acq, chain);
4348 free(acq, M_IPSEC_SAQ);
4355 key_flush_spacq(time_t now)
4357 struct secspacq *acq, *nextacq;
4361 for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4362 nextacq = LIST_NEXT(acq, chain);
4363 if (now - acq->created > V_key_blockacq_lifetime
4364 && __LIST_CHAINED(acq)) {
4365 LIST_REMOVE(acq, chain);
4366 free(acq, M_IPSEC_SAQ);
4374 * scanning SPD and SAD to check status for each entries,
4375 * and do to remove or to expire.
4376 * XXX: year 2038 problem may remain.
4379 key_timehandler(void *arg)
4381 VNET_ITERATOR_DECL(vnet_iter);
4382 time_t now = time_second;
4384 VNET_LIST_RLOCK_NOSLEEP();
4385 VNET_FOREACH(vnet_iter) {
4386 CURVNET_SET(vnet_iter);
4390 key_flush_spacq(now);
4393 VNET_LIST_RUNLOCK_NOSLEEP();
4395 #ifndef IPSEC_DEBUG2
4396 /* do exchange to tick time !! */
4397 callout_schedule(&key_timer, hz);
4398 #endif /* IPSEC_DEBUG2 */
4406 key_randomfill(&value, sizeof(value));
4411 key_randomfill(void *p, size_t l)
4415 static int warn = 1;
4418 n = (size_t)read_random(p, (u_int)l);
4422 bcopy(&v, (u_int8_t *)p + n,
4423 l - n < sizeof(v) ? l - n : sizeof(v));
4427 printf("WARNING: pseudo-random number generator "
4428 "used for IPsec processing\n");
4435 * map SADB_SATYPE_* to IPPROTO_*.
4436 * if satype == SADB_SATYPE then satype is mapped to ~0.
4438 * 0: invalid satype.
4441 key_satype2proto(u_int8_t satype)
4444 case SADB_SATYPE_UNSPEC:
4445 return IPSEC_PROTO_ANY;
4446 case SADB_SATYPE_AH:
4448 case SADB_SATYPE_ESP:
4450 case SADB_X_SATYPE_IPCOMP:
4451 return IPPROTO_IPCOMP;
4452 case SADB_X_SATYPE_TCPSIGNATURE:
4461 * map IPPROTO_* to SADB_SATYPE_*
4463 * 0: invalid protocol type.
4466 key_proto2satype(u_int16_t proto)
4470 return SADB_SATYPE_AH;
4472 return SADB_SATYPE_ESP;
4473 case IPPROTO_IPCOMP:
4474 return SADB_X_SATYPE_IPCOMP;
4476 return SADB_X_SATYPE_TCPSIGNATURE;
4485 * SADB_GETSPI processing is to receive
4486 * <base, (SA2), src address, dst address, (SPI range)>
4487 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4488 * tree with the status of LARVAL, and send
4489 * <base, SA(*), address(SD)>
4492 * IN: mhp: pointer to the pointer to each header.
4493 * OUT: NULL if fail.
4494 * other if success, return pointer to the message to send.
4497 key_getspi(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4499 struct sadb_address *src0, *dst0;
4500 struct secasindex saidx;
4501 struct secashead *newsah;
4502 struct secasvar *newsav;
4509 IPSEC_ASSERT(so != NULL, ("null socket"));
4510 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4511 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4512 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4514 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4515 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4516 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4518 return key_senderror(so, m, EINVAL);
4520 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4521 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4522 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4524 return key_senderror(so, m, EINVAL);
4526 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4527 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4528 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4530 mode = IPSEC_MODE_ANY;
4534 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4535 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4537 /* map satype to proto */
4538 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4539 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4541 return key_senderror(so, m, EINVAL);
4545 * Make sure the port numbers are zero.
4546 * In case of NAT-T we will update them later if needed.
4548 switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4550 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4551 sizeof(struct sockaddr_in))
4552 return key_senderror(so, m, EINVAL);
4553 ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4556 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4557 sizeof(struct sockaddr_in6))
4558 return key_senderror(so, m, EINVAL);
4559 ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4564 switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4566 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4567 sizeof(struct sockaddr_in))
4568 return key_senderror(so, m, EINVAL);
4569 ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4572 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4573 sizeof(struct sockaddr_in6))
4574 return key_senderror(so, m, EINVAL);
4575 ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4581 /* XXX boundary check against sa_len */
4582 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4586 * Handle NAT-T info if present.
4587 * We made sure the port numbers are zero above, so we do
4588 * not have to worry in case we do not update them.
4590 if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
4591 ipseclog((LOG_DEBUG, "%s: NAT-T OAi present\n", __func__));
4592 if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
4593 ipseclog((LOG_DEBUG, "%s: NAT-T OAr present\n", __func__));
4595 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4596 mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4597 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4598 struct sadb_x_nat_t_type *type;
4599 struct sadb_x_nat_t_port *sport, *dport;
4601 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4602 mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4603 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4604 ipseclog((LOG_DEBUG, "%s: invalid nat-t message "
4605 "passed.\n", __func__));
4606 return key_senderror(so, m, EINVAL);
4609 sport = (struct sadb_x_nat_t_port *)
4610 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4611 dport = (struct sadb_x_nat_t_port *)
4612 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4615 KEY_PORTTOSADDR(&saidx.src, sport->sadb_x_nat_t_port_port);
4617 KEY_PORTTOSADDR(&saidx.dst, dport->sadb_x_nat_t_port_port);
4621 /* SPI allocation */
4622 spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4625 return key_senderror(so, m, EINVAL);
4627 /* get a SA index */
4628 if ((newsah = key_getsah(&saidx)) == NULL) {
4629 /* create a new SA index */
4630 if ((newsah = key_newsah(&saidx)) == NULL) {
4631 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4632 return key_senderror(so, m, ENOBUFS);
4638 newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4639 if (newsav == NULL) {
4640 /* XXX don't free new SA index allocated in above. */
4641 return key_senderror(so, m, error);
4645 newsav->spi = htonl(spi);
4647 /* delete the entry in acqtree */
4648 if (mhp->msg->sadb_msg_seq != 0) {
4650 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4651 /* reset counter in order to deletion by timehandler. */
4652 acq->created = time_second;
4658 struct mbuf *n, *nn;
4659 struct sadb_sa *m_sa;
4660 struct sadb_msg *newmsg;
4663 /* create new sadb_msg to reply. */
4664 len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4665 PFKEY_ALIGN8(sizeof(struct sadb_sa));
4667 MGETHDR(n, M_NOWAIT, MT_DATA);
4669 if (!(MCLGET(n, M_NOWAIT))) {
4675 return key_senderror(so, m, ENOBUFS);
4681 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4682 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4684 m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4685 m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4686 m_sa->sadb_sa_exttype = SADB_EXT_SA;
4687 m_sa->sadb_sa_spi = htonl(spi);
4688 off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4690 IPSEC_ASSERT(off == len,
4691 ("length inconsistency (off %u len %u)", off, len));
4693 n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4694 SADB_EXT_ADDRESS_DST);
4697 return key_senderror(so, m, ENOBUFS);
4700 if (n->m_len < sizeof(struct sadb_msg)) {
4701 n = m_pullup(n, sizeof(struct sadb_msg));
4703 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4706 n->m_pkthdr.len = 0;
4707 for (nn = n; nn; nn = nn->m_next)
4708 n->m_pkthdr.len += nn->m_len;
4710 newmsg = mtod(n, struct sadb_msg *);
4711 newmsg->sadb_msg_seq = newsav->seq;
4712 newmsg->sadb_msg_errno = 0;
4713 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4716 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4721 * allocating new SPI
4722 * called by key_getspi().
4728 key_do_getnewspi(struct sadb_spirange *spirange, struct secasindex *saidx)
4732 int count = V_key_spi_trycnt;
4734 /* set spi range to allocate */
4735 if (spirange != NULL) {
4736 min = spirange->sadb_spirange_min;
4737 max = spirange->sadb_spirange_max;
4739 min = V_key_spi_minval;
4740 max = V_key_spi_maxval;
4742 /* IPCOMP needs 2-byte SPI */
4743 if (saidx->proto == IPPROTO_IPCOMP) {
4750 t = min; min = max; max = t;
4755 if (key_checkspidup(saidx, min) != NULL) {
4756 ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4761 count--; /* taking one cost. */
4769 /* when requesting to allocate spi ranged */
4771 /* generate pseudo-random SPI value ranged. */
4772 newspi = min + (key_random() % (max - min + 1));
4774 if (key_checkspidup(saidx, newspi) == NULL)
4778 if (count == 0 || newspi == 0) {
4779 ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4786 keystat.getspi_count =
4787 (keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4793 * SADB_UPDATE processing
4795 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4796 * key(AE), (identity(SD),) (sensitivity)>
4797 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4799 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4800 * (identity(SD),) (sensitivity)>
4803 * m will always be freed.
4806 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4808 struct sadb_sa *sa0;
4809 struct sadb_address *src0, *dst0;
4811 struct sadb_x_nat_t_type *type;
4812 struct sadb_x_nat_t_port *sport, *dport;
4813 struct sadb_address *iaddr, *raddr;
4814 struct sadb_x_nat_t_frag *frag;
4816 struct secasindex saidx;
4817 struct secashead *sah;
4818 struct secasvar *sav;
4824 IPSEC_ASSERT(so != NULL, ("null socket"));
4825 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4826 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4827 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4829 /* map satype to proto */
4830 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4831 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4833 return key_senderror(so, m, EINVAL);
4836 if (mhp->ext[SADB_EXT_SA] == NULL ||
4837 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4838 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4839 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4840 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4841 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4842 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4843 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4844 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4845 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4846 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4847 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4849 return key_senderror(so, m, EINVAL);
4851 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4852 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4853 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4854 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4856 return key_senderror(so, m, EINVAL);
4858 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4859 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4860 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4862 mode = IPSEC_MODE_ANY;
4865 /* XXX boundary checking for other extensions */
4867 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4868 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4869 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4871 /* XXX boundary check against sa_len */
4872 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4875 * Make sure the port numbers are zero.
4876 * In case of NAT-T we will update them later if needed.
4878 KEY_PORTTOSADDR(&saidx.src, 0);
4879 KEY_PORTTOSADDR(&saidx.dst, 0);
4883 * Handle NAT-T info if present.
4885 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4886 mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4887 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4889 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4890 mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4891 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4892 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
4894 return key_senderror(so, m, EINVAL);
4897 type = (struct sadb_x_nat_t_type *)
4898 mhp->ext[SADB_X_EXT_NAT_T_TYPE];
4899 sport = (struct sadb_x_nat_t_port *)
4900 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4901 dport = (struct sadb_x_nat_t_port *)
4902 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4907 if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
4908 mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
4909 if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
4910 mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
4911 ipseclog((LOG_DEBUG, "%s: invalid message\n",
4913 return key_senderror(so, m, EINVAL);
4915 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
4916 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
4917 ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
4919 iaddr = raddr = NULL;
4921 if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
4922 if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
4923 ipseclog((LOG_DEBUG, "%s: invalid message\n",
4925 return key_senderror(so, m, EINVAL);
4927 frag = (struct sadb_x_nat_t_frag *)
4928 mhp->ext[SADB_X_EXT_NAT_T_FRAG];
4934 /* get a SA header */
4935 if ((sah = key_getsah(&saidx)) == NULL) {
4936 ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
4937 return key_senderror(so, m, ENOENT);
4940 /* set spidx if there */
4942 error = key_setident(sah, m, mhp);
4944 return key_senderror(so, m, error);
4946 /* find a SA with sequence number. */
4947 #ifdef IPSEC_DOSEQCHECK
4948 if (mhp->msg->sadb_msg_seq != 0
4949 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4950 ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
4951 "exists.\n", __func__, mhp->msg->sadb_msg_seq));
4952 return key_senderror(so, m, ENOENT);
4956 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
4959 ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
4960 __func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4961 return key_senderror(so, m, EINVAL);
4965 /* validity check */
4966 if (sav->sah->saidx.proto != proto) {
4967 ipseclog((LOG_DEBUG, "%s: protocol mismatched "
4968 "(DB=%u param=%u)\n", __func__,
4969 sav->sah->saidx.proto, proto));
4970 return key_senderror(so, m, EINVAL);
4972 #ifdef IPSEC_DOSEQCHECK
4973 if (sav->spi != sa0->sadb_sa_spi) {
4974 ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
4976 (u_int32_t)ntohl(sav->spi),
4977 (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4978 return key_senderror(so, m, EINVAL);
4981 if (sav->pid != mhp->msg->sadb_msg_pid) {
4982 ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
4983 __func__, sav->pid, mhp->msg->sadb_msg_pid));
4984 return key_senderror(so, m, EINVAL);
4987 /* copy sav values */
4988 error = key_setsaval(sav, m, mhp);
4991 return key_senderror(so, m, error);
4996 * Handle more NAT-T info if present,
4997 * now that we have a sav to fill.
5000 sav->natt_type = type->sadb_x_nat_t_type_type;
5003 KEY_PORTTOSADDR(&sav->sah->saidx.src,
5004 sport->sadb_x_nat_t_port_port);
5006 KEY_PORTTOSADDR(&sav->sah->saidx.dst,
5007 dport->sadb_x_nat_t_port_port);
5011 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5012 * We should actually check for a minimum MTU here, if we
5013 * want to support it in ip_output.
5016 sav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5020 /* check SA values to be mature. */
5021 if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
5023 return key_senderror(so, m, 0);
5029 /* set msg buf from mhp */
5030 n = key_getmsgbuf_x1(m, mhp);
5032 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5033 return key_senderror(so, m, ENOBUFS);
5037 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5042 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5043 * only called by key_update().
5046 * others : found, pointer to a SA.
5048 #ifdef IPSEC_DOSEQCHECK
5049 static struct secasvar *
5050 key_getsavbyseq(struct secashead *sah, u_int32_t seq)
5052 struct secasvar *sav;
5055 state = SADB_SASTATE_LARVAL;
5057 /* search SAD with sequence number ? */
5058 LIST_FOREACH(sav, &sah->savtree[state], chain) {
5060 KEY_CHKSASTATE(state, sav->state, __func__);
5062 if (sav->seq == seq) {
5064 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
5065 printf("DP %s cause refcnt++:%d SA:%p\n",
5066 __func__, sav->refcnt, sav));
5076 * SADB_ADD processing
5077 * add an entry to SA database, when received
5078 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5079 * key(AE), (identity(SD),) (sensitivity)>
5082 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5083 * (identity(SD),) (sensitivity)>
5086 * IGNORE identity and sensitivity messages.
5088 * m will always be freed.
5091 key_add(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5093 struct sadb_sa *sa0;
5094 struct sadb_address *src0, *dst0;
5096 struct sadb_x_nat_t_type *type;
5097 struct sadb_address *iaddr, *raddr;
5098 struct sadb_x_nat_t_frag *frag;
5100 struct secasindex saidx;
5101 struct secashead *newsah;
5102 struct secasvar *newsav;
5108 IPSEC_ASSERT(so != NULL, ("null socket"));
5109 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5110 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5111 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5113 /* map satype to proto */
5114 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5115 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5117 return key_senderror(so, m, EINVAL);
5120 if (mhp->ext[SADB_EXT_SA] == NULL ||
5121 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5122 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5123 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5124 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5125 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5126 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5127 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5128 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5129 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5130 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5131 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5133 return key_senderror(so, m, EINVAL);
5135 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5136 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5137 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5139 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5141 return key_senderror(so, m, EINVAL);
5143 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5144 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5145 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5147 mode = IPSEC_MODE_ANY;
5151 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5152 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5153 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5155 /* XXX boundary check against sa_len */
5156 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5159 * Make sure the port numbers are zero.
5160 * In case of NAT-T we will update them later if needed.
5162 KEY_PORTTOSADDR(&saidx.src, 0);
5163 KEY_PORTTOSADDR(&saidx.dst, 0);
5167 * Handle NAT-T info if present.
5169 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5170 mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5171 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5172 struct sadb_x_nat_t_port *sport, *dport;
5174 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5175 mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5176 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5177 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5179 return key_senderror(so, m, EINVAL);
5182 type = (struct sadb_x_nat_t_type *)
5183 mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5184 sport = (struct sadb_x_nat_t_port *)
5185 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5186 dport = (struct sadb_x_nat_t_port *)
5187 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5190 KEY_PORTTOSADDR(&saidx.src,
5191 sport->sadb_x_nat_t_port_port);
5193 KEY_PORTTOSADDR(&saidx.dst,
5194 dport->sadb_x_nat_t_port_port);
5198 if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5199 mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5200 if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5201 mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5202 ipseclog((LOG_DEBUG, "%s: invalid message\n",
5204 return key_senderror(so, m, EINVAL);
5206 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5207 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5208 ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5210 iaddr = raddr = NULL;
5212 if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5213 if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5214 ipseclog((LOG_DEBUG, "%s: invalid message\n",
5216 return key_senderror(so, m, EINVAL);
5218 frag = (struct sadb_x_nat_t_frag *)
5219 mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5225 /* get a SA header */
5226 if ((newsah = key_getsah(&saidx)) == NULL) {
5227 /* create a new SA header */
5228 if ((newsah = key_newsah(&saidx)) == NULL) {
5229 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
5230 return key_senderror(so, m, ENOBUFS);
5234 /* set spidx if there */
5236 error = key_setident(newsah, m, mhp);
5238 return key_senderror(so, m, error);
5241 /* create new SA entry. */
5242 /* We can create new SA only if SPI is differenct. */
5244 newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5246 if (newsav != NULL) {
5247 ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5248 return key_senderror(so, m, EEXIST);
5250 newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5251 if (newsav == NULL) {
5252 return key_senderror(so, m, error);
5257 * Handle more NAT-T info if present,
5258 * now that we have a sav to fill.
5261 newsav->natt_type = type->sadb_x_nat_t_type_type;
5265 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5266 * We should actually check for a minimum MTU here, if we
5267 * want to support it in ip_output.
5270 newsav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5274 /* check SA values to be mature. */
5275 if ((error = key_mature(newsav)) != 0) {
5276 KEY_FREESAV(&newsav);
5277 return key_senderror(so, m, error);
5281 * don't call key_freesav() here, as we would like to keep the SA
5282 * in the database on success.
5288 /* set msg buf from mhp */
5289 n = key_getmsgbuf_x1(m, mhp);
5291 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5292 return key_senderror(so, m, ENOBUFS);
5296 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5302 key_setident(struct secashead *sah, struct mbuf *m,
5303 const struct sadb_msghdr *mhp)
5305 const struct sadb_ident *idsrc, *iddst;
5306 int idsrclen, iddstlen;
5308 IPSEC_ASSERT(sah != NULL, ("null secashead"));
5309 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5310 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5311 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5313 /* don't make buffer if not there */
5314 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5315 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5321 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5322 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5323 ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5327 idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5328 iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5329 idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5330 iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5332 /* validity check */
5333 if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5334 ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5338 switch (idsrc->sadb_ident_type) {
5339 case SADB_IDENTTYPE_PREFIX:
5340 case SADB_IDENTTYPE_FQDN:
5341 case SADB_IDENTTYPE_USERFQDN:
5343 /* XXX do nothing */
5349 /* make structure */
5350 sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5351 if (sah->idents == NULL) {
5352 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5355 sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5356 if (sah->identd == NULL) {
5357 free(sah->idents, M_IPSEC_MISC);
5359 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5362 sah->idents->type = idsrc->sadb_ident_type;
5363 sah->idents->id = idsrc->sadb_ident_id;
5365 sah->identd->type = iddst->sadb_ident_type;
5366 sah->identd->id = iddst->sadb_ident_id;
5372 * m will not be freed on return.
5373 * it is caller's responsibility to free the result.
5375 static struct mbuf *
5376 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
5380 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5381 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5382 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5384 /* create new sadb_msg to reply. */
5385 n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5386 SADB_EXT_SA, SADB_X_EXT_SA2,
5387 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5388 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5389 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5393 if (n->m_len < sizeof(struct sadb_msg)) {
5394 n = m_pullup(n, sizeof(struct sadb_msg));
5398 mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5399 mtod(n, struct sadb_msg *)->sadb_msg_len =
5400 PFKEY_UNIT64(n->m_pkthdr.len);
5406 * SADB_DELETE processing
5408 * <base, SA(*), address(SD)>
5409 * from the ikmpd, and set SADB_SASTATE_DEAD,
5411 * <base, SA(*), address(SD)>
5414 * m will always be freed.
5417 key_delete(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5419 struct sadb_sa *sa0;
5420 struct sadb_address *src0, *dst0;
5421 struct secasindex saidx;
5422 struct secashead *sah;
5423 struct secasvar *sav = NULL;
5426 IPSEC_ASSERT(so != NULL, ("null socket"));
5427 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5428 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5429 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5431 /* map satype to proto */
5432 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5433 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5435 return key_senderror(so, m, EINVAL);
5438 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5439 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5440 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5442 return key_senderror(so, m, EINVAL);
5445 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5446 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5447 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5449 return key_senderror(so, m, EINVAL);
5452 if (mhp->ext[SADB_EXT_SA] == NULL) {
5454 * Caller wants us to delete all non-LARVAL SAs
5455 * that match the src/dst. This is used during
5456 * IKE INITIAL-CONTACT.
5458 ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5459 return key_delete_all(so, m, mhp, proto);
5460 } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5461 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5463 return key_senderror(so, m, EINVAL);
5466 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5467 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5468 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5470 /* XXX boundary check against sa_len */
5471 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5474 * Make sure the port numbers are zero.
5475 * In case of NAT-T we will update them later if needed.
5477 KEY_PORTTOSADDR(&saidx.src, 0);
5478 KEY_PORTTOSADDR(&saidx.dst, 0);
5482 * Handle NAT-T info if present.
5484 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5485 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5486 struct sadb_x_nat_t_port *sport, *dport;
5488 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5489 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5490 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5492 return key_senderror(so, m, EINVAL);
5495 sport = (struct sadb_x_nat_t_port *)
5496 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5497 dport = (struct sadb_x_nat_t_port *)
5498 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5501 KEY_PORTTOSADDR(&saidx.src,
5502 sport->sadb_x_nat_t_port_port);
5504 KEY_PORTTOSADDR(&saidx.dst,
5505 dport->sadb_x_nat_t_port_port);
5509 /* get a SA header */
5511 LIST_FOREACH(sah, &V_sahtree, chain) {
5512 if (sah->state == SADB_SASTATE_DEAD)
5514 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5517 /* get a SA with SPI. */
5518 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5524 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5525 return key_senderror(so, m, ENOENT);
5528 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5534 struct sadb_msg *newmsg;
5536 /* create new sadb_msg to reply. */
5537 /* XXX-BZ NAT-T extensions? */
5538 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5539 SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5541 return key_senderror(so, m, ENOBUFS);
5543 if (n->m_len < sizeof(struct sadb_msg)) {
5544 n = m_pullup(n, sizeof(struct sadb_msg));
5546 return key_senderror(so, m, ENOBUFS);
5548 newmsg = mtod(n, struct sadb_msg *);
5549 newmsg->sadb_msg_errno = 0;
5550 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5553 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5558 * delete all SAs for src/dst. Called from key_delete().
5561 key_delete_all(struct socket *so, struct mbuf *m,
5562 const struct sadb_msghdr *mhp, u_int16_t proto)
5564 struct sadb_address *src0, *dst0;
5565 struct secasindex saidx;
5566 struct secashead *sah;
5567 struct secasvar *sav, *nextsav;
5568 u_int stateidx, state;
5570 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5571 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5573 /* XXX boundary check against sa_len */
5574 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5577 * Make sure the port numbers are zero.
5578 * In case of NAT-T we will update them later if needed.
5580 KEY_PORTTOSADDR(&saidx.src, 0);
5581 KEY_PORTTOSADDR(&saidx.dst, 0);
5585 * Handle NAT-T info if present.
5588 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5589 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5590 struct sadb_x_nat_t_port *sport, *dport;
5592 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5593 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5594 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5596 return key_senderror(so, m, EINVAL);
5599 sport = (struct sadb_x_nat_t_port *)
5600 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5601 dport = (struct sadb_x_nat_t_port *)
5602 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5605 KEY_PORTTOSADDR(&saidx.src,
5606 sport->sadb_x_nat_t_port_port);
5608 KEY_PORTTOSADDR(&saidx.dst,
5609 dport->sadb_x_nat_t_port_port);
5614 LIST_FOREACH(sah, &V_sahtree, chain) {
5615 if (sah->state == SADB_SASTATE_DEAD)
5617 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5620 /* Delete all non-LARVAL SAs. */
5622 stateidx < _ARRAYLEN(saorder_state_alive);
5624 state = saorder_state_alive[stateidx];
5625 if (state == SADB_SASTATE_LARVAL)
5627 for (sav = LIST_FIRST(&sah->savtree[state]);
5628 sav != NULL; sav = nextsav) {
5629 nextsav = LIST_NEXT(sav, chain);
5631 if (sav->state != state) {
5632 ipseclog((LOG_DEBUG, "%s: invalid "
5633 "sav->state (queue %d SA %d)\n",
5634 __func__, state, sav->state));
5638 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5646 struct sadb_msg *newmsg;
5648 /* create new sadb_msg to reply. */
5649 /* XXX-BZ NAT-T extensions? */
5650 n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5651 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5653 return key_senderror(so, m, ENOBUFS);
5655 if (n->m_len < sizeof(struct sadb_msg)) {
5656 n = m_pullup(n, sizeof(struct sadb_msg));
5658 return key_senderror(so, m, ENOBUFS);
5660 newmsg = mtod(n, struct sadb_msg *);
5661 newmsg->sadb_msg_errno = 0;
5662 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5665 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5670 * SADB_GET processing
5672 * <base, SA(*), address(SD)>
5673 * from the ikmpd, and get a SP and a SA to respond,
5675 * <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5676 * (identity(SD),) (sensitivity)>
5679 * m will always be freed.
5682 key_get(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5684 struct sadb_sa *sa0;
5685 struct sadb_address *src0, *dst0;
5686 struct secasindex saidx;
5687 struct secashead *sah;
5688 struct secasvar *sav = NULL;
5691 IPSEC_ASSERT(so != NULL, ("null socket"));
5692 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5693 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5694 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5696 /* map satype to proto */
5697 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5698 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5700 return key_senderror(so, m, EINVAL);
5703 if (mhp->ext[SADB_EXT_SA] == NULL ||
5704 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5705 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5706 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5708 return key_senderror(so, m, EINVAL);
5710 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5711 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5712 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5713 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5715 return key_senderror(so, m, EINVAL);
5718 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5719 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5720 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5722 /* XXX boundary check against sa_len */
5723 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5726 * Make sure the port numbers are zero.
5727 * In case of NAT-T we will update them later if needed.
5729 KEY_PORTTOSADDR(&saidx.src, 0);
5730 KEY_PORTTOSADDR(&saidx.dst, 0);
5734 * Handle NAT-T info if present.
5737 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5738 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5739 struct sadb_x_nat_t_port *sport, *dport;
5741 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5742 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5743 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5745 return key_senderror(so, m, EINVAL);
5748 sport = (struct sadb_x_nat_t_port *)
5749 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5750 dport = (struct sadb_x_nat_t_port *)
5751 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5754 KEY_PORTTOSADDR(&saidx.src,
5755 sport->sadb_x_nat_t_port_port);
5757 KEY_PORTTOSADDR(&saidx.dst,
5758 dport->sadb_x_nat_t_port_port);
5762 /* get a SA header */
5764 LIST_FOREACH(sah, &V_sahtree, chain) {
5765 if (sah->state == SADB_SASTATE_DEAD)
5767 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5770 /* get a SA with SPI. */
5771 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5777 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5778 return key_senderror(so, m, ENOENT);
5785 /* map proto to satype */
5786 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5787 ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5789 return key_senderror(so, m, EINVAL);
5792 /* create new sadb_msg to reply. */
5793 n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5794 mhp->msg->sadb_msg_pid);
5796 return key_senderror(so, m, ENOBUFS);
5799 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5803 /* XXX make it sysctl-configurable? */
5805 key_getcomb_setlifetime(struct sadb_comb *comb)
5808 comb->sadb_comb_soft_allocations = 1;
5809 comb->sadb_comb_hard_allocations = 1;
5810 comb->sadb_comb_soft_bytes = 0;
5811 comb->sadb_comb_hard_bytes = 0;
5812 comb->sadb_comb_hard_addtime = 86400; /* 1 day */
5813 comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5814 comb->sadb_comb_soft_usetime = 28800; /* 8 hours */
5815 comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5819 * XXX reorder combinations by preference
5820 * XXX no idea if the user wants ESP authentication or not
5822 static struct mbuf *
5825 struct sadb_comb *comb;
5826 struct enc_xform *algo;
5827 struct mbuf *result = NULL, *m, *n;
5831 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5834 for (i = 1; i <= SADB_EALG_MAX; i++) {
5835 algo = esp_algorithm_lookup(i);
5839 /* discard algorithms with key size smaller than system min */
5840 if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
5842 if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
5843 encmin = V_ipsec_esp_keymin;
5845 encmin = _BITS(algo->minkey);
5847 if (V_ipsec_esp_auth)
5848 m = key_getcomb_ah();
5850 IPSEC_ASSERT(l <= MLEN,
5851 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
5852 MGET(m, M_NOWAIT, MT_DATA);
5857 bzero(mtod(m, caddr_t), m->m_len);
5864 for (n = m; n; n = n->m_next)
5866 IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
5868 for (off = 0; off < totlen; off += l) {
5869 n = m_pulldown(m, off, l, &o);
5871 /* m is already freed */
5874 comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5875 bzero(comb, sizeof(*comb));
5876 key_getcomb_setlifetime(comb);
5877 comb->sadb_comb_encrypt = i;
5878 comb->sadb_comb_encrypt_minbits = encmin;
5879 comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5897 key_getsizes_ah(const struct auth_hash *ah, int alg, u_int16_t* min,
5901 *min = *max = ah->keysize;
5902 if (ah->keysize == 0) {
5904 * Transform takes arbitrary key size but algorithm
5905 * key size is restricted. Enforce this here.
5908 case SADB_X_AALG_MD5: *min = *max = 16; break;
5909 case SADB_X_AALG_SHA: *min = *max = 20; break;
5910 case SADB_X_AALG_NULL: *min = 1; *max = 256; break;
5911 case SADB_X_AALG_SHA2_256: *min = *max = 32; break;
5912 case SADB_X_AALG_SHA2_384: *min = *max = 48; break;
5913 case SADB_X_AALG_SHA2_512: *min = *max = 64; break;
5915 DPRINTF(("%s: unknown AH algorithm %u\n",
5923 * XXX reorder combinations by preference
5925 static struct mbuf *
5928 struct sadb_comb *comb;
5929 struct auth_hash *algo;
5931 u_int16_t minkeysize, maxkeysize;
5933 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5936 for (i = 1; i <= SADB_AALG_MAX; i++) {
5938 /* we prefer HMAC algorithms, not old algorithms */
5939 if (i != SADB_AALG_SHA1HMAC &&
5940 i != SADB_AALG_MD5HMAC &&
5941 i != SADB_X_AALG_SHA2_256 &&
5942 i != SADB_X_AALG_SHA2_384 &&
5943 i != SADB_X_AALG_SHA2_512)
5946 algo = ah_algorithm_lookup(i);
5949 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5950 /* discard algorithms with key size smaller than system min */
5951 if (_BITS(minkeysize) < V_ipsec_ah_keymin)
5955 IPSEC_ASSERT(l <= MLEN,
5956 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
5957 MGET(m, M_NOWAIT, MT_DATA);
5964 M_PREPEND(m, l, M_NOWAIT);
5968 comb = mtod(m, struct sadb_comb *);
5969 bzero(comb, sizeof(*comb));
5970 key_getcomb_setlifetime(comb);
5971 comb->sadb_comb_auth = i;
5972 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5973 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5980 * not really an official behavior. discussed in pf_key@inner.net in Sep2000.
5981 * XXX reorder combinations by preference
5983 static struct mbuf *
5984 key_getcomb_ipcomp()
5986 struct sadb_comb *comb;
5987 struct comp_algo *algo;
5990 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5993 for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5994 algo = ipcomp_algorithm_lookup(i);
5999 IPSEC_ASSERT(l <= MLEN,
6000 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6001 MGET(m, M_NOWAIT, MT_DATA);
6008 M_PREPEND(m, l, M_NOWAIT);
6012 comb = mtod(m, struct sadb_comb *);
6013 bzero(comb, sizeof(*comb));
6014 key_getcomb_setlifetime(comb);
6015 comb->sadb_comb_encrypt = i;
6016 /* what should we set into sadb_comb_*_{min,max}bits? */
6023 * XXX no way to pass mode (transport/tunnel) to userland
6024 * XXX replay checking?
6025 * XXX sysctl interface to ipsec_{ah,esp}_keymin
6027 static struct mbuf *
6028 key_getprop(const struct secasindex *saidx)
6030 struct sadb_prop *prop;
6032 const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6035 switch (saidx->proto) {
6037 m = key_getcomb_esp();
6040 m = key_getcomb_ah();
6042 case IPPROTO_IPCOMP:
6043 m = key_getcomb_ipcomp();
6051 M_PREPEND(m, l, M_NOWAIT);
6056 for (n = m; n; n = n->m_next)
6059 prop = mtod(m, struct sadb_prop *);
6060 bzero(prop, sizeof(*prop));
6061 prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6062 prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6063 prop->sadb_prop_replay = 32; /* XXX */
6069 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6071 * <base, SA, address(SD), (address(P)), x_policy,
6072 * (identity(SD),) (sensitivity,) proposal>
6073 * to KMD, and expect to receive
6074 * <base> with SADB_ACQUIRE if error occured,
6076 * <base, src address, dst address, (SPI range)> with SADB_GETSPI
6077 * from KMD by PF_KEY.
6079 * XXX x_policy is outside of RFC2367 (KAME extension).
6080 * XXX sensitivity is not supported.
6081 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6082 * see comment for key_getcomb_ipcomp().
6086 * others: error number
6089 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6091 struct mbuf *result = NULL, *m;
6092 struct secacq *newacq;
6097 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6098 satype = key_proto2satype(saidx->proto);
6099 IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6102 * We never do anything about acquirng SA. There is anather
6103 * solution that kernel blocks to send SADB_ACQUIRE message until
6104 * getting something message from IKEd. In later case, to be
6105 * managed with ACQUIRING list.
6107 /* Get an entry to check whether sending message or not. */
6108 if ((newacq = key_getacq(saidx)) != NULL) {
6109 if (V_key_blockacq_count < newacq->count) {
6110 /* reset counter and do send message. */
6113 /* increment counter and do nothing. */
6118 /* make new entry for blocking to send SADB_ACQUIRE. */
6119 if ((newacq = key_newacq(saidx)) == NULL)
6125 m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6133 * No SADB_X_EXT_NAT_T_* here: we do not know
6134 * anything related to NAT-T at this time.
6137 /* set sadb_address for saidx's. */
6138 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6139 &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6146 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6147 &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6154 /* XXX proxy address (optional) */
6156 /* set sadb_x_policy */
6158 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6166 /* XXX identity (optional) */
6168 if (idexttype && fqdn) {
6169 /* create identity extension (FQDN) */
6170 struct sadb_ident *id;
6173 fqdnlen = strlen(fqdn) + 1; /* +1 for terminating-NUL */
6174 id = (struct sadb_ident *)p;
6175 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6176 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6177 id->sadb_ident_exttype = idexttype;
6178 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6179 bcopy(fqdn, id + 1, fqdnlen);
6180 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6184 /* create identity extension (USERFQDN) */
6185 struct sadb_ident *id;
6189 /* +1 for terminating-NUL */
6190 userfqdnlen = strlen(userfqdn) + 1;
6193 id = (struct sadb_ident *)p;
6194 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6195 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6196 id->sadb_ident_exttype = idexttype;
6197 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6198 /* XXX is it correct? */
6199 if (curproc && curproc->p_cred)
6200 id->sadb_ident_id = curproc->p_cred->p_ruid;
6201 if (userfqdn && userfqdnlen)
6202 bcopy(userfqdn, id + 1, userfqdnlen);
6203 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6207 /* XXX sensitivity (optional) */
6209 /* create proposal/combination extension */
6210 m = key_getprop(saidx);
6213 * spec conformant: always attach proposal/combination extension,
6214 * the problem is that we have no way to attach it for ipcomp,
6215 * due to the way sadb_comb is declared in RFC2367.
6224 * outside of spec; make proposal/combination extension optional.
6230 if ((result->m_flags & M_PKTHDR) == 0) {
6235 if (result->m_len < sizeof(struct sadb_msg)) {
6236 result = m_pullup(result, sizeof(struct sadb_msg));
6237 if (result == NULL) {
6243 result->m_pkthdr.len = 0;
6244 for (m = result; m; m = m->m_next)
6245 result->m_pkthdr.len += m->m_len;
6247 mtod(result, struct sadb_msg *)->sadb_msg_len =
6248 PFKEY_UNIT64(result->m_pkthdr.len);
6250 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6258 static struct secacq *
6259 key_newacq(const struct secasindex *saidx)
6261 struct secacq *newacq;
6264 newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6265 if (newacq == NULL) {
6266 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6271 bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
6272 newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6273 newacq->created = time_second;
6276 /* add to acqtree */
6278 LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
6284 static struct secacq *
6285 key_getacq(const struct secasindex *saidx)
6290 LIST_FOREACH(acq, &V_acqtree, chain) {
6291 if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6299 static struct secacq *
6300 key_getacqbyseq(u_int32_t seq)
6305 LIST_FOREACH(acq, &V_acqtree, chain) {
6306 if (acq->seq == seq)
6314 static struct secspacq *
6315 key_newspacq(struct secpolicyindex *spidx)
6317 struct secspacq *acq;
6320 acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6322 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6327 bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6328 acq->created = time_second;
6331 /* add to spacqtree */
6333 LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6339 static struct secspacq *
6340 key_getspacq(struct secpolicyindex *spidx)
6342 struct secspacq *acq;
6345 LIST_FOREACH(acq, &V_spacqtree, chain) {
6346 if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6347 /* NB: return holding spacq_lock */
6357 * SADB_ACQUIRE processing,
6358 * in first situation, is receiving
6360 * from the ikmpd, and clear sequence of its secasvar entry.
6362 * In second situation, is receiving
6363 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6364 * from a user land process, and return
6365 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6368 * m will always be freed.
6371 key_acquire2(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6373 const struct sadb_address *src0, *dst0;
6374 struct secasindex saidx;
6375 struct secashead *sah;
6379 IPSEC_ASSERT(so != NULL, ("null socket"));
6380 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6381 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6382 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6385 * Error message from KMd.
6386 * We assume that if error was occured in IKEd, the length of PFKEY
6387 * message is equal to the size of sadb_msg structure.
6388 * We do not raise error even if error occured in this function.
6390 if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6393 /* check sequence number */
6394 if (mhp->msg->sadb_msg_seq == 0) {
6395 ipseclog((LOG_DEBUG, "%s: must specify sequence "
6396 "number.\n", __func__));
6401 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6403 * the specified larval SA is already gone, or we got
6404 * a bogus sequence number. we can silently ignore it.
6410 /* reset acq counter in order to deletion by timehander. */
6411 acq->created = time_second;
6418 * This message is from user land.
6421 /* map satype to proto */
6422 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6423 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6425 return key_senderror(so, m, EINVAL);
6428 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6429 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6430 mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6432 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6434 return key_senderror(so, m, EINVAL);
6436 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6437 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6438 mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6440 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6442 return key_senderror(so, m, EINVAL);
6445 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6446 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6448 /* XXX boundary check against sa_len */
6449 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6452 * Make sure the port numbers are zero.
6453 * In case of NAT-T we will update them later if needed.
6455 KEY_PORTTOSADDR(&saidx.src, 0);
6456 KEY_PORTTOSADDR(&saidx.dst, 0);
6460 * Handle NAT-T info if present.
6463 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
6464 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
6465 struct sadb_x_nat_t_port *sport, *dport;
6467 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
6468 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
6469 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
6471 return key_senderror(so, m, EINVAL);
6474 sport = (struct sadb_x_nat_t_port *)
6475 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
6476 dport = (struct sadb_x_nat_t_port *)
6477 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
6480 KEY_PORTTOSADDR(&saidx.src,
6481 sport->sadb_x_nat_t_port_port);
6483 KEY_PORTTOSADDR(&saidx.dst,
6484 dport->sadb_x_nat_t_port_port);
6488 /* get a SA index */
6490 LIST_FOREACH(sah, &V_sahtree, chain) {
6491 if (sah->state == SADB_SASTATE_DEAD)
6493 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6498 ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6499 return key_senderror(so, m, EEXIST);
6502 error = key_acquire(&saidx, NULL);
6504 ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6505 __func__, mhp->msg->sadb_msg_errno));
6506 return key_senderror(so, m, error);
6509 return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6513 * SADB_REGISTER processing.
6514 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6517 * from the ikmpd, and register a socket to send PF_KEY messages,
6521 * If socket is detached, must free from regnode.
6523 * m will always be freed.
6526 key_register(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6528 struct secreg *reg, *newreg = 0;
6530 IPSEC_ASSERT(so != NULL, ("null socket"));
6531 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6532 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6533 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6535 /* check for invalid register message */
6536 if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6537 return key_senderror(so, m, EINVAL);
6539 /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6540 if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6543 /* check whether existing or not */
6545 LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6546 if (reg->so == so) {
6548 ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6550 return key_senderror(so, m, EEXIST);
6554 /* create regnode */
6555 newreg = malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6556 if (newreg == NULL) {
6558 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6559 return key_senderror(so, m, ENOBUFS);
6563 ((struct keycb *)sotorawcb(so))->kp_registered++;
6565 /* add regnode to regtree. */
6566 LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6572 struct sadb_msg *newmsg;
6573 struct sadb_supported *sup;
6574 u_int len, alen, elen;
6577 struct sadb_alg *alg;
6579 /* create new sadb_msg to reply. */
6581 for (i = 1; i <= SADB_AALG_MAX; i++) {
6582 if (ah_algorithm_lookup(i))
6583 alen += sizeof(struct sadb_alg);
6586 alen += sizeof(struct sadb_supported);
6588 for (i = 1; i <= SADB_EALG_MAX; i++) {
6589 if (esp_algorithm_lookup(i))
6590 elen += sizeof(struct sadb_alg);
6593 elen += sizeof(struct sadb_supported);
6595 len = sizeof(struct sadb_msg) + alen + elen;
6598 return key_senderror(so, m, ENOBUFS);
6600 MGETHDR(n, M_NOWAIT, MT_DATA);
6602 if (!(MCLGET(n, M_NOWAIT))) {
6608 return key_senderror(so, m, ENOBUFS);
6610 n->m_pkthdr.len = n->m_len = len;
6614 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6615 newmsg = mtod(n, struct sadb_msg *);
6616 newmsg->sadb_msg_errno = 0;
6617 newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6618 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6620 /* for authentication algorithm */
6622 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6623 sup->sadb_supported_len = PFKEY_UNIT64(alen);
6624 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6625 off += PFKEY_ALIGN8(sizeof(*sup));
6627 for (i = 1; i <= SADB_AALG_MAX; i++) {
6628 struct auth_hash *aalgo;
6629 u_int16_t minkeysize, maxkeysize;
6631 aalgo = ah_algorithm_lookup(i);
6634 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6635 alg->sadb_alg_id = i;
6636 alg->sadb_alg_ivlen = 0;
6637 key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6638 alg->sadb_alg_minbits = _BITS(minkeysize);
6639 alg->sadb_alg_maxbits = _BITS(maxkeysize);
6640 off += PFKEY_ALIGN8(sizeof(*alg));
6644 /* for encryption algorithm */
6646 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6647 sup->sadb_supported_len = PFKEY_UNIT64(elen);
6648 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6649 off += PFKEY_ALIGN8(sizeof(*sup));
6651 for (i = 1; i <= SADB_EALG_MAX; i++) {
6652 struct enc_xform *ealgo;
6654 ealgo = esp_algorithm_lookup(i);
6657 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6658 alg->sadb_alg_id = i;
6659 alg->sadb_alg_ivlen = ealgo->blocksize;
6660 alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6661 alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6662 off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6666 IPSEC_ASSERT(off == len,
6667 ("length assumption failed (off %u len %u)", off, len));
6670 return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6675 * free secreg entry registered.
6676 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6679 key_freereg(struct socket *so)
6684 IPSEC_ASSERT(so != NULL, ("NULL so"));
6687 * check whether existing or not.
6688 * check all type of SA, because there is a potential that
6689 * one socket is registered to multiple type of SA.
6692 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6693 LIST_FOREACH(reg, &V_regtree[i], chain) {
6694 if (reg->so == so && __LIST_CHAINED(reg)) {
6695 LIST_REMOVE(reg, chain);
6696 free(reg, M_IPSEC_SAR);
6705 * SADB_EXPIRE processing
6707 * <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6709 * NOTE: We send only soft lifetime extension.
6712 * others : error number
6715 key_expire(struct secasvar *sav, int hard)
6718 struct mbuf *result = NULL, *m;
6721 struct sadb_lifetime *lt;
6723 IPSEC_ASSERT (sav != NULL, ("null sav"));
6724 IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6726 /* set msg header */
6727 satype = key_proto2satype(sav->sah->saidx.proto);
6728 IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6729 m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6736 /* create SA extension */
6737 m = key_setsadbsa(sav);
6744 /* create SA extension */
6745 m = key_setsadbxsa2(sav->sah->saidx.mode,
6746 sav->replay ? sav->replay->count : 0,
6747 sav->sah->saidx.reqid);
6754 /* create lifetime extension (current and soft) */
6755 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6756 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
6763 bzero(mtod(m, caddr_t), len);
6764 lt = mtod(m, struct sadb_lifetime *);
6765 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6766 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6767 lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6768 lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6769 lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6770 lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6771 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6772 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6774 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
6775 lt->sadb_lifetime_allocations = sav->lft_h->allocations;
6776 lt->sadb_lifetime_bytes = sav->lft_h->bytes;
6777 lt->sadb_lifetime_addtime = sav->lft_h->addtime;
6778 lt->sadb_lifetime_usetime = sav->lft_h->usetime;
6780 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6781 lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6782 lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6783 lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6784 lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6788 /* set sadb_address for source */
6789 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6790 &sav->sah->saidx.src.sa,
6791 FULLMASK, IPSEC_ULPROTO_ANY);
6798 /* set sadb_address for destination */
6799 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6800 &sav->sah->saidx.dst.sa,
6801 FULLMASK, IPSEC_ULPROTO_ANY);
6809 * XXX-BZ Handle NAT-T extensions here.
6812 if ((result->m_flags & M_PKTHDR) == 0) {
6817 if (result->m_len < sizeof(struct sadb_msg)) {
6818 result = m_pullup(result, sizeof(struct sadb_msg));
6819 if (result == NULL) {
6825 result->m_pkthdr.len = 0;
6826 for (m = result; m; m = m->m_next)
6827 result->m_pkthdr.len += m->m_len;
6829 mtod(result, struct sadb_msg *)->sadb_msg_len =
6830 PFKEY_UNIT64(result->m_pkthdr.len);
6832 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6841 * SADB_FLUSH processing
6844 * from the ikmpd, and free all entries in secastree.
6848 * NOTE: to do is only marking SADB_SASTATE_DEAD.
6850 * m will always be freed.
6853 key_flush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6855 struct sadb_msg *newmsg;
6856 struct secashead *sah, *nextsah;
6857 struct secasvar *sav, *nextsav;
6862 IPSEC_ASSERT(so != NULL, ("null socket"));
6863 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6864 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6866 /* map satype to proto */
6867 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6868 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6870 return key_senderror(so, m, EINVAL);
6873 /* no SATYPE specified, i.e. flushing all SA. */
6875 for (sah = LIST_FIRST(&V_sahtree);
6878 nextsah = LIST_NEXT(sah, chain);
6880 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6881 && proto != sah->saidx.proto)
6885 stateidx < _ARRAYLEN(saorder_state_alive);
6887 state = saorder_state_any[stateidx];
6888 for (sav = LIST_FIRST(&sah->savtree[state]);
6892 nextsav = LIST_NEXT(sav, chain);
6894 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6899 sah->state = SADB_SASTATE_DEAD;
6903 if (m->m_len < sizeof(struct sadb_msg) ||
6904 sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6905 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6906 return key_senderror(so, m, ENOBUFS);
6912 m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6913 newmsg = mtod(m, struct sadb_msg *);
6914 newmsg->sadb_msg_errno = 0;
6915 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6917 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6921 * SADB_DUMP processing
6922 * dump all entries including status of DEAD in SAD.
6925 * from the ikmpd, and dump all secasvar leaves
6930 * m will always be freed.
6933 key_dump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6935 struct secashead *sah;
6936 struct secasvar *sav;
6942 struct sadb_msg *newmsg;
6945 IPSEC_ASSERT(so != NULL, ("null socket"));
6946 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6947 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6948 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6950 /* map satype to proto */
6951 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6952 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6954 return key_senderror(so, m, EINVAL);
6957 /* count sav entries to be sent to the userland. */
6960 LIST_FOREACH(sah, &V_sahtree, chain) {
6961 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6962 && proto != sah->saidx.proto)
6966 stateidx < _ARRAYLEN(saorder_state_any);
6968 state = saorder_state_any[stateidx];
6969 LIST_FOREACH(sav, &sah->savtree[state], chain) {
6977 return key_senderror(so, m, ENOENT);
6980 /* send this to the userland, one at a time. */
6982 LIST_FOREACH(sah, &V_sahtree, chain) {
6983 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6984 && proto != sah->saidx.proto)
6987 /* map proto to satype */
6988 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6990 ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
6991 "SAD.\n", __func__));
6992 return key_senderror(so, m, EINVAL);
6996 stateidx < _ARRAYLEN(saorder_state_any);
6998 state = saorder_state_any[stateidx];
6999 LIST_FOREACH(sav, &sah->savtree[state], chain) {
7000 n = key_setdumpsa(sav, SADB_DUMP, satype,
7001 --cnt, mhp->msg->sadb_msg_pid);
7004 return key_senderror(so, m, ENOBUFS);
7006 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7017 * SADB_X_PROMISC processing
7019 * m will always be freed.
7022 key_promisc(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7026 IPSEC_ASSERT(so != NULL, ("null socket"));
7027 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7028 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7029 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7031 olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7033 if (olen < sizeof(struct sadb_msg)) {
7035 return key_senderror(so, m, EINVAL);
7040 } else if (olen == sizeof(struct sadb_msg)) {
7041 /* enable/disable promisc mode */
7044 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7045 return key_senderror(so, m, EINVAL);
7046 mhp->msg->sadb_msg_errno = 0;
7047 switch (mhp->msg->sadb_msg_satype) {
7050 kp->kp_promisc = mhp->msg->sadb_msg_satype;
7053 return key_senderror(so, m, EINVAL);
7056 /* send the original message back to everyone */
7057 mhp->msg->sadb_msg_errno = 0;
7058 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7060 /* send packet as is */
7062 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7064 /* TODO: if sadb_msg_seq is specified, send to specific pid */
7065 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7069 static int (*key_typesw[])(struct socket *, struct mbuf *,
7070 const struct sadb_msghdr *) = {
7071 NULL, /* SADB_RESERVED */
7072 key_getspi, /* SADB_GETSPI */
7073 key_update, /* SADB_UPDATE */
7074 key_add, /* SADB_ADD */
7075 key_delete, /* SADB_DELETE */
7076 key_get, /* SADB_GET */
7077 key_acquire2, /* SADB_ACQUIRE */
7078 key_register, /* SADB_REGISTER */
7079 NULL, /* SADB_EXPIRE */
7080 key_flush, /* SADB_FLUSH */
7081 key_dump, /* SADB_DUMP */
7082 key_promisc, /* SADB_X_PROMISC */
7083 NULL, /* SADB_X_PCHANGE */
7084 key_spdadd, /* SADB_X_SPDUPDATE */
7085 key_spdadd, /* SADB_X_SPDADD */
7086 key_spddelete, /* SADB_X_SPDDELETE */
7087 key_spdget, /* SADB_X_SPDGET */
7088 NULL, /* SADB_X_SPDACQUIRE */
7089 key_spddump, /* SADB_X_SPDDUMP */
7090 key_spdflush, /* SADB_X_SPDFLUSH */
7091 key_spdadd, /* SADB_X_SPDSETIDX */
7092 NULL, /* SADB_X_SPDEXPIRE */
7093 key_spddelete2, /* SADB_X_SPDDELETE2 */
7097 * parse sadb_msg buffer to process PFKEYv2,
7098 * and create a data to response if needed.
7099 * I think to be dealed with mbuf directly.
7101 * msgp : pointer to pointer to a received buffer pulluped.
7102 * This is rewrited to response.
7103 * so : pointer to socket.
7105 * length for buffer to send to user process.
7108 key_parse(struct mbuf *m, struct socket *so)
7110 struct sadb_msg *msg;
7111 struct sadb_msghdr mh;
7116 IPSEC_ASSERT(so != NULL, ("null socket"));
7117 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7119 #if 0 /*kdebug_sadb assumes msg in linear buffer*/
7120 KEYDEBUG(KEYDEBUG_KEY_DUMP,
7121 ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
7125 if (m->m_len < sizeof(struct sadb_msg)) {
7126 m = m_pullup(m, sizeof(struct sadb_msg));
7130 msg = mtod(m, struct sadb_msg *);
7131 orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7132 target = KEY_SENDUP_ONE;
7134 if ((m->m_flags & M_PKTHDR) == 0 ||
7135 m->m_pkthdr.len != m->m_pkthdr.len) {
7136 ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7137 PFKEYSTAT_INC(out_invlen);
7142 if (msg->sadb_msg_version != PF_KEY_V2) {
7143 ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7144 __func__, msg->sadb_msg_version));
7145 PFKEYSTAT_INC(out_invver);
7150 if (msg->sadb_msg_type > SADB_MAX) {
7151 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7152 __func__, msg->sadb_msg_type));
7153 PFKEYSTAT_INC(out_invmsgtype);
7158 /* for old-fashioned code - should be nuked */
7159 if (m->m_pkthdr.len > MCLBYTES) {
7166 MGETHDR(n, M_NOWAIT, MT_DATA);
7167 if (n && m->m_pkthdr.len > MHLEN) {
7168 if (!(MCLGET(n, M_NOWAIT))) {
7177 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7178 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7184 /* align the mbuf chain so that extensions are in contiguous region. */
7185 error = key_align(m, &mh);
7192 switch (msg->sadb_msg_satype) {
7193 case SADB_SATYPE_UNSPEC:
7194 switch (msg->sadb_msg_type) {
7202 ipseclog((LOG_DEBUG, "%s: must specify satype "
7203 "when msg type=%u.\n", __func__,
7204 msg->sadb_msg_type));
7205 PFKEYSTAT_INC(out_invsatype);
7210 case SADB_SATYPE_AH:
7211 case SADB_SATYPE_ESP:
7212 case SADB_X_SATYPE_IPCOMP:
7213 case SADB_X_SATYPE_TCPSIGNATURE:
7214 switch (msg->sadb_msg_type) {
7216 case SADB_X_SPDDELETE:
7218 case SADB_X_SPDDUMP:
7219 case SADB_X_SPDFLUSH:
7220 case SADB_X_SPDSETIDX:
7221 case SADB_X_SPDUPDATE:
7222 case SADB_X_SPDDELETE2:
7223 ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7224 __func__, msg->sadb_msg_type));
7225 PFKEYSTAT_INC(out_invsatype);
7230 case SADB_SATYPE_RSVP:
7231 case SADB_SATYPE_OSPFV2:
7232 case SADB_SATYPE_RIPV2:
7233 case SADB_SATYPE_MIP:
7234 ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7235 __func__, msg->sadb_msg_satype));
7236 PFKEYSTAT_INC(out_invsatype);
7239 case 1: /* XXX: What does it do? */
7240 if (msg->sadb_msg_type == SADB_X_PROMISC)
7244 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7245 __func__, msg->sadb_msg_satype));
7246 PFKEYSTAT_INC(out_invsatype);
7251 /* check field of upper layer protocol and address family */
7252 if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7253 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7254 struct sadb_address *src0, *dst0;
7257 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7258 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7260 /* check upper layer protocol */
7261 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7262 ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7263 "mismatched.\n", __func__));
7264 PFKEYSTAT_INC(out_invaddr);
7270 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7271 PFKEY_ADDR_SADDR(dst0)->sa_family) {
7272 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7274 PFKEYSTAT_INC(out_invaddr);
7278 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7279 PFKEY_ADDR_SADDR(dst0)->sa_len) {
7280 ipseclog((LOG_DEBUG, "%s: address struct size "
7281 "mismatched.\n", __func__));
7282 PFKEYSTAT_INC(out_invaddr);
7287 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7289 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7290 sizeof(struct sockaddr_in)) {
7291 PFKEYSTAT_INC(out_invaddr);
7297 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7298 sizeof(struct sockaddr_in6)) {
7299 PFKEYSTAT_INC(out_invaddr);
7305 ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7307 PFKEYSTAT_INC(out_invaddr);
7308 error = EAFNOSUPPORT;
7312 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7314 plen = sizeof(struct in_addr) << 3;
7317 plen = sizeof(struct in6_addr) << 3;
7320 plen = 0; /*fool gcc*/
7324 /* check max prefix length */
7325 if (src0->sadb_address_prefixlen > plen ||
7326 dst0->sadb_address_prefixlen > plen) {
7327 ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7329 PFKEYSTAT_INC(out_invaddr);
7335 * prefixlen == 0 is valid because there can be a case when
7336 * all addresses are matched.
7340 if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7341 key_typesw[msg->sadb_msg_type] == NULL) {
7342 PFKEYSTAT_INC(out_invmsgtype);
7347 return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7350 msg->sadb_msg_errno = error;
7351 return key_sendup_mbuf(so, m, target);
7355 key_senderror(struct socket *so, struct mbuf *m, int code)
7357 struct sadb_msg *msg;
7359 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7360 ("mbuf too small, len %u", m->m_len));
7362 msg = mtod(m, struct sadb_msg *);
7363 msg->sadb_msg_errno = code;
7364 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7368 * set the pointer to each header into message buffer.
7369 * m will be freed on error.
7370 * XXX larger-than-MCLBYTES extension?
7373 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
7376 struct sadb_ext *ext;
7381 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7382 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7383 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7384 ("mbuf too small, len %u", m->m_len));
7387 bzero(mhp, sizeof(*mhp));
7389 mhp->msg = mtod(m, struct sadb_msg *);
7390 mhp->ext[0] = (struct sadb_ext *)mhp->msg; /*XXX backward compat */
7392 end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7393 extlen = end; /*just in case extlen is not updated*/
7394 for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7395 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7397 /* m is already freed */
7400 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7403 switch (ext->sadb_ext_type) {
7405 case SADB_EXT_ADDRESS_SRC:
7406 case SADB_EXT_ADDRESS_DST:
7407 case SADB_EXT_ADDRESS_PROXY:
7408 case SADB_EXT_LIFETIME_CURRENT:
7409 case SADB_EXT_LIFETIME_HARD:
7410 case SADB_EXT_LIFETIME_SOFT:
7411 case SADB_EXT_KEY_AUTH:
7412 case SADB_EXT_KEY_ENCRYPT:
7413 case SADB_EXT_IDENTITY_SRC:
7414 case SADB_EXT_IDENTITY_DST:
7415 case SADB_EXT_SENSITIVITY:
7416 case SADB_EXT_PROPOSAL:
7417 case SADB_EXT_SUPPORTED_AUTH:
7418 case SADB_EXT_SUPPORTED_ENCRYPT:
7419 case SADB_EXT_SPIRANGE:
7420 case SADB_X_EXT_POLICY:
7421 case SADB_X_EXT_SA2:
7423 case SADB_X_EXT_NAT_T_TYPE:
7424 case SADB_X_EXT_NAT_T_SPORT:
7425 case SADB_X_EXT_NAT_T_DPORT:
7426 case SADB_X_EXT_NAT_T_OAI:
7427 case SADB_X_EXT_NAT_T_OAR:
7428 case SADB_X_EXT_NAT_T_FRAG:
7430 /* duplicate check */
7432 * XXX Are there duplication payloads of either
7433 * KEY_AUTH or KEY_ENCRYPT ?
7435 if (mhp->ext[ext->sadb_ext_type] != NULL) {
7436 ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7437 "%u\n", __func__, ext->sadb_ext_type));
7439 PFKEYSTAT_INC(out_dupext);
7444 ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7445 __func__, ext->sadb_ext_type));
7447 PFKEYSTAT_INC(out_invexttype);
7451 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7453 if (key_validate_ext(ext, extlen)) {
7455 PFKEYSTAT_INC(out_invlen);
7459 n = m_pulldown(m, off, extlen, &toff);
7461 /* m is already freed */
7464 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7466 mhp->ext[ext->sadb_ext_type] = ext;
7467 mhp->extoff[ext->sadb_ext_type] = off;
7468 mhp->extlen[ext->sadb_ext_type] = extlen;
7473 PFKEYSTAT_INC(out_invlen);
7481 key_validate_ext(const struct sadb_ext *ext, int len)
7483 const struct sockaddr *sa;
7484 enum { NONE, ADDR } checktype = NONE;
7486 const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7488 if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7491 /* if it does not match minimum/maximum length, bail */
7492 if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7493 ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7495 if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7497 if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7500 /* more checks based on sadb_ext_type XXX need more */
7501 switch (ext->sadb_ext_type) {
7502 case SADB_EXT_ADDRESS_SRC:
7503 case SADB_EXT_ADDRESS_DST:
7504 case SADB_EXT_ADDRESS_PROXY:
7505 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7508 case SADB_EXT_IDENTITY_SRC:
7509 case SADB_EXT_IDENTITY_DST:
7510 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7511 SADB_X_IDENTTYPE_ADDR) {
7512 baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7522 switch (checktype) {
7526 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7527 if (len < baselen + sal)
7529 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7542 for (i = 0; i < IPSEC_DIR_MAX; i++)
7543 TAILQ_INIT(&V_sptree[i]);
7545 LIST_INIT(&V_sahtree);
7547 for (i = 0; i <= SADB_SATYPE_MAX; i++)
7548 LIST_INIT(&V_regtree[i]);
7550 LIST_INIT(&V_acqtree);
7551 LIST_INIT(&V_spacqtree);
7553 if (!IS_DEFAULT_VNET(curvnet))
7557 REGTREE_LOCK_INIT();
7558 SAHTREE_LOCK_INIT();
7562 #ifndef IPSEC_DEBUG2
7563 callout_init(&key_timer, 1);
7564 callout_reset(&key_timer, hz, key_timehandler, NULL);
7565 #endif /*IPSEC_DEBUG2*/
7567 /* initialize key statistics */
7568 keystat.getspi_count = 1;
7570 printf("IPsec: Initialized Security Association Processing.\n");
7577 TAILQ_HEAD(, secpolicy) drainq;
7578 struct secpolicy *sp, *nextsp;
7579 struct secacq *acq, *nextacq;
7580 struct secspacq *spacq, *nextspacq;
7581 struct secashead *sah, *nextsah;
7585 TAILQ_INIT(&drainq);
7587 for (i = 0; i < IPSEC_DIR_MAX; i++) {
7588 TAILQ_CONCAT(&drainq, &V_sptree[i], chain);
7591 sp = TAILQ_FIRST(&drainq);
7592 while (sp != NULL) {
7593 nextsp = TAILQ_NEXT(sp, chain);
7599 for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
7600 nextsah = LIST_NEXT(sah, chain);
7601 if (__LIST_CHAINED(sah)) {
7602 LIST_REMOVE(sah, chain);
7603 free(sah, M_IPSEC_SAH);
7609 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7610 LIST_FOREACH(reg, &V_regtree[i], chain) {
7611 if (__LIST_CHAINED(reg)) {
7612 LIST_REMOVE(reg, chain);
7613 free(reg, M_IPSEC_SAR);
7621 for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
7622 nextacq = LIST_NEXT(acq, chain);
7623 if (__LIST_CHAINED(acq)) {
7624 LIST_REMOVE(acq, chain);
7625 free(acq, M_IPSEC_SAQ);
7631 for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
7632 spacq = nextspacq) {
7633 nextspacq = LIST_NEXT(spacq, chain);
7634 if (__LIST_CHAINED(spacq)) {
7635 LIST_REMOVE(spacq, chain);
7636 free(spacq, M_IPSEC_SAQ);
7644 * XXX: maybe This function is called after INBOUND IPsec processing.
7646 * Special check for tunnel-mode packets.
7647 * We must make some checks for consistency between inner and outer IP header.
7649 * xxx more checks to be provided
7652 key_checktunnelsanity(struct secasvar *sav, u_int family, caddr_t src,
7655 IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7657 /* XXX: check inner IP header */
7662 /* record data transfer on SA, and update timestamps */
7664 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
7666 IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7667 IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7672 * XXX Currently, there is a difference of bytes size
7673 * between inbound and outbound processing.
7675 sav->lft_c->bytes += m->m_pkthdr.len;
7676 /* to check bytes lifetime is done in key_timehandler(). */
7679 * We use the number of packets as the unit of
7680 * allocations. We increment the variable
7681 * whenever {esp,ah}_{in,out}put is called.
7683 sav->lft_c->allocations++;
7684 /* XXX check for expires? */
7687 * NOTE: We record CURRENT usetime by using wall clock,
7688 * in seconds. HARD and SOFT lifetime are measured by the time
7689 * difference (again in seconds) from usetime.
7693 * -----+-----+--------+---> t
7694 * <--------------> HARD
7697 sav->lft_c->usetime = time_second;
7698 /* XXX check for expires? */
7704 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7706 IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7707 SAHTREE_LOCK_ASSERT();
7709 if (sav->state != state) {
7710 if (__LIST_CHAINED(sav))
7711 LIST_REMOVE(sav, chain);
7713 LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7718 * Take one of the kernel's security keys and convert it into a PF_KEY
7719 * structure within an mbuf, suitable for sending up to a waiting
7720 * application in user land.
7723 * src: A pointer to a kernel security key.
7724 * exttype: Which type of key this is. Refer to the PF_KEY data structures.
7726 * a valid mbuf or NULL indicating an error
7730 static struct mbuf *
7731 key_setkey(struct seckey *src, u_int16_t exttype)
7740 len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
7741 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
7746 p = mtod(m, struct sadb_key *);
7748 p->sadb_key_len = PFKEY_UNIT64(len);
7749 p->sadb_key_exttype = exttype;
7750 p->sadb_key_bits = src->bits;
7751 bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
7757 * Take one of the kernel's lifetime data structures and convert it
7758 * into a PF_KEY structure within an mbuf, suitable for sending up to
7759 * a waiting application in user land.
7762 * src: A pointer to a kernel lifetime structure.
7763 * exttype: Which type of lifetime this is. Refer to the PF_KEY
7764 * data structures for more information.
7766 * a valid mbuf or NULL indicating an error
7770 static struct mbuf *
7771 key_setlifetime(struct seclifetime *src, u_int16_t exttype)
7773 struct mbuf *m = NULL;
7774 struct sadb_lifetime *p;
7775 int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
7780 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
7785 p = mtod(m, struct sadb_lifetime *);
7788 p->sadb_lifetime_len = PFKEY_UNIT64(len);
7789 p->sadb_lifetime_exttype = exttype;
7790 p->sadb_lifetime_allocations = src->allocations;
7791 p->sadb_lifetime_bytes = src->bytes;
7792 p->sadb_lifetime_addtime = src->addtime;
7793 p->sadb_lifetime_usetime = src->usetime;