2 /* $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $ */
5 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the project nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * This code is referd to RFC 2367
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
41 #include <sys/types.h>
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
46 #include <sys/mutex.h>
48 #include <sys/domain.h>
49 #include <sys/protosw.h>
50 #include <sys/malloc.h>
51 #include <sys/rmlock.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/sysctl.h>
55 #include <sys/errno.h>
57 #include <sys/queue.h>
58 #include <sys/refcount.h>
59 #include <sys/syslog.h>
62 #include <net/if_var.h>
64 #include <net/raw_cb.h>
66 #include <netinet/in.h>
67 #include <netinet/in_systm.h>
68 #include <netinet/ip.h>
69 #include <netinet/in_var.h>
72 #include <netinet/ip6.h>
73 #include <netinet6/in6_var.h>
74 #include <netinet6/ip6_var.h>
77 #if defined(INET) || defined(INET6)
78 #include <netinet/in_pcb.h>
81 #include <netinet6/in6_pcb.h>
84 #include <net/pfkeyv2.h>
85 #include <netipsec/keydb.h>
86 #include <netipsec/key.h>
87 #include <netipsec/keysock.h>
88 #include <netipsec/key_debug.h>
90 #include <netipsec/ipsec.h>
92 #include <netipsec/ipsec6.h>
95 #include <netipsec/xform.h>
97 #include <machine/stdarg.h>
100 #include <sys/random.h>
102 #define FULLMASK 0xff
103 #define _BITS(bytes) ((bytes) << 3)
106 * Note on SA reference counting:
107 * - SAs that are not in DEAD state will have (total external reference + 1)
108 * following value in reference count field. they cannot be freed and are
109 * referenced from SA header.
110 * - SAs that are in DEAD state will have (total external reference)
111 * in reference count field. they are ready to be freed. reference from
112 * SA header will be removed in key_delsav(), when the reference count
113 * field hits 0 (= no external reference other than from SA header.
116 VNET_DEFINE(u_int32_t, key_debug_level) = 0;
117 static VNET_DEFINE(u_int, key_spi_trycnt) = 1000;
118 static VNET_DEFINE(u_int32_t, key_spi_minval) = 0x100;
119 static VNET_DEFINE(u_int32_t, key_spi_maxval) = 0x0fffffff; /* XXX */
120 static VNET_DEFINE(u_int32_t, policy_id) = 0;
121 /*interval to initialize randseed,1(m)*/
122 static VNET_DEFINE(u_int, key_int_random) = 60;
123 /* interval to expire acquiring, 30(s)*/
124 static VNET_DEFINE(u_int, key_larval_lifetime) = 30;
125 /* counter for blocking SADB_ACQUIRE.*/
126 static VNET_DEFINE(int, key_blockacq_count) = 10;
127 /* lifetime for blocking SADB_ACQUIRE.*/
128 static VNET_DEFINE(int, key_blockacq_lifetime) = 20;
129 /* preferred old sa rather than new sa.*/
130 static VNET_DEFINE(int, key_preferred_oldsa) = 1;
131 #define V_key_spi_trycnt VNET(key_spi_trycnt)
132 #define V_key_spi_minval VNET(key_spi_minval)
133 #define V_key_spi_maxval VNET(key_spi_maxval)
134 #define V_policy_id VNET(policy_id)
135 #define V_key_int_random VNET(key_int_random)
136 #define V_key_larval_lifetime VNET(key_larval_lifetime)
137 #define V_key_blockacq_count VNET(key_blockacq_count)
138 #define V_key_blockacq_lifetime VNET(key_blockacq_lifetime)
139 #define V_key_preferred_oldsa VNET(key_preferred_oldsa)
141 static VNET_DEFINE(u_int32_t, acq_seq) = 0;
142 #define V_acq_seq VNET(acq_seq)
145 static VNET_DEFINE(TAILQ_HEAD(_sptree, secpolicy), sptree[IPSEC_DIR_MAX]);
146 static struct rmlock sptree_lock;
147 #define V_sptree VNET(sptree)
148 #define SPTREE_LOCK_INIT() rm_init(&sptree_lock, "sptree")
149 #define SPTREE_LOCK_DESTROY() rm_destroy(&sptree_lock)
150 #define SPTREE_RLOCK_TRACKER struct rm_priotracker sptree_tracker
151 #define SPTREE_RLOCK() rm_rlock(&sptree_lock, &sptree_tracker)
152 #define SPTREE_RUNLOCK() rm_runlock(&sptree_lock, &sptree_tracker)
153 #define SPTREE_RLOCK_ASSERT() rm_assert(&sptree_lock, RA_RLOCKED)
154 #define SPTREE_WLOCK() rm_wlock(&sptree_lock)
155 #define SPTREE_WUNLOCK() rm_wunlock(&sptree_lock)
156 #define SPTREE_WLOCK_ASSERT() rm_assert(&sptree_lock, RA_WLOCKED)
157 #define SPTREE_UNLOCK_ASSERT() rm_assert(&sptree_lock, RA_UNLOCKED)
159 static VNET_DEFINE(LIST_HEAD(_sahtree, secashead), sahtree); /* SAD */
160 #define V_sahtree VNET(sahtree)
161 static struct mtx sahtree_lock;
162 #define SAHTREE_LOCK_INIT() \
163 mtx_init(&sahtree_lock, "sahtree", \
164 "fast ipsec security association database", MTX_DEF)
165 #define SAHTREE_LOCK_DESTROY() mtx_destroy(&sahtree_lock)
166 #define SAHTREE_LOCK() mtx_lock(&sahtree_lock)
167 #define SAHTREE_UNLOCK() mtx_unlock(&sahtree_lock)
168 #define SAHTREE_LOCK_ASSERT() mtx_assert(&sahtree_lock, MA_OWNED)
171 static VNET_DEFINE(LIST_HEAD(_regtree, secreg), regtree[SADB_SATYPE_MAX + 1]);
172 #define V_regtree VNET(regtree)
173 static struct mtx regtree_lock;
174 #define REGTREE_LOCK_INIT() \
175 mtx_init(®tree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
176 #define REGTREE_LOCK_DESTROY() mtx_destroy(®tree_lock)
177 #define REGTREE_LOCK() mtx_lock(®tree_lock)
178 #define REGTREE_UNLOCK() mtx_unlock(®tree_lock)
179 #define REGTREE_LOCK_ASSERT() mtx_assert(®tree_lock, MA_OWNED)
181 static VNET_DEFINE(LIST_HEAD(_acqtree, secacq), acqtree); /* acquiring list */
182 #define V_acqtree VNET(acqtree)
183 static struct mtx acq_lock;
184 #define ACQ_LOCK_INIT() \
185 mtx_init(&acq_lock, "acqtree", "fast ipsec acquire list", MTX_DEF)
186 #define ACQ_LOCK_DESTROY() mtx_destroy(&acq_lock)
187 #define ACQ_LOCK() mtx_lock(&acq_lock)
188 #define ACQ_UNLOCK() mtx_unlock(&acq_lock)
189 #define ACQ_LOCK_ASSERT() mtx_assert(&acq_lock, MA_OWNED)
191 /* SP acquiring list */
192 static VNET_DEFINE(LIST_HEAD(_spacqtree, secspacq), spacqtree);
193 #define V_spacqtree VNET(spacqtree)
194 static struct mtx spacq_lock;
195 #define SPACQ_LOCK_INIT() \
196 mtx_init(&spacq_lock, "spacqtree", \
197 "fast ipsec security policy acquire list", MTX_DEF)
198 #define SPACQ_LOCK_DESTROY() mtx_destroy(&spacq_lock)
199 #define SPACQ_LOCK() mtx_lock(&spacq_lock)
200 #define SPACQ_UNLOCK() mtx_unlock(&spacq_lock)
201 #define SPACQ_LOCK_ASSERT() mtx_assert(&spacq_lock, MA_OWNED)
203 /* search order for SAs */
204 static const u_int saorder_state_valid_prefer_old[] = {
205 SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
207 static const u_int saorder_state_valid_prefer_new[] = {
208 SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
210 static const u_int saorder_state_alive[] = {
212 SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
214 static const u_int saorder_state_any[] = {
215 SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
216 SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
219 static const int minsize[] = {
220 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
221 sizeof(struct sadb_sa), /* SADB_EXT_SA */
222 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
223 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
224 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
225 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_SRC */
226 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_DST */
227 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_PROXY */
228 sizeof(struct sadb_key), /* SADB_EXT_KEY_AUTH */
229 sizeof(struct sadb_key), /* SADB_EXT_KEY_ENCRYPT */
230 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_SRC */
231 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_DST */
232 sizeof(struct sadb_sens), /* SADB_EXT_SENSITIVITY */
233 sizeof(struct sadb_prop), /* SADB_EXT_PROPOSAL */
234 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_AUTH */
235 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_ENCRYPT */
236 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
237 0, /* SADB_X_EXT_KMPRIVATE */
238 sizeof(struct sadb_x_policy), /* SADB_X_EXT_POLICY */
239 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
240 sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
241 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
242 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
243 sizeof(struct sadb_address), /* SADB_X_EXT_NAT_T_OAI */
244 sizeof(struct sadb_address), /* SADB_X_EXT_NAT_T_OAR */
245 sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
247 static const int maxsize[] = {
248 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
249 sizeof(struct sadb_sa), /* SADB_EXT_SA */
250 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
251 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
252 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
253 0, /* SADB_EXT_ADDRESS_SRC */
254 0, /* SADB_EXT_ADDRESS_DST */
255 0, /* SADB_EXT_ADDRESS_PROXY */
256 0, /* SADB_EXT_KEY_AUTH */
257 0, /* SADB_EXT_KEY_ENCRYPT */
258 0, /* SADB_EXT_IDENTITY_SRC */
259 0, /* SADB_EXT_IDENTITY_DST */
260 0, /* SADB_EXT_SENSITIVITY */
261 0, /* SADB_EXT_PROPOSAL */
262 0, /* SADB_EXT_SUPPORTED_AUTH */
263 0, /* SADB_EXT_SUPPORTED_ENCRYPT */
264 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
265 0, /* SADB_X_EXT_KMPRIVATE */
266 0, /* SADB_X_EXT_POLICY */
267 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
268 sizeof(struct sadb_x_nat_t_type),/* SADB_X_EXT_NAT_T_TYPE */
269 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_SPORT */
270 sizeof(struct sadb_x_nat_t_port),/* SADB_X_EXT_NAT_T_DPORT */
271 0, /* SADB_X_EXT_NAT_T_OAI */
272 0, /* SADB_X_EXT_NAT_T_OAR */
273 sizeof(struct sadb_x_nat_t_frag),/* SADB_X_EXT_NAT_T_FRAG */
276 static VNET_DEFINE(int, ipsec_esp_keymin) = 256;
277 static VNET_DEFINE(int, ipsec_esp_auth) = 0;
278 static VNET_DEFINE(int, ipsec_ah_keymin) = 128;
280 #define V_ipsec_esp_keymin VNET(ipsec_esp_keymin)
281 #define V_ipsec_esp_auth VNET(ipsec_esp_auth)
282 #define V_ipsec_ah_keymin VNET(ipsec_ah_keymin)
285 SYSCTL_DECL(_net_key);
288 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL, debug,
289 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_debug_level), 0, "");
291 /* max count of trial for the decision of spi value */
292 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt,
293 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_trycnt), 0, "");
295 /* minimum spi value to allocate automatically. */
296 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE, spi_minval,
297 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_minval), 0, "");
299 /* maximun spi value to allocate automatically. */
300 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE, spi_maxval,
301 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_spi_maxval), 0, "");
303 /* interval to initialize randseed */
304 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random,
305 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_int_random), 0, "");
307 /* lifetime for larval SA */
308 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME, larval_lifetime,
309 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_larval_lifetime), 0, "");
311 /* counter for blocking to send SADB_ACQUIRE to IKEd */
312 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT, blockacq_count,
313 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_blockacq_count), 0, "");
315 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
316 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME, blockacq_lifetime,
317 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_blockacq_lifetime), 0, "");
320 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH, esp_auth,
321 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_esp_auth), 0, "");
323 /* minimum ESP key length */
324 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin,
325 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_esp_keymin), 0, "");
327 /* minimum AH key length */
328 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN, ah_keymin,
329 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_ah_keymin), 0, "");
331 /* perfered old SA rather than new SA */
332 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA, preferred_oldsa,
333 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(key_preferred_oldsa), 0, "");
335 #define __LIST_CHAINED(elm) \
336 (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
337 #define LIST_INSERT_TAIL(head, elm, type, field) \
339 struct type *curelm = LIST_FIRST(head); \
340 if (curelm == NULL) {\
341 LIST_INSERT_HEAD(head, elm, field); \
343 while (LIST_NEXT(curelm, field)) \
344 curelm = LIST_NEXT(curelm, field);\
345 LIST_INSERT_AFTER(curelm, elm, field);\
349 #define KEY_CHKSASTATE(head, sav, name) \
351 if ((head) != (sav)) { \
352 ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
353 (name), (head), (sav))); \
358 #define KEY_CHKSPDIR(head, sp, name) \
360 if ((head) != (sp)) { \
361 ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
362 "anyway continue.\n", \
363 (name), (head), (sp))); \
367 MALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
368 MALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
369 MALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
370 MALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
371 MALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
372 MALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
373 MALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
376 * set parameters into secpolicyindex buffer.
377 * Must allocate secpolicyindex buffer passed to this function.
379 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
381 bzero((idx), sizeof(struct secpolicyindex)); \
382 (idx)->dir = (_dir); \
383 (idx)->prefs = (ps); \
384 (idx)->prefd = (pd); \
385 (idx)->ul_proto = (ulp); \
386 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
387 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
391 * set parameters into secasindex buffer.
392 * Must allocate secasindex buffer before calling this function.
394 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
396 bzero((idx), sizeof(struct secasindex)); \
397 (idx)->proto = (p); \
399 (idx)->reqid = (r); \
400 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
401 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
406 u_long getspi_count; /* the avarage of count to try to get new SPI */
410 struct sadb_msg *msg;
411 struct sadb_ext *ext[SADB_EXT_MAX + 1];
412 int extoff[SADB_EXT_MAX + 1];
413 int extlen[SADB_EXT_MAX + 1];
417 static struct callout key_timer;
420 static struct secasvar *key_allocsa_policy(const struct secasindex *);
421 static void key_freesp_so(struct secpolicy **);
422 static struct secasvar *key_do_allocsa_policy(struct secashead *, u_int);
423 static void key_unlink(struct secpolicy *);
424 static struct secpolicy *key_getsp(struct secpolicyindex *);
425 static struct secpolicy *key_getspbyid(u_int32_t);
426 static u_int32_t key_newreqid(void);
427 static struct mbuf *key_gather_mbuf(struct mbuf *,
428 const struct sadb_msghdr *, int, int, ...);
429 static int key_spdadd(struct socket *, struct mbuf *,
430 const struct sadb_msghdr *);
431 static u_int32_t key_getnewspid(void);
432 static int key_spddelete(struct socket *, struct mbuf *,
433 const struct sadb_msghdr *);
434 static int key_spddelete2(struct socket *, struct mbuf *,
435 const struct sadb_msghdr *);
436 static int key_spdget(struct socket *, struct mbuf *,
437 const struct sadb_msghdr *);
438 static int key_spdflush(struct socket *, struct mbuf *,
439 const struct sadb_msghdr *);
440 static int key_spddump(struct socket *, struct mbuf *,
441 const struct sadb_msghdr *);
442 static struct mbuf *key_setdumpsp(struct secpolicy *,
443 u_int8_t, u_int32_t, u_int32_t);
444 static u_int key_getspreqmsglen(struct secpolicy *);
445 static int key_spdexpire(struct secpolicy *);
446 static struct secashead *key_newsah(struct secasindex *);
447 static void key_delsah(struct secashead *);
448 static struct secasvar *key_newsav(struct mbuf *,
449 const struct sadb_msghdr *, struct secashead *, int *,
451 #define KEY_NEWSAV(m, sadb, sah, e) \
452 key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
453 static void key_delsav(struct secasvar *);
454 static struct secashead *key_getsah(struct secasindex *);
455 static struct secasvar *key_checkspidup(struct secasindex *, u_int32_t);
456 static struct secasvar *key_getsavbyspi(struct secashead *, u_int32_t);
457 static int key_setsaval(struct secasvar *, struct mbuf *,
458 const struct sadb_msghdr *);
459 static int key_mature(struct secasvar *);
460 static struct mbuf *key_setdumpsa(struct secasvar *, u_int8_t,
461 u_int8_t, u_int32_t, u_int32_t);
462 static struct mbuf *key_setsadbmsg(u_int8_t, u_int16_t, u_int8_t,
463 u_int32_t, pid_t, u_int16_t);
464 static struct mbuf *key_setsadbsa(struct secasvar *);
465 static struct mbuf *key_setsadbaddr(u_int16_t,
466 const struct sockaddr *, u_int8_t, u_int16_t);
468 static struct mbuf *key_setsadbxport(u_int16_t, u_int16_t);
469 static struct mbuf *key_setsadbxtype(u_int16_t);
471 static void key_porttosaddr(struct sockaddr *, u_int16_t);
472 #define KEY_PORTTOSADDR(saddr, port) \
473 key_porttosaddr((struct sockaddr *)(saddr), (port))
474 static struct mbuf *key_setsadbxsa2(u_int8_t, u_int32_t, u_int32_t);
475 static struct mbuf *key_setsadbxpolicy(u_int16_t, u_int8_t,
477 static struct seckey *key_dup_keymsg(const struct sadb_key *, u_int,
478 struct malloc_type *);
479 static struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
480 struct malloc_type *type);
482 static int key_ismyaddr6(struct sockaddr_in6 *);
485 /* flags for key_cmpsaidx() */
486 #define CMP_HEAD 1 /* protocol, addresses. */
487 #define CMP_MODE_REQID 2 /* additionally HEAD, reqid, mode. */
488 #define CMP_REQID 3 /* additionally HEAD, reaid. */
489 #define CMP_EXACTLY 4 /* all elements. */
490 static int key_cmpsaidx(const struct secasindex *,
491 const struct secasindex *, int);
492 static int key_cmpspidx_exactly(struct secpolicyindex *,
493 struct secpolicyindex *);
494 static int key_cmpspidx_withmask(struct secpolicyindex *,
495 struct secpolicyindex *);
496 static int key_sockaddrcmp(const struct sockaddr *,
497 const struct sockaddr *, int);
498 static int key_bbcmp(const void *, const void *, u_int);
499 static u_int16_t key_satype2proto(u_int8_t);
500 static u_int8_t key_proto2satype(u_int16_t);
502 static int key_getspi(struct socket *, struct mbuf *,
503 const struct sadb_msghdr *);
504 static u_int32_t key_do_getnewspi(struct sadb_spirange *,
505 struct secasindex *);
506 static int key_update(struct socket *, struct mbuf *,
507 const struct sadb_msghdr *);
508 #ifdef IPSEC_DOSEQCHECK
509 static struct secasvar *key_getsavbyseq(struct secashead *, u_int32_t);
511 static int key_add(struct socket *, struct mbuf *,
512 const struct sadb_msghdr *);
513 static int key_setident(struct secashead *, struct mbuf *,
514 const struct sadb_msghdr *);
515 static struct mbuf *key_getmsgbuf_x1(struct mbuf *,
516 const struct sadb_msghdr *);
517 static int key_delete(struct socket *, struct mbuf *,
518 const struct sadb_msghdr *);
519 static int key_delete_all(struct socket *, struct mbuf *,
520 const struct sadb_msghdr *, u_int16_t);
521 static int key_get(struct socket *, struct mbuf *,
522 const struct sadb_msghdr *);
524 static void key_getcomb_setlifetime(struct sadb_comb *);
525 static struct mbuf *key_getcomb_esp(void);
526 static struct mbuf *key_getcomb_ah(void);
527 static struct mbuf *key_getcomb_ipcomp(void);
528 static struct mbuf *key_getprop(const struct secasindex *);
530 static int key_acquire(const struct secasindex *, struct secpolicy *);
531 static struct secacq *key_newacq(const struct secasindex *);
532 static struct secacq *key_getacq(const struct secasindex *);
533 static struct secacq *key_getacqbyseq(u_int32_t);
534 static struct secspacq *key_newspacq(struct secpolicyindex *);
535 static struct secspacq *key_getspacq(struct secpolicyindex *);
536 static int key_acquire2(struct socket *, struct mbuf *,
537 const struct sadb_msghdr *);
538 static int key_register(struct socket *, struct mbuf *,
539 const struct sadb_msghdr *);
540 static int key_expire(struct secasvar *);
541 static int key_flush(struct socket *, struct mbuf *,
542 const struct sadb_msghdr *);
543 static int key_dump(struct socket *, struct mbuf *,
544 const struct sadb_msghdr *);
545 static int key_promisc(struct socket *, struct mbuf *,
546 const struct sadb_msghdr *);
547 static int key_senderror(struct socket *, struct mbuf *, int);
548 static int key_validate_ext(const struct sadb_ext *, int);
549 static int key_align(struct mbuf *, struct sadb_msghdr *);
550 static struct mbuf *key_setlifetime(struct seclifetime *src,
552 static struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
555 static const char *key_getfqdn(void);
556 static const char *key_getuserfqdn(void);
558 static void key_sa_chgstate(struct secasvar *, u_int8_t);
561 sa_initref(struct secasvar *sav)
564 refcount_init(&sav->refcnt, 1);
567 sa_addref(struct secasvar *sav)
570 refcount_acquire(&sav->refcnt);
571 IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
574 sa_delref(struct secasvar *sav)
577 IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
578 return (refcount_release(&sav->refcnt));
581 #define SP_ADDREF(p) refcount_acquire(&(p)->refcnt)
582 #define SP_DELREF(p) refcount_release(&(p)->refcnt)
585 * Update the refcnt while holding the SPTREE lock.
588 key_addref(struct secpolicy *sp)
595 * Return 0 when there are known to be no SP's for the specified
596 * direction. Otherwise return 1. This is used by IPsec code
597 * to optimize performance.
600 key_havesp(u_int dir)
603 return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
604 TAILQ_FIRST(&V_sptree[dir]) != NULL : 1);
607 /* %%% IPsec policy management */
609 * allocating a SP for OUTBOUND or INBOUND packet.
610 * Must call key_freesp() later.
611 * OUT: NULL: not found
612 * others: found and return the pointer.
615 key_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where,
618 SPTREE_RLOCK_TRACKER;
619 struct secpolicy *sp;
621 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
622 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
623 ("invalid direction %u", dir));
625 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
626 printf("DP %s from %s:%u\n", __func__, where, tag));
629 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
630 printf("*** objects\n");
631 kdebug_secpolicyindex(spidx));
634 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
635 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
636 printf("*** in SPD\n");
637 kdebug_secpolicyindex(&sp->spidx));
638 if (key_cmpspidx_withmask(&sp->spidx, spidx))
645 KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
647 /* found a SPD entry */
648 sp->lastused = time_second;
653 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
654 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
655 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
660 * allocating a SP for OUTBOUND or INBOUND packet.
661 * Must call key_freesp() later.
662 * OUT: NULL: not found
663 * others: found and return the pointer.
666 key_allocsp2(u_int32_t spi, union sockaddr_union *dst, u_int8_t proto,
667 u_int dir, const char* where, int tag)
669 SPTREE_RLOCK_TRACKER;
670 struct secpolicy *sp;
672 IPSEC_ASSERT(dst != NULL, ("null dst"));
673 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
674 ("invalid direction %u", dir));
676 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
677 printf("DP %s from %s:%u\n", __func__, where, tag));
680 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
681 printf("*** objects\n");
682 printf("spi %u proto %u dir %u\n", spi, proto, dir);
683 kdebug_sockaddr(&dst->sa));
686 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
687 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
688 printf("*** in SPD\n");
689 kdebug_secpolicyindex(&sp->spidx));
690 /* compare simple values, then dst address */
691 if (sp->spidx.ul_proto != proto)
693 /* NB: spi's must exist and match */
694 if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
696 if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
703 KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
705 /* found a SPD entry */
706 sp->lastused = time_second;
711 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
712 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
713 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
719 * return a policy that matches this particular inbound packet.
723 key_gettunnel(const struct sockaddr *osrc,
724 const struct sockaddr *odst,
725 const struct sockaddr *isrc,
726 const struct sockaddr *idst,
727 const char* where, int tag)
729 struct secpolicy *sp;
730 const int dir = IPSEC_DIR_INBOUND;
731 struct ipsecrequest *r1, *r2, *p;
732 struct secpolicyindex spidx;
734 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
735 printf("DP %s from %s:%u\n", __func__, where, tag));
737 if (isrc->sa_family != idst->sa_family) {
738 ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
739 __func__, isrc->sa_family, idst->sa_family));
745 LIST_FOREACH(sp, &V_sptree[dir], chain) {
746 if (sp->state == IPSEC_SPSTATE_DEAD)
750 for (p = sp->req; p; p = p->next) {
751 if (p->saidx.mode != IPSEC_MODE_TUNNEL)
758 /* here we look at address matches only */
760 if (isrc->sa_len > sizeof(spidx.src) ||
761 idst->sa_len > sizeof(spidx.dst))
763 bcopy(isrc, &spidx.src, isrc->sa_len);
764 bcopy(idst, &spidx.dst, idst->sa_len);
765 if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
768 if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
769 key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
773 if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
774 key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
783 sp->lastused = time_second;
788 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
789 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
790 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
796 * allocating an SA entry for an *OUTBOUND* packet.
797 * checking each request entries in SP, and acquire an SA if need.
798 * OUT: 0: there are valid requests.
799 * ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
802 key_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
806 struct secasvar *sav;
808 IPSEC_ASSERT(isr != NULL, ("null isr"));
809 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
810 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
811 saidx->mode == IPSEC_MODE_TUNNEL,
812 ("unexpected policy %u", saidx->mode));
815 * XXX guard against protocol callbacks from the crypto
816 * thread as they reference ipsecrequest.sav which we
817 * temporarily null out below. Need to rethink how we
818 * handle bundled SA's in the callback thread.
820 IPSECREQUEST_LOCK_ASSERT(isr);
822 /* get current level */
823 level = ipsec_get_reqlevel(isr);
826 * We check new SA in the IPsec request because a different
827 * SA may be involved each time this request is checked, either
828 * because new SAs are being configured, or this request is
829 * associated with an unconnected datagram socket, or this request
830 * is associated with a system default policy.
832 * key_allocsa_policy should allocate the oldest SA available.
833 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
835 sav = key_allocsa_policy(saidx);
836 if (sav != isr->sav) {
837 /* SA need to be updated. */
838 if (!IPSECREQUEST_UPGRADE(isr)) {
839 /* Kick everyone off. */
840 IPSECREQUEST_UNLOCK(isr);
841 IPSECREQUEST_WLOCK(isr);
843 if (isr->sav != NULL)
844 KEY_FREESAV(&isr->sav);
846 IPSECREQUEST_DOWNGRADE(isr);
847 } else if (sav != NULL)
850 /* When there is SA. */
851 if (isr->sav != NULL) {
852 if (isr->sav->state != SADB_SASTATE_MATURE &&
853 isr->sav->state != SADB_SASTATE_DYING)
859 error = key_acquire(saidx, isr->sp);
861 /* XXX What should I do ? */
862 ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
867 if (level != IPSEC_LEVEL_REQUIRE) {
868 /* XXX sigh, the interface to this routine is botched */
869 IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
877 * allocating a SA for policy entry from SAD.
878 * NOTE: searching SAD of aliving state.
879 * OUT: NULL: not found.
880 * others: found and return the pointer.
882 static struct secasvar *
883 key_allocsa_policy(const struct secasindex *saidx)
885 #define N(a) _ARRAYLEN(a)
886 struct secashead *sah;
887 struct secasvar *sav;
888 u_int stateidx, arraysize;
889 const u_int *state_valid;
891 state_valid = NULL; /* silence gcc */
892 arraysize = 0; /* silence gcc */
895 LIST_FOREACH(sah, &V_sahtree, chain) {
896 if (sah->state == SADB_SASTATE_DEAD)
898 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
899 if (V_key_preferred_oldsa) {
900 state_valid = saorder_state_valid_prefer_old;
901 arraysize = N(saorder_state_valid_prefer_old);
903 state_valid = saorder_state_valid_prefer_new;
904 arraysize = N(saorder_state_valid_prefer_new);
913 /* search valid state */
914 for (stateidx = 0; stateidx < arraysize; stateidx++) {
915 sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
925 * searching SAD with direction, protocol, mode and state.
926 * called by key_allocsa_policy().
929 * others : found, pointer to a SA.
931 static struct secasvar *
932 key_do_allocsa_policy(struct secashead *sah, u_int state)
934 struct secasvar *sav, *nextsav, *candidate, *d;
940 for (sav = LIST_FIRST(&sah->savtree[state]);
944 nextsav = LIST_NEXT(sav, chain);
947 KEY_CHKSASTATE(sav->state, state, __func__);
950 if (candidate == NULL) {
955 /* Which SA is the better ? */
957 IPSEC_ASSERT(candidate->lft_c != NULL,
958 ("null candidate lifetime"));
959 IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
961 /* What the best method is to compare ? */
962 if (V_key_preferred_oldsa) {
963 if (candidate->lft_c->addtime >
964 sav->lft_c->addtime) {
971 /* preferred new sa rather than old sa */
972 if (candidate->lft_c->addtime <
973 sav->lft_c->addtime) {
980 * prepared to delete the SA when there is more
981 * suitable candidate and the lifetime of the SA is not
984 if (d->lft_h->addtime != 0) {
985 struct mbuf *m, *result;
988 key_sa_chgstate(d, SADB_SASTATE_DEAD);
990 IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
992 satype = key_proto2satype(d->sah->saidx.proto);
996 m = key_setsadbmsg(SADB_DELETE, 0,
997 satype, 0, 0, d->refcnt - 1);
1002 /* set sadb_address for saidx's. */
1003 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
1004 &d->sah->saidx.src.sa,
1005 d->sah->saidx.src.sa.sa_len << 3,
1011 /* set sadb_address for saidx's. */
1012 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
1013 &d->sah->saidx.dst.sa,
1014 d->sah->saidx.dst.sa.sa_len << 3,
1020 /* create SA extension */
1021 m = key_setsadbsa(d);
1026 if (result->m_len < sizeof(struct sadb_msg)) {
1027 result = m_pullup(result,
1028 sizeof(struct sadb_msg));
1033 result->m_pkthdr.len = 0;
1034 for (m = result; m; m = m->m_next)
1035 result->m_pkthdr.len += m->m_len;
1036 mtod(result, struct sadb_msg *)->sadb_msg_len =
1037 PFKEY_UNIT64(result->m_pkthdr.len);
1039 if (key_sendup_mbuf(NULL, result,
1040 KEY_SENDUP_REGISTERED))
1047 sa_addref(candidate);
1048 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1049 printf("DP %s cause refcnt++:%d SA:%p\n",
1050 __func__, candidate->refcnt, candidate));
1058 * allocating a usable SA entry for a *INBOUND* packet.
1059 * Must call key_freesav() later.
1060 * OUT: positive: pointer to a usable sav (i.e. MATURE or DYING state).
1061 * NULL: not found, or error occured.
1063 * In the comparison, no source address is used--for RFC2401 conformance.
1064 * To quote, from section 4.1:
1065 * A security association is uniquely identified by a triple consisting
1066 * of a Security Parameter Index (SPI), an IP Destination Address, and a
1067 * security protocol (AH or ESP) identifier.
1068 * Note that, however, we do need to keep source address in IPsec SA.
1069 * IKE specification and PF_KEY specification do assume that we
1070 * keep source address in IPsec SA. We see a tricky situation here.
1073 key_allocsa(union sockaddr_union *dst, u_int proto, u_int32_t spi,
1074 const char* where, int tag)
1076 struct secashead *sah;
1077 struct secasvar *sav;
1078 u_int stateidx, arraysize, state;
1079 const u_int *saorder_state_valid;
1084 IPSEC_ASSERT(dst != NULL, ("null dst address"));
1086 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1087 printf("DP %s from %s:%u\n", __func__, where, tag));
1090 natt_chkport = (dst->sa.sa_family == AF_INET &&
1091 dst->sa.sa_len == sizeof(struct sockaddr_in) &&
1092 dst->sin.sin_port != 0);
1097 * XXX: to be checked internal IP header somewhere. Also when
1098 * IPsec tunnel packet is received. But ESP tunnel mode is
1099 * encrypted so we can't check internal IP header.
1102 if (V_key_preferred_oldsa) {
1103 saorder_state_valid = saorder_state_valid_prefer_old;
1104 arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1106 saorder_state_valid = saorder_state_valid_prefer_new;
1107 arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1109 LIST_FOREACH(sah, &V_sahtree, chain) {
1112 /* search valid state */
1113 for (stateidx = 0; stateidx < arraysize; stateidx++) {
1114 state = saorder_state_valid[stateidx];
1115 LIST_FOREACH(sav, &sah->savtree[state], chain) {
1117 KEY_CHKSASTATE(sav->state, state, __func__);
1118 /* do not return entries w/ unusable state */
1119 if (sav->state != SADB_SASTATE_MATURE &&
1120 sav->state != SADB_SASTATE_DYING)
1122 if (proto != sav->sah->saidx.proto)
1124 if (spi != sav->spi)
1129 * Really only check ports when this is a NAT-T
1130 * SA. Otherwise other lookups providing ports
1133 if (sav->natt_type && natt_chkport)
1136 #if 0 /* don't check src */
1137 /* check src address */
1138 if (key_sockaddrcmp(&src->sa,
1139 &sav->sah->saidx.src.sa, checkport) != 0)
1142 /* check dst address */
1143 if (key_sockaddrcmp(&dst->sa,
1144 &sav->sah->saidx.dst.sa, checkport) != 0)
1155 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1156 printf("DP %s return SA:%p; refcnt %u\n", __func__,
1157 sav, sav ? sav->refcnt : 0));
1162 * Must be called after calling key_allocsp().
1163 * For both the packet without socket and key_freeso().
1166 _key_freesp(struct secpolicy **spp, const char* where, int tag)
1168 struct ipsecrequest *isr, *nextisr;
1169 struct secpolicy *sp = *spp;
1171 IPSEC_ASSERT(sp != NULL, ("null sp"));
1172 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1173 printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1174 __func__, sp, sp->id, where, tag, sp->refcnt));
1176 if (SP_DELREF(sp) == 0)
1179 for (isr = sp->req; isr != NULL; isr = nextisr) {
1180 if (isr->sav != NULL) {
1181 KEY_FREESAV(&isr->sav);
1184 nextisr = isr->next;
1187 free(sp, M_IPSEC_SP);
1191 key_unlink(struct secpolicy *sp)
1194 IPSEC_ASSERT(sp != NULL, ("null sp"));
1195 IPSEC_ASSERT(sp->spidx.dir == IPSEC_DIR_INBOUND ||
1196 sp->spidx.dir == IPSEC_DIR_OUTBOUND,
1197 ("invalid direction %u", sp->spidx.dir));
1198 SPTREE_UNLOCK_ASSERT();
1201 if (sp->state == IPSEC_SPSTATE_DEAD) {
1205 sp->state = IPSEC_SPSTATE_DEAD;
1206 TAILQ_REMOVE(&V_sptree[sp->spidx.dir], sp, chain);
1212 * Must be called after calling key_allocsp().
1213 * For the packet with socket.
1216 key_freeso(struct socket *so)
1218 IPSEC_ASSERT(so != NULL, ("null so"));
1220 switch (so->so_proto->pr_domain->dom_family) {
1221 #if defined(INET) || defined(INET6)
1229 struct inpcb *pcb = sotoinpcb(so);
1231 /* Does it have a PCB ? */
1234 key_freesp_so(&pcb->inp_sp->sp_in);
1235 key_freesp_so(&pcb->inp_sp->sp_out);
1238 #endif /* INET || INET6 */
1240 ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
1241 __func__, so->so_proto->pr_domain->dom_family));
1247 key_freesp_so(struct secpolicy **sp)
1249 IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
1251 if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1252 (*sp)->policy == IPSEC_POLICY_BYPASS)
1255 IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1256 ("invalid policy %u", (*sp)->policy));
1261 key_addrefsa(struct secasvar *sav, const char* where, int tag)
1264 IPSEC_ASSERT(sav != NULL, ("null sav"));
1265 IPSEC_ASSERT(sav->refcnt > 0, ("refcount must exist"));
1271 * Must be called after calling key_allocsa().
1272 * This function is called by key_freesp() to free some SA allocated
1276 key_freesav(struct secasvar **psav, const char* where, int tag)
1278 struct secasvar *sav = *psav;
1280 IPSEC_ASSERT(sav != NULL, ("null sav"));
1282 if (sa_delref(sav)) {
1283 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1284 printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1285 __func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1289 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1290 printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1291 __func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1295 /* %%% SPD management */
1298 * OUT: NULL : not found
1299 * others : found, pointer to a SP.
1301 static struct secpolicy *
1302 key_getsp(struct secpolicyindex *spidx)
1304 SPTREE_RLOCK_TRACKER;
1305 struct secpolicy *sp;
1307 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1310 TAILQ_FOREACH(sp, &V_sptree[spidx->dir], chain) {
1311 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1323 * OUT: NULL : not found
1324 * others : found, pointer to a SP.
1326 static struct secpolicy *
1327 key_getspbyid(u_int32_t id)
1329 SPTREE_RLOCK_TRACKER;
1330 struct secpolicy *sp;
1333 TAILQ_FOREACH(sp, &V_sptree[IPSEC_DIR_INBOUND], chain) {
1340 TAILQ_FOREACH(sp, &V_sptree[IPSEC_DIR_OUTBOUND], chain) {
1353 key_newsp(const char* where, int tag)
1355 struct secpolicy *newsp = NULL;
1357 newsp = (struct secpolicy *)
1358 malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
1360 refcount_init(&newsp->refcnt, 1);
1362 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1363 printf("DP %s from %s:%u return SP:%p\n", __func__,
1364 where, tag, newsp));
1369 * create secpolicy structure from sadb_x_policy structure.
1370 * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1371 * so must be set properly later.
1374 key_msg2sp(struct sadb_x_policy *xpl0, size_t len, int *error)
1376 struct secpolicy *newsp;
1378 IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1379 IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1381 if (len != PFKEY_EXTLEN(xpl0)) {
1382 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1387 if ((newsp = KEY_NEWSP()) == NULL) {
1392 newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1393 newsp->policy = xpl0->sadb_x_policy_type;
1396 switch (xpl0->sadb_x_policy_type) {
1397 case IPSEC_POLICY_DISCARD:
1398 case IPSEC_POLICY_NONE:
1399 case IPSEC_POLICY_ENTRUST:
1400 case IPSEC_POLICY_BYPASS:
1404 case IPSEC_POLICY_IPSEC:
1407 struct sadb_x_ipsecrequest *xisr;
1408 struct ipsecrequest **p_isr = &newsp->req;
1410 /* validity check */
1411 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1412 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1419 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1420 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1424 if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1425 ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1426 "length.\n", __func__));
1432 /* allocate request buffer */
1433 /* NB: data structure is zero'd */
1434 *p_isr = ipsec_newisr();
1435 if ((*p_isr) == NULL) {
1436 ipseclog((LOG_DEBUG,
1437 "%s: No more memory.\n", __func__));
1444 switch (xisr->sadb_x_ipsecrequest_proto) {
1447 case IPPROTO_IPCOMP:
1450 ipseclog((LOG_DEBUG,
1451 "%s: invalid proto type=%u\n", __func__,
1452 xisr->sadb_x_ipsecrequest_proto));
1454 *error = EPROTONOSUPPORT;
1457 (*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1459 switch (xisr->sadb_x_ipsecrequest_mode) {
1460 case IPSEC_MODE_TRANSPORT:
1461 case IPSEC_MODE_TUNNEL:
1463 case IPSEC_MODE_ANY:
1465 ipseclog((LOG_DEBUG,
1466 "%s: invalid mode=%u\n", __func__,
1467 xisr->sadb_x_ipsecrequest_mode));
1472 (*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1474 switch (xisr->sadb_x_ipsecrequest_level) {
1475 case IPSEC_LEVEL_DEFAULT:
1476 case IPSEC_LEVEL_USE:
1477 case IPSEC_LEVEL_REQUIRE:
1479 case IPSEC_LEVEL_UNIQUE:
1480 /* validity check */
1482 * If range violation of reqid, kernel will
1483 * update it, don't refuse it.
1485 if (xisr->sadb_x_ipsecrequest_reqid
1486 > IPSEC_MANUAL_REQID_MAX) {
1487 ipseclog((LOG_DEBUG,
1488 "%s: reqid=%d range "
1489 "violation, updated by kernel.\n",
1491 xisr->sadb_x_ipsecrequest_reqid));
1492 xisr->sadb_x_ipsecrequest_reqid = 0;
1495 /* allocate new reqid id if reqid is zero. */
1496 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1498 if ((reqid = key_newreqid()) == 0) {
1503 (*p_isr)->saidx.reqid = reqid;
1504 xisr->sadb_x_ipsecrequest_reqid = reqid;
1506 /* set it for manual keying. */
1507 (*p_isr)->saidx.reqid =
1508 xisr->sadb_x_ipsecrequest_reqid;
1513 ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1515 xisr->sadb_x_ipsecrequest_level));
1520 (*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1522 /* set IP addresses if there */
1523 if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1524 struct sockaddr *paddr;
1526 paddr = (struct sockaddr *)(xisr + 1);
1528 /* validity check */
1530 > sizeof((*p_isr)->saidx.src)) {
1531 ipseclog((LOG_DEBUG, "%s: invalid "
1532 "request address length.\n",
1538 bcopy(paddr, &(*p_isr)->saidx.src,
1541 paddr = (struct sockaddr *)((caddr_t)paddr
1544 /* validity check */
1546 > sizeof((*p_isr)->saidx.dst)) {
1547 ipseclog((LOG_DEBUG, "%s: invalid "
1548 "request address length.\n",
1554 bcopy(paddr, &(*p_isr)->saidx.dst,
1558 (*p_isr)->sp = newsp;
1560 /* initialization for the next. */
1561 p_isr = &(*p_isr)->next;
1562 tlen -= xisr->sadb_x_ipsecrequest_len;
1564 /* validity check */
1566 ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1573 xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1574 + xisr->sadb_x_ipsecrequest_len);
1579 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1592 static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1594 auto_reqid = (auto_reqid == ~0
1595 ? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1597 /* XXX should be unique check */
1603 * copy secpolicy struct to sadb_x_policy structure indicated.
1606 key_sp2msg(struct secpolicy *sp)
1608 struct sadb_x_policy *xpl;
1613 IPSEC_ASSERT(sp != NULL, ("null policy"));
1615 tlen = key_getspreqmsglen(sp);
1617 m = m_get2(tlen, M_NOWAIT, MT_DATA, 0);
1622 xpl = mtod(m, struct sadb_x_policy *);
1625 xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1626 xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1627 xpl->sadb_x_policy_type = sp->policy;
1628 xpl->sadb_x_policy_dir = sp->spidx.dir;
1629 xpl->sadb_x_policy_id = sp->id;
1630 p = (caddr_t)xpl + sizeof(*xpl);
1632 /* if is the policy for ipsec ? */
1633 if (sp->policy == IPSEC_POLICY_IPSEC) {
1634 struct sadb_x_ipsecrequest *xisr;
1635 struct ipsecrequest *isr;
1637 for (isr = sp->req; isr != NULL; isr = isr->next) {
1639 xisr = (struct sadb_x_ipsecrequest *)p;
1641 xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1642 xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1643 xisr->sadb_x_ipsecrequest_level = isr->level;
1644 xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1647 bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1648 p += isr->saidx.src.sa.sa_len;
1649 bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1650 p += isr->saidx.src.sa.sa_len;
1652 xisr->sadb_x_ipsecrequest_len =
1653 PFKEY_ALIGN8(sizeof(*xisr)
1654 + isr->saidx.src.sa.sa_len
1655 + isr->saidx.dst.sa.sa_len);
1662 /* m will not be freed nor modified */
1663 static struct mbuf *
1664 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1665 int ndeep, int nitem, ...)
1670 struct mbuf *result = NULL, *n;
1673 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1674 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1676 va_start(ap, nitem);
1677 for (i = 0; i < nitem; i++) {
1678 idx = va_arg(ap, int);
1679 if (idx < 0 || idx > SADB_EXT_MAX)
1681 /* don't attempt to pull empty extension */
1682 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1684 if (idx != SADB_EXT_RESERVED &&
1685 (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1688 if (idx == SADB_EXT_RESERVED) {
1689 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1691 IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1693 MGETHDR(n, M_NOWAIT, MT_DATA);
1698 m_copydata(m, 0, sizeof(struct sadb_msg),
1700 } else if (i < ndeep) {
1701 len = mhp->extlen[idx];
1702 n = m_get2(len, M_NOWAIT, MT_DATA, 0);
1707 m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1710 n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1723 if ((result->m_flags & M_PKTHDR) != 0) {
1724 result->m_pkthdr.len = 0;
1725 for (n = result; n; n = n->m_next)
1726 result->m_pkthdr.len += n->m_len;
1738 * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1739 * add an entry to SP database, when received
1740 * <base, address(SD), (lifetime(H),) policy>
1742 * Adding to SP database,
1744 * <base, address(SD), (lifetime(H),) policy>
1745 * to the socket which was send.
1747 * SPDADD set a unique policy entry.
1748 * SPDSETIDX like SPDADD without a part of policy requests.
1749 * SPDUPDATE replace a unique policy entry.
1751 * m will always be freed.
1754 key_spdadd(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
1756 struct sadb_address *src0, *dst0;
1757 struct sadb_x_policy *xpl0, *xpl;
1758 struct sadb_lifetime *lft = NULL;
1759 struct secpolicyindex spidx;
1760 struct secpolicy *newsp;
1763 IPSEC_ASSERT(so != NULL, ("null socket"));
1764 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1765 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1766 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1768 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1769 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1770 mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1771 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1772 return key_senderror(so, m, EINVAL);
1774 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1775 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1776 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1777 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1779 return key_senderror(so, m, EINVAL);
1781 if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1782 if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1783 < sizeof(struct sadb_lifetime)) {
1784 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1786 return key_senderror(so, m, EINVAL);
1788 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1791 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1792 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1793 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1796 * Note: do not parse SADB_X_EXT_NAT_T_* here:
1797 * we are processing traffic endpoints.
1801 /* XXX boundary check against sa_len */
1802 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1805 src0->sadb_address_prefixlen,
1806 dst0->sadb_address_prefixlen,
1807 src0->sadb_address_proto,
1810 /* checking the direciton. */
1811 switch (xpl0->sadb_x_policy_dir) {
1812 case IPSEC_DIR_INBOUND:
1813 case IPSEC_DIR_OUTBOUND:
1816 ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
1817 mhp->msg->sadb_msg_errno = EINVAL;
1822 /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1823 if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1824 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1825 ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
1826 return key_senderror(so, m, EINVAL);
1829 /* policy requests are mandatory when action is ipsec. */
1830 if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1831 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1832 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1833 ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
1835 return key_senderror(so, m, EINVAL);
1839 * checking there is SP already or not.
1840 * SPDUPDATE doesn't depend on whether there is a SP or not.
1841 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1844 newsp = key_getsp(&spidx);
1845 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1851 if (newsp != NULL) {
1853 ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1855 return key_senderror(so, m, EEXIST);
1859 /* XXX: there is race between key_getsp and key_msg2sp. */
1861 /* allocation new SP entry */
1862 if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1863 return key_senderror(so, m, error);
1866 if ((newsp->id = key_getnewspid()) == 0) {
1868 return key_senderror(so, m, ENOBUFS);
1871 /* XXX boundary check against sa_len */
1872 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1875 src0->sadb_address_prefixlen,
1876 dst0->sadb_address_prefixlen,
1877 src0->sadb_address_proto,
1880 /* sanity check on addr pair */
1881 if (((struct sockaddr *)(src0 + 1))->sa_family !=
1882 ((struct sockaddr *)(dst0+ 1))->sa_family) {
1884 return key_senderror(so, m, EINVAL);
1886 if (((struct sockaddr *)(src0 + 1))->sa_len !=
1887 ((struct sockaddr *)(dst0+ 1))->sa_len) {
1889 return key_senderror(so, m, EINVAL);
1892 if (newsp->req && newsp->req->saidx.src.sa.sa_family &&
1893 newsp->req->saidx.dst.sa.sa_family) {
1894 if (newsp->req->saidx.src.sa.sa_family !=
1895 newsp->req->saidx.dst.sa.sa_family) {
1897 return key_senderror(so, m, EINVAL);
1902 newsp->created = time_second;
1903 newsp->lastused = newsp->created;
1904 newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1905 newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1908 TAILQ_INSERT_TAIL(&V_sptree[newsp->spidx.dir], newsp, chain);
1909 newsp->state = IPSEC_SPSTATE_ALIVE;
1912 /* delete the entry in spacqtree */
1913 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1914 struct secspacq *spacq = key_getspacq(&spidx);
1915 if (spacq != NULL) {
1916 /* reset counter in order to deletion by timehandler. */
1917 spacq->created = time_second;
1924 struct mbuf *n, *mpolicy;
1925 struct sadb_msg *newmsg;
1929 * Note: do not send SADB_X_EXT_NAT_T_* here:
1930 * we are sending traffic endpoints.
1933 /* create new sadb_msg to reply. */
1935 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1936 SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1937 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1939 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1941 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1944 return key_senderror(so, m, ENOBUFS);
1946 if (n->m_len < sizeof(*newmsg)) {
1947 n = m_pullup(n, sizeof(*newmsg));
1949 return key_senderror(so, m, ENOBUFS);
1951 newmsg = mtod(n, struct sadb_msg *);
1952 newmsg->sadb_msg_errno = 0;
1953 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1956 mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1957 sizeof(*xpl), &off);
1958 if (mpolicy == NULL) {
1959 /* n is already freed */
1960 return key_senderror(so, m, ENOBUFS);
1962 xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1963 if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1965 return key_senderror(so, m, EINVAL);
1967 xpl->sadb_x_policy_id = newsp->id;
1970 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
1975 * get new policy id.
1983 u_int32_t newid = 0;
1984 int count = V_key_spi_trycnt; /* XXX */
1985 struct secpolicy *sp;
1987 /* when requesting to allocate spi ranged */
1989 newid = (V_policy_id = (V_policy_id == ~0 ? 1 : V_policy_id + 1));
1991 if ((sp = key_getspbyid(newid)) == NULL)
1997 if (count == 0 || newid == 0) {
1998 ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
2007 * SADB_SPDDELETE processing
2009 * <base, address(SD), policy(*)>
2010 * from the user(?), and set SADB_SASTATE_DEAD,
2012 * <base, address(SD), policy(*)>
2014 * policy(*) including direction of policy.
2016 * m will always be freed.
2019 key_spddelete(struct socket *so, struct mbuf *m,
2020 const struct sadb_msghdr *mhp)
2022 struct sadb_address *src0, *dst0;
2023 struct sadb_x_policy *xpl0;
2024 struct secpolicyindex spidx;
2025 struct secpolicy *sp;
2027 IPSEC_ASSERT(so != NULL, ("null so"));
2028 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2029 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2030 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2032 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2033 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2034 mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2035 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2037 return key_senderror(so, m, EINVAL);
2039 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2040 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2041 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2042 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2044 return key_senderror(so, m, EINVAL);
2047 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2048 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2049 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2052 * Note: do not parse SADB_X_EXT_NAT_T_* here:
2053 * we are processing traffic endpoints.
2057 /* XXX boundary check against sa_len */
2058 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2061 src0->sadb_address_prefixlen,
2062 dst0->sadb_address_prefixlen,
2063 src0->sadb_address_proto,
2066 /* checking the direciton. */
2067 switch (xpl0->sadb_x_policy_dir) {
2068 case IPSEC_DIR_INBOUND:
2069 case IPSEC_DIR_OUTBOUND:
2072 ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2073 return key_senderror(so, m, EINVAL);
2076 /* Is there SP in SPD ? */
2077 if ((sp = key_getsp(&spidx)) == NULL) {
2078 ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2079 return key_senderror(so, m, EINVAL);
2082 /* save policy id to buffer to be returned. */
2083 xpl0->sadb_x_policy_id = sp->id;
2090 struct sadb_msg *newmsg;
2093 * Note: do not send SADB_X_EXT_NAT_T_* here:
2094 * we are sending traffic endpoints.
2097 /* create new sadb_msg to reply. */
2098 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2099 SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2101 return key_senderror(so, m, ENOBUFS);
2103 newmsg = mtod(n, struct sadb_msg *);
2104 newmsg->sadb_msg_errno = 0;
2105 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2108 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2113 * SADB_SPDDELETE2 processing
2116 * from the user(?), and set SADB_SASTATE_DEAD,
2120 * policy(*) including direction of policy.
2122 * m will always be freed.
2125 key_spddelete2(struct socket *so, struct mbuf *m,
2126 const struct sadb_msghdr *mhp)
2129 struct secpolicy *sp;
2131 IPSEC_ASSERT(so != NULL, ("null socket"));
2132 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2133 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2134 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2136 if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2137 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2138 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2139 return key_senderror(so, m, EINVAL);
2142 id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2144 /* Is there SP in SPD ? */
2145 if ((sp = key_getspbyid(id)) == NULL) {
2146 ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2147 return key_senderror(so, m, EINVAL);
2154 struct mbuf *n, *nn;
2155 struct sadb_msg *newmsg;
2158 /* create new sadb_msg to reply. */
2159 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2161 MGETHDR(n, M_NOWAIT, MT_DATA);
2162 if (n && len > MHLEN) {
2163 if (!(MCLGET(n, M_NOWAIT))) {
2169 return key_senderror(so, m, ENOBUFS);
2175 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2176 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2178 IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2181 n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2182 mhp->extlen[SADB_X_EXT_POLICY], M_NOWAIT);
2185 return key_senderror(so, m, ENOBUFS);
2188 n->m_pkthdr.len = 0;
2189 for (nn = n; nn; nn = nn->m_next)
2190 n->m_pkthdr.len += nn->m_len;
2192 newmsg = mtod(n, struct sadb_msg *);
2193 newmsg->sadb_msg_errno = 0;
2194 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2197 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2202 * SADB_X_GET processing
2207 * <base, address(SD), policy>
2209 * policy(*) including direction of policy.
2211 * m will always be freed.
2214 key_spdget(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2217 struct secpolicy *sp;
2220 IPSEC_ASSERT(so != NULL, ("null socket"));
2221 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2222 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2223 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2225 if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2226 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2227 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2229 return key_senderror(so, m, EINVAL);
2232 id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2234 /* Is there SP in SPD ? */
2235 if ((sp = key_getspbyid(id)) == NULL) {
2236 ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2237 return key_senderror(so, m, ENOENT);
2240 n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2244 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2246 return key_senderror(so, m, ENOBUFS);
2250 * SADB_X_SPDACQUIRE processing.
2251 * Acquire policy and SA(s) for a *OUTBOUND* packet.
2254 * to KMD, and expect to receive
2255 * <base> with SADB_X_SPDACQUIRE if error occured,
2258 * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2259 * policy(*) is without policy requests.
2262 * others: error number
2265 key_spdacquire(struct secpolicy *sp)
2267 struct mbuf *result = NULL, *m;
2268 struct secspacq *newspacq;
2270 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2271 IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2272 IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2273 ("policy not IPSEC %u", sp->policy));
2275 /* Get an entry to check whether sent message or not. */
2276 newspacq = key_getspacq(&sp->spidx);
2277 if (newspacq != NULL) {
2278 if (V_key_blockacq_count < newspacq->count) {
2279 /* reset counter and do send message. */
2280 newspacq->count = 0;
2282 /* increment counter and do nothing. */
2289 /* make new entry for blocking to send SADB_ACQUIRE. */
2290 newspacq = key_newspacq(&sp->spidx);
2291 if (newspacq == NULL)
2295 /* create new sadb_msg to reply. */
2296 m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2302 result->m_pkthdr.len = 0;
2303 for (m = result; m; m = m->m_next)
2304 result->m_pkthdr.len += m->m_len;
2306 mtod(result, struct sadb_msg *)->sadb_msg_len =
2307 PFKEY_UNIT64(result->m_pkthdr.len);
2309 return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2313 * SADB_SPDFLUSH processing
2316 * from the user, and free all entries in secpctree.
2320 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2322 * m will always be freed.
2325 key_spdflush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2327 TAILQ_HEAD(, secpolicy) drainq;
2328 struct sadb_msg *newmsg;
2329 struct secpolicy *sp, *nextsp;
2332 IPSEC_ASSERT(so != NULL, ("null socket"));
2333 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2334 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2335 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2337 if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2338 return key_senderror(so, m, EINVAL);
2340 TAILQ_INIT(&drainq);
2342 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2343 TAILQ_CONCAT(&drainq, &V_sptree[dir], chain);
2346 * We need to set state to DEAD for each policy to be sure,
2347 * that another thread won't try to unlink it.
2349 TAILQ_FOREACH(sp, &drainq, chain)
2350 sp->state = IPSEC_SPSTATE_DEAD;
2352 sp = TAILQ_FIRST(&drainq);
2353 while (sp != NULL) {
2354 nextsp = TAILQ_NEXT(sp, chain);
2359 if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2360 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2361 return key_senderror(so, m, ENOBUFS);
2367 m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2368 newmsg = mtod(m, struct sadb_msg *);
2369 newmsg->sadb_msg_errno = 0;
2370 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2372 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2376 * SADB_SPDDUMP processing
2379 * from the user, and dump all SP leaves
2384 * m will always be freed.
2387 key_spddump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
2389 SPTREE_RLOCK_TRACKER;
2390 struct secpolicy *sp;
2395 IPSEC_ASSERT(so != NULL, ("null socket"));
2396 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2397 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2398 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2400 /* search SPD entry and get buffer size. */
2403 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2404 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
2411 return key_senderror(so, m, ENOENT);
2414 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2415 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
2417 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2418 mhp->msg->sadb_msg_pid);
2421 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2430 static struct mbuf *
2431 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq,
2434 struct mbuf *result = NULL, *m;
2435 struct seclifetime lt;
2437 m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2443 * Note: do not send SADB_X_EXT_NAT_T_* here:
2444 * we are sending traffic endpoints.
2446 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2447 &sp->spidx.src.sa, sp->spidx.prefs,
2448 sp->spidx.ul_proto);
2453 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2454 &sp->spidx.dst.sa, sp->spidx.prefd,
2455 sp->spidx.ul_proto);
2466 lt.addtime=sp->created;
2467 lt.usetime= sp->lastused;
2468 m = key_setlifetime(<, SADB_EXT_LIFETIME_CURRENT);
2473 lt.addtime=sp->lifetime;
2474 lt.usetime= sp->validtime;
2475 m = key_setlifetime(<, SADB_EXT_LIFETIME_HARD);
2481 if ((result->m_flags & M_PKTHDR) == 0)
2484 if (result->m_len < sizeof(struct sadb_msg)) {
2485 result = m_pullup(result, sizeof(struct sadb_msg));
2490 result->m_pkthdr.len = 0;
2491 for (m = result; m; m = m->m_next)
2492 result->m_pkthdr.len += m->m_len;
2494 mtod(result, struct sadb_msg *)->sadb_msg_len =
2495 PFKEY_UNIT64(result->m_pkthdr.len);
2505 * get PFKEY message length for security policy and request.
2508 key_getspreqmsglen(struct secpolicy *sp)
2512 tlen = sizeof(struct sadb_x_policy);
2514 /* if is the policy for ipsec ? */
2515 if (sp->policy != IPSEC_POLICY_IPSEC)
2518 /* get length of ipsec requests */
2520 struct ipsecrequest *isr;
2523 for (isr = sp->req; isr != NULL; isr = isr->next) {
2524 len = sizeof(struct sadb_x_ipsecrequest)
2525 + isr->saidx.src.sa.sa_len
2526 + isr->saidx.dst.sa.sa_len;
2528 tlen += PFKEY_ALIGN8(len);
2536 * SADB_SPDEXPIRE processing
2538 * <base, address(SD), lifetime(CH), policy>
2542 * others : error number
2545 key_spdexpire(struct secpolicy *sp)
2547 struct mbuf *result = NULL, *m;
2550 struct sadb_lifetime *lt;
2552 /* XXX: Why do we lock ? */
2554 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2556 /* set msg header */
2557 m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2564 /* create lifetime extension (current and hard) */
2565 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2566 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
2573 bzero(mtod(m, caddr_t), len);
2574 lt = mtod(m, struct sadb_lifetime *);
2575 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2576 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2577 lt->sadb_lifetime_allocations = 0;
2578 lt->sadb_lifetime_bytes = 0;
2579 lt->sadb_lifetime_addtime = sp->created;
2580 lt->sadb_lifetime_usetime = sp->lastused;
2581 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2582 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2583 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2584 lt->sadb_lifetime_allocations = 0;
2585 lt->sadb_lifetime_bytes = 0;
2586 lt->sadb_lifetime_addtime = sp->lifetime;
2587 lt->sadb_lifetime_usetime = sp->validtime;
2591 * Note: do not send SADB_X_EXT_NAT_T_* here:
2592 * we are sending traffic endpoints.
2595 /* set sadb_address for source */
2596 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2598 sp->spidx.prefs, sp->spidx.ul_proto);
2605 /* set sadb_address for destination */
2606 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2608 sp->spidx.prefd, sp->spidx.ul_proto);
2623 if ((result->m_flags & M_PKTHDR) == 0) {
2628 if (result->m_len < sizeof(struct sadb_msg)) {
2629 result = m_pullup(result, sizeof(struct sadb_msg));
2630 if (result == NULL) {
2636 result->m_pkthdr.len = 0;
2637 for (m = result; m; m = m->m_next)
2638 result->m_pkthdr.len += m->m_len;
2640 mtod(result, struct sadb_msg *)->sadb_msg_len =
2641 PFKEY_UNIT64(result->m_pkthdr.len);
2643 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2651 /* %%% SAD management */
2653 * allocating a memory for new SA head, and copy from the values of mhp.
2654 * OUT: NULL : failure due to the lack of memory.
2655 * others : pointer to new SA head.
2657 static struct secashead *
2658 key_newsah(struct secasindex *saidx)
2660 struct secashead *newsah;
2662 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2664 newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2665 if (newsah != NULL) {
2667 for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2668 LIST_INIT(&newsah->savtree[i]);
2669 newsah->saidx = *saidx;
2671 /* add to saidxtree */
2672 newsah->state = SADB_SASTATE_MATURE;
2675 LIST_INSERT_HEAD(&V_sahtree, newsah, chain);
2682 * delete SA index and all SA registerd.
2685 key_delsah(struct secashead *sah)
2687 struct secasvar *sav, *nextsav;
2691 IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2692 SAHTREE_LOCK_ASSERT();
2694 /* searching all SA registerd in the secindex. */
2696 stateidx < _ARRAYLEN(saorder_state_any);
2698 u_int state = saorder_state_any[stateidx];
2699 LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2700 if (sav->refcnt == 0) {
2702 KEY_CHKSASTATE(state, sav->state, __func__);
2704 * do NOT call KEY_FREESAV here:
2705 * it will only delete the sav if refcnt == 1,
2706 * where we already know that refcnt == 0
2710 /* give up to delete this sa */
2715 if (!zombie) { /* delete only if there are savs */
2716 /* remove from tree of SA index */
2717 if (__LIST_CHAINED(sah))
2718 LIST_REMOVE(sah, chain);
2719 free(sah, M_IPSEC_SAH);
2724 * allocating a new SA with LARVAL state. key_add() and key_getspi() call,
2725 * and copy the values of mhp into new buffer.
2726 * When SAD message type is GETSPI:
2727 * to set sequence number from acq_seq++,
2728 * to set zero to SPI.
2729 * not to call key_setsava().
2731 * others : pointer to new secasvar.
2733 * does not modify mbuf. does not free mbuf on error.
2735 static struct secasvar *
2736 key_newsav(struct mbuf *m, const struct sadb_msghdr *mhp,
2737 struct secashead *sah, int *errp, const char *where, int tag)
2739 struct secasvar *newsav;
2740 const struct sadb_sa *xsa;
2742 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2743 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2744 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2745 IPSEC_ASSERT(sah != NULL, ("null secashead"));
2747 newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2748 if (newsav == NULL) {
2749 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2754 switch (mhp->msg->sadb_msg_type) {
2758 #ifdef IPSEC_DOSEQCHECK
2759 /* sync sequence number */
2760 if (mhp->msg->sadb_msg_seq == 0)
2762 (V_acq_seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq));
2765 newsav->seq = mhp->msg->sadb_msg_seq;
2770 if (mhp->ext[SADB_EXT_SA] == NULL) {
2771 free(newsav, M_IPSEC_SA);
2773 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2778 xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2779 newsav->spi = xsa->sadb_sa_spi;
2780 newsav->seq = mhp->msg->sadb_msg_seq;
2783 free(newsav, M_IPSEC_SA);
2790 /* copy sav values */
2791 if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2792 *errp = key_setsaval(newsav, m, mhp);
2794 free(newsav, M_IPSEC_SA);
2800 SECASVAR_LOCK_INIT(newsav);
2803 newsav->created = time_second;
2804 newsav->pid = mhp->msg->sadb_msg_pid;
2809 newsav->state = SADB_SASTATE_LARVAL;
2812 LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2816 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2817 printf("DP %s from %s:%u return SP:%p\n", __func__,
2818 where, tag, newsav));
2824 * free() SA variable entry.
2827 key_cleansav(struct secasvar *sav)
2830 * Cleanup xform state. Note that zeroize'ing causes the
2831 * keys to be cleared; otherwise we must do it ourself.
2833 if (sav->tdb_xform != NULL) {
2834 sav->tdb_xform->xf_zeroize(sav);
2835 sav->tdb_xform = NULL;
2837 KASSERT(sav->iv == NULL, ("iv but no xform"));
2838 if (sav->key_auth != NULL)
2839 bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2840 if (sav->key_enc != NULL)
2841 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2843 if (sav->key_auth != NULL) {
2844 if (sav->key_auth->key_data != NULL)
2845 free(sav->key_auth->key_data, M_IPSEC_MISC);
2846 free(sav->key_auth, M_IPSEC_MISC);
2847 sav->key_auth = NULL;
2849 if (sav->key_enc != NULL) {
2850 if (sav->key_enc->key_data != NULL)
2851 free(sav->key_enc->key_data, M_IPSEC_MISC);
2852 free(sav->key_enc, M_IPSEC_MISC);
2853 sav->key_enc = NULL;
2856 bzero(sav->sched, sav->schedlen);
2857 free(sav->sched, M_IPSEC_MISC);
2860 if (sav->replay != NULL) {
2861 free(sav->replay, M_IPSEC_MISC);
2864 if (sav->lft_c != NULL) {
2865 free(sav->lft_c, M_IPSEC_MISC);
2868 if (sav->lft_h != NULL) {
2869 free(sav->lft_h, M_IPSEC_MISC);
2872 if (sav->lft_s != NULL) {
2873 free(sav->lft_s, M_IPSEC_MISC);
2879 * free() SA variable entry.
2882 key_delsav(struct secasvar *sav)
2884 IPSEC_ASSERT(sav != NULL, ("null sav"));
2885 IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2887 /* remove from SA header */
2888 if (__LIST_CHAINED(sav))
2889 LIST_REMOVE(sav, chain);
2891 SECASVAR_LOCK_DESTROY(sav);
2892 free(sav, M_IPSEC_SA);
2899 * others : found, pointer to a SA.
2901 static struct secashead *
2902 key_getsah(struct secasindex *saidx)
2904 struct secashead *sah;
2907 LIST_FOREACH(sah, &V_sahtree, chain) {
2908 if (sah->state == SADB_SASTATE_DEAD)
2910 if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2919 * check not to be duplicated SPI.
2920 * NOTE: this function is too slow due to searching all SAD.
2923 * others : found, pointer to a SA.
2925 static struct secasvar *
2926 key_checkspidup(struct secasindex *saidx, u_int32_t spi)
2928 struct secashead *sah;
2929 struct secasvar *sav;
2931 /* check address family */
2932 if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2933 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2941 LIST_FOREACH(sah, &V_sahtree, chain) {
2942 if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2944 sav = key_getsavbyspi(sah, spi);
2954 * search SAD litmited alive SA, protocol, SPI.
2957 * others : found, pointer to a SA.
2959 static struct secasvar *
2960 key_getsavbyspi(struct secashead *sah, u_int32_t spi)
2962 struct secasvar *sav;
2963 u_int stateidx, state;
2966 SAHTREE_LOCK_ASSERT();
2967 /* search all status */
2969 stateidx < _ARRAYLEN(saorder_state_alive);
2972 state = saorder_state_alive[stateidx];
2973 LIST_FOREACH(sav, &sah->savtree[state], chain) {
2976 if (sav->state != state) {
2977 ipseclog((LOG_DEBUG, "%s: "
2978 "invalid sav->state (queue: %d SA: %d)\n",
2979 __func__, state, sav->state));
2983 if (sav->spi == spi)
2992 * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
2993 * You must update these if need.
2997 * does not modify mbuf. does not free mbuf on error.
3000 key_setsaval(struct secasvar *sav, struct mbuf *m,
3001 const struct sadb_msghdr *mhp)
3005 IPSEC_ASSERT(m != NULL, ("null mbuf"));
3006 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
3007 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
3009 /* initialization */
3011 sav->key_auth = NULL;
3012 sav->key_enc = NULL;
3019 sav->tdb_xform = NULL; /* transform */
3020 sav->tdb_encalgxform = NULL; /* encoding algorithm */
3021 sav->tdb_authalgxform = NULL; /* authentication algorithm */
3022 sav->tdb_compalgxform = NULL; /* compression algorithm */
3023 /* Initialize even if NAT-T not compiled in: */
3025 sav->natt_esp_frag_len = 0;
3028 if (mhp->ext[SADB_EXT_SA] != NULL) {
3029 const struct sadb_sa *sa0;
3031 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3032 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3037 sav->alg_auth = sa0->sadb_sa_auth;
3038 sav->alg_enc = sa0->sadb_sa_encrypt;
3039 sav->flags = sa0->sadb_sa_flags;
3042 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3043 sav->replay = (struct secreplay *)
3044 malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
3045 if (sav->replay == NULL) {
3046 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3051 if (sa0->sadb_sa_replay != 0)
3052 sav->replay->bitmap = (caddr_t)(sav->replay+1);
3053 sav->replay->wsize = sa0->sadb_sa_replay;
3057 /* Authentication keys */
3058 if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3059 const struct sadb_key *key0;
3062 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3063 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3066 if (len < sizeof(*key0)) {
3070 switch (mhp->msg->sadb_msg_satype) {
3071 case SADB_SATYPE_AH:
3072 case SADB_SATYPE_ESP:
3073 case SADB_X_SATYPE_TCPSIGNATURE:
3074 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3075 sav->alg_auth != SADB_X_AALG_NULL)
3078 case SADB_X_SATYPE_IPCOMP:
3084 ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3089 sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
3091 if (sav->key_auth == NULL ) {
3092 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3099 /* Encryption key */
3100 if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3101 const struct sadb_key *key0;
3104 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3105 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3108 if (len < sizeof(*key0)) {
3112 switch (mhp->msg->sadb_msg_satype) {
3113 case SADB_SATYPE_ESP:
3114 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3115 sav->alg_enc != SADB_EALG_NULL) {
3119 sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
3122 if (sav->key_enc == NULL) {
3123 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3129 case SADB_X_SATYPE_IPCOMP:
3130 if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3132 sav->key_enc = NULL; /*just in case*/
3134 case SADB_SATYPE_AH:
3135 case SADB_X_SATYPE_TCPSIGNATURE:
3141 ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3150 switch (mhp->msg->sadb_msg_satype) {
3151 case SADB_SATYPE_AH:
3152 error = xform_init(sav, XF_AH);
3154 case SADB_SATYPE_ESP:
3155 error = xform_init(sav, XF_ESP);
3157 case SADB_X_SATYPE_IPCOMP:
3158 error = xform_init(sav, XF_IPCOMP);
3160 case SADB_X_SATYPE_TCPSIGNATURE:
3161 error = xform_init(sav, XF_TCPSIGNATURE);
3165 ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3166 __func__, mhp->msg->sadb_msg_satype));
3171 sav->created = time_second;
3173 /* make lifetime for CURRENT */
3174 sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
3175 if (sav->lft_c == NULL) {
3176 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3181 sav->lft_c->allocations = 0;
3182 sav->lft_c->bytes = 0;
3183 sav->lft_c->addtime = time_second;
3184 sav->lft_c->usetime = 0;
3186 /* lifetimes for HARD and SOFT */
3188 const struct sadb_lifetime *lft0;
3190 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3192 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3196 sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3197 if (sav->lft_h == NULL) {
3198 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3202 /* to be initialize ? */
3205 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3207 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3211 sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3212 if (sav->lft_s == NULL) {
3213 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3217 /* to be initialize ? */
3224 /* initialization */
3231 * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3236 key_mature(struct secasvar *sav)
3240 /* check SPI value */
3241 switch (sav->sah->saidx.proto) {
3245 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
3246 * 1-255 reserved by IANA for future use,
3247 * 0 for implementation specific, local use.
3249 if (ntohl(sav->spi) <= 255) {
3250 ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3251 __func__, (u_int32_t)ntohl(sav->spi)));
3258 switch (sav->sah->saidx.proto) {
3261 if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3262 (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3263 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3264 "given to old-esp.\n", __func__));
3267 error = xform_init(sav, XF_ESP);
3271 if (sav->flags & SADB_X_EXT_DERIV) {
3272 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3273 "given to AH SA.\n", __func__));
3276 if (sav->alg_enc != SADB_EALG_NONE) {
3277 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3278 "mismated.\n", __func__));
3281 error = xform_init(sav, XF_AH);
3283 case IPPROTO_IPCOMP:
3284 if (sav->alg_auth != SADB_AALG_NONE) {
3285 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3286 "mismated.\n", __func__));
3289 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3290 && ntohl(sav->spi) >= 0x10000) {
3291 ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3295 error = xform_init(sav, XF_IPCOMP);
3298 if (sav->alg_enc != SADB_EALG_NONE) {
3299 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3300 "mismated.\n", __func__));
3303 error = xform_init(sav, XF_TCPSIGNATURE);
3306 ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3307 error = EPROTONOSUPPORT;
3312 key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3319 * subroutine for SADB_GET and SADB_DUMP.
3321 static struct mbuf *
3322 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3323 u_int32_t seq, u_int32_t pid)
3325 struct mbuf *result = NULL, *tres = NULL, *m;
3328 SADB_EXT_SA, SADB_X_EXT_SA2,
3329 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3330 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3331 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3332 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3333 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3335 SADB_X_EXT_NAT_T_TYPE,
3336 SADB_X_EXT_NAT_T_SPORT, SADB_X_EXT_NAT_T_DPORT,
3337 SADB_X_EXT_NAT_T_OAI, SADB_X_EXT_NAT_T_OAR,
3338 SADB_X_EXT_NAT_T_FRAG,
3342 m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3347 for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3349 switch (dumporder[i]) {
3351 m = key_setsadbsa(sav);
3356 case SADB_X_EXT_SA2:
3357 m = key_setsadbxsa2(sav->sah->saidx.mode,
3358 sav->replay ? sav->replay->count : 0,
3359 sav->sah->saidx.reqid);
3364 case SADB_EXT_ADDRESS_SRC:
3365 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3366 &sav->sah->saidx.src.sa,
3367 FULLMASK, IPSEC_ULPROTO_ANY);
3372 case SADB_EXT_ADDRESS_DST:
3373 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3374 &sav->sah->saidx.dst.sa,
3375 FULLMASK, IPSEC_ULPROTO_ANY);
3380 case SADB_EXT_KEY_AUTH:
3383 m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3388 case SADB_EXT_KEY_ENCRYPT:
3391 m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3396 case SADB_EXT_LIFETIME_CURRENT:
3399 m = key_setlifetime(sav->lft_c,
3400 SADB_EXT_LIFETIME_CURRENT);
3405 case SADB_EXT_LIFETIME_HARD:
3408 m = key_setlifetime(sav->lft_h,
3409 SADB_EXT_LIFETIME_HARD);
3414 case SADB_EXT_LIFETIME_SOFT:
3417 m = key_setlifetime(sav->lft_s,
3418 SADB_EXT_LIFETIME_SOFT);
3425 case SADB_X_EXT_NAT_T_TYPE:
3426 m = key_setsadbxtype(sav->natt_type);
3431 case SADB_X_EXT_NAT_T_DPORT:
3432 m = key_setsadbxport(
3433 KEY_PORTFROMSADDR(&sav->sah->saidx.dst),
3434 SADB_X_EXT_NAT_T_DPORT);
3439 case SADB_X_EXT_NAT_T_SPORT:
3440 m = key_setsadbxport(
3441 KEY_PORTFROMSADDR(&sav->sah->saidx.src),
3442 SADB_X_EXT_NAT_T_SPORT);
3447 case SADB_X_EXT_NAT_T_OAI:
3448 case SADB_X_EXT_NAT_T_OAR:
3449 case SADB_X_EXT_NAT_T_FRAG:
3450 /* We do not (yet) support those. */
3454 case SADB_EXT_ADDRESS_PROXY:
3455 case SADB_EXT_IDENTITY_SRC:
3456 case SADB_EXT_IDENTITY_DST:
3457 /* XXX: should we brought from SPD ? */
3458 case SADB_EXT_SENSITIVITY:
3471 m_cat(result, tres);
3472 if (result->m_len < sizeof(struct sadb_msg)) {
3473 result = m_pullup(result, sizeof(struct sadb_msg));
3478 result->m_pkthdr.len = 0;
3479 for (m = result; m; m = m->m_next)
3480 result->m_pkthdr.len += m->m_len;
3482 mtod(result, struct sadb_msg *)->sadb_msg_len =
3483 PFKEY_UNIT64(result->m_pkthdr.len);
3494 * set data into sadb_msg.
3496 static struct mbuf *
3497 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3498 pid_t pid, u_int16_t reserved)
3504 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3507 MGETHDR(m, M_NOWAIT, MT_DATA);
3508 if (m && len > MHLEN) {
3509 if (!(MCLGET(m, M_NOWAIT))) {
3516 m->m_pkthdr.len = m->m_len = len;
3519 p = mtod(m, struct sadb_msg *);
3522 p->sadb_msg_version = PF_KEY_V2;
3523 p->sadb_msg_type = type;
3524 p->sadb_msg_errno = 0;
3525 p->sadb_msg_satype = satype;
3526 p->sadb_msg_len = PFKEY_UNIT64(tlen);
3527 p->sadb_msg_reserved = reserved;
3528 p->sadb_msg_seq = seq;
3529 p->sadb_msg_pid = (u_int32_t)pid;
3535 * copy secasvar data into sadb_address.
3537 static struct mbuf *
3538 key_setsadbsa(struct secasvar *sav)
3544 len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3545 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3550 p = mtod(m, struct sadb_sa *);
3552 p->sadb_sa_len = PFKEY_UNIT64(len);
3553 p->sadb_sa_exttype = SADB_EXT_SA;
3554 p->sadb_sa_spi = sav->spi;
3555 p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3556 p->sadb_sa_state = sav->state;
3557 p->sadb_sa_auth = sav->alg_auth;
3558 p->sadb_sa_encrypt = sav->alg_enc;
3559 p->sadb_sa_flags = sav->flags;
3565 * set data into sadb_address.
3567 static struct mbuf *
3568 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr,
3569 u_int8_t prefixlen, u_int16_t ul_proto)
3572 struct sadb_address *p;
3575 len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3576 PFKEY_ALIGN8(saddr->sa_len);
3577 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3582 p = mtod(m, struct sadb_address *);
3585 p->sadb_address_len = PFKEY_UNIT64(len);
3586 p->sadb_address_exttype = exttype;
3587 p->sadb_address_proto = ul_proto;
3588 if (prefixlen == FULLMASK) {
3589 switch (saddr->sa_family) {
3591 prefixlen = sizeof(struct in_addr) << 3;
3594 prefixlen = sizeof(struct in6_addr) << 3;
3600 p->sadb_address_prefixlen = prefixlen;
3601 p->sadb_address_reserved = 0;
3604 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3611 * set data into sadb_x_sa2.
3613 static struct mbuf *
3614 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3617 struct sadb_x_sa2 *p;
3620 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3621 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3626 p = mtod(m, struct sadb_x_sa2 *);
3629 p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3630 p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3631 p->sadb_x_sa2_mode = mode;
3632 p->sadb_x_sa2_reserved1 = 0;
3633 p->sadb_x_sa2_reserved2 = 0;
3634 p->sadb_x_sa2_sequence = seq;
3635 p->sadb_x_sa2_reqid = reqid;
3642 * Set a type in sadb_x_nat_t_type.
3644 static struct mbuf *
3645 key_setsadbxtype(u_int16_t type)
3649 struct sadb_x_nat_t_type *p;
3651 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_type));
3653 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3658 p = mtod(m, struct sadb_x_nat_t_type *);
3661 p->sadb_x_nat_t_type_len = PFKEY_UNIT64(len);
3662 p->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
3663 p->sadb_x_nat_t_type_type = type;
3668 * Set a port in sadb_x_nat_t_port.
3669 * In contrast to default RFC 2367 behaviour, port is in network byte order.
3671 static struct mbuf *
3672 key_setsadbxport(u_int16_t port, u_int16_t type)
3676 struct sadb_x_nat_t_port *p;
3678 len = PFKEY_ALIGN8(sizeof(struct sadb_x_nat_t_port));
3680 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3685 p = mtod(m, struct sadb_x_nat_t_port *);
3688 p->sadb_x_nat_t_port_len = PFKEY_UNIT64(len);
3689 p->sadb_x_nat_t_port_exttype = type;
3690 p->sadb_x_nat_t_port_port = port;
3696 * Get port from sockaddr. Port is in network byte order.
3699 key_portfromsaddr(struct sockaddr *sa)
3702 switch (sa->sa_family) {
3705 return ((struct sockaddr_in *)sa)->sin_port;
3709 return ((struct sockaddr_in6 *)sa)->sin6_port;
3712 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
3713 printf("DP %s unexpected address family %d\n",
3714 __func__, sa->sa_family));
3717 #endif /* IPSEC_NAT_T */
3720 * Set port in struct sockaddr. Port is in network byte order.
3723 key_porttosaddr(struct sockaddr *sa, u_int16_t port)
3726 switch (sa->sa_family) {
3729 ((struct sockaddr_in *)sa)->sin_port = port;
3734 ((struct sockaddr_in6 *)sa)->sin6_port = port;
3738 ipseclog((LOG_DEBUG, "%s: unexpected address family %d.\n",
3739 __func__, sa->sa_family));
3745 * set data into sadb_x_policy
3747 static struct mbuf *
3748 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3751 struct sadb_x_policy *p;
3754 len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3755 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
3760 p = mtod(m, struct sadb_x_policy *);
3763 p->sadb_x_policy_len = PFKEY_UNIT64(len);
3764 p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3765 p->sadb_x_policy_type = type;
3766 p->sadb_x_policy_dir = dir;
3767 p->sadb_x_policy_id = id;
3773 /* Take a key message (sadb_key) from the socket and turn it into one
3774 * of the kernel's key structures (seckey).
3776 * IN: pointer to the src
3777 * OUT: NULL no more memory
3780 key_dup_keymsg(const struct sadb_key *src, u_int len,
3781 struct malloc_type *type)
3784 dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
3786 dst->bits = src->sadb_key_bits;
3787 dst->key_data = (char *)malloc(len, type, M_NOWAIT);
3788 if (dst->key_data != NULL) {
3789 bcopy((const char *)src + sizeof(struct sadb_key),
3790 dst->key_data, len);
3792 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3798 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3805 /* Take a lifetime message (sadb_lifetime) passed in on a socket and
3806 * turn it into one of the kernel's lifetime structures (seclifetime).
3808 * IN: pointer to the destination, source and malloc type
3809 * OUT: NULL, no more memory
3812 static struct seclifetime *
3813 key_dup_lifemsg(const struct sadb_lifetime *src, struct malloc_type *type)
3815 struct seclifetime *dst = NULL;
3817 dst = (struct seclifetime *)malloc(sizeof(struct seclifetime),
3821 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3823 dst->allocations = src->sadb_lifetime_allocations;
3824 dst->bytes = src->sadb_lifetime_bytes;
3825 dst->addtime = src->sadb_lifetime_addtime;
3826 dst->usetime = src->sadb_lifetime_usetime;
3831 /* compare my own address
3832 * OUT: 1: true, i.e. my address.
3836 key_ismyaddr(struct sockaddr *sa)
3839 IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3840 switch (sa->sa_family) {
3843 return (in_localip(satosin(sa)->sin_addr));
3847 return key_ismyaddr6((struct sockaddr_in6 *)sa);
3856 * compare my own address for IPv6.
3861 key_ismyaddr6(struct sockaddr_in6 *sin6)
3863 struct in6_addr in6;
3865 if (!IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr))
3866 return (in6_localip(&sin6->sin6_addr));
3868 /* Convert address into kernel-internal form */
3869 in6 = sin6->sin6_addr;
3870 in6.s6_addr16[1] = htons(sin6->sin6_scope_id & 0xffff);
3871 return (in6_localip(&in6));
3876 * compare two secasindex structure.
3877 * flag can specify to compare 2 saidxes.
3878 * compare two secasindex structure without both mode and reqid.
3879 * don't compare port.
3881 * saidx0: source, it can be in SAD.
3888 key_cmpsaidx(const struct secasindex *saidx0, const struct secasindex *saidx1,
3894 if (saidx0 == NULL && saidx1 == NULL)
3897 if (saidx0 == NULL || saidx1 == NULL)
3900 if (saidx0->proto != saidx1->proto)
3903 if (flag == CMP_EXACTLY) {
3904 if (saidx0->mode != saidx1->mode)
3906 if (saidx0->reqid != saidx1->reqid)
3908 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
3909 bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
3913 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3914 if (flag == CMP_MODE_REQID
3915 ||flag == CMP_REQID) {
3917 * If reqid of SPD is non-zero, unique SA is required.
3918 * The result must be of same reqid in this case.
3920 if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3924 if (flag == CMP_MODE_REQID) {
3925 if (saidx0->mode != IPSEC_MODE_ANY
3926 && saidx0->mode != saidx1->mode)
3932 * If NAT-T is enabled, check ports for tunnel mode.
3933 * Do not check ports if they are set to zero in the SPD.
3934 * Also do not do it for native transport mode, as there
3935 * is no port information available in the SP.
3937 if ((saidx1->mode == IPSEC_MODE_TUNNEL ||
3938 (saidx1->mode == IPSEC_MODE_TRANSPORT &&
3939 saidx1->proto == IPPROTO_ESP)) &&
3940 saidx1->src.sa.sa_family == AF_INET &&
3941 saidx1->dst.sa.sa_family == AF_INET &&
3942 ((const struct sockaddr_in *)(&saidx1->src))->sin_port &&
3943 ((const struct sockaddr_in *)(&saidx1->dst))->sin_port)
3945 #endif /* IPSEC_NAT_T */
3947 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, chkport) != 0) {
3950 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, chkport) != 0) {
3959 * compare two secindex structure exactly.
3961 * spidx0: source, it is often in SPD.
3962 * spidx1: object, it is often from PFKEY message.
3968 key_cmpspidx_exactly(struct secpolicyindex *spidx0,
3969 struct secpolicyindex *spidx1)
3972 if (spidx0 == NULL && spidx1 == NULL)
3975 if (spidx0 == NULL || spidx1 == NULL)
3978 if (spidx0->prefs != spidx1->prefs
3979 || spidx0->prefd != spidx1->prefd
3980 || spidx0->ul_proto != spidx1->ul_proto)
3983 return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
3984 key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
3988 * compare two secindex structure with mask.
3990 * spidx0: source, it is often in SPD.
3991 * spidx1: object, it is often from IP header.
3997 key_cmpspidx_withmask(struct secpolicyindex *spidx0,
3998 struct secpolicyindex *spidx1)
4001 if (spidx0 == NULL && spidx1 == NULL)
4004 if (spidx0 == NULL || spidx1 == NULL)
4007 if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
4008 spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
4009 spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
4010 spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
4013 /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4014 if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4015 && spidx0->ul_proto != spidx1->ul_proto)
4018 switch (spidx0->src.sa.sa_family) {
4020 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
4021 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
4023 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
4024 &spidx1->src.sin.sin_addr, spidx0->prefs))
4028 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
4029 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
4032 * scope_id check. if sin6_scope_id is 0, we regard it
4033 * as a wildcard scope, which matches any scope zone ID.
4035 if (spidx0->src.sin6.sin6_scope_id &&
4036 spidx1->src.sin6.sin6_scope_id &&
4037 spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
4039 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
4040 &spidx1->src.sin6.sin6_addr, spidx0->prefs))
4045 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
4050 switch (spidx0->dst.sa.sa_family) {
4052 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
4053 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
4055 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
4056 &spidx1->dst.sin.sin_addr, spidx0->prefd))
4060 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
4061 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
4064 * scope_id check. if sin6_scope_id is 0, we regard it
4065 * as a wildcard scope, which matches any scope zone ID.
4067 if (spidx0->dst.sin6.sin6_scope_id &&
4068 spidx1->dst.sin6.sin6_scope_id &&
4069 spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
4071 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
4072 &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
4077 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
4082 /* XXX Do we check other field ? e.g. flowinfo */
4087 /* returns 0 on match */
4089 key_sockaddrcmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
4095 #define satosin(s) ((const struct sockaddr_in *)s)
4099 #define satosin6(s) ((const struct sockaddr_in6 *)s)
4100 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4103 switch (sa1->sa_family) {
4105 if (sa1->sa_len != sizeof(struct sockaddr_in))
4107 if (satosin(sa1)->sin_addr.s_addr !=
4108 satosin(sa2)->sin_addr.s_addr) {
4111 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4115 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4116 return 1; /*EINVAL*/
4117 if (satosin6(sa1)->sin6_scope_id !=
4118 satosin6(sa2)->sin6_scope_id) {
4121 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4122 &satosin6(sa2)->sin6_addr)) {
4126 satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4131 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4142 * compare two buffers with mask.
4146 * bits: Number of bits to compare
4152 key_bbcmp(const void *a1, const void *a2, u_int bits)
4154 const unsigned char *p1 = a1;
4155 const unsigned char *p2 = a2;
4157 /* XXX: This could be considerably faster if we compare a word
4158 * at a time, but it is complicated on LSB Endian machines */
4160 /* Handle null pointers */
4161 if (p1 == NULL || p2 == NULL)
4171 u_int8_t mask = ~((1<<(8-bits))-1);
4172 if ((*p1 & mask) != (*p2 & mask))
4175 return 1; /* Match! */
4179 key_flush_spd(time_t now)
4181 SPTREE_RLOCK_TRACKER;
4182 struct secpolicy *sp;
4186 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4189 TAILQ_FOREACH(sp, &V_sptree[dir], chain) {
4190 if (sp->lifetime == 0 && sp->validtime == 0)
4192 if ((sp->lifetime &&
4193 now - sp->created > sp->lifetime) ||
4195 now - sp->lastused > sp->validtime)) {
4209 key_flush_sad(time_t now)
4211 struct secashead *sah, *nextsah;
4212 struct secasvar *sav, *nextsav;
4216 LIST_FOREACH_SAFE(sah, &V_sahtree, chain, nextsah) {
4217 /* if sah has been dead, then delete it and process next sah. */
4218 if (sah->state == SADB_SASTATE_DEAD) {
4223 /* if LARVAL entry doesn't become MATURE, delete it. */
4224 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4225 /* Need to also check refcnt for a larval SA ??? */
4226 if (now - sav->created > V_key_larval_lifetime)
4231 * check MATURE entry to start to send expire message
4234 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4235 /* we don't need to check. */
4236 if (sav->lft_s == NULL)
4240 if (sav->lft_c == NULL) {
4241 ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4242 "time, why?\n", __func__));
4246 /* check SOFT lifetime */
4247 if (sav->lft_s->addtime != 0 &&
4248 now - sav->created > sav->lft_s->addtime) {
4249 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4251 * Actually, only send expire message if
4252 * SA has been used, as it was done before,
4253 * but should we always send such message,
4254 * and let IKE daemon decide if it should be
4255 * renegotiated or not ?
4256 * XXX expire message will actually NOT be
4257 * sent if SA is only used after soft
4258 * lifetime has been reached, see below
4261 if (sav->lft_c->usetime != 0)
4264 /* check SOFT lifetime by bytes */
4266 * XXX I don't know the way to delete this SA
4267 * when new SA is installed. Caution when it's
4268 * installed too big lifetime by time.
4270 else if (sav->lft_s->bytes != 0 &&
4271 sav->lft_s->bytes < sav->lft_c->bytes) {
4273 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4275 * XXX If we keep to send expire
4276 * message in the status of
4277 * DYING. Do remove below code.
4283 /* check DYING entry to change status to DEAD. */
4284 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4285 /* we don't need to check. */
4286 if (sav->lft_h == NULL)
4290 if (sav->lft_c == NULL) {
4291 ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4292 "time, why?\n", __func__));
4296 if (sav->lft_h->addtime != 0 &&
4297 now - sav->created > sav->lft_h->addtime) {
4298 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4301 #if 0 /* XXX Should we keep to send expire message until HARD lifetime ? */
4302 else if (sav->lft_s != NULL
4303 && sav->lft_s->addtime != 0
4304 && now - sav->created > sav->lft_s->addtime) {
4306 * XXX: should be checked to be
4307 * installed the valid SA.
4311 * If there is no SA then sending
4317 /* check HARD lifetime by bytes */
4318 else if (sav->lft_h->bytes != 0 &&
4319 sav->lft_h->bytes < sav->lft_c->bytes) {
4320 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4325 /* delete entry in DEAD */
4326 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4328 if (sav->state != SADB_SASTATE_DEAD) {
4329 ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4330 "(queue: %d SA: %d): kill it anyway\n",
4332 SADB_SASTATE_DEAD, sav->state));
4335 * do not call key_freesav() here.
4336 * sav should already be freed, and sav->refcnt
4337 * shows other references to sav
4338 * (such as from SPD).
4346 key_flush_acq(time_t now)
4348 struct secacq *acq, *nextacq;
4352 for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
4353 nextacq = LIST_NEXT(acq, chain);
4354 if (now - acq->created > V_key_blockacq_lifetime
4355 && __LIST_CHAINED(acq)) {
4356 LIST_REMOVE(acq, chain);
4357 free(acq, M_IPSEC_SAQ);
4364 key_flush_spacq(time_t now)
4366 struct secspacq *acq, *nextacq;
4370 for (acq = LIST_FIRST(&V_spacqtree); acq != NULL; acq = nextacq) {
4371 nextacq = LIST_NEXT(acq, chain);
4372 if (now - acq->created > V_key_blockacq_lifetime
4373 && __LIST_CHAINED(acq)) {
4374 LIST_REMOVE(acq, chain);
4375 free(acq, M_IPSEC_SAQ);
4383 * scanning SPD and SAD to check status for each entries,
4384 * and do to remove or to expire.
4385 * XXX: year 2038 problem may remain.
4388 key_timehandler(void *arg)
4390 VNET_ITERATOR_DECL(vnet_iter);
4391 time_t now = time_second;
4393 VNET_LIST_RLOCK_NOSLEEP();
4394 VNET_FOREACH(vnet_iter) {
4395 CURVNET_SET(vnet_iter);
4399 key_flush_spacq(now);
4402 VNET_LIST_RUNLOCK_NOSLEEP();
4404 #ifndef IPSEC_DEBUG2
4405 /* do exchange to tick time !! */
4406 callout_schedule(&key_timer, hz);
4407 #endif /* IPSEC_DEBUG2 */
4415 key_randomfill(&value, sizeof(value));
4420 key_randomfill(void *p, size_t l)
4424 static int warn = 1;
4427 n = (size_t)read_random(p, (u_int)l);
4431 bcopy(&v, (u_int8_t *)p + n,
4432 l - n < sizeof(v) ? l - n : sizeof(v));
4436 printf("WARNING: pseudo-random number generator "
4437 "used for IPsec processing\n");
4444 * map SADB_SATYPE_* to IPPROTO_*.
4445 * if satype == SADB_SATYPE then satype is mapped to ~0.
4447 * 0: invalid satype.
4450 key_satype2proto(u_int8_t satype)
4453 case SADB_SATYPE_UNSPEC:
4454 return IPSEC_PROTO_ANY;
4455 case SADB_SATYPE_AH:
4457 case SADB_SATYPE_ESP:
4459 case SADB_X_SATYPE_IPCOMP:
4460 return IPPROTO_IPCOMP;
4461 case SADB_X_SATYPE_TCPSIGNATURE:
4470 * map IPPROTO_* to SADB_SATYPE_*
4472 * 0: invalid protocol type.
4475 key_proto2satype(u_int16_t proto)
4479 return SADB_SATYPE_AH;
4481 return SADB_SATYPE_ESP;
4482 case IPPROTO_IPCOMP:
4483 return SADB_X_SATYPE_IPCOMP;
4485 return SADB_X_SATYPE_TCPSIGNATURE;
4494 * SADB_GETSPI processing is to receive
4495 * <base, (SA2), src address, dst address, (SPI range)>
4496 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4497 * tree with the status of LARVAL, and send
4498 * <base, SA(*), address(SD)>
4501 * IN: mhp: pointer to the pointer to each header.
4502 * OUT: NULL if fail.
4503 * other if success, return pointer to the message to send.
4506 key_getspi(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4508 struct sadb_address *src0, *dst0;
4509 struct secasindex saidx;
4510 struct secashead *newsah;
4511 struct secasvar *newsav;
4518 IPSEC_ASSERT(so != NULL, ("null socket"));
4519 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4520 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4521 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4523 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4524 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4525 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4527 return key_senderror(so, m, EINVAL);
4529 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4530 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4531 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4533 return key_senderror(so, m, EINVAL);
4535 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4536 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4537 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4539 mode = IPSEC_MODE_ANY;
4543 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4544 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4546 /* map satype to proto */
4547 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4548 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4550 return key_senderror(so, m, EINVAL);
4554 * Make sure the port numbers are zero.
4555 * In case of NAT-T we will update them later if needed.
4557 switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4559 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4560 sizeof(struct sockaddr_in))
4561 return key_senderror(so, m, EINVAL);
4562 ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4565 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4566 sizeof(struct sockaddr_in6))
4567 return key_senderror(so, m, EINVAL);
4568 ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4573 switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4575 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4576 sizeof(struct sockaddr_in))
4577 return key_senderror(so, m, EINVAL);
4578 ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4581 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4582 sizeof(struct sockaddr_in6))
4583 return key_senderror(so, m, EINVAL);
4584 ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4590 /* XXX boundary check against sa_len */
4591 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4595 * Handle NAT-T info if present.
4596 * We made sure the port numbers are zero above, so we do
4597 * not have to worry in case we do not update them.
4599 if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL)
4600 ipseclog((LOG_DEBUG, "%s: NAT-T OAi present\n", __func__));
4601 if (mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL)
4602 ipseclog((LOG_DEBUG, "%s: NAT-T OAr present\n", __func__));
4604 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4605 mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4606 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4607 struct sadb_x_nat_t_type *type;
4608 struct sadb_x_nat_t_port *sport, *dport;
4610 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4611 mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4612 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4613 ipseclog((LOG_DEBUG, "%s: invalid nat-t message "
4614 "passed.\n", __func__));
4615 return key_senderror(so, m, EINVAL);
4618 sport = (struct sadb_x_nat_t_port *)
4619 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4620 dport = (struct sadb_x_nat_t_port *)
4621 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4624 KEY_PORTTOSADDR(&saidx.src, sport->sadb_x_nat_t_port_port);
4626 KEY_PORTTOSADDR(&saidx.dst, dport->sadb_x_nat_t_port_port);
4630 /* SPI allocation */
4631 spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4634 return key_senderror(so, m, EINVAL);
4636 /* get a SA index */
4637 if ((newsah = key_getsah(&saidx)) == NULL) {
4638 /* create a new SA index */
4639 if ((newsah = key_newsah(&saidx)) == NULL) {
4640 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4641 return key_senderror(so, m, ENOBUFS);
4647 newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4648 if (newsav == NULL) {
4649 /* XXX don't free new SA index allocated in above. */
4650 return key_senderror(so, m, error);
4654 newsav->spi = htonl(spi);
4656 /* delete the entry in acqtree */
4657 if (mhp->msg->sadb_msg_seq != 0) {
4659 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4660 /* reset counter in order to deletion by timehandler. */
4661 acq->created = time_second;
4667 struct mbuf *n, *nn;
4668 struct sadb_sa *m_sa;
4669 struct sadb_msg *newmsg;
4672 /* create new sadb_msg to reply. */
4673 len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4674 PFKEY_ALIGN8(sizeof(struct sadb_sa));
4676 MGETHDR(n, M_NOWAIT, MT_DATA);
4678 if (!(MCLGET(n, M_NOWAIT))) {
4684 return key_senderror(so, m, ENOBUFS);
4690 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4691 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4693 m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4694 m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4695 m_sa->sadb_sa_exttype = SADB_EXT_SA;
4696 m_sa->sadb_sa_spi = htonl(spi);
4697 off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4699 IPSEC_ASSERT(off == len,
4700 ("length inconsistency (off %u len %u)", off, len));
4702 n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4703 SADB_EXT_ADDRESS_DST);
4706 return key_senderror(so, m, ENOBUFS);
4709 if (n->m_len < sizeof(struct sadb_msg)) {
4710 n = m_pullup(n, sizeof(struct sadb_msg));
4712 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4715 n->m_pkthdr.len = 0;
4716 for (nn = n; nn; nn = nn->m_next)
4717 n->m_pkthdr.len += nn->m_len;
4719 newmsg = mtod(n, struct sadb_msg *);
4720 newmsg->sadb_msg_seq = newsav->seq;
4721 newmsg->sadb_msg_errno = 0;
4722 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4725 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4730 * allocating new SPI
4731 * called by key_getspi().
4737 key_do_getnewspi(struct sadb_spirange *spirange, struct secasindex *saidx)
4741 int count = V_key_spi_trycnt;
4743 /* set spi range to allocate */
4744 if (spirange != NULL) {
4745 min = spirange->sadb_spirange_min;
4746 max = spirange->sadb_spirange_max;
4748 min = V_key_spi_minval;
4749 max = V_key_spi_maxval;
4751 /* IPCOMP needs 2-byte SPI */
4752 if (saidx->proto == IPPROTO_IPCOMP) {
4759 t = min; min = max; max = t;
4764 if (key_checkspidup(saidx, min) != NULL) {
4765 ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4770 count--; /* taking one cost. */
4778 /* when requesting to allocate spi ranged */
4780 /* generate pseudo-random SPI value ranged. */
4781 newspi = min + (key_random() % (max - min + 1));
4783 if (key_checkspidup(saidx, newspi) == NULL)
4787 if (count == 0 || newspi == 0) {
4788 ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4795 keystat.getspi_count =
4796 (keystat.getspi_count + V_key_spi_trycnt - count) / 2;
4802 * SADB_UPDATE processing
4804 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4805 * key(AE), (identity(SD),) (sensitivity)>
4806 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4808 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4809 * (identity(SD),) (sensitivity)>
4812 * m will always be freed.
4815 key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
4817 struct sadb_sa *sa0;
4818 struct sadb_address *src0, *dst0;
4820 struct sadb_x_nat_t_type *type;
4821 struct sadb_x_nat_t_port *sport, *dport;
4822 struct sadb_address *iaddr, *raddr;
4823 struct sadb_x_nat_t_frag *frag;
4825 struct secasindex saidx;
4826 struct secashead *sah;
4827 struct secasvar *sav;
4833 IPSEC_ASSERT(so != NULL, ("null socket"));
4834 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4835 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4836 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4838 /* map satype to proto */
4839 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4840 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4842 return key_senderror(so, m, EINVAL);
4845 if (mhp->ext[SADB_EXT_SA] == NULL ||
4846 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4847 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4848 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4849 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4850 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4851 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4852 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4853 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4854 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4855 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4856 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4858 return key_senderror(so, m, EINVAL);
4860 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4861 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4862 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4863 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4865 return key_senderror(so, m, EINVAL);
4867 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4868 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4869 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4871 mode = IPSEC_MODE_ANY;
4874 /* XXX boundary checking for other extensions */
4876 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4877 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4878 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4880 /* XXX boundary check against sa_len */
4881 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4884 * Make sure the port numbers are zero.
4885 * In case of NAT-T we will update them later if needed.
4887 KEY_PORTTOSADDR(&saidx.src, 0);
4888 KEY_PORTTOSADDR(&saidx.dst, 0);
4892 * Handle NAT-T info if present.
4894 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
4895 mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
4896 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
4898 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
4899 mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
4900 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
4901 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
4903 return key_senderror(so, m, EINVAL);
4906 type = (struct sadb_x_nat_t_type *)
4907 mhp->ext[SADB_X_EXT_NAT_T_TYPE];
4908 sport = (struct sadb_x_nat_t_port *)
4909 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
4910 dport = (struct sadb_x_nat_t_port *)
4911 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
4916 if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
4917 mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
4918 if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
4919 mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
4920 ipseclog((LOG_DEBUG, "%s: invalid message\n",
4922 return key_senderror(so, m, EINVAL);
4924 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
4925 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
4926 ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
4928 iaddr = raddr = NULL;
4930 if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
4931 if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
4932 ipseclog((LOG_DEBUG, "%s: invalid message\n",
4934 return key_senderror(so, m, EINVAL);
4936 frag = (struct sadb_x_nat_t_frag *)
4937 mhp->ext[SADB_X_EXT_NAT_T_FRAG];
4943 /* get a SA header */
4944 if ((sah = key_getsah(&saidx)) == NULL) {
4945 ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
4946 return key_senderror(so, m, ENOENT);
4949 /* set spidx if there */
4951 error = key_setident(sah, m, mhp);
4953 return key_senderror(so, m, error);
4955 /* find a SA with sequence number. */
4956 #ifdef IPSEC_DOSEQCHECK
4957 if (mhp->msg->sadb_msg_seq != 0
4958 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4959 ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
4960 "exists.\n", __func__, mhp->msg->sadb_msg_seq));
4961 return key_senderror(so, m, ENOENT);
4965 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
4968 ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
4969 __func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4970 return key_senderror(so, m, EINVAL);
4974 /* validity check */
4975 if (sav->sah->saidx.proto != proto) {
4976 ipseclog((LOG_DEBUG, "%s: protocol mismatched "
4977 "(DB=%u param=%u)\n", __func__,
4978 sav->sah->saidx.proto, proto));
4979 return key_senderror(so, m, EINVAL);
4981 #ifdef IPSEC_DOSEQCHECK
4982 if (sav->spi != sa0->sadb_sa_spi) {
4983 ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
4985 (u_int32_t)ntohl(sav->spi),
4986 (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4987 return key_senderror(so, m, EINVAL);
4990 if (sav->pid != mhp->msg->sadb_msg_pid) {
4991 ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
4992 __func__, sav->pid, mhp->msg->sadb_msg_pid));
4993 return key_senderror(so, m, EINVAL);
4996 /* copy sav values */
4997 error = key_setsaval(sav, m, mhp);
5000 return key_senderror(so, m, error);
5005 * Handle more NAT-T info if present,
5006 * now that we have a sav to fill.
5009 sav->natt_type = type->sadb_x_nat_t_type_type;
5012 KEY_PORTTOSADDR(&sav->sah->saidx.src,
5013 sport->sadb_x_nat_t_port_port);
5015 KEY_PORTTOSADDR(&sav->sah->saidx.dst,
5016 dport->sadb_x_nat_t_port_port);
5020 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5021 * We should actually check for a minimum MTU here, if we
5022 * want to support it in ip_output.
5025 sav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5029 /* check SA values to be mature. */
5030 if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
5032 return key_senderror(so, m, 0);
5038 /* set msg buf from mhp */
5039 n = key_getmsgbuf_x1(m, mhp);
5041 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5042 return key_senderror(so, m, ENOBUFS);
5046 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5051 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5052 * only called by key_update().
5055 * others : found, pointer to a SA.
5057 #ifdef IPSEC_DOSEQCHECK
5058 static struct secasvar *
5059 key_getsavbyseq(struct secashead *sah, u_int32_t seq)
5061 struct secasvar *sav;
5064 state = SADB_SASTATE_LARVAL;
5066 /* search SAD with sequence number ? */
5067 LIST_FOREACH(sav, &sah->savtree[state], chain) {
5069 KEY_CHKSASTATE(state, sav->state, __func__);
5071 if (sav->seq == seq) {
5073 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
5074 printf("DP %s cause refcnt++:%d SA:%p\n",
5075 __func__, sav->refcnt, sav));
5085 * SADB_ADD processing
5086 * add an entry to SA database, when received
5087 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5088 * key(AE), (identity(SD),) (sensitivity)>
5091 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5092 * (identity(SD),) (sensitivity)>
5095 * IGNORE identity and sensitivity messages.
5097 * m will always be freed.
5100 key_add(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5102 struct sadb_sa *sa0;
5103 struct sadb_address *src0, *dst0;
5105 struct sadb_x_nat_t_type *type;
5106 struct sadb_address *iaddr, *raddr;
5107 struct sadb_x_nat_t_frag *frag;
5109 struct secasindex saidx;
5110 struct secashead *newsah;
5111 struct secasvar *newsav;
5117 IPSEC_ASSERT(so != NULL, ("null socket"));
5118 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5119 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5120 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5122 /* map satype to proto */
5123 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5124 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5126 return key_senderror(so, m, EINVAL);
5129 if (mhp->ext[SADB_EXT_SA] == NULL ||
5130 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5131 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5132 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5133 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5134 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5135 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5136 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5137 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5138 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5139 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5140 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5142 return key_senderror(so, m, EINVAL);
5144 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5145 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5146 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5148 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5150 return key_senderror(so, m, EINVAL);
5152 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5153 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5154 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5156 mode = IPSEC_MODE_ANY;
5160 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5161 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5162 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5164 /* XXX boundary check against sa_len */
5165 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5168 * Make sure the port numbers are zero.
5169 * In case of NAT-T we will update them later if needed.
5171 KEY_PORTTOSADDR(&saidx.src, 0);
5172 KEY_PORTTOSADDR(&saidx.dst, 0);
5176 * Handle NAT-T info if present.
5178 if (mhp->ext[SADB_X_EXT_NAT_T_TYPE] != NULL &&
5179 mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5180 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5181 struct sadb_x_nat_t_port *sport, *dport;
5183 if (mhp->extlen[SADB_X_EXT_NAT_T_TYPE] < sizeof(*type) ||
5184 mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5185 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5186 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5188 return key_senderror(so, m, EINVAL);
5191 type = (struct sadb_x_nat_t_type *)
5192 mhp->ext[SADB_X_EXT_NAT_T_TYPE];
5193 sport = (struct sadb_x_nat_t_port *)
5194 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5195 dport = (struct sadb_x_nat_t_port *)
5196 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5199 KEY_PORTTOSADDR(&saidx.src,
5200 sport->sadb_x_nat_t_port_port);
5202 KEY_PORTTOSADDR(&saidx.dst,
5203 dport->sadb_x_nat_t_port_port);
5207 if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL &&
5208 mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) {
5209 if (mhp->extlen[SADB_X_EXT_NAT_T_OAI] < sizeof(*iaddr) ||
5210 mhp->extlen[SADB_X_EXT_NAT_T_OAR] < sizeof(*raddr)) {
5211 ipseclog((LOG_DEBUG, "%s: invalid message\n",
5213 return key_senderror(so, m, EINVAL);
5215 iaddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAI];
5216 raddr = (struct sadb_address *)mhp->ext[SADB_X_EXT_NAT_T_OAR];
5217 ipseclog((LOG_DEBUG, "%s: NAT-T OAi/r present\n", __func__));
5219 iaddr = raddr = NULL;
5221 if (mhp->ext[SADB_X_EXT_NAT_T_FRAG] != NULL) {
5222 if (mhp->extlen[SADB_X_EXT_NAT_T_FRAG] < sizeof(*frag)) {
5223 ipseclog((LOG_DEBUG, "%s: invalid message\n",
5225 return key_senderror(so, m, EINVAL);
5227 frag = (struct sadb_x_nat_t_frag *)
5228 mhp->ext[SADB_X_EXT_NAT_T_FRAG];
5234 /* get a SA header */
5235 if ((newsah = key_getsah(&saidx)) == NULL) {
5236 /* create a new SA header */
5237 if ((newsah = key_newsah(&saidx)) == NULL) {
5238 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
5239 return key_senderror(so, m, ENOBUFS);
5243 /* set spidx if there */
5245 error = key_setident(newsah, m, mhp);
5247 return key_senderror(so, m, error);
5250 /* create new SA entry. */
5251 /* We can create new SA only if SPI is differenct. */
5253 newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
5255 if (newsav != NULL) {
5256 ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
5257 return key_senderror(so, m, EEXIST);
5259 newsav = KEY_NEWSAV(m, mhp, newsah, &error);
5260 if (newsav == NULL) {
5261 return key_senderror(so, m, error);
5266 * Handle more NAT-T info if present,
5267 * now that we have a sav to fill.
5270 newsav->natt_type = type->sadb_x_nat_t_type_type;
5274 * In case SADB_X_EXT_NAT_T_FRAG was not given, leave it at 0.
5275 * We should actually check for a minimum MTU here, if we
5276 * want to support it in ip_output.
5279 newsav->natt_esp_frag_len = frag->sadb_x_nat_t_frag_fraglen;
5283 /* check SA values to be mature. */
5284 if ((error = key_mature(newsav)) != 0) {
5285 KEY_FREESAV(&newsav);
5286 return key_senderror(so, m, error);
5290 * don't call key_freesav() here, as we would like to keep the SA
5291 * in the database on success.
5297 /* set msg buf from mhp */
5298 n = key_getmsgbuf_x1(m, mhp);
5300 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5301 return key_senderror(so, m, ENOBUFS);
5305 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5311 key_setident(struct secashead *sah, struct mbuf *m,
5312 const struct sadb_msghdr *mhp)
5314 const struct sadb_ident *idsrc, *iddst;
5315 int idsrclen, iddstlen;
5317 IPSEC_ASSERT(sah != NULL, ("null secashead"));
5318 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5319 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5320 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5322 /* don't make buffer if not there */
5323 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5324 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5330 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5331 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5332 ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
5336 idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5337 iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5338 idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5339 iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5341 /* validity check */
5342 if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5343 ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
5347 switch (idsrc->sadb_ident_type) {
5348 case SADB_IDENTTYPE_PREFIX:
5349 case SADB_IDENTTYPE_FQDN:
5350 case SADB_IDENTTYPE_USERFQDN:
5352 /* XXX do nothing */
5358 /* make structure */
5359 sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5360 if (sah->idents == NULL) {
5361 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5364 sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5365 if (sah->identd == NULL) {
5366 free(sah->idents, M_IPSEC_MISC);
5368 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5371 sah->idents->type = idsrc->sadb_ident_type;
5372 sah->idents->id = idsrc->sadb_ident_id;
5374 sah->identd->type = iddst->sadb_ident_type;
5375 sah->identd->id = iddst->sadb_ident_id;
5381 * m will not be freed on return.
5382 * it is caller's responsibility to free the result.
5384 static struct mbuf *
5385 key_getmsgbuf_x1(struct mbuf *m, const struct sadb_msghdr *mhp)
5389 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5390 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5391 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5393 /* create new sadb_msg to reply. */
5394 n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5395 SADB_EXT_SA, SADB_X_EXT_SA2,
5396 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5397 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5398 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5402 if (n->m_len < sizeof(struct sadb_msg)) {
5403 n = m_pullup(n, sizeof(struct sadb_msg));
5407 mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5408 mtod(n, struct sadb_msg *)->sadb_msg_len =
5409 PFKEY_UNIT64(n->m_pkthdr.len);
5415 * SADB_DELETE processing
5417 * <base, SA(*), address(SD)>
5418 * from the ikmpd, and set SADB_SASTATE_DEAD,
5420 * <base, SA(*), address(SD)>
5423 * m will always be freed.
5426 key_delete(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5428 struct sadb_sa *sa0;
5429 struct sadb_address *src0, *dst0;
5430 struct secasindex saidx;
5431 struct secashead *sah;
5432 struct secasvar *sav = NULL;
5435 IPSEC_ASSERT(so != NULL, ("null socket"));
5436 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5437 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5438 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5440 /* map satype to proto */
5441 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5442 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5444 return key_senderror(so, m, EINVAL);
5447 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5448 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5449 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5451 return key_senderror(so, m, EINVAL);
5454 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5455 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5456 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5458 return key_senderror(so, m, EINVAL);
5461 if (mhp->ext[SADB_EXT_SA] == NULL) {
5463 * Caller wants us to delete all non-LARVAL SAs
5464 * that match the src/dst. This is used during
5465 * IKE INITIAL-CONTACT.
5467 ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5468 return key_delete_all(so, m, mhp, proto);
5469 } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5470 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5472 return key_senderror(so, m, EINVAL);
5475 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5476 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5477 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5479 /* XXX boundary check against sa_len */
5480 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5483 * Make sure the port numbers are zero.
5484 * In case of NAT-T we will update them later if needed.
5486 KEY_PORTTOSADDR(&saidx.src, 0);
5487 KEY_PORTTOSADDR(&saidx.dst, 0);
5491 * Handle NAT-T info if present.
5493 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5494 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5495 struct sadb_x_nat_t_port *sport, *dport;
5497 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5498 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5499 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5501 return key_senderror(so, m, EINVAL);
5504 sport = (struct sadb_x_nat_t_port *)
5505 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5506 dport = (struct sadb_x_nat_t_port *)
5507 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5510 KEY_PORTTOSADDR(&saidx.src,
5511 sport->sadb_x_nat_t_port_port);
5513 KEY_PORTTOSADDR(&saidx.dst,
5514 dport->sadb_x_nat_t_port_port);
5518 /* get a SA header */
5520 LIST_FOREACH(sah, &V_sahtree, chain) {
5521 if (sah->state == SADB_SASTATE_DEAD)
5523 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5526 /* get a SA with SPI. */
5527 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5533 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5534 return key_senderror(so, m, ENOENT);
5537 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5543 struct sadb_msg *newmsg;
5545 /* create new sadb_msg to reply. */
5546 /* XXX-BZ NAT-T extensions? */
5547 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5548 SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5550 return key_senderror(so, m, ENOBUFS);
5552 if (n->m_len < sizeof(struct sadb_msg)) {
5553 n = m_pullup(n, sizeof(struct sadb_msg));
5555 return key_senderror(so, m, ENOBUFS);
5557 newmsg = mtod(n, struct sadb_msg *);
5558 newmsg->sadb_msg_errno = 0;
5559 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5562 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5567 * delete all SAs for src/dst. Called from key_delete().
5570 key_delete_all(struct socket *so, struct mbuf *m,
5571 const struct sadb_msghdr *mhp, u_int16_t proto)
5573 struct sadb_address *src0, *dst0;
5574 struct secasindex saidx;
5575 struct secashead *sah;
5576 struct secasvar *sav, *nextsav;
5577 u_int stateidx, state;
5579 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5580 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5582 /* XXX boundary check against sa_len */
5583 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5586 * Make sure the port numbers are zero.
5587 * In case of NAT-T we will update them later if needed.
5589 KEY_PORTTOSADDR(&saidx.src, 0);
5590 KEY_PORTTOSADDR(&saidx.dst, 0);
5594 * Handle NAT-T info if present.
5597 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5598 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5599 struct sadb_x_nat_t_port *sport, *dport;
5601 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5602 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5603 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5605 return key_senderror(so, m, EINVAL);
5608 sport = (struct sadb_x_nat_t_port *)
5609 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5610 dport = (struct sadb_x_nat_t_port *)
5611 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5614 KEY_PORTTOSADDR(&saidx.src,
5615 sport->sadb_x_nat_t_port_port);
5617 KEY_PORTTOSADDR(&saidx.dst,
5618 dport->sadb_x_nat_t_port_port);
5623 LIST_FOREACH(sah, &V_sahtree, chain) {
5624 if (sah->state == SADB_SASTATE_DEAD)
5626 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5629 /* Delete all non-LARVAL SAs. */
5631 stateidx < _ARRAYLEN(saorder_state_alive);
5633 state = saorder_state_alive[stateidx];
5634 if (state == SADB_SASTATE_LARVAL)
5636 for (sav = LIST_FIRST(&sah->savtree[state]);
5637 sav != NULL; sav = nextsav) {
5638 nextsav = LIST_NEXT(sav, chain);
5640 if (sav->state != state) {
5641 ipseclog((LOG_DEBUG, "%s: invalid "
5642 "sav->state (queue %d SA %d)\n",
5643 __func__, state, sav->state));
5647 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5655 struct sadb_msg *newmsg;
5657 /* create new sadb_msg to reply. */
5658 /* XXX-BZ NAT-T extensions? */
5659 n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5660 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5662 return key_senderror(so, m, ENOBUFS);
5664 if (n->m_len < sizeof(struct sadb_msg)) {
5665 n = m_pullup(n, sizeof(struct sadb_msg));
5667 return key_senderror(so, m, ENOBUFS);
5669 newmsg = mtod(n, struct sadb_msg *);
5670 newmsg->sadb_msg_errno = 0;
5671 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5674 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5679 * SADB_GET processing
5681 * <base, SA(*), address(SD)>
5682 * from the ikmpd, and get a SP and a SA to respond,
5684 * <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5685 * (identity(SD),) (sensitivity)>
5688 * m will always be freed.
5691 key_get(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
5693 struct sadb_sa *sa0;
5694 struct sadb_address *src0, *dst0;
5695 struct secasindex saidx;
5696 struct secashead *sah;
5697 struct secasvar *sav = NULL;
5700 IPSEC_ASSERT(so != NULL, ("null socket"));
5701 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5702 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5703 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5705 /* map satype to proto */
5706 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5707 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5709 return key_senderror(so, m, EINVAL);
5712 if (mhp->ext[SADB_EXT_SA] == NULL ||
5713 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5714 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5715 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5717 return key_senderror(so, m, EINVAL);
5719 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5720 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5721 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5722 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5724 return key_senderror(so, m, EINVAL);
5727 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5728 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5729 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5731 /* XXX boundary check against sa_len */
5732 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5735 * Make sure the port numbers are zero.
5736 * In case of NAT-T we will update them later if needed.
5738 KEY_PORTTOSADDR(&saidx.src, 0);
5739 KEY_PORTTOSADDR(&saidx.dst, 0);
5743 * Handle NAT-T info if present.
5746 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
5747 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
5748 struct sadb_x_nat_t_port *sport, *dport;
5750 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
5751 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
5752 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
5754 return key_senderror(so, m, EINVAL);
5757 sport = (struct sadb_x_nat_t_port *)
5758 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
5759 dport = (struct sadb_x_nat_t_port *)
5760 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
5763 KEY_PORTTOSADDR(&saidx.src,
5764 sport->sadb_x_nat_t_port_port);
5766 KEY_PORTTOSADDR(&saidx.dst,
5767 dport->sadb_x_nat_t_port_port);
5771 /* get a SA header */
5773 LIST_FOREACH(sah, &V_sahtree, chain) {
5774 if (sah->state == SADB_SASTATE_DEAD)
5776 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5779 /* get a SA with SPI. */
5780 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5786 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5787 return key_senderror(so, m, ENOENT);
5794 /* map proto to satype */
5795 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5796 ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5798 return key_senderror(so, m, EINVAL);
5801 /* create new sadb_msg to reply. */
5802 n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5803 mhp->msg->sadb_msg_pid);
5805 return key_senderror(so, m, ENOBUFS);
5808 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5812 /* XXX make it sysctl-configurable? */
5814 key_getcomb_setlifetime(struct sadb_comb *comb)
5817 comb->sadb_comb_soft_allocations = 1;
5818 comb->sadb_comb_hard_allocations = 1;
5819 comb->sadb_comb_soft_bytes = 0;
5820 comb->sadb_comb_hard_bytes = 0;
5821 comb->sadb_comb_hard_addtime = 86400; /* 1 day */
5822 comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5823 comb->sadb_comb_soft_usetime = 28800; /* 8 hours */
5824 comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5828 * XXX reorder combinations by preference
5829 * XXX no idea if the user wants ESP authentication or not
5831 static struct mbuf *
5834 struct sadb_comb *comb;
5835 struct enc_xform *algo;
5836 struct mbuf *result = NULL, *m, *n;
5840 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5843 for (i = 1; i <= SADB_EALG_MAX; i++) {
5844 algo = esp_algorithm_lookup(i);
5848 /* discard algorithms with key size smaller than system min */
5849 if (_BITS(algo->maxkey) < V_ipsec_esp_keymin)
5851 if (_BITS(algo->minkey) < V_ipsec_esp_keymin)
5852 encmin = V_ipsec_esp_keymin;
5854 encmin = _BITS(algo->minkey);
5856 if (V_ipsec_esp_auth)
5857 m = key_getcomb_ah();
5859 IPSEC_ASSERT(l <= MLEN,
5860 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
5861 MGET(m, M_NOWAIT, MT_DATA);
5866 bzero(mtod(m, caddr_t), m->m_len);
5873 for (n = m; n; n = n->m_next)
5875 IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
5877 for (off = 0; off < totlen; off += l) {
5878 n = m_pulldown(m, off, l, &o);
5880 /* m is already freed */
5883 comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5884 bzero(comb, sizeof(*comb));
5885 key_getcomb_setlifetime(comb);
5886 comb->sadb_comb_encrypt = i;
5887 comb->sadb_comb_encrypt_minbits = encmin;
5888 comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5906 key_getsizes_ah(const struct auth_hash *ah, int alg, u_int16_t* min,
5910 *min = *max = ah->keysize;
5911 if (ah->keysize == 0) {
5913 * Transform takes arbitrary key size but algorithm
5914 * key size is restricted. Enforce this here.
5917 case SADB_X_AALG_MD5: *min = *max = 16; break;
5918 case SADB_X_AALG_SHA: *min = *max = 20; break;
5919 case SADB_X_AALG_NULL: *min = 1; *max = 256; break;
5920 case SADB_X_AALG_SHA2_256: *min = *max = 32; break;
5921 case SADB_X_AALG_SHA2_384: *min = *max = 48; break;
5922 case SADB_X_AALG_SHA2_512: *min = *max = 64; break;
5924 DPRINTF(("%s: unknown AH algorithm %u\n",
5932 * XXX reorder combinations by preference
5934 static struct mbuf *
5937 struct sadb_comb *comb;
5938 struct auth_hash *algo;
5940 u_int16_t minkeysize, maxkeysize;
5942 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5945 for (i = 1; i <= SADB_AALG_MAX; i++) {
5947 /* we prefer HMAC algorithms, not old algorithms */
5948 if (i != SADB_AALG_SHA1HMAC &&
5949 i != SADB_AALG_MD5HMAC &&
5950 i != SADB_X_AALG_SHA2_256 &&
5951 i != SADB_X_AALG_SHA2_384 &&
5952 i != SADB_X_AALG_SHA2_512)
5955 algo = ah_algorithm_lookup(i);
5958 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5959 /* discard algorithms with key size smaller than system min */
5960 if (_BITS(minkeysize) < V_ipsec_ah_keymin)
5964 IPSEC_ASSERT(l <= MLEN,
5965 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
5966 MGET(m, M_NOWAIT, MT_DATA);
5973 M_PREPEND(m, l, M_NOWAIT);
5977 comb = mtod(m, struct sadb_comb *);
5978 bzero(comb, sizeof(*comb));
5979 key_getcomb_setlifetime(comb);
5980 comb->sadb_comb_auth = i;
5981 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5982 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5989 * not really an official behavior. discussed in pf_key@inner.net in Sep2000.
5990 * XXX reorder combinations by preference
5992 static struct mbuf *
5993 key_getcomb_ipcomp()
5995 struct sadb_comb *comb;
5996 struct comp_algo *algo;
5999 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6002 for (i = 1; i <= SADB_X_CALG_MAX; i++) {
6003 algo = ipcomp_algorithm_lookup(i);
6008 IPSEC_ASSERT(l <= MLEN,
6009 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
6010 MGET(m, M_NOWAIT, MT_DATA);
6017 M_PREPEND(m, l, M_NOWAIT);
6021 comb = mtod(m, struct sadb_comb *);
6022 bzero(comb, sizeof(*comb));
6023 key_getcomb_setlifetime(comb);
6024 comb->sadb_comb_encrypt = i;
6025 /* what should we set into sadb_comb_*_{min,max}bits? */
6032 * XXX no way to pass mode (transport/tunnel) to userland
6033 * XXX replay checking?
6034 * XXX sysctl interface to ipsec_{ah,esp}_keymin
6036 static struct mbuf *
6037 key_getprop(const struct secasindex *saidx)
6039 struct sadb_prop *prop;
6041 const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
6044 switch (saidx->proto) {
6046 m = key_getcomb_esp();
6049 m = key_getcomb_ah();
6051 case IPPROTO_IPCOMP:
6052 m = key_getcomb_ipcomp();
6060 M_PREPEND(m, l, M_NOWAIT);
6065 for (n = m; n; n = n->m_next)
6068 prop = mtod(m, struct sadb_prop *);
6069 bzero(prop, sizeof(*prop));
6070 prop->sadb_prop_len = PFKEY_UNIT64(totlen);
6071 prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
6072 prop->sadb_prop_replay = 32; /* XXX */
6078 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
6080 * <base, SA, address(SD), (address(P)), x_policy,
6081 * (identity(SD),) (sensitivity,) proposal>
6082 * to KMD, and expect to receive
6083 * <base> with SADB_ACQUIRE if error occured,
6085 * <base, src address, dst address, (SPI range)> with SADB_GETSPI
6086 * from KMD by PF_KEY.
6088 * XXX x_policy is outside of RFC2367 (KAME extension).
6089 * XXX sensitivity is not supported.
6090 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
6091 * see comment for key_getcomb_ipcomp().
6095 * others: error number
6098 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
6100 struct mbuf *result = NULL, *m;
6101 struct secacq *newacq;
6106 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
6107 satype = key_proto2satype(saidx->proto);
6108 IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
6111 * We never do anything about acquirng SA. There is anather
6112 * solution that kernel blocks to send SADB_ACQUIRE message until
6113 * getting something message from IKEd. In later case, to be
6114 * managed with ACQUIRING list.
6116 /* Get an entry to check whether sending message or not. */
6117 if ((newacq = key_getacq(saidx)) != NULL) {
6118 if (V_key_blockacq_count < newacq->count) {
6119 /* reset counter and do send message. */
6122 /* increment counter and do nothing. */
6127 /* make new entry for blocking to send SADB_ACQUIRE. */
6128 if ((newacq = key_newacq(saidx)) == NULL)
6134 m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6142 * No SADB_X_EXT_NAT_T_* here: we do not know
6143 * anything related to NAT-T at this time.
6146 /* set sadb_address for saidx's. */
6147 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6148 &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6155 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6156 &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
6163 /* XXX proxy address (optional) */
6165 /* set sadb_x_policy */
6167 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6175 /* XXX identity (optional) */
6177 if (idexttype && fqdn) {
6178 /* create identity extension (FQDN) */
6179 struct sadb_ident *id;
6182 fqdnlen = strlen(fqdn) + 1; /* +1 for terminating-NUL */
6183 id = (struct sadb_ident *)p;
6184 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6185 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6186 id->sadb_ident_exttype = idexttype;
6187 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6188 bcopy(fqdn, id + 1, fqdnlen);
6189 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6193 /* create identity extension (USERFQDN) */
6194 struct sadb_ident *id;
6198 /* +1 for terminating-NUL */
6199 userfqdnlen = strlen(userfqdn) + 1;
6202 id = (struct sadb_ident *)p;
6203 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6204 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6205 id->sadb_ident_exttype = idexttype;
6206 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6207 /* XXX is it correct? */
6208 if (curproc && curproc->p_cred)
6209 id->sadb_ident_id = curproc->p_cred->p_ruid;
6210 if (userfqdn && userfqdnlen)
6211 bcopy(userfqdn, id + 1, userfqdnlen);
6212 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6216 /* XXX sensitivity (optional) */
6218 /* create proposal/combination extension */
6219 m = key_getprop(saidx);
6222 * spec conformant: always attach proposal/combination extension,
6223 * the problem is that we have no way to attach it for ipcomp,
6224 * due to the way sadb_comb is declared in RFC2367.
6233 * outside of spec; make proposal/combination extension optional.
6239 if ((result->m_flags & M_PKTHDR) == 0) {
6244 if (result->m_len < sizeof(struct sadb_msg)) {
6245 result = m_pullup(result, sizeof(struct sadb_msg));
6246 if (result == NULL) {
6252 result->m_pkthdr.len = 0;
6253 for (m = result; m; m = m->m_next)
6254 result->m_pkthdr.len += m->m_len;
6256 mtod(result, struct sadb_msg *)->sadb_msg_len =
6257 PFKEY_UNIT64(result->m_pkthdr.len);
6259 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6267 static struct secacq *
6268 key_newacq(const struct secasindex *saidx)
6270 struct secacq *newacq;
6273 newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6274 if (newacq == NULL) {
6275 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6280 bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
6281 newacq->seq = (V_acq_seq == ~0 ? 1 : ++V_acq_seq);
6282 newacq->created = time_second;
6285 /* add to acqtree */
6287 LIST_INSERT_HEAD(&V_acqtree, newacq, chain);
6293 static struct secacq *
6294 key_getacq(const struct secasindex *saidx)
6299 LIST_FOREACH(acq, &V_acqtree, chain) {
6300 if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6308 static struct secacq *
6309 key_getacqbyseq(u_int32_t seq)
6314 LIST_FOREACH(acq, &V_acqtree, chain) {
6315 if (acq->seq == seq)
6323 static struct secspacq *
6324 key_newspacq(struct secpolicyindex *spidx)
6326 struct secspacq *acq;
6329 acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
6331 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6336 bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6337 acq->created = time_second;
6340 /* add to spacqtree */
6342 LIST_INSERT_HEAD(&V_spacqtree, acq, chain);
6348 static struct secspacq *
6349 key_getspacq(struct secpolicyindex *spidx)
6351 struct secspacq *acq;
6354 LIST_FOREACH(acq, &V_spacqtree, chain) {
6355 if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
6356 /* NB: return holding spacq_lock */
6366 * SADB_ACQUIRE processing,
6367 * in first situation, is receiving
6369 * from the ikmpd, and clear sequence of its secasvar entry.
6371 * In second situation, is receiving
6372 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6373 * from a user land process, and return
6374 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6377 * m will always be freed.
6380 key_acquire2(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6382 const struct sadb_address *src0, *dst0;
6383 struct secasindex saidx;
6384 struct secashead *sah;
6388 IPSEC_ASSERT(so != NULL, ("null socket"));
6389 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6390 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6391 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6394 * Error message from KMd.
6395 * We assume that if error was occured in IKEd, the length of PFKEY
6396 * message is equal to the size of sadb_msg structure.
6397 * We do not raise error even if error occured in this function.
6399 if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6402 /* check sequence number */
6403 if (mhp->msg->sadb_msg_seq == 0) {
6404 ipseclog((LOG_DEBUG, "%s: must specify sequence "
6405 "number.\n", __func__));
6410 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6412 * the specified larval SA is already gone, or we got
6413 * a bogus sequence number. we can silently ignore it.
6419 /* reset acq counter in order to deletion by timehander. */
6420 acq->created = time_second;
6427 * This message is from user land.
6430 /* map satype to proto */
6431 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6432 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6434 return key_senderror(so, m, EINVAL);
6437 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6438 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6439 mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6441 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6443 return key_senderror(so, m, EINVAL);
6445 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6446 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6447 mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6449 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
6451 return key_senderror(so, m, EINVAL);
6454 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6455 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6457 /* XXX boundary check against sa_len */
6458 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6461 * Make sure the port numbers are zero.
6462 * In case of NAT-T we will update them later if needed.
6464 KEY_PORTTOSADDR(&saidx.src, 0);
6465 KEY_PORTTOSADDR(&saidx.dst, 0);
6469 * Handle NAT-T info if present.
6472 if (mhp->ext[SADB_X_EXT_NAT_T_SPORT] != NULL &&
6473 mhp->ext[SADB_X_EXT_NAT_T_DPORT] != NULL) {
6474 struct sadb_x_nat_t_port *sport, *dport;
6476 if (mhp->extlen[SADB_X_EXT_NAT_T_SPORT] < sizeof(*sport) ||
6477 mhp->extlen[SADB_X_EXT_NAT_T_DPORT] < sizeof(*dport)) {
6478 ipseclog((LOG_DEBUG, "%s: invalid message.\n",
6480 return key_senderror(so, m, EINVAL);
6483 sport = (struct sadb_x_nat_t_port *)
6484 mhp->ext[SADB_X_EXT_NAT_T_SPORT];
6485 dport = (struct sadb_x_nat_t_port *)
6486 mhp->ext[SADB_X_EXT_NAT_T_DPORT];
6489 KEY_PORTTOSADDR(&saidx.src,
6490 sport->sadb_x_nat_t_port_port);
6492 KEY_PORTTOSADDR(&saidx.dst,
6493 dport->sadb_x_nat_t_port_port);
6497 /* get a SA index */
6499 LIST_FOREACH(sah, &V_sahtree, chain) {
6500 if (sah->state == SADB_SASTATE_DEAD)
6502 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6507 ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6508 return key_senderror(so, m, EEXIST);
6511 error = key_acquire(&saidx, NULL);
6513 ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6514 __func__, mhp->msg->sadb_msg_errno));
6515 return key_senderror(so, m, error);
6518 return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6522 * SADB_REGISTER processing.
6523 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6526 * from the ikmpd, and register a socket to send PF_KEY messages,
6530 * If socket is detached, must free from regnode.
6532 * m will always be freed.
6535 key_register(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6537 struct secreg *reg, *newreg = 0;
6539 IPSEC_ASSERT(so != NULL, ("null socket"));
6540 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6541 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6542 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6544 /* check for invalid register message */
6545 if (mhp->msg->sadb_msg_satype >= sizeof(V_regtree)/sizeof(V_regtree[0]))
6546 return key_senderror(so, m, EINVAL);
6548 /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6549 if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6552 /* check whether existing or not */
6554 LIST_FOREACH(reg, &V_regtree[mhp->msg->sadb_msg_satype], chain) {
6555 if (reg->so == so) {
6557 ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6559 return key_senderror(so, m, EEXIST);
6563 /* create regnode */
6564 newreg = malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6565 if (newreg == NULL) {
6567 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6568 return key_senderror(so, m, ENOBUFS);
6572 ((struct keycb *)sotorawcb(so))->kp_registered++;
6574 /* add regnode to regtree. */
6575 LIST_INSERT_HEAD(&V_regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6581 struct sadb_msg *newmsg;
6582 struct sadb_supported *sup;
6583 u_int len, alen, elen;
6586 struct sadb_alg *alg;
6588 /* create new sadb_msg to reply. */
6590 for (i = 1; i <= SADB_AALG_MAX; i++) {
6591 if (ah_algorithm_lookup(i))
6592 alen += sizeof(struct sadb_alg);
6595 alen += sizeof(struct sadb_supported);
6597 for (i = 1; i <= SADB_EALG_MAX; i++) {
6598 if (esp_algorithm_lookup(i))
6599 elen += sizeof(struct sadb_alg);
6602 elen += sizeof(struct sadb_supported);
6604 len = sizeof(struct sadb_msg) + alen + elen;
6607 return key_senderror(so, m, ENOBUFS);
6609 MGETHDR(n, M_NOWAIT, MT_DATA);
6611 if (!(MCLGET(n, M_NOWAIT))) {
6617 return key_senderror(so, m, ENOBUFS);
6619 n->m_pkthdr.len = n->m_len = len;
6623 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6624 newmsg = mtod(n, struct sadb_msg *);
6625 newmsg->sadb_msg_errno = 0;
6626 newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6627 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6629 /* for authentication algorithm */
6631 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6632 sup->sadb_supported_len = PFKEY_UNIT64(alen);
6633 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6634 off += PFKEY_ALIGN8(sizeof(*sup));
6636 for (i = 1; i <= SADB_AALG_MAX; i++) {
6637 struct auth_hash *aalgo;
6638 u_int16_t minkeysize, maxkeysize;
6640 aalgo = ah_algorithm_lookup(i);
6643 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6644 alg->sadb_alg_id = i;
6645 alg->sadb_alg_ivlen = 0;
6646 key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6647 alg->sadb_alg_minbits = _BITS(minkeysize);
6648 alg->sadb_alg_maxbits = _BITS(maxkeysize);
6649 off += PFKEY_ALIGN8(sizeof(*alg));
6653 /* for encryption algorithm */
6655 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6656 sup->sadb_supported_len = PFKEY_UNIT64(elen);
6657 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6658 off += PFKEY_ALIGN8(sizeof(*sup));
6660 for (i = 1; i <= SADB_EALG_MAX; i++) {
6661 struct enc_xform *ealgo;
6663 ealgo = esp_algorithm_lookup(i);
6666 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6667 alg->sadb_alg_id = i;
6668 alg->sadb_alg_ivlen = ealgo->blocksize;
6669 alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6670 alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6671 off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6675 IPSEC_ASSERT(off == len,
6676 ("length assumption failed (off %u len %u)", off, len));
6679 return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6684 * free secreg entry registered.
6685 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6688 key_freereg(struct socket *so)
6693 IPSEC_ASSERT(so != NULL, ("NULL so"));
6696 * check whether existing or not.
6697 * check all type of SA, because there is a potential that
6698 * one socket is registered to multiple type of SA.
6701 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6702 LIST_FOREACH(reg, &V_regtree[i], chain) {
6703 if (reg->so == so && __LIST_CHAINED(reg)) {
6704 LIST_REMOVE(reg, chain);
6705 free(reg, M_IPSEC_SAR);
6714 * SADB_EXPIRE processing
6716 * <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6718 * NOTE: We send only soft lifetime extension.
6721 * others : error number
6724 key_expire(struct secasvar *sav)
6727 struct mbuf *result = NULL, *m;
6730 struct sadb_lifetime *lt;
6732 IPSEC_ASSERT (sav != NULL, ("null sav"));
6733 IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6735 /* set msg header */
6736 satype = key_proto2satype(sav->sah->saidx.proto);
6737 IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6738 m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6745 /* create SA extension */
6746 m = key_setsadbsa(sav);
6753 /* create SA extension */
6754 m = key_setsadbxsa2(sav->sah->saidx.mode,
6755 sav->replay ? sav->replay->count : 0,
6756 sav->sah->saidx.reqid);
6763 /* create lifetime extension (current and soft) */
6764 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6765 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
6772 bzero(mtod(m, caddr_t), len);
6773 lt = mtod(m, struct sadb_lifetime *);
6774 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6775 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6776 lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6777 lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6778 lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6779 lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6780 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6781 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6782 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6783 lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6784 lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6785 lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6786 lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6789 /* set sadb_address for source */
6790 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6791 &sav->sah->saidx.src.sa,
6792 FULLMASK, IPSEC_ULPROTO_ANY);
6799 /* set sadb_address for destination */
6800 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6801 &sav->sah->saidx.dst.sa,
6802 FULLMASK, IPSEC_ULPROTO_ANY);
6810 * XXX-BZ Handle NAT-T extensions here.
6813 if ((result->m_flags & M_PKTHDR) == 0) {
6818 if (result->m_len < sizeof(struct sadb_msg)) {
6819 result = m_pullup(result, sizeof(struct sadb_msg));
6820 if (result == NULL) {
6826 result->m_pkthdr.len = 0;
6827 for (m = result; m; m = m->m_next)
6828 result->m_pkthdr.len += m->m_len;
6830 mtod(result, struct sadb_msg *)->sadb_msg_len =
6831 PFKEY_UNIT64(result->m_pkthdr.len);
6833 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6842 * SADB_FLUSH processing
6845 * from the ikmpd, and free all entries in secastree.
6849 * NOTE: to do is only marking SADB_SASTATE_DEAD.
6851 * m will always be freed.
6854 key_flush(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6856 struct sadb_msg *newmsg;
6857 struct secashead *sah, *nextsah;
6858 struct secasvar *sav, *nextsav;
6863 IPSEC_ASSERT(so != NULL, ("null socket"));
6864 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6865 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6867 /* map satype to proto */
6868 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6869 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6871 return key_senderror(so, m, EINVAL);
6874 /* no SATYPE specified, i.e. flushing all SA. */
6876 for (sah = LIST_FIRST(&V_sahtree);
6879 nextsah = LIST_NEXT(sah, chain);
6881 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6882 && proto != sah->saidx.proto)
6886 stateidx < _ARRAYLEN(saorder_state_alive);
6888 state = saorder_state_any[stateidx];
6889 for (sav = LIST_FIRST(&sah->savtree[state]);
6893 nextsav = LIST_NEXT(sav, chain);
6895 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6900 sah->state = SADB_SASTATE_DEAD;
6904 if (m->m_len < sizeof(struct sadb_msg) ||
6905 sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6906 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6907 return key_senderror(so, m, ENOBUFS);
6913 m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6914 newmsg = mtod(m, struct sadb_msg *);
6915 newmsg->sadb_msg_errno = 0;
6916 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6918 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6922 * SADB_DUMP processing
6923 * dump all entries including status of DEAD in SAD.
6926 * from the ikmpd, and dump all secasvar leaves
6931 * m will always be freed.
6934 key_dump(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
6936 struct secashead *sah;
6937 struct secasvar *sav;
6943 struct sadb_msg *newmsg;
6946 IPSEC_ASSERT(so != NULL, ("null socket"));
6947 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6948 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6949 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6951 /* map satype to proto */
6952 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6953 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6955 return key_senderror(so, m, EINVAL);
6958 /* count sav entries to be sent to the userland. */
6961 LIST_FOREACH(sah, &V_sahtree, chain) {
6962 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6963 && proto != sah->saidx.proto)
6967 stateidx < _ARRAYLEN(saorder_state_any);
6969 state = saorder_state_any[stateidx];
6970 LIST_FOREACH(sav, &sah->savtree[state], chain) {
6978 return key_senderror(so, m, ENOENT);
6981 /* send this to the userland, one at a time. */
6983 LIST_FOREACH(sah, &V_sahtree, chain) {
6984 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6985 && proto != sah->saidx.proto)
6988 /* map proto to satype */
6989 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6991 ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
6992 "SAD.\n", __func__));
6993 return key_senderror(so, m, EINVAL);
6997 stateidx < _ARRAYLEN(saorder_state_any);
6999 state = saorder_state_any[stateidx];
7000 LIST_FOREACH(sav, &sah->savtree[state], chain) {
7001 n = key_setdumpsa(sav, SADB_DUMP, satype,
7002 --cnt, mhp->msg->sadb_msg_pid);
7005 return key_senderror(so, m, ENOBUFS);
7007 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
7018 * SADB_X_PROMISC processing
7020 * m will always be freed.
7023 key_promisc(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp)
7027 IPSEC_ASSERT(so != NULL, ("null socket"));
7028 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7029 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7030 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
7032 olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7034 if (olen < sizeof(struct sadb_msg)) {
7036 return key_senderror(so, m, EINVAL);
7041 } else if (olen == sizeof(struct sadb_msg)) {
7042 /* enable/disable promisc mode */
7045 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
7046 return key_senderror(so, m, EINVAL);
7047 mhp->msg->sadb_msg_errno = 0;
7048 switch (mhp->msg->sadb_msg_satype) {
7051 kp->kp_promisc = mhp->msg->sadb_msg_satype;
7054 return key_senderror(so, m, EINVAL);
7057 /* send the original message back to everyone */
7058 mhp->msg->sadb_msg_errno = 0;
7059 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7061 /* send packet as is */
7063 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
7065 /* TODO: if sadb_msg_seq is specified, send to specific pid */
7066 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
7070 static int (*key_typesw[])(struct socket *, struct mbuf *,
7071 const struct sadb_msghdr *) = {
7072 NULL, /* SADB_RESERVED */
7073 key_getspi, /* SADB_GETSPI */
7074 key_update, /* SADB_UPDATE */
7075 key_add, /* SADB_ADD */
7076 key_delete, /* SADB_DELETE */
7077 key_get, /* SADB_GET */
7078 key_acquire2, /* SADB_ACQUIRE */
7079 key_register, /* SADB_REGISTER */
7080 NULL, /* SADB_EXPIRE */
7081 key_flush, /* SADB_FLUSH */
7082 key_dump, /* SADB_DUMP */
7083 key_promisc, /* SADB_X_PROMISC */
7084 NULL, /* SADB_X_PCHANGE */
7085 key_spdadd, /* SADB_X_SPDUPDATE */
7086 key_spdadd, /* SADB_X_SPDADD */
7087 key_spddelete, /* SADB_X_SPDDELETE */
7088 key_spdget, /* SADB_X_SPDGET */
7089 NULL, /* SADB_X_SPDACQUIRE */
7090 key_spddump, /* SADB_X_SPDDUMP */
7091 key_spdflush, /* SADB_X_SPDFLUSH */
7092 key_spdadd, /* SADB_X_SPDSETIDX */
7093 NULL, /* SADB_X_SPDEXPIRE */
7094 key_spddelete2, /* SADB_X_SPDDELETE2 */
7098 * parse sadb_msg buffer to process PFKEYv2,
7099 * and create a data to response if needed.
7100 * I think to be dealed with mbuf directly.
7102 * msgp : pointer to pointer to a received buffer pulluped.
7103 * This is rewrited to response.
7104 * so : pointer to socket.
7106 * length for buffer to send to user process.
7109 key_parse(struct mbuf *m, struct socket *so)
7111 struct sadb_msg *msg;
7112 struct sadb_msghdr mh;
7117 IPSEC_ASSERT(so != NULL, ("null socket"));
7118 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7120 #if 0 /*kdebug_sadb assumes msg in linear buffer*/
7121 KEYDEBUG(KEYDEBUG_KEY_DUMP,
7122 ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
7126 if (m->m_len < sizeof(struct sadb_msg)) {
7127 m = m_pullup(m, sizeof(struct sadb_msg));
7131 msg = mtod(m, struct sadb_msg *);
7132 orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7133 target = KEY_SENDUP_ONE;
7135 if ((m->m_flags & M_PKTHDR) == 0 ||
7136 m->m_pkthdr.len != m->m_pkthdr.len) {
7137 ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
7138 PFKEYSTAT_INC(out_invlen);
7143 if (msg->sadb_msg_version != PF_KEY_V2) {
7144 ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
7145 __func__, msg->sadb_msg_version));
7146 PFKEYSTAT_INC(out_invver);
7151 if (msg->sadb_msg_type > SADB_MAX) {
7152 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7153 __func__, msg->sadb_msg_type));
7154 PFKEYSTAT_INC(out_invmsgtype);
7159 /* for old-fashioned code - should be nuked */
7160 if (m->m_pkthdr.len > MCLBYTES) {
7167 MGETHDR(n, M_NOWAIT, MT_DATA);
7168 if (n && m->m_pkthdr.len > MHLEN) {
7169 if (!(MCLGET(n, M_NOWAIT))) {
7178 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7179 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7185 /* align the mbuf chain so that extensions are in contiguous region. */
7186 error = key_align(m, &mh);
7193 switch (msg->sadb_msg_satype) {
7194 case SADB_SATYPE_UNSPEC:
7195 switch (msg->sadb_msg_type) {
7203 ipseclog((LOG_DEBUG, "%s: must specify satype "
7204 "when msg type=%u.\n", __func__,
7205 msg->sadb_msg_type));
7206 PFKEYSTAT_INC(out_invsatype);
7211 case SADB_SATYPE_AH:
7212 case SADB_SATYPE_ESP:
7213 case SADB_X_SATYPE_IPCOMP:
7214 case SADB_X_SATYPE_TCPSIGNATURE:
7215 switch (msg->sadb_msg_type) {
7217 case SADB_X_SPDDELETE:
7219 case SADB_X_SPDDUMP:
7220 case SADB_X_SPDFLUSH:
7221 case SADB_X_SPDSETIDX:
7222 case SADB_X_SPDUPDATE:
7223 case SADB_X_SPDDELETE2:
7224 ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
7225 __func__, msg->sadb_msg_type));
7226 PFKEYSTAT_INC(out_invsatype);
7231 case SADB_SATYPE_RSVP:
7232 case SADB_SATYPE_OSPFV2:
7233 case SADB_SATYPE_RIPV2:
7234 case SADB_SATYPE_MIP:
7235 ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
7236 __func__, msg->sadb_msg_satype));
7237 PFKEYSTAT_INC(out_invsatype);
7240 case 1: /* XXX: What does it do? */
7241 if (msg->sadb_msg_type == SADB_X_PROMISC)
7245 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
7246 __func__, msg->sadb_msg_satype));
7247 PFKEYSTAT_INC(out_invsatype);
7252 /* check field of upper layer protocol and address family */
7253 if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7254 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7255 struct sadb_address *src0, *dst0;
7258 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7259 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7261 /* check upper layer protocol */
7262 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7263 ipseclog((LOG_DEBUG, "%s: upper layer protocol "
7264 "mismatched.\n", __func__));
7265 PFKEYSTAT_INC(out_invaddr);
7271 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7272 PFKEY_ADDR_SADDR(dst0)->sa_family) {
7273 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
7275 PFKEYSTAT_INC(out_invaddr);
7279 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7280 PFKEY_ADDR_SADDR(dst0)->sa_len) {
7281 ipseclog((LOG_DEBUG, "%s: address struct size "
7282 "mismatched.\n", __func__));
7283 PFKEYSTAT_INC(out_invaddr);
7288 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7290 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7291 sizeof(struct sockaddr_in)) {
7292 PFKEYSTAT_INC(out_invaddr);
7298 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7299 sizeof(struct sockaddr_in6)) {
7300 PFKEYSTAT_INC(out_invaddr);
7306 ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
7308 PFKEYSTAT_INC(out_invaddr);
7309 error = EAFNOSUPPORT;
7313 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7315 plen = sizeof(struct in_addr) << 3;
7318 plen = sizeof(struct in6_addr) << 3;
7321 plen = 0; /*fool gcc*/
7325 /* check max prefix length */
7326 if (src0->sadb_address_prefixlen > plen ||
7327 dst0->sadb_address_prefixlen > plen) {
7328 ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
7330 PFKEYSTAT_INC(out_invaddr);
7336 * prefixlen == 0 is valid because there can be a case when
7337 * all addresses are matched.
7341 if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7342 key_typesw[msg->sadb_msg_type] == NULL) {
7343 PFKEYSTAT_INC(out_invmsgtype);
7348 return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7351 msg->sadb_msg_errno = error;
7352 return key_sendup_mbuf(so, m, target);
7356 key_senderror(struct socket *so, struct mbuf *m, int code)
7358 struct sadb_msg *msg;
7360 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7361 ("mbuf too small, len %u", m->m_len));
7363 msg = mtod(m, struct sadb_msg *);
7364 msg->sadb_msg_errno = code;
7365 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7369 * set the pointer to each header into message buffer.
7370 * m will be freed on error.
7371 * XXX larger-than-MCLBYTES extension?
7374 key_align(struct mbuf *m, struct sadb_msghdr *mhp)
7377 struct sadb_ext *ext;
7382 IPSEC_ASSERT(m != NULL, ("null mbuf"));
7383 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
7384 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
7385 ("mbuf too small, len %u", m->m_len));
7388 bzero(mhp, sizeof(*mhp));
7390 mhp->msg = mtod(m, struct sadb_msg *);
7391 mhp->ext[0] = (struct sadb_ext *)mhp->msg; /*XXX backward compat */
7393 end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7394 extlen = end; /*just in case extlen is not updated*/
7395 for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7396 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7398 /* m is already freed */
7401 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7404 switch (ext->sadb_ext_type) {
7406 case SADB_EXT_ADDRESS_SRC:
7407 case SADB_EXT_ADDRESS_DST:
7408 case SADB_EXT_ADDRESS_PROXY:
7409 case SADB_EXT_LIFETIME_CURRENT:
7410 case SADB_EXT_LIFETIME_HARD:
7411 case SADB_EXT_LIFETIME_SOFT:
7412 case SADB_EXT_KEY_AUTH:
7413 case SADB_EXT_KEY_ENCRYPT:
7414 case SADB_EXT_IDENTITY_SRC:
7415 case SADB_EXT_IDENTITY_DST:
7416 case SADB_EXT_SENSITIVITY:
7417 case SADB_EXT_PROPOSAL:
7418 case SADB_EXT_SUPPORTED_AUTH:
7419 case SADB_EXT_SUPPORTED_ENCRYPT:
7420 case SADB_EXT_SPIRANGE:
7421 case SADB_X_EXT_POLICY:
7422 case SADB_X_EXT_SA2:
7424 case SADB_X_EXT_NAT_T_TYPE:
7425 case SADB_X_EXT_NAT_T_SPORT:
7426 case SADB_X_EXT_NAT_T_DPORT:
7427 case SADB_X_EXT_NAT_T_OAI:
7428 case SADB_X_EXT_NAT_T_OAR:
7429 case SADB_X_EXT_NAT_T_FRAG:
7431 /* duplicate check */
7433 * XXX Are there duplication payloads of either
7434 * KEY_AUTH or KEY_ENCRYPT ?
7436 if (mhp->ext[ext->sadb_ext_type] != NULL) {
7437 ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
7438 "%u\n", __func__, ext->sadb_ext_type));
7440 PFKEYSTAT_INC(out_dupext);
7445 ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
7446 __func__, ext->sadb_ext_type));
7448 PFKEYSTAT_INC(out_invexttype);
7452 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7454 if (key_validate_ext(ext, extlen)) {
7456 PFKEYSTAT_INC(out_invlen);
7460 n = m_pulldown(m, off, extlen, &toff);
7462 /* m is already freed */
7465 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7467 mhp->ext[ext->sadb_ext_type] = ext;
7468 mhp->extoff[ext->sadb_ext_type] = off;
7469 mhp->extlen[ext->sadb_ext_type] = extlen;
7474 PFKEYSTAT_INC(out_invlen);
7482 key_validate_ext(const struct sadb_ext *ext, int len)
7484 const struct sockaddr *sa;
7485 enum { NONE, ADDR } checktype = NONE;
7487 const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7489 if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7492 /* if it does not match minimum/maximum length, bail */
7493 if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7494 ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7496 if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7498 if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7501 /* more checks based on sadb_ext_type XXX need more */
7502 switch (ext->sadb_ext_type) {
7503 case SADB_EXT_ADDRESS_SRC:
7504 case SADB_EXT_ADDRESS_DST:
7505 case SADB_EXT_ADDRESS_PROXY:
7506 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7509 case SADB_EXT_IDENTITY_SRC:
7510 case SADB_EXT_IDENTITY_DST:
7511 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7512 SADB_X_IDENTTYPE_ADDR) {
7513 baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7523 switch (checktype) {
7527 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7528 if (len < baselen + sal)
7530 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7543 for (i = 0; i < IPSEC_DIR_MAX; i++)
7544 TAILQ_INIT(&V_sptree[i]);
7546 LIST_INIT(&V_sahtree);
7548 for (i = 0; i <= SADB_SATYPE_MAX; i++)
7549 LIST_INIT(&V_regtree[i]);
7551 LIST_INIT(&V_acqtree);
7552 LIST_INIT(&V_spacqtree);
7554 if (!IS_DEFAULT_VNET(curvnet))
7558 REGTREE_LOCK_INIT();
7559 SAHTREE_LOCK_INIT();
7563 #ifndef IPSEC_DEBUG2
7564 callout_init(&key_timer, CALLOUT_MPSAFE);
7565 callout_reset(&key_timer, hz, key_timehandler, NULL);
7566 #endif /*IPSEC_DEBUG2*/
7568 /* initialize key statistics */
7569 keystat.getspi_count = 1;
7571 printf("IPsec: Initialized Security Association Processing.\n");
7578 TAILQ_HEAD(, secpolicy) drainq;
7579 struct secpolicy *sp, *nextsp;
7580 struct secacq *acq, *nextacq;
7581 struct secspacq *spacq, *nextspacq;
7582 struct secashead *sah, *nextsah;
7586 TAILQ_INIT(&drainq);
7588 for (i = 0; i < IPSEC_DIR_MAX; i++) {
7589 TAILQ_CONCAT(&drainq, &V_sptree[i], chain);
7592 sp = TAILQ_FIRST(&drainq);
7593 while (sp != NULL) {
7594 nextsp = TAILQ_NEXT(sp, chain);
7600 for (sah = LIST_FIRST(&V_sahtree); sah != NULL; sah = nextsah) {
7601 nextsah = LIST_NEXT(sah, chain);
7602 if (__LIST_CHAINED(sah)) {
7603 LIST_REMOVE(sah, chain);
7604 free(sah, M_IPSEC_SAH);
7610 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7611 LIST_FOREACH(reg, &V_regtree[i], chain) {
7612 if (__LIST_CHAINED(reg)) {
7613 LIST_REMOVE(reg, chain);
7614 free(reg, M_IPSEC_SAR);
7622 for (acq = LIST_FIRST(&V_acqtree); acq != NULL; acq = nextacq) {
7623 nextacq = LIST_NEXT(acq, chain);
7624 if (__LIST_CHAINED(acq)) {
7625 LIST_REMOVE(acq, chain);
7626 free(acq, M_IPSEC_SAQ);
7632 for (spacq = LIST_FIRST(&V_spacqtree); spacq != NULL;
7633 spacq = nextspacq) {
7634 nextspacq = LIST_NEXT(spacq, chain);
7635 if (__LIST_CHAINED(spacq)) {
7636 LIST_REMOVE(spacq, chain);
7637 free(spacq, M_IPSEC_SAQ);
7645 * XXX: maybe This function is called after INBOUND IPsec processing.
7647 * Special check for tunnel-mode packets.
7648 * We must make some checks for consistency between inner and outer IP header.
7650 * xxx more checks to be provided
7653 key_checktunnelsanity(struct secasvar *sav, u_int family, caddr_t src,
7656 IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7658 /* XXX: check inner IP header */
7663 /* record data transfer on SA, and update timestamps */
7665 key_sa_recordxfer(struct secasvar *sav, struct mbuf *m)
7667 IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7668 IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7673 * XXX Currently, there is a difference of bytes size
7674 * between inbound and outbound processing.
7676 sav->lft_c->bytes += m->m_pkthdr.len;
7677 /* to check bytes lifetime is done in key_timehandler(). */
7680 * We use the number of packets as the unit of
7681 * allocations. We increment the variable
7682 * whenever {esp,ah}_{in,out}put is called.
7684 sav->lft_c->allocations++;
7685 /* XXX check for expires? */
7688 * NOTE: We record CURRENT usetime by using wall clock,
7689 * in seconds. HARD and SOFT lifetime are measured by the time
7690 * difference (again in seconds) from usetime.
7694 * -----+-----+--------+---> t
7695 * <--------------> HARD
7698 sav->lft_c->usetime = time_second;
7699 /* XXX check for expires? */
7705 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7707 IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7708 SAHTREE_LOCK_ASSERT();
7710 if (sav->state != state) {
7711 if (__LIST_CHAINED(sav))
7712 LIST_REMOVE(sav, chain);
7714 LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7719 key_sa_stir_iv(struct secasvar *sav)
7722 IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7723 key_randomfill(sav->iv, sav->ivlen);
7727 * Take one of the kernel's security keys and convert it into a PF_KEY
7728 * structure within an mbuf, suitable for sending up to a waiting
7729 * application in user land.
7732 * src: A pointer to a kernel security key.
7733 * exttype: Which type of key this is. Refer to the PF_KEY data structures.
7735 * a valid mbuf or NULL indicating an error
7739 static struct mbuf *
7740 key_setkey(struct seckey *src, u_int16_t exttype)
7749 len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
7750 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
7755 p = mtod(m, struct sadb_key *);
7757 p->sadb_key_len = PFKEY_UNIT64(len);
7758 p->sadb_key_exttype = exttype;
7759 p->sadb_key_bits = src->bits;
7760 bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
7766 * Take one of the kernel's lifetime data structures and convert it
7767 * into a PF_KEY structure within an mbuf, suitable for sending up to
7768 * a waiting application in user land.
7771 * src: A pointer to a kernel lifetime structure.
7772 * exttype: Which type of lifetime this is. Refer to the PF_KEY
7773 * data structures for more information.
7775 * a valid mbuf or NULL indicating an error
7779 static struct mbuf *
7780 key_setlifetime(struct seclifetime *src, u_int16_t exttype)
7782 struct mbuf *m = NULL;
7783 struct sadb_lifetime *p;
7784 int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
7789 m = m_get2(len, M_NOWAIT, MT_DATA, 0);
7794 p = mtod(m, struct sadb_lifetime *);
7797 p->sadb_lifetime_len = PFKEY_UNIT64(len);
7798 p->sadb_lifetime_exttype = exttype;
7799 p->sadb_lifetime_allocations = src->allocations;
7800 p->sadb_lifetime_bytes = src->bytes;
7801 p->sadb_lifetime_addtime = src->addtime;
7802 p->sadb_lifetime_usetime = src->usetime;