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/socket.h>
52 #include <sys/socketvar.h>
53 #include <sys/sysctl.h>
54 #include <sys/errno.h>
56 #include <sys/queue.h>
57 #include <sys/refcount.h>
58 #include <sys/syslog.h>
61 #include <net/route.h>
62 #include <net/raw_cb.h>
64 #include <netinet/in.h>
65 #include <netinet/in_systm.h>
66 #include <netinet/ip.h>
67 #include <netinet/in_var.h>
70 #include <netinet/ip6.h>
71 #include <netinet6/in6_var.h>
72 #include <netinet6/ip6_var.h>
76 #include <netinet/in_pcb.h>
79 #include <netinet6/in6_pcb.h>
82 #include <net/pfkeyv2.h>
83 #include <netipsec/keydb.h>
84 #include <netipsec/key.h>
85 #include <netipsec/keysock.h>
86 #include <netipsec/key_debug.h>
88 #include <netipsec/ipsec.h>
90 #include <netipsec/ipsec6.h>
93 #include <netipsec/xform.h>
95 #include <machine/stdarg.h>
98 #include <sys/random.h>
100 #define FULLMASK 0xff
101 #define _BITS(bytes) ((bytes) << 3)
104 * Note on SA reference counting:
105 * - SAs that are not in DEAD state will have (total external reference + 1)
106 * following value in reference count field. they cannot be freed and are
107 * referenced from SA header.
108 * - SAs that are in DEAD state will have (total external reference)
109 * in reference count field. they are ready to be freed. reference from
110 * SA header will be removed in key_delsav(), when the reference count
111 * field hits 0 (= no external reference other than from SA header.
114 u_int32_t key_debug_level = 0;
115 static u_int key_spi_trycnt = 1000;
116 static u_int32_t key_spi_minval = 0x100;
117 static u_int32_t key_spi_maxval = 0x0fffffff; /* XXX */
118 static u_int32_t policy_id = 0;
119 static u_int key_int_random = 60; /*interval to initialize randseed,1(m)*/
120 static u_int key_larval_lifetime = 30; /* interval to expire acquiring, 30(s)*/
121 static int key_blockacq_count = 10; /* counter for blocking SADB_ACQUIRE.*/
122 static int key_blockacq_lifetime = 20; /* lifetime for blocking SADB_ACQUIRE.*/
123 static int key_preferred_oldsa = 1; /* preferred old sa rather than new sa.*/
125 static u_int32_t acq_seq = 0;
127 static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX]; /* SPD */
128 static struct mtx sptree_lock;
129 #define SPTREE_LOCK_INIT() \
130 mtx_init(&sptree_lock, "sptree", \
131 "fast ipsec security policy database", MTX_DEF)
132 #define SPTREE_LOCK_DESTROY() mtx_destroy(&sptree_lock)
133 #define SPTREE_LOCK() mtx_lock(&sptree_lock)
134 #define SPTREE_UNLOCK() mtx_unlock(&sptree_lock)
135 #define SPTREE_LOCK_ASSERT() mtx_assert(&sptree_lock, MA_OWNED)
137 static LIST_HEAD(_sahtree, secashead) sahtree; /* SAD */
138 static struct mtx sahtree_lock;
139 #define SAHTREE_LOCK_INIT() \
140 mtx_init(&sahtree_lock, "sahtree", \
141 "fast ipsec security association database", MTX_DEF)
142 #define SAHTREE_LOCK_DESTROY() mtx_destroy(&sahtree_lock)
143 #define SAHTREE_LOCK() mtx_lock(&sahtree_lock)
144 #define SAHTREE_UNLOCK() mtx_unlock(&sahtree_lock)
145 #define SAHTREE_LOCK_ASSERT() mtx_assert(&sahtree_lock, MA_OWNED)
148 static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
149 static struct mtx regtree_lock;
150 #define REGTREE_LOCK_INIT() \
151 mtx_init(®tree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
152 #define REGTREE_LOCK_DESTROY() mtx_destroy(®tree_lock)
153 #define REGTREE_LOCK() mtx_lock(®tree_lock)
154 #define REGTREE_UNLOCK() mtx_unlock(®tree_lock)
155 #define REGTREE_LOCK_ASSERT() mtx_assert(®tree_lock, MA_OWNED)
157 static LIST_HEAD(_acqtree, secacq) acqtree; /* acquiring list */
158 static struct mtx acq_lock;
159 #define ACQ_LOCK_INIT() \
160 mtx_init(&acq_lock, "acqtree", "fast ipsec acquire list", MTX_DEF)
161 #define ACQ_LOCK_DESTROY() mtx_destroy(&acq_lock)
162 #define ACQ_LOCK() mtx_lock(&acq_lock)
163 #define ACQ_UNLOCK() mtx_unlock(&acq_lock)
164 #define ACQ_LOCK_ASSERT() mtx_assert(&acq_lock, MA_OWNED)
166 static LIST_HEAD(_spacqtree, secspacq) spacqtree; /* SP acquiring list */
167 static struct mtx spacq_lock;
168 #define SPACQ_LOCK_INIT() \
169 mtx_init(&spacq_lock, "spacqtree", \
170 "fast ipsec security policy acquire list", MTX_DEF)
171 #define SPACQ_LOCK_DESTROY() mtx_destroy(&spacq_lock)
172 #define SPACQ_LOCK() mtx_lock(&spacq_lock)
173 #define SPACQ_UNLOCK() mtx_unlock(&spacq_lock)
174 #define SPACQ_LOCK_ASSERT() mtx_assert(&spacq_lock, MA_OWNED)
176 /* search order for SAs */
177 static const u_int saorder_state_valid_prefer_old[] = {
178 SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
180 static const u_int saorder_state_valid_prefer_new[] = {
181 SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
183 static u_int saorder_state_alive[] = {
185 SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
187 static u_int saorder_state_any[] = {
188 SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
189 SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
192 static const int minsize[] = {
193 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
194 sizeof(struct sadb_sa), /* SADB_EXT_SA */
195 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
196 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
197 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
198 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_SRC */
199 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_DST */
200 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_PROXY */
201 sizeof(struct sadb_key), /* SADB_EXT_KEY_AUTH */
202 sizeof(struct sadb_key), /* SADB_EXT_KEY_ENCRYPT */
203 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_SRC */
204 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_DST */
205 sizeof(struct sadb_sens), /* SADB_EXT_SENSITIVITY */
206 sizeof(struct sadb_prop), /* SADB_EXT_PROPOSAL */
207 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_AUTH */
208 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_ENCRYPT */
209 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
210 0, /* SADB_X_EXT_KMPRIVATE */
211 sizeof(struct sadb_x_policy), /* SADB_X_EXT_POLICY */
212 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
214 static const int maxsize[] = {
215 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
216 sizeof(struct sadb_sa), /* SADB_EXT_SA */
217 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
218 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
219 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
220 0, /* SADB_EXT_ADDRESS_SRC */
221 0, /* SADB_EXT_ADDRESS_DST */
222 0, /* SADB_EXT_ADDRESS_PROXY */
223 0, /* SADB_EXT_KEY_AUTH */
224 0, /* SADB_EXT_KEY_ENCRYPT */
225 0, /* SADB_EXT_IDENTITY_SRC */
226 0, /* SADB_EXT_IDENTITY_DST */
227 0, /* SADB_EXT_SENSITIVITY */
228 0, /* SADB_EXT_PROPOSAL */
229 0, /* SADB_EXT_SUPPORTED_AUTH */
230 0, /* SADB_EXT_SUPPORTED_ENCRYPT */
231 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
232 0, /* SADB_X_EXT_KMPRIVATE */
233 0, /* SADB_X_EXT_POLICY */
234 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
237 static int ipsec_esp_keymin = 256;
238 static int ipsec_esp_auth = 0;
239 static int ipsec_ah_keymin = 128;
242 SYSCTL_DECL(_net_key);
245 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL, debug, CTLFLAG_RW, \
246 &key_debug_level, 0, "");
248 /* max count of trial for the decision of spi value */
249 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt, CTLFLAG_RW, \
250 &key_spi_trycnt, 0, "");
252 /* minimum spi value to allocate automatically. */
253 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE, spi_minval, CTLFLAG_RW, \
254 &key_spi_minval, 0, "");
256 /* maximun spi value to allocate automatically. */
257 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE, spi_maxval, CTLFLAG_RW, \
258 &key_spi_maxval, 0, "");
260 /* interval to initialize randseed */
261 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random, CTLFLAG_RW, \
262 &key_int_random, 0, "");
264 /* lifetime for larval SA */
265 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME, larval_lifetime, CTLFLAG_RW, \
266 &key_larval_lifetime, 0, "");
268 /* counter for blocking to send SADB_ACQUIRE to IKEd */
269 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT, blockacq_count, CTLFLAG_RW, \
270 &key_blockacq_count, 0, "");
272 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
273 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME, blockacq_lifetime, CTLFLAG_RW, \
274 &key_blockacq_lifetime, 0, "");
277 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH, esp_auth, CTLFLAG_RW, \
278 &ipsec_esp_auth, 0, "");
280 /* minimum ESP key length */
281 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin, CTLFLAG_RW, \
282 &ipsec_esp_keymin, 0, "");
284 /* minimum AH key length */
285 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN, ah_keymin, CTLFLAG_RW, \
286 &ipsec_ah_keymin, 0, "");
288 /* perfered old SA rather than new SA */
289 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA, preferred_oldsa, CTLFLAG_RW,\
290 &key_preferred_oldsa, 0, "");
292 #define __LIST_CHAINED(elm) \
293 (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
294 #define LIST_INSERT_TAIL(head, elm, type, field) \
296 struct type *curelm = LIST_FIRST(head); \
297 if (curelm == NULL) {\
298 LIST_INSERT_HEAD(head, elm, field); \
300 while (LIST_NEXT(curelm, field)) \
301 curelm = LIST_NEXT(curelm, field);\
302 LIST_INSERT_AFTER(curelm, elm, field);\
306 #define KEY_CHKSASTATE(head, sav, name) \
308 if ((head) != (sav)) { \
309 ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
310 (name), (head), (sav))); \
315 #define KEY_CHKSPDIR(head, sp, name) \
317 if ((head) != (sp)) { \
318 ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
319 "anyway continue.\n", \
320 (name), (head), (sp))); \
324 MALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
325 MALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
326 MALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
327 MALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
328 MALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
329 MALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
330 MALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
333 * set parameters into secpolicyindex buffer.
334 * Must allocate secpolicyindex buffer passed to this function.
336 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
338 bzero((idx), sizeof(struct secpolicyindex)); \
339 (idx)->dir = (_dir); \
340 (idx)->prefs = (ps); \
341 (idx)->prefd = (pd); \
342 (idx)->ul_proto = (ulp); \
343 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
344 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
348 * set parameters into secasindex buffer.
349 * Must allocate secasindex buffer before calling this function.
351 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
353 bzero((idx), sizeof(struct secasindex)); \
354 (idx)->proto = (p); \
356 (idx)->reqid = (r); \
357 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
358 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
363 u_long getspi_count; /* the avarage of count to try to get new SPI */
367 struct sadb_msg *msg;
368 struct sadb_ext *ext[SADB_EXT_MAX + 1];
369 int extoff[SADB_EXT_MAX + 1];
370 int extlen[SADB_EXT_MAX + 1];
373 static struct secasvar *key_allocsa_policy __P((const struct secasindex *));
374 static void key_freesp_so __P((struct secpolicy **));
375 static struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
376 static void key_delsp __P((struct secpolicy *));
377 static struct secpolicy *key_getsp __P((struct secpolicyindex *));
378 static void _key_delsp(struct secpolicy *sp);
379 static struct secpolicy *key_getspbyid __P((u_int32_t));
380 static u_int32_t key_newreqid __P((void));
381 static struct mbuf *key_gather_mbuf __P((struct mbuf *,
382 const struct sadb_msghdr *, int, int, ...));
383 static int key_spdadd __P((struct socket *, struct mbuf *,
384 const struct sadb_msghdr *));
385 static u_int32_t key_getnewspid __P((void));
386 static int key_spddelete __P((struct socket *, struct mbuf *,
387 const struct sadb_msghdr *));
388 static int key_spddelete2 __P((struct socket *, struct mbuf *,
389 const struct sadb_msghdr *));
390 static int key_spdget __P((struct socket *, struct mbuf *,
391 const struct sadb_msghdr *));
392 static int key_spdflush __P((struct socket *, struct mbuf *,
393 const struct sadb_msghdr *));
394 static int key_spddump __P((struct socket *, struct mbuf *,
395 const struct sadb_msghdr *));
396 static struct mbuf *key_setdumpsp __P((struct secpolicy *,
397 u_int8_t, u_int32_t, u_int32_t));
398 static u_int key_getspreqmsglen __P((struct secpolicy *));
399 static int key_spdexpire __P((struct secpolicy *));
400 static struct secashead *key_newsah __P((struct secasindex *));
401 static void key_delsah __P((struct secashead *));
402 static struct secasvar *key_newsav __P((struct mbuf *,
403 const struct sadb_msghdr *, struct secashead *, int *,
405 #define KEY_NEWSAV(m, sadb, sah, e) \
406 key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
407 static void key_delsav __P((struct secasvar *));
408 static struct secashead *key_getsah __P((struct secasindex *));
409 static struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
410 static struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
411 static int key_setsaval __P((struct secasvar *, struct mbuf *,
412 const struct sadb_msghdr *));
413 static int key_mature __P((struct secasvar *));
414 static struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
415 u_int8_t, u_int32_t, u_int32_t));
416 static struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
417 u_int32_t, pid_t, u_int16_t));
418 static struct mbuf *key_setsadbsa __P((struct secasvar *));
419 static struct mbuf *key_setsadbaddr __P((u_int16_t,
420 const struct sockaddr *, u_int8_t, u_int16_t));
421 static struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
422 static struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
424 static struct seckey *key_dup_keymsg(const struct sadb_key *, u_int,
425 struct malloc_type *);
426 static struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
427 struct malloc_type *type);
429 static int key_ismyaddr6 __P((struct sockaddr_in6 *));
432 /* flags for key_cmpsaidx() */
433 #define CMP_HEAD 1 /* protocol, addresses. */
434 #define CMP_MODE_REQID 2 /* additionally HEAD, reqid, mode. */
435 #define CMP_REQID 3 /* additionally HEAD, reaid. */
436 #define CMP_EXACTLY 4 /* all elements. */
437 static int key_cmpsaidx
438 __P((const struct secasindex *, const struct secasindex *, int));
440 static int key_cmpspidx_exactly
441 __P((struct secpolicyindex *, struct secpolicyindex *));
442 static int key_cmpspidx_withmask
443 __P((struct secpolicyindex *, struct secpolicyindex *));
444 static int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
445 static int key_bbcmp __P((const void *, const void *, u_int));
446 static u_int16_t key_satype2proto __P((u_int8_t));
447 static u_int8_t key_proto2satype __P((u_int16_t));
449 static int key_getspi __P((struct socket *, struct mbuf *,
450 const struct sadb_msghdr *));
451 static u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
452 struct secasindex *));
453 static int key_update __P((struct socket *, struct mbuf *,
454 const struct sadb_msghdr *));
455 #ifdef IPSEC_DOSEQCHECK
456 static struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
458 static int key_add __P((struct socket *, struct mbuf *,
459 const struct sadb_msghdr *));
460 static int key_setident __P((struct secashead *, struct mbuf *,
461 const struct sadb_msghdr *));
462 static struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
463 const struct sadb_msghdr *));
464 static int key_delete __P((struct socket *, struct mbuf *,
465 const struct sadb_msghdr *));
466 static int key_get __P((struct socket *, struct mbuf *,
467 const struct sadb_msghdr *));
469 static void key_getcomb_setlifetime __P((struct sadb_comb *));
470 static struct mbuf *key_getcomb_esp __P((void));
471 static struct mbuf *key_getcomb_ah __P((void));
472 static struct mbuf *key_getcomb_ipcomp __P((void));
473 static struct mbuf *key_getprop __P((const struct secasindex *));
475 static int key_acquire __P((const struct secasindex *, struct secpolicy *));
476 static struct secacq *key_newacq __P((const struct secasindex *));
477 static struct secacq *key_getacq __P((const struct secasindex *));
478 static struct secacq *key_getacqbyseq __P((u_int32_t));
479 static struct secspacq *key_newspacq __P((struct secpolicyindex *));
480 static struct secspacq *key_getspacq __P((struct secpolicyindex *));
481 static int key_acquire2 __P((struct socket *, struct mbuf *,
482 const struct sadb_msghdr *));
483 static int key_register __P((struct socket *, struct mbuf *,
484 const struct sadb_msghdr *));
485 static int key_expire __P((struct secasvar *));
486 static int key_flush __P((struct socket *, struct mbuf *,
487 const struct sadb_msghdr *));
488 static int key_dump __P((struct socket *, struct mbuf *,
489 const struct sadb_msghdr *));
490 static int key_promisc __P((struct socket *, struct mbuf *,
491 const struct sadb_msghdr *));
492 static int key_senderror __P((struct socket *, struct mbuf *, int));
493 static int key_validate_ext __P((const struct sadb_ext *, int));
494 static int key_align __P((struct mbuf *, struct sadb_msghdr *));
495 static struct mbuf *key_setlifetime(struct seclifetime *src,
497 static struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
500 static const char *key_getfqdn __P((void));
501 static const char *key_getuserfqdn __P((void));
503 static void key_sa_chgstate __P((struct secasvar *, u_int8_t));
504 static struct mbuf *key_alloc_mbuf __P((int));
507 sa_initref(struct secasvar *sav)
510 refcount_init(&sav->refcnt, 1);
513 sa_addref(struct secasvar *sav)
516 refcount_acquire(&sav->refcnt);
517 IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
520 sa_delref(struct secasvar *sav)
523 IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
524 return (refcount_release(&sav->refcnt));
527 #define SP_ADDREF(p) do { \
529 IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow")); \
531 #define SP_DELREF(p) do { \
532 IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow")); \
538 * Update the refcnt while holding the SPTREE lock.
541 key_addref(struct secpolicy *sp)
549 * Return 0 when there are known to be no SP's for the specified
550 * direction. Otherwise return 1. This is used by IPsec code
551 * to optimize performance.
554 key_havesp(u_int dir)
556 return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
557 LIST_FIRST(&sptree[dir]) != NULL : 1);
560 /* %%% IPsec policy management */
562 * allocating a SP for OUTBOUND or INBOUND packet.
563 * Must call key_freesp() later.
564 * OUT: NULL: not found
565 * others: found and return the pointer.
568 key_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
570 struct secpolicy *sp;
572 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
573 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
574 ("invalid direction %u", dir));
576 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
577 printf("DP %s from %s:%u\n", __func__, where, tag));
580 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
581 printf("*** objects\n");
582 kdebug_secpolicyindex(spidx));
585 LIST_FOREACH(sp, &sptree[dir], chain) {
586 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
587 printf("*** in SPD\n");
588 kdebug_secpolicyindex(&sp->spidx));
590 if (sp->state == IPSEC_SPSTATE_DEAD)
592 if (key_cmpspidx_withmask(&sp->spidx, spidx))
599 KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
601 /* found a SPD entry */
602 sp->lastused = time_second;
607 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
608 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
609 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
614 * allocating a SP for OUTBOUND or INBOUND packet.
615 * Must call key_freesp() later.
616 * OUT: NULL: not found
617 * others: found and return the pointer.
620 key_allocsp2(u_int32_t spi,
621 union sockaddr_union *dst,
624 const char* where, int tag)
626 struct secpolicy *sp;
628 IPSEC_ASSERT(dst != NULL, ("null dst"));
629 IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
630 ("invalid direction %u", dir));
632 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
633 printf("DP %s from %s:%u\n", __func__, where, tag));
636 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
637 printf("*** objects\n");
638 printf("spi %u proto %u dir %u\n", spi, proto, dir);
639 kdebug_sockaddr(&dst->sa));
642 LIST_FOREACH(sp, &sptree[dir], chain) {
643 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
644 printf("*** in SPD\n");
645 kdebug_secpolicyindex(&sp->spidx));
647 if (sp->state == IPSEC_SPSTATE_DEAD)
649 /* compare simple values, then dst address */
650 if (sp->spidx.ul_proto != proto)
652 /* NB: spi's must exist and match */
653 if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
655 if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
662 KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
664 /* found a SPD entry */
665 sp->lastused = time_second;
670 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
671 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
672 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
677 * return a policy that matches this particular inbound packet.
681 key_gettunnel(const struct sockaddr *osrc,
682 const struct sockaddr *odst,
683 const struct sockaddr *isrc,
684 const struct sockaddr *idst,
685 const char* where, int tag)
687 struct secpolicy *sp;
688 const int dir = IPSEC_DIR_INBOUND;
689 struct ipsecrequest *r1, *r2, *p;
690 struct secpolicyindex spidx;
692 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
693 printf("DP %s from %s:%u\n", __func__, where, tag));
695 if (isrc->sa_family != idst->sa_family) {
696 ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
697 __func__, isrc->sa_family, idst->sa_family));
703 LIST_FOREACH(sp, &sptree[dir], chain) {
704 if (sp->state == IPSEC_SPSTATE_DEAD)
708 for (p = sp->req; p; p = p->next) {
709 if (p->saidx.mode != IPSEC_MODE_TUNNEL)
716 /* here we look at address matches only */
718 if (isrc->sa_len > sizeof(spidx.src) ||
719 idst->sa_len > sizeof(spidx.dst))
721 bcopy(isrc, &spidx.src, isrc->sa_len);
722 bcopy(idst, &spidx.dst, idst->sa_len);
723 if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
726 if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
727 key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
731 if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
732 key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
741 sp->lastused = time_second;
746 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
747 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
748 sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
753 * allocating an SA entry for an *OUTBOUND* packet.
754 * checking each request entries in SP, and acquire an SA if need.
755 * OUT: 0: there are valid requests.
756 * ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
759 key_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
764 IPSEC_ASSERT(isr != NULL, ("null isr"));
765 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
766 IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
767 saidx->mode == IPSEC_MODE_TUNNEL,
768 ("unexpected policy %u", saidx->mode));
771 * XXX guard against protocol callbacks from the crypto
772 * thread as they reference ipsecrequest.sav which we
773 * temporarily null out below. Need to rethink how we
774 * handle bundled SA's in the callback thread.
776 IPSECREQUEST_LOCK_ASSERT(isr);
778 /* get current level */
779 level = ipsec_get_reqlevel(isr);
782 * We do allocate new SA only if the state of SA in the holder is
783 * SADB_SASTATE_DEAD. The SA for outbound must be the oldest.
785 if (isr->sav != NULL) {
786 if (isr->sav->sah == NULL)
787 panic("%s: sah is null.\n", __func__);
788 if (isr->sav == (struct secasvar *)LIST_FIRST(
789 &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
790 KEY_FREESAV(&isr->sav);
796 * we free any SA stashed in the IPsec request because a different
797 * SA may be involved each time this request is checked, either
798 * because new SAs are being configured, or this request is
799 * associated with an unconnected datagram socket, or this request
800 * is associated with a system default policy.
802 * The operation may have negative impact to performance. We may
803 * want to check cached SA carefully, rather than picking new SA
806 if (isr->sav != NULL) {
807 KEY_FREESAV(&isr->sav);
813 * new SA allocation if no SA found.
814 * key_allocsa_policy should allocate the oldest SA available.
815 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
817 if (isr->sav == NULL)
818 isr->sav = key_allocsa_policy(saidx);
820 /* When there is SA. */
821 if (isr->sav != NULL) {
822 if (isr->sav->state != SADB_SASTATE_MATURE &&
823 isr->sav->state != SADB_SASTATE_DYING)
829 error = key_acquire(saidx, isr->sp);
831 /* XXX What should I do ? */
832 ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
837 if (level != IPSEC_LEVEL_REQUIRE) {
838 /* XXX sigh, the interface to this routine is botched */
839 IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
847 * allocating a SA for policy entry from SAD.
848 * NOTE: searching SAD of aliving state.
849 * OUT: NULL: not found.
850 * others: found and return the pointer.
852 static struct secasvar *
853 key_allocsa_policy(const struct secasindex *saidx)
855 #define N(a) _ARRAYLEN(a)
856 struct secashead *sah;
857 struct secasvar *sav;
858 u_int stateidx, arraysize;
859 const u_int *state_valid;
862 LIST_FOREACH(sah, &sahtree, chain) {
863 if (sah->state == SADB_SASTATE_DEAD)
865 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
866 if (key_preferred_oldsa) {
867 state_valid = saorder_state_valid_prefer_old;
868 arraysize = N(saorder_state_valid_prefer_old);
870 state_valid = saorder_state_valid_prefer_new;
871 arraysize = N(saorder_state_valid_prefer_new);
882 /* search valid state */
883 for (stateidx = 0; stateidx < arraysize; stateidx++) {
884 sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
894 * searching SAD with direction, protocol, mode and state.
895 * called by key_allocsa_policy().
898 * others : found, pointer to a SA.
900 static struct secasvar *
901 key_do_allocsa_policy(struct secashead *sah, u_int state)
903 struct secasvar *sav, *nextsav, *candidate, *d;
909 for (sav = LIST_FIRST(&sah->savtree[state]);
913 nextsav = LIST_NEXT(sav, chain);
916 KEY_CHKSASTATE(sav->state, state, __func__);
919 if (candidate == NULL) {
924 /* Which SA is the better ? */
926 IPSEC_ASSERT(candidate->lft_c != NULL,
927 ("null candidate lifetime"));
928 IPSEC_ASSERT(sav->lft_c != NULL, ("null sav lifetime"));
930 /* What the best method is to compare ? */
931 if (key_preferred_oldsa) {
932 if (candidate->lft_c->addtime >
933 sav->lft_c->addtime) {
940 /* preferred new sa rather than old sa */
941 if (candidate->lft_c->addtime <
942 sav->lft_c->addtime) {
949 * prepared to delete the SA when there is more
950 * suitable candidate and the lifetime of the SA is not
953 if (d->lft_h->addtime != 0) {
954 struct mbuf *m, *result;
957 key_sa_chgstate(d, SADB_SASTATE_DEAD);
959 IPSEC_ASSERT(d->refcnt > 0, ("bogus ref count"));
961 satype = key_proto2satype(d->sah->saidx.proto);
965 m = key_setsadbmsg(SADB_DELETE, 0,
966 satype, 0, 0, d->refcnt - 1);
971 /* set sadb_address for saidx's. */
972 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
973 &d->sah->saidx.src.sa,
974 d->sah->saidx.src.sa.sa_len << 3,
980 /* set sadb_address for saidx's. */
981 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
982 &d->sah->saidx.dst.sa,
983 d->sah->saidx.dst.sa.sa_len << 3,
989 /* create SA extension */
990 m = key_setsadbsa(d);
995 if (result->m_len < sizeof(struct sadb_msg)) {
996 result = m_pullup(result,
997 sizeof(struct sadb_msg));
1002 result->m_pkthdr.len = 0;
1003 for (m = result; m; m = m->m_next)
1004 result->m_pkthdr.len += m->m_len;
1005 mtod(result, struct sadb_msg *)->sadb_msg_len =
1006 PFKEY_UNIT64(result->m_pkthdr.len);
1008 if (key_sendup_mbuf(NULL, result,
1009 KEY_SENDUP_REGISTERED))
1016 sa_addref(candidate);
1017 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1018 printf("DP %s cause refcnt++:%d SA:%p\n",
1019 __func__, candidate->refcnt, candidate));
1027 * allocating a usable SA entry for a *INBOUND* packet.
1028 * Must call key_freesav() later.
1029 * OUT: positive: pointer to a usable sav (i.e. MATURE or DYING state).
1030 * NULL: not found, or error occured.
1032 * In the comparison, no source address is used--for RFC2401 conformance.
1033 * To quote, from section 4.1:
1034 * A security association is uniquely identified by a triple consisting
1035 * of a Security Parameter Index (SPI), an IP Destination Address, and a
1036 * security protocol (AH or ESP) identifier.
1037 * Note that, however, we do need to keep source address in IPsec SA.
1038 * IKE specification and PF_KEY specification do assume that we
1039 * keep source address in IPsec SA. We see a tricky situation here.
1043 union sockaddr_union *dst,
1046 const char* where, int tag)
1048 struct secashead *sah;
1049 struct secasvar *sav;
1050 u_int stateidx, arraysize, state;
1051 const u_int *saorder_state_valid;
1053 IPSEC_ASSERT(dst != NULL, ("null dst address"));
1055 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1056 printf("DP %s from %s:%u\n", __func__, where, tag));
1060 * XXX: to be checked internal IP header somewhere. Also when
1061 * IPsec tunnel packet is received. But ESP tunnel mode is
1062 * encrypted so we can't check internal IP header.
1065 if (key_preferred_oldsa) {
1066 saorder_state_valid = saorder_state_valid_prefer_old;
1067 arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1069 saorder_state_valid = saorder_state_valid_prefer_new;
1070 arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1072 LIST_FOREACH(sah, &sahtree, chain) {
1073 /* search valid state */
1074 for (stateidx = 0; stateidx < arraysize; stateidx++) {
1075 state = saorder_state_valid[stateidx];
1076 LIST_FOREACH(sav, &sah->savtree[state], chain) {
1078 KEY_CHKSASTATE(sav->state, state, __func__);
1079 /* do not return entries w/ unusable state */
1080 if (sav->state != SADB_SASTATE_MATURE &&
1081 sav->state != SADB_SASTATE_DYING)
1083 if (proto != sav->sah->saidx.proto)
1085 if (spi != sav->spi)
1087 #if 0 /* don't check src */
1088 /* check src address */
1089 if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, 0) != 0)
1092 /* check dst address */
1093 if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, 0) != 0)
1104 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1105 printf("DP %s return SA:%p; refcnt %u\n", __func__,
1106 sav, sav ? sav->refcnt : 0));
1111 * Must be called after calling key_allocsp().
1112 * For both the packet without socket and key_freeso().
1115 _key_freesp(struct secpolicy **spp, const char* where, int tag)
1117 struct secpolicy *sp = *spp;
1119 IPSEC_ASSERT(sp != NULL, ("null sp"));
1124 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1125 printf("DP %s SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
1126 __func__, sp, sp->id, where, tag, sp->refcnt));
1128 if (sp->refcnt == 0) {
1136 * Must be called after calling key_allocsp().
1137 * For the packet with socket.
1140 key_freeso(struct socket *so)
1142 IPSEC_ASSERT(so != NULL, ("null so"));
1144 switch (so->so_proto->pr_domain->dom_family) {
1145 #if defined(INET) || defined(INET6)
1153 struct inpcb *pcb = sotoinpcb(so);
1155 /* Does it have a PCB ? */
1158 key_freesp_so(&pcb->inp_sp->sp_in);
1159 key_freesp_so(&pcb->inp_sp->sp_out);
1162 #endif /* INET || INET6 */
1164 ipseclog((LOG_DEBUG, "%s: unknown address family=%d.\n",
1165 __func__, so->so_proto->pr_domain->dom_family));
1171 key_freesp_so(struct secpolicy **sp)
1173 IPSEC_ASSERT(sp != NULL && *sp != NULL, ("null sp"));
1175 if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
1176 (*sp)->policy == IPSEC_POLICY_BYPASS)
1179 IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
1180 ("invalid policy %u", (*sp)->policy));
1185 * Must be called after calling key_allocsa().
1186 * This function is called by key_freesp() to free some SA allocated
1190 key_freesav(struct secasvar **psav, const char* where, int tag)
1192 struct secasvar *sav = *psav;
1194 IPSEC_ASSERT(sav != NULL, ("null sav"));
1196 if (sa_delref(sav)) {
1197 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1198 printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1199 __func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1203 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1204 printf("DP %s SA:%p (SPI %u) from %s:%u; refcnt now %u\n",
1205 __func__, sav, ntohl(sav->spi), where, tag, sav->refcnt));
1209 /* %%% SPD management */
1211 * free security policy entry.
1214 key_delsp(struct secpolicy *sp)
1216 struct ipsecrequest *isr, *nextisr;
1218 IPSEC_ASSERT(sp != NULL, ("null sp"));
1219 SPTREE_LOCK_ASSERT();
1221 sp->state = IPSEC_SPSTATE_DEAD;
1223 IPSEC_ASSERT(sp->refcnt == 0,
1224 ("SP with references deleted (refcnt %u)", sp->refcnt));
1226 /* remove from SP index */
1227 if (__LIST_CHAINED(sp))
1228 LIST_REMOVE(sp, chain);
1230 for (isr = sp->req; isr != NULL; isr = nextisr) {
1231 if (isr->sav != NULL) {
1232 KEY_FREESAV(&isr->sav);
1236 nextisr = isr->next;
1244 * OUT: NULL : not found
1245 * others : found, pointer to a SP.
1247 static struct secpolicy *
1248 key_getsp(struct secpolicyindex *spidx)
1250 struct secpolicy *sp;
1252 IPSEC_ASSERT(spidx != NULL, ("null spidx"));
1255 LIST_FOREACH(sp, &sptree[spidx->dir], chain) {
1256 if (sp->state == IPSEC_SPSTATE_DEAD)
1258 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1270 * OUT: NULL : not found
1271 * others : found, pointer to a SP.
1273 static struct secpolicy *
1274 key_getspbyid(u_int32_t id)
1276 struct secpolicy *sp;
1279 LIST_FOREACH(sp, &sptree[IPSEC_DIR_INBOUND], chain) {
1280 if (sp->state == IPSEC_SPSTATE_DEAD)
1288 LIST_FOREACH(sp, &sptree[IPSEC_DIR_OUTBOUND], chain) {
1289 if (sp->state == IPSEC_SPSTATE_DEAD)
1303 key_newsp(const char* where, int tag)
1305 struct secpolicy *newsp = NULL;
1307 newsp = (struct secpolicy *)
1308 malloc(sizeof(struct secpolicy), M_IPSEC_SP, M_NOWAIT|M_ZERO);
1310 SECPOLICY_LOCK_INIT(newsp);
1315 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1316 printf("DP %s from %s:%u return SP:%p\n", __func__,
1317 where, tag, newsp));
1322 _key_delsp(struct secpolicy *sp)
1324 SECPOLICY_LOCK_DESTROY(sp);
1325 free(sp, M_IPSEC_SP);
1329 * create secpolicy structure from sadb_x_policy structure.
1330 * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1331 * so must be set properly later.
1334 key_msg2sp(xpl0, len, error)
1335 struct sadb_x_policy *xpl0;
1339 struct secpolicy *newsp;
1341 IPSEC_ASSERT(xpl0 != NULL, ("null xpl0"));
1342 IPSEC_ASSERT(len >= sizeof(*xpl0), ("policy too short: %zu", len));
1344 if (len != PFKEY_EXTLEN(xpl0)) {
1345 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n", __func__));
1350 if ((newsp = KEY_NEWSP()) == NULL) {
1355 newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1356 newsp->policy = xpl0->sadb_x_policy_type;
1359 switch (xpl0->sadb_x_policy_type) {
1360 case IPSEC_POLICY_DISCARD:
1361 case IPSEC_POLICY_NONE:
1362 case IPSEC_POLICY_ENTRUST:
1363 case IPSEC_POLICY_BYPASS:
1367 case IPSEC_POLICY_IPSEC:
1370 struct sadb_x_ipsecrequest *xisr;
1371 struct ipsecrequest **p_isr = &newsp->req;
1373 /* validity check */
1374 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1375 ipseclog((LOG_DEBUG, "%s: Invalid msg length.\n",
1382 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1383 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1387 if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1388 ipseclog((LOG_DEBUG, "%s: invalid ipsecrequest "
1389 "length.\n", __func__));
1395 /* allocate request buffer */
1396 /* NB: data structure is zero'd */
1397 *p_isr = ipsec_newisr();
1398 if ((*p_isr) == NULL) {
1399 ipseclog((LOG_DEBUG,
1400 "%s: No more memory.\n", __func__));
1407 switch (xisr->sadb_x_ipsecrequest_proto) {
1410 case IPPROTO_IPCOMP:
1413 ipseclog((LOG_DEBUG,
1414 "%s: invalid proto type=%u\n", __func__,
1415 xisr->sadb_x_ipsecrequest_proto));
1417 *error = EPROTONOSUPPORT;
1420 (*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1422 switch (xisr->sadb_x_ipsecrequest_mode) {
1423 case IPSEC_MODE_TRANSPORT:
1424 case IPSEC_MODE_TUNNEL:
1426 case IPSEC_MODE_ANY:
1428 ipseclog((LOG_DEBUG,
1429 "%s: invalid mode=%u\n", __func__,
1430 xisr->sadb_x_ipsecrequest_mode));
1435 (*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1437 switch (xisr->sadb_x_ipsecrequest_level) {
1438 case IPSEC_LEVEL_DEFAULT:
1439 case IPSEC_LEVEL_USE:
1440 case IPSEC_LEVEL_REQUIRE:
1442 case IPSEC_LEVEL_UNIQUE:
1443 /* validity check */
1445 * If range violation of reqid, kernel will
1446 * update it, don't refuse it.
1448 if (xisr->sadb_x_ipsecrequest_reqid
1449 > IPSEC_MANUAL_REQID_MAX) {
1450 ipseclog((LOG_DEBUG,
1451 "%s: reqid=%d range "
1452 "violation, updated by kernel.\n",
1454 xisr->sadb_x_ipsecrequest_reqid));
1455 xisr->sadb_x_ipsecrequest_reqid = 0;
1458 /* allocate new reqid id if reqid is zero. */
1459 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1461 if ((reqid = key_newreqid()) == 0) {
1466 (*p_isr)->saidx.reqid = reqid;
1467 xisr->sadb_x_ipsecrequest_reqid = reqid;
1469 /* set it for manual keying. */
1470 (*p_isr)->saidx.reqid =
1471 xisr->sadb_x_ipsecrequest_reqid;
1476 ipseclog((LOG_DEBUG, "%s: invalid level=%u\n",
1478 xisr->sadb_x_ipsecrequest_level));
1483 (*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1485 /* set IP addresses if there */
1486 if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1487 struct sockaddr *paddr;
1489 paddr = (struct sockaddr *)(xisr + 1);
1491 /* validity check */
1493 > sizeof((*p_isr)->saidx.src)) {
1494 ipseclog((LOG_DEBUG, "%s: invalid "
1495 "request address length.\n",
1501 bcopy(paddr, &(*p_isr)->saidx.src,
1504 paddr = (struct sockaddr *)((caddr_t)paddr
1507 /* validity check */
1509 > sizeof((*p_isr)->saidx.dst)) {
1510 ipseclog((LOG_DEBUG, "%s: invalid "
1511 "request address length.\n",
1517 bcopy(paddr, &(*p_isr)->saidx.dst,
1521 (*p_isr)->sp = newsp;
1523 /* initialization for the next. */
1524 p_isr = &(*p_isr)->next;
1525 tlen -= xisr->sadb_x_ipsecrequest_len;
1527 /* validity check */
1529 ipseclog((LOG_DEBUG, "%s: becoming tlen < 0.\n",
1536 xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
1537 + xisr->sadb_x_ipsecrequest_len);
1542 ipseclog((LOG_DEBUG, "%s: invalid policy type.\n", __func__));
1555 static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1557 auto_reqid = (auto_reqid == ~0
1558 ? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1560 /* XXX should be unique check */
1566 * copy secpolicy struct to sadb_x_policy structure indicated.
1570 struct secpolicy *sp;
1572 struct sadb_x_policy *xpl;
1577 IPSEC_ASSERT(sp != NULL, ("null policy"));
1579 tlen = key_getspreqmsglen(sp);
1581 m = key_alloc_mbuf(tlen);
1582 if (!m || m->m_next) { /*XXX*/
1590 xpl = mtod(m, struct sadb_x_policy *);
1593 xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1594 xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1595 xpl->sadb_x_policy_type = sp->policy;
1596 xpl->sadb_x_policy_dir = sp->spidx.dir;
1597 xpl->sadb_x_policy_id = sp->id;
1598 p = (caddr_t)xpl + sizeof(*xpl);
1600 /* if is the policy for ipsec ? */
1601 if (sp->policy == IPSEC_POLICY_IPSEC) {
1602 struct sadb_x_ipsecrequest *xisr;
1603 struct ipsecrequest *isr;
1605 for (isr = sp->req; isr != NULL; isr = isr->next) {
1607 xisr = (struct sadb_x_ipsecrequest *)p;
1609 xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1610 xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1611 xisr->sadb_x_ipsecrequest_level = isr->level;
1612 xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1615 bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
1616 p += isr->saidx.src.sa.sa_len;
1617 bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
1618 p += isr->saidx.src.sa.sa_len;
1620 xisr->sadb_x_ipsecrequest_len =
1621 PFKEY_ALIGN8(sizeof(*xisr)
1622 + isr->saidx.src.sa.sa_len
1623 + isr->saidx.dst.sa.sa_len);
1630 /* m will not be freed nor modified */
1631 static struct mbuf *
1633 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1634 int ndeep, int nitem, ...)
1636 key_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
1638 const struct sadb_msghdr *mhp;
1647 struct mbuf *result = NULL, *n;
1650 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1651 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1653 va_start(ap, nitem);
1654 for (i = 0; i < nitem; i++) {
1655 idx = va_arg(ap, int);
1656 if (idx < 0 || idx > SADB_EXT_MAX)
1658 /* don't attempt to pull empty extension */
1659 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
1661 if (idx != SADB_EXT_RESERVED &&
1662 (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
1665 if (idx == SADB_EXT_RESERVED) {
1666 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
1668 IPSEC_ASSERT(len <= MHLEN, ("header too big %u", len));
1670 MGETHDR(n, M_DONTWAIT, MT_DATA);
1675 m_copydata(m, 0, sizeof(struct sadb_msg),
1677 } else if (i < ndeep) {
1678 len = mhp->extlen[idx];
1679 n = key_alloc_mbuf(len);
1680 if (!n || n->m_next) { /*XXX*/
1685 m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
1688 n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
1701 if ((result->m_flags & M_PKTHDR) != 0) {
1702 result->m_pkthdr.len = 0;
1703 for (n = result; n; n = n->m_next)
1704 result->m_pkthdr.len += n->m_len;
1715 * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
1716 * add an entry to SP database, when received
1717 * <base, address(SD), (lifetime(H),) policy>
1719 * Adding to SP database,
1721 * <base, address(SD), (lifetime(H),) policy>
1722 * to the socket which was send.
1724 * SPDADD set a unique policy entry.
1725 * SPDSETIDX like SPDADD without a part of policy requests.
1726 * SPDUPDATE replace a unique policy entry.
1728 * m will always be freed.
1731 key_spdadd(so, m, mhp)
1734 const struct sadb_msghdr *mhp;
1736 struct sadb_address *src0, *dst0;
1737 struct sadb_x_policy *xpl0, *xpl;
1738 struct sadb_lifetime *lft = NULL;
1739 struct secpolicyindex spidx;
1740 struct secpolicy *newsp;
1743 IPSEC_ASSERT(so != NULL, ("null socket"));
1744 IPSEC_ASSERT(m != NULL, ("null mbuf"));
1745 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
1746 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
1748 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
1749 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
1750 mhp->ext[SADB_X_EXT_POLICY] == NULL) {
1751 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
1752 return key_senderror(so, m, EINVAL);
1754 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
1755 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
1756 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
1757 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1759 return key_senderror(so, m, EINVAL);
1761 if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
1762 if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
1763 < sizeof(struct sadb_lifetime)) {
1764 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
1766 return key_senderror(so, m, EINVAL);
1768 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
1771 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
1772 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
1773 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
1776 /* XXX boundary check against sa_len */
1777 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1780 src0->sadb_address_prefixlen,
1781 dst0->sadb_address_prefixlen,
1782 src0->sadb_address_proto,
1785 /* checking the direciton. */
1786 switch (xpl0->sadb_x_policy_dir) {
1787 case IPSEC_DIR_INBOUND:
1788 case IPSEC_DIR_OUTBOUND:
1791 ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
1792 mhp->msg->sadb_msg_errno = EINVAL;
1797 /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
1798 if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
1799 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1800 ipseclog((LOG_DEBUG, "%s: Invalid policy type.\n", __func__));
1801 return key_senderror(so, m, EINVAL);
1804 /* policy requests are mandatory when action is ipsec. */
1805 if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
1806 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
1807 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
1808 ipseclog((LOG_DEBUG, "%s: some policy requests part required\n",
1810 return key_senderror(so, m, EINVAL);
1814 * checking there is SP already or not.
1815 * SPDUPDATE doesn't depend on whether there is a SP or not.
1816 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
1819 newsp = key_getsp(&spidx);
1820 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1822 newsp->state = IPSEC_SPSTATE_DEAD;
1826 if (newsp != NULL) {
1828 ipseclog((LOG_DEBUG, "%s: a SP entry exists already.\n",
1830 return key_senderror(so, m, EEXIST);
1834 /* allocation new SP entry */
1835 if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
1836 return key_senderror(so, m, error);
1839 if ((newsp->id = key_getnewspid()) == 0) {
1841 return key_senderror(so, m, ENOBUFS);
1844 /* XXX boundary check against sa_len */
1845 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
1848 src0->sadb_address_prefixlen,
1849 dst0->sadb_address_prefixlen,
1850 src0->sadb_address_proto,
1853 /* sanity check on addr pair */
1854 if (((struct sockaddr *)(src0 + 1))->sa_family !=
1855 ((struct sockaddr *)(dst0+ 1))->sa_family) {
1857 return key_senderror(so, m, EINVAL);
1859 if (((struct sockaddr *)(src0 + 1))->sa_len !=
1860 ((struct sockaddr *)(dst0+ 1))->sa_len) {
1862 return key_senderror(so, m, EINVAL);
1865 if (newsp->req && newsp->req->saidx.src.sa.sa_family) {
1866 struct sockaddr *sa;
1867 sa = (struct sockaddr *)(src0 + 1);
1868 if (sa->sa_family != newsp->req->saidx.src.sa.sa_family) {
1870 return key_senderror(so, m, EINVAL);
1873 if (newsp->req && newsp->req->saidx.dst.sa.sa_family) {
1874 struct sockaddr *sa;
1875 sa = (struct sockaddr *)(dst0 + 1);
1876 if (sa->sa_family != newsp->req->saidx.dst.sa.sa_family) {
1878 return key_senderror(so, m, EINVAL);
1883 newsp->created = time_second;
1884 newsp->lastused = newsp->created;
1885 newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
1886 newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
1888 newsp->refcnt = 1; /* do not reclaim until I say I do */
1889 newsp->state = IPSEC_SPSTATE_ALIVE;
1890 LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain);
1892 /* delete the entry in spacqtree */
1893 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
1894 struct secspacq *spacq = key_getspacq(&spidx);
1895 if (spacq != NULL) {
1896 /* reset counter in order to deletion by timehandler. */
1897 spacq->created = time_second;
1904 struct mbuf *n, *mpolicy;
1905 struct sadb_msg *newmsg;
1908 /* create new sadb_msg to reply. */
1910 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
1911 SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
1912 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1914 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
1916 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
1919 return key_senderror(so, m, ENOBUFS);
1921 if (n->m_len < sizeof(*newmsg)) {
1922 n = m_pullup(n, sizeof(*newmsg));
1924 return key_senderror(so, m, ENOBUFS);
1926 newmsg = mtod(n, struct sadb_msg *);
1927 newmsg->sadb_msg_errno = 0;
1928 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
1931 mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
1932 sizeof(*xpl), &off);
1933 if (mpolicy == NULL) {
1934 /* n is already freed */
1935 return key_senderror(so, m, ENOBUFS);
1937 xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
1938 if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
1940 return key_senderror(so, m, EINVAL);
1942 xpl->sadb_x_policy_id = newsp->id;
1945 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
1950 * get new policy id.
1958 u_int32_t newid = 0;
1959 int count = key_spi_trycnt; /* XXX */
1960 struct secpolicy *sp;
1962 /* when requesting to allocate spi ranged */
1964 newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
1966 if ((sp = key_getspbyid(newid)) == NULL)
1972 if (count == 0 || newid == 0) {
1973 ipseclog((LOG_DEBUG, "%s: to allocate policy id is failed.\n",
1982 * SADB_SPDDELETE processing
1984 * <base, address(SD), policy(*)>
1985 * from the user(?), and set SADB_SASTATE_DEAD,
1987 * <base, address(SD), policy(*)>
1989 * policy(*) including direction of policy.
1991 * m will always be freed.
1994 key_spddelete(so, m, mhp)
1997 const struct sadb_msghdr *mhp;
1999 struct sadb_address *src0, *dst0;
2000 struct sadb_x_policy *xpl0;
2001 struct secpolicyindex spidx;
2002 struct secpolicy *sp;
2004 IPSEC_ASSERT(so != NULL, ("null so"));
2005 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2006 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2007 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2009 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2010 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2011 mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2012 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2014 return key_senderror(so, m, EINVAL);
2016 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2017 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2018 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2019 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2021 return key_senderror(so, m, EINVAL);
2024 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2025 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2026 xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
2029 /* XXX boundary check against sa_len */
2030 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2033 src0->sadb_address_prefixlen,
2034 dst0->sadb_address_prefixlen,
2035 src0->sadb_address_proto,
2038 /* checking the direciton. */
2039 switch (xpl0->sadb_x_policy_dir) {
2040 case IPSEC_DIR_INBOUND:
2041 case IPSEC_DIR_OUTBOUND:
2044 ipseclog((LOG_DEBUG, "%s: Invalid SP direction.\n", __func__));
2045 return key_senderror(so, m, EINVAL);
2048 /* Is there SP in SPD ? */
2049 if ((sp = key_getsp(&spidx)) == NULL) {
2050 ipseclog((LOG_DEBUG, "%s: no SP found.\n", __func__));
2051 return key_senderror(so, m, EINVAL);
2054 /* save policy id to buffer to be returned. */
2055 xpl0->sadb_x_policy_id = sp->id;
2057 sp->state = IPSEC_SPSTATE_DEAD;
2062 struct sadb_msg *newmsg;
2064 /* create new sadb_msg to reply. */
2065 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
2066 SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
2068 return key_senderror(so, m, ENOBUFS);
2070 newmsg = mtod(n, struct sadb_msg *);
2071 newmsg->sadb_msg_errno = 0;
2072 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2075 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2080 * SADB_SPDDELETE2 processing
2083 * from the user(?), and set SADB_SASTATE_DEAD,
2087 * policy(*) including direction of policy.
2089 * m will always be freed.
2092 key_spddelete2(so, m, mhp)
2095 const struct sadb_msghdr *mhp;
2098 struct secpolicy *sp;
2100 IPSEC_ASSERT(so != NULL, ("null socket"));
2101 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2102 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2103 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2105 if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2106 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2107 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n", __func__));
2108 return key_senderror(so, m, EINVAL);
2111 id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2113 /* Is there SP in SPD ? */
2114 if ((sp = key_getspbyid(id)) == NULL) {
2115 ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2116 return key_senderror(so, m, EINVAL);
2119 sp->state = IPSEC_SPSTATE_DEAD;
2123 struct mbuf *n, *nn;
2124 struct sadb_msg *newmsg;
2127 /* create new sadb_msg to reply. */
2128 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2130 MGETHDR(n, M_DONTWAIT, MT_DATA);
2131 if (n && len > MHLEN) {
2132 MCLGET(n, M_DONTWAIT);
2133 if ((n->m_flags & M_EXT) == 0) {
2139 return key_senderror(so, m, ENOBUFS);
2145 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2146 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2148 IPSEC_ASSERT(off == len, ("length inconsistency (off %u len %u)",
2151 n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2152 mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
2155 return key_senderror(so, m, ENOBUFS);
2158 n->m_pkthdr.len = 0;
2159 for (nn = n; nn; nn = nn->m_next)
2160 n->m_pkthdr.len += nn->m_len;
2162 newmsg = mtod(n, struct sadb_msg *);
2163 newmsg->sadb_msg_errno = 0;
2164 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2167 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2172 * SADB_X_GET processing
2177 * <base, address(SD), policy>
2179 * policy(*) including direction of policy.
2181 * m will always be freed.
2184 key_spdget(so, m, mhp)
2187 const struct sadb_msghdr *mhp;
2190 struct secpolicy *sp;
2193 IPSEC_ASSERT(so != NULL, ("null socket"));
2194 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2195 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2196 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2198 if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2199 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2200 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2202 return key_senderror(so, m, EINVAL);
2205 id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2207 /* Is there SP in SPD ? */
2208 if ((sp = key_getspbyid(id)) == NULL) {
2209 ipseclog((LOG_DEBUG, "%s: no SP found id:%u.\n", __func__, id));
2210 return key_senderror(so, m, ENOENT);
2213 n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2216 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2218 return key_senderror(so, m, ENOBUFS);
2222 * SADB_X_SPDACQUIRE processing.
2223 * Acquire policy and SA(s) for a *OUTBOUND* packet.
2226 * to KMD, and expect to receive
2227 * <base> with SADB_X_SPDACQUIRE if error occured,
2230 * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2231 * policy(*) is without policy requests.
2234 * others: error number
2238 struct secpolicy *sp;
2240 struct mbuf *result = NULL, *m;
2241 struct secspacq *newspacq;
2243 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2244 IPSEC_ASSERT(sp->req == NULL, ("policy exists"));
2245 IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
2246 ("policy not IPSEC %u", sp->policy));
2248 /* Get an entry to check whether sent message or not. */
2249 newspacq = key_getspacq(&sp->spidx);
2250 if (newspacq != NULL) {
2251 if (key_blockacq_count < newspacq->count) {
2252 /* reset counter and do send message. */
2253 newspacq->count = 0;
2255 /* increment counter and do nothing. */
2261 /* make new entry for blocking to send SADB_ACQUIRE. */
2262 newspacq = key_newspacq(&sp->spidx);
2263 if (newspacq == NULL)
2267 /* create new sadb_msg to reply. */
2268 m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2274 result->m_pkthdr.len = 0;
2275 for (m = result; m; m = m->m_next)
2276 result->m_pkthdr.len += m->m_len;
2278 mtod(result, struct sadb_msg *)->sadb_msg_len =
2279 PFKEY_UNIT64(result->m_pkthdr.len);
2281 return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2285 * SADB_SPDFLUSH processing
2288 * from the user, and free all entries in secpctree.
2292 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2294 * m will always be freed.
2297 key_spdflush(so, m, mhp)
2300 const struct sadb_msghdr *mhp;
2302 struct sadb_msg *newmsg;
2303 struct secpolicy *sp;
2306 IPSEC_ASSERT(so != NULL, ("null socket"));
2307 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2308 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2309 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2311 if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2312 return key_senderror(so, m, EINVAL);
2314 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2316 LIST_FOREACH(sp, &sptree[dir], chain)
2317 sp->state = IPSEC_SPSTATE_DEAD;
2321 if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2322 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2323 return key_senderror(so, m, ENOBUFS);
2329 m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2330 newmsg = mtod(m, struct sadb_msg *);
2331 newmsg->sadb_msg_errno = 0;
2332 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2334 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2338 * SADB_SPDDUMP processing
2341 * from the user, and dump all SP leaves
2346 * m will always be freed.
2349 key_spddump(so, m, mhp)
2352 const struct sadb_msghdr *mhp;
2354 struct secpolicy *sp;
2359 IPSEC_ASSERT(so != NULL, ("null socket"));
2360 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2361 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2362 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2364 /* search SPD entry and get buffer size. */
2366 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2367 LIST_FOREACH(sp, &sptree[dir], chain) {
2373 return key_senderror(so, m, ENOENT);
2375 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2376 LIST_FOREACH(sp, &sptree[dir], chain) {
2378 n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
2379 mhp->msg->sadb_msg_pid);
2382 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2390 static struct mbuf *
2391 key_setdumpsp(struct secpolicy *sp, u_int8_t type, u_int32_t seq, u_int32_t pid)
2393 struct mbuf *result = NULL, *m;
2394 struct seclifetime lt;
2396 m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2401 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2402 &sp->spidx.src.sa, sp->spidx.prefs,
2403 sp->spidx.ul_proto);
2408 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2409 &sp->spidx.dst.sa, sp->spidx.prefd,
2410 sp->spidx.ul_proto);
2421 lt.addtime=sp->created;
2422 lt.usetime= sp->lastused;
2423 m = key_setlifetime(<, SADB_EXT_LIFETIME_CURRENT);
2428 lt.addtime=sp->lifetime;
2429 lt.usetime= sp->validtime;
2430 m = key_setlifetime(<, SADB_EXT_LIFETIME_HARD);
2436 if ((result->m_flags & M_PKTHDR) == 0)
2439 if (result->m_len < sizeof(struct sadb_msg)) {
2440 result = m_pullup(result, sizeof(struct sadb_msg));
2445 result->m_pkthdr.len = 0;
2446 for (m = result; m; m = m->m_next)
2447 result->m_pkthdr.len += m->m_len;
2449 mtod(result, struct sadb_msg *)->sadb_msg_len =
2450 PFKEY_UNIT64(result->m_pkthdr.len);
2460 * get PFKEY message length for security policy and request.
2463 key_getspreqmsglen(sp)
2464 struct secpolicy *sp;
2468 tlen = sizeof(struct sadb_x_policy);
2470 /* if is the policy for ipsec ? */
2471 if (sp->policy != IPSEC_POLICY_IPSEC)
2474 /* get length of ipsec requests */
2476 struct ipsecrequest *isr;
2479 for (isr = sp->req; isr != NULL; isr = isr->next) {
2480 len = sizeof(struct sadb_x_ipsecrequest)
2481 + isr->saidx.src.sa.sa_len
2482 + isr->saidx.dst.sa.sa_len;
2484 tlen += PFKEY_ALIGN8(len);
2492 * SADB_SPDEXPIRE processing
2494 * <base, address(SD), lifetime(CH), policy>
2498 * others : error number
2502 struct secpolicy *sp;
2504 struct mbuf *result = NULL, *m;
2507 struct sadb_lifetime *lt;
2509 /* XXX: Why do we lock ? */
2511 IPSEC_ASSERT(sp != NULL, ("null secpolicy"));
2513 /* set msg header */
2514 m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2521 /* create lifetime extension (current and hard) */
2522 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2523 m = key_alloc_mbuf(len);
2524 if (!m || m->m_next) { /*XXX*/
2530 bzero(mtod(m, caddr_t), len);
2531 lt = mtod(m, struct sadb_lifetime *);
2532 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2533 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2534 lt->sadb_lifetime_allocations = 0;
2535 lt->sadb_lifetime_bytes = 0;
2536 lt->sadb_lifetime_addtime = sp->created;
2537 lt->sadb_lifetime_usetime = sp->lastused;
2538 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
2539 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2540 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2541 lt->sadb_lifetime_allocations = 0;
2542 lt->sadb_lifetime_bytes = 0;
2543 lt->sadb_lifetime_addtime = sp->lifetime;
2544 lt->sadb_lifetime_usetime = sp->validtime;
2547 /* set sadb_address for source */
2548 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2550 sp->spidx.prefs, sp->spidx.ul_proto);
2557 /* set sadb_address for destination */
2558 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2560 sp->spidx.prefd, sp->spidx.ul_proto);
2575 if ((result->m_flags & M_PKTHDR) == 0) {
2580 if (result->m_len < sizeof(struct sadb_msg)) {
2581 result = m_pullup(result, sizeof(struct sadb_msg));
2582 if (result == NULL) {
2588 result->m_pkthdr.len = 0;
2589 for (m = result; m; m = m->m_next)
2590 result->m_pkthdr.len += m->m_len;
2592 mtod(result, struct sadb_msg *)->sadb_msg_len =
2593 PFKEY_UNIT64(result->m_pkthdr.len);
2595 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
2603 /* %%% SAD management */
2605 * allocating a memory for new SA head, and copy from the values of mhp.
2606 * OUT: NULL : failure due to the lack of memory.
2607 * others : pointer to new SA head.
2609 static struct secashead *
2611 struct secasindex *saidx;
2613 struct secashead *newsah;
2615 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
2617 newsah = malloc(sizeof(struct secashead), M_IPSEC_SAH, M_NOWAIT|M_ZERO);
2618 if (newsah != NULL) {
2620 for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
2621 LIST_INIT(&newsah->savtree[i]);
2622 newsah->saidx = *saidx;
2624 /* add to saidxtree */
2625 newsah->state = SADB_SASTATE_MATURE;
2628 LIST_INSERT_HEAD(&sahtree, newsah, chain);
2635 * delete SA index and all SA registerd.
2639 struct secashead *sah;
2641 struct secasvar *sav, *nextsav;
2645 IPSEC_ASSERT(sah != NULL, ("NULL sah"));
2646 SAHTREE_LOCK_ASSERT();
2648 /* searching all SA registerd in the secindex. */
2650 stateidx < _ARRAYLEN(saorder_state_any);
2652 u_int state = saorder_state_any[stateidx];
2653 LIST_FOREACH_SAFE(sav, &sah->savtree[state], chain, nextsav) {
2654 if (sav->refcnt == 0) {
2656 KEY_CHKSASTATE(state, sav->state, __func__);
2659 /* give up to delete this sa */
2664 if (!zombie) { /* delete only if there are savs */
2665 /* remove from tree of SA index */
2666 if (__LIST_CHAINED(sah))
2667 LIST_REMOVE(sah, chain);
2668 if (sah->sa_route.ro_rt) {
2669 RTFREE(sah->sa_route.ro_rt);
2670 sah->sa_route.ro_rt = (struct rtentry *)NULL;
2672 free(sah, M_IPSEC_SAH);
2677 * allocating a new SA with LARVAL state. key_add() and key_getspi() call,
2678 * and copy the values of mhp into new buffer.
2679 * When SAD message type is GETSPI:
2680 * to set sequence number from acq_seq++,
2681 * to set zero to SPI.
2682 * not to call key_setsava().
2684 * others : pointer to new secasvar.
2686 * does not modify mbuf. does not free mbuf on error.
2688 static struct secasvar *
2689 key_newsav(m, mhp, sah, errp, where, tag)
2691 const struct sadb_msghdr *mhp;
2692 struct secashead *sah;
2697 struct secasvar *newsav;
2698 const struct sadb_sa *xsa;
2700 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2701 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2702 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2703 IPSEC_ASSERT(sah != NULL, ("null secashead"));
2705 newsav = malloc(sizeof(struct secasvar), M_IPSEC_SA, M_NOWAIT|M_ZERO);
2706 if (newsav == NULL) {
2707 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
2712 switch (mhp->msg->sadb_msg_type) {
2716 #ifdef IPSEC_DOSEQCHECK
2717 /* sync sequence number */
2718 if (mhp->msg->sadb_msg_seq == 0)
2720 (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
2723 newsav->seq = mhp->msg->sadb_msg_seq;
2728 if (mhp->ext[SADB_EXT_SA] == NULL) {
2729 free(newsav, M_IPSEC_SA);
2731 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
2736 xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2737 newsav->spi = xsa->sadb_sa_spi;
2738 newsav->seq = mhp->msg->sadb_msg_seq;
2741 free(newsav, M_IPSEC_SA);
2748 /* copy sav values */
2749 if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
2750 *errp = key_setsaval(newsav, m, mhp);
2752 free(newsav, M_IPSEC_SA);
2758 SECASVAR_LOCK_INIT(newsav);
2761 newsav->created = time_second;
2762 newsav->pid = mhp->msg->sadb_msg_pid;
2767 newsav->state = SADB_SASTATE_LARVAL;
2769 /* XXX locking??? */
2770 LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2773 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
2774 printf("DP %s from %s:%u return SP:%p\n", __func__,
2775 where, tag, newsav));
2781 * free() SA variable entry.
2784 key_cleansav(struct secasvar *sav)
2787 * Cleanup xform state. Note that zeroize'ing causes the
2788 * keys to be cleared; otherwise we must do it ourself.
2790 if (sav->tdb_xform != NULL) {
2791 sav->tdb_xform->xf_zeroize(sav);
2792 sav->tdb_xform = NULL;
2794 KASSERT(sav->iv == NULL, ("iv but no xform"));
2795 if (sav->key_auth != NULL)
2796 bzero(sav->key_auth->key_data, _KEYLEN(sav->key_auth));
2797 if (sav->key_enc != NULL)
2798 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
2800 if (sav->key_auth != NULL) {
2801 if (sav->key_auth->key_data != NULL)
2802 free(sav->key_auth->key_data, M_IPSEC_MISC);
2803 free(sav->key_auth, M_IPSEC_MISC);
2804 sav->key_auth = NULL;
2806 if (sav->key_enc != NULL) {
2807 if (sav->key_enc->key_data != NULL)
2808 free(sav->key_enc->key_data, M_IPSEC_MISC);
2809 free(sav->key_enc, M_IPSEC_MISC);
2810 sav->key_enc = NULL;
2813 bzero(sav->sched, sav->schedlen);
2814 free(sav->sched, M_IPSEC_MISC);
2817 if (sav->replay != NULL) {
2818 free(sav->replay, M_IPSEC_MISC);
2821 if (sav->lft_c != NULL) {
2822 free(sav->lft_c, M_IPSEC_MISC);
2825 if (sav->lft_h != NULL) {
2826 free(sav->lft_h, M_IPSEC_MISC);
2829 if (sav->lft_s != NULL) {
2830 free(sav->lft_s, M_IPSEC_MISC);
2836 * free() SA variable entry.
2840 struct secasvar *sav;
2842 IPSEC_ASSERT(sav != NULL, ("null sav"));
2843 IPSEC_ASSERT(sav->refcnt == 0, ("reference count %u > 0", sav->refcnt));
2845 /* remove from SA header */
2846 if (__LIST_CHAINED(sav))
2847 LIST_REMOVE(sav, chain);
2849 SECASVAR_LOCK_DESTROY(sav);
2850 free(sav, M_IPSEC_SA);
2857 * others : found, pointer to a SA.
2859 static struct secashead *
2861 struct secasindex *saidx;
2863 struct secashead *sah;
2866 LIST_FOREACH(sah, &sahtree, chain) {
2867 if (sah->state == SADB_SASTATE_DEAD)
2869 if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2878 * check not to be duplicated SPI.
2879 * NOTE: this function is too slow due to searching all SAD.
2882 * others : found, pointer to a SA.
2884 static struct secasvar *
2885 key_checkspidup(saidx, spi)
2886 struct secasindex *saidx;
2889 struct secashead *sah;
2890 struct secasvar *sav;
2892 /* check address family */
2893 if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
2894 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
2902 LIST_FOREACH(sah, &sahtree, chain) {
2903 if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
2905 sav = key_getsavbyspi(sah, spi);
2915 * search SAD litmited alive SA, protocol, SPI.
2918 * others : found, pointer to a SA.
2920 static struct secasvar *
2921 key_getsavbyspi(sah, spi)
2922 struct secashead *sah;
2925 struct secasvar *sav;
2926 u_int stateidx, state;
2929 SAHTREE_LOCK_ASSERT();
2930 /* search all status */
2932 stateidx < _ARRAYLEN(saorder_state_alive);
2935 state = saorder_state_alive[stateidx];
2936 LIST_FOREACH(sav, &sah->savtree[state], chain) {
2939 if (sav->state != state) {
2940 ipseclog((LOG_DEBUG, "%s: "
2941 "invalid sav->state (queue: %d SA: %d)\n",
2942 __func__, state, sav->state));
2946 if (sav->spi == spi)
2955 * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
2956 * You must update these if need.
2960 * does not modify mbuf. does not free mbuf on error.
2963 key_setsaval(sav, m, mhp)
2964 struct secasvar *sav;
2966 const struct sadb_msghdr *mhp;
2970 IPSEC_ASSERT(m != NULL, ("null mbuf"));
2971 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
2972 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
2974 /* initialization */
2976 sav->key_auth = NULL;
2977 sav->key_enc = NULL;
2984 sav->tdb_xform = NULL; /* transform */
2985 sav->tdb_encalgxform = NULL; /* encoding algorithm */
2986 sav->tdb_authalgxform = NULL; /* authentication algorithm */
2987 sav->tdb_compalgxform = NULL; /* compression algorithm */
2990 if (mhp->ext[SADB_EXT_SA] != NULL) {
2991 const struct sadb_sa *sa0;
2993 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
2994 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
2999 sav->alg_auth = sa0->sadb_sa_auth;
3000 sav->alg_enc = sa0->sadb_sa_encrypt;
3001 sav->flags = sa0->sadb_sa_flags;
3004 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3005 sav->replay = (struct secreplay *)
3006 malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_IPSEC_MISC, M_NOWAIT|M_ZERO);
3007 if (sav->replay == NULL) {
3008 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3013 if (sa0->sadb_sa_replay != 0)
3014 sav->replay->bitmap = (caddr_t)(sav->replay+1);
3015 sav->replay->wsize = sa0->sadb_sa_replay;
3019 /* Authentication keys */
3020 if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3021 const struct sadb_key *key0;
3024 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3025 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3028 if (len < sizeof(*key0)) {
3032 switch (mhp->msg->sadb_msg_satype) {
3033 case SADB_SATYPE_AH:
3034 case SADB_SATYPE_ESP:
3035 case SADB_X_SATYPE_TCPSIGNATURE:
3036 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3037 sav->alg_auth != SADB_X_AALG_NULL)
3040 case SADB_X_SATYPE_IPCOMP:
3046 ipseclog((LOG_DEBUG, "%s: invalid key_auth values.\n",
3051 sav->key_auth = (struct seckey *)key_dup_keymsg(key0, len,
3053 if (sav->key_auth == NULL ) {
3054 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3061 /* Encryption key */
3062 if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3063 const struct sadb_key *key0;
3066 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3067 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3070 if (len < sizeof(*key0)) {
3074 switch (mhp->msg->sadb_msg_satype) {
3075 case SADB_SATYPE_ESP:
3076 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3077 sav->alg_enc != SADB_EALG_NULL) {
3081 sav->key_enc = (struct seckey *)key_dup_keymsg(key0,
3084 if (sav->key_enc == NULL) {
3085 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3091 case SADB_X_SATYPE_IPCOMP:
3092 if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3094 sav->key_enc = NULL; /*just in case*/
3096 case SADB_SATYPE_AH:
3097 case SADB_X_SATYPE_TCPSIGNATURE:
3103 ipseclog((LOG_DEBUG, "%s: invalid key_enc value.\n",
3112 switch (mhp->msg->sadb_msg_satype) {
3113 case SADB_SATYPE_AH:
3114 error = xform_init(sav, XF_AH);
3116 case SADB_SATYPE_ESP:
3117 error = xform_init(sav, XF_ESP);
3119 case SADB_X_SATYPE_IPCOMP:
3120 error = xform_init(sav, XF_IPCOMP);
3122 case SADB_X_SATYPE_TCPSIGNATURE:
3123 error = xform_init(sav, XF_TCPSIGNATURE);
3127 ipseclog((LOG_DEBUG, "%s: unable to initialize SA type %u.\n",
3128 __func__, mhp->msg->sadb_msg_satype));
3133 sav->created = time_second;
3135 /* make lifetime for CURRENT */
3136 sav->lft_c = malloc(sizeof(struct seclifetime), M_IPSEC_MISC, M_NOWAIT);
3137 if (sav->lft_c == NULL) {
3138 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3143 sav->lft_c->allocations = 0;
3144 sav->lft_c->bytes = 0;
3145 sav->lft_c->addtime = time_second;
3146 sav->lft_c->usetime = 0;
3148 /* lifetimes for HARD and SOFT */
3150 const struct sadb_lifetime *lft0;
3152 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3154 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3158 sav->lft_h = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3159 if (sav->lft_h == NULL) {
3160 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3164 /* to be initialize ? */
3167 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3169 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3173 sav->lft_s = key_dup_lifemsg(lft0, M_IPSEC_MISC);
3174 if (sav->lft_s == NULL) {
3175 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
3179 /* to be initialize ? */
3186 /* initialization */
3193 * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3198 key_mature(struct secasvar *sav)
3202 /* check SPI value */
3203 switch (sav->sah->saidx.proto) {
3207 * RFC 4302, 2.4. Security Parameters Index (SPI), SPI values
3208 * 1-255 reserved by IANA for future use,
3209 * 0 for implementation specific, local use.
3211 if (ntohl(sav->spi) <= 255) {
3212 ipseclog((LOG_DEBUG, "%s: illegal range of SPI %u.\n",
3213 __func__, (u_int32_t)ntohl(sav->spi)));
3220 switch (sav->sah->saidx.proto) {
3223 if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
3224 (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
3225 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3226 "given to old-esp.\n", __func__));
3229 error = xform_init(sav, XF_ESP);
3233 if (sav->flags & SADB_X_EXT_DERIV) {
3234 ipseclog((LOG_DEBUG, "%s: invalid flag (derived) "
3235 "given to AH SA.\n", __func__));
3238 if (sav->alg_enc != SADB_EALG_NONE) {
3239 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3240 "mismated.\n", __func__));
3243 error = xform_init(sav, XF_AH);
3245 case IPPROTO_IPCOMP:
3246 if (sav->alg_auth != SADB_AALG_NONE) {
3247 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3248 "mismated.\n", __func__));
3251 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3252 && ntohl(sav->spi) >= 0x10000) {
3253 ipseclog((LOG_DEBUG, "%s: invalid cpi for IPComp.\n",
3257 error = xform_init(sav, XF_IPCOMP);
3260 if (sav->alg_enc != SADB_EALG_NONE) {
3261 ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
3262 "mismated.\n", __func__));
3265 error = xform_init(sav, XF_TCPSIGNATURE);
3268 ipseclog((LOG_DEBUG, "%s: Invalid satype.\n", __func__));
3269 error = EPROTONOSUPPORT;
3274 key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3281 * subroutine for SADB_GET and SADB_DUMP.
3283 static struct mbuf *
3284 key_setdumpsa(struct secasvar *sav, u_int8_t type, u_int8_t satype,
3285 u_int32_t seq, u_int32_t pid)
3287 struct mbuf *result = NULL, *tres = NULL, *m;
3290 SADB_EXT_SA, SADB_X_EXT_SA2,
3291 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3292 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3293 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3294 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3295 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3298 m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3303 for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3305 switch (dumporder[i]) {
3307 m = key_setsadbsa(sav);
3312 case SADB_X_EXT_SA2:
3313 m = key_setsadbxsa2(sav->sah->saidx.mode,
3314 sav->replay ? sav->replay->count : 0,
3315 sav->sah->saidx.reqid);
3320 case SADB_EXT_ADDRESS_SRC:
3321 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3322 &sav->sah->saidx.src.sa,
3323 FULLMASK, IPSEC_ULPROTO_ANY);
3328 case SADB_EXT_ADDRESS_DST:
3329 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3330 &sav->sah->saidx.dst.sa,
3331 FULLMASK, IPSEC_ULPROTO_ANY);
3336 case SADB_EXT_KEY_AUTH:
3339 m = key_setkey(sav->key_auth, SADB_EXT_KEY_AUTH);
3344 case SADB_EXT_KEY_ENCRYPT:
3347 m = key_setkey(sav->key_enc, SADB_EXT_KEY_ENCRYPT);
3352 case SADB_EXT_LIFETIME_CURRENT:
3355 m = key_setlifetime(sav->lft_c,
3356 SADB_EXT_LIFETIME_CURRENT);
3361 case SADB_EXT_LIFETIME_HARD:
3364 m = key_setlifetime(sav->lft_h,
3365 SADB_EXT_LIFETIME_HARD);
3370 case SADB_EXT_LIFETIME_SOFT:
3373 m = key_setlifetime(sav->lft_s,
3374 SADB_EXT_LIFETIME_SOFT);
3380 case SADB_EXT_ADDRESS_PROXY:
3381 case SADB_EXT_IDENTITY_SRC:
3382 case SADB_EXT_IDENTITY_DST:
3383 /* XXX: should we brought from SPD ? */
3384 case SADB_EXT_SENSITIVITY:
3397 m_cat(result, tres);
3398 if (result->m_len < sizeof(struct sadb_msg)) {
3399 result = m_pullup(result, sizeof(struct sadb_msg));
3404 result->m_pkthdr.len = 0;
3405 for (m = result; m; m = m->m_next)
3406 result->m_pkthdr.len += m->m_len;
3408 mtod(result, struct sadb_msg *)->sadb_msg_len =
3409 PFKEY_UNIT64(result->m_pkthdr.len);
3420 * set data into sadb_msg.
3422 static struct mbuf *
3423 key_setsadbmsg(u_int8_t type, u_int16_t tlen, u_int8_t satype, u_int32_t seq,
3424 pid_t pid, u_int16_t reserved)
3430 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3433 MGETHDR(m, M_DONTWAIT, MT_DATA);
3434 if (m && len > MHLEN) {
3435 MCLGET(m, M_DONTWAIT);
3436 if ((m->m_flags & M_EXT) == 0) {
3443 m->m_pkthdr.len = m->m_len = len;
3446 p = mtod(m, struct sadb_msg *);
3449 p->sadb_msg_version = PF_KEY_V2;
3450 p->sadb_msg_type = type;
3451 p->sadb_msg_errno = 0;
3452 p->sadb_msg_satype = satype;
3453 p->sadb_msg_len = PFKEY_UNIT64(tlen);
3454 p->sadb_msg_reserved = reserved;
3455 p->sadb_msg_seq = seq;
3456 p->sadb_msg_pid = (u_int32_t)pid;
3462 * copy secasvar data into sadb_address.
3464 static struct mbuf *
3466 struct secasvar *sav;
3472 len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3473 m = key_alloc_mbuf(len);
3474 if (!m || m->m_next) { /*XXX*/
3480 p = mtod(m, struct sadb_sa *);
3483 p->sadb_sa_len = PFKEY_UNIT64(len);
3484 p->sadb_sa_exttype = SADB_EXT_SA;
3485 p->sadb_sa_spi = sav->spi;
3486 p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3487 p->sadb_sa_state = sav->state;
3488 p->sadb_sa_auth = sav->alg_auth;
3489 p->sadb_sa_encrypt = sav->alg_enc;
3490 p->sadb_sa_flags = sav->flags;
3496 * set data into sadb_address.
3498 static struct mbuf *
3499 key_setsadbaddr(u_int16_t exttype, const struct sockaddr *saddr, u_int8_t prefixlen, u_int16_t ul_proto)
3502 struct sadb_address *p;
3505 len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3506 PFKEY_ALIGN8(saddr->sa_len);
3507 m = key_alloc_mbuf(len);
3508 if (!m || m->m_next) { /*XXX*/
3514 p = mtod(m, struct sadb_address *);
3517 p->sadb_address_len = PFKEY_UNIT64(len);
3518 p->sadb_address_exttype = exttype;
3519 p->sadb_address_proto = ul_proto;
3520 if (prefixlen == FULLMASK) {
3521 switch (saddr->sa_family) {
3523 prefixlen = sizeof(struct in_addr) << 3;
3526 prefixlen = sizeof(struct in6_addr) << 3;
3532 p->sadb_address_prefixlen = prefixlen;
3533 p->sadb_address_reserved = 0;
3536 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3543 * set data into sadb_x_sa2.
3545 static struct mbuf *
3546 key_setsadbxsa2(u_int8_t mode, u_int32_t seq, u_int32_t reqid)
3549 struct sadb_x_sa2 *p;
3552 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3553 m = key_alloc_mbuf(len);
3554 if (!m || m->m_next) { /*XXX*/
3560 p = mtod(m, struct sadb_x_sa2 *);
3563 p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3564 p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3565 p->sadb_x_sa2_mode = mode;
3566 p->sadb_x_sa2_reserved1 = 0;
3567 p->sadb_x_sa2_reserved2 = 0;
3568 p->sadb_x_sa2_sequence = seq;
3569 p->sadb_x_sa2_reqid = reqid;
3575 * set data into sadb_x_policy
3577 static struct mbuf *
3578 key_setsadbxpolicy(u_int16_t type, u_int8_t dir, u_int32_t id)
3581 struct sadb_x_policy *p;
3584 len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3585 m = key_alloc_mbuf(len);
3586 if (!m || m->m_next) { /*XXX*/
3592 p = mtod(m, struct sadb_x_policy *);
3595 p->sadb_x_policy_len = PFKEY_UNIT64(len);
3596 p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3597 p->sadb_x_policy_type = type;
3598 p->sadb_x_policy_dir = dir;
3599 p->sadb_x_policy_id = id;
3605 /* Take a key message (sadb_key) from the socket and turn it into one
3606 * of the kernel's key structures (seckey).
3608 * IN: pointer to the src
3609 * OUT: NULL no more memory
3612 key_dup_keymsg(const struct sadb_key *src, u_int len,
3613 struct malloc_type *type)
3616 dst = (struct seckey *)malloc(sizeof(struct seckey), type, M_NOWAIT);
3618 dst->bits = src->sadb_key_bits;
3619 dst->key_data = (char *)malloc(len, type, M_NOWAIT);
3620 if (dst->key_data != NULL) {
3621 bcopy((const char *)src + sizeof(struct sadb_key),
3622 dst->key_data, len);
3624 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3630 ipseclog((LOG_DEBUG, "%s: No more memory.\n",
3637 /* Take a lifetime message (sadb_lifetime) passed in on a socket and
3638 * turn it into one of the kernel's lifetime structures (seclifetime).
3640 * IN: pointer to the destination, source and malloc type
3641 * OUT: NULL, no more memory
3644 static struct seclifetime *
3645 key_dup_lifemsg(const struct sadb_lifetime *src,
3646 struct malloc_type *type)
3648 struct seclifetime *dst = NULL;
3650 dst = (struct seclifetime *)malloc(sizeof(struct seclifetime),
3654 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
3656 dst->allocations = src->sadb_lifetime_allocations;
3657 dst->bytes = src->sadb_lifetime_bytes;
3658 dst->addtime = src->sadb_lifetime_addtime;
3659 dst->usetime = src->sadb_lifetime_usetime;
3664 /* compare my own address
3665 * OUT: 1: true, i.e. my address.
3670 struct sockaddr *sa;
3673 struct sockaddr_in *sin;
3674 struct in_ifaddr *ia;
3677 IPSEC_ASSERT(sa != NULL, ("null sockaddr"));
3679 switch (sa->sa_family) {
3682 sin = (struct sockaddr_in *)sa;
3683 for (ia = in_ifaddrhead.tqh_first; ia;
3684 ia = ia->ia_link.tqe_next)
3686 if (sin->sin_family == ia->ia_addr.sin_family &&
3687 sin->sin_len == ia->ia_addr.sin_len &&
3688 sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3697 return key_ismyaddr6((struct sockaddr_in6 *)sa);
3706 * compare my own address for IPv6.
3709 * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3711 #include <netinet6/in6_var.h>
3715 struct sockaddr_in6 *sin6;
3717 struct in6_ifaddr *ia;
3718 struct in6_multi *in6m;
3720 for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
3721 if (key_sockaddrcmp((struct sockaddr *)&sin6,
3722 (struct sockaddr *)&ia->ia_addr, 0) == 0)
3727 * XXX why do we care about multlicast here while we don't care
3728 * about IPv4 multicast??
3732 IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
3737 /* loopback, just for safety */
3738 if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
3746 * compare two secasindex structure.
3747 * flag can specify to compare 2 saidxes.
3748 * compare two secasindex structure without both mode and reqid.
3749 * don't compare port.
3751 * saidx0: source, it can be in SAD.
3759 const struct secasindex *saidx0,
3760 const struct secasindex *saidx1,
3764 if (saidx0 == NULL && saidx1 == NULL)
3767 if (saidx0 == NULL || saidx1 == NULL)
3770 if (saidx0->proto != saidx1->proto)
3773 if (flag == CMP_EXACTLY) {
3774 if (saidx0->mode != saidx1->mode)
3776 if (saidx0->reqid != saidx1->reqid)
3778 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
3779 bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
3783 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
3784 if (flag == CMP_MODE_REQID
3785 ||flag == CMP_REQID) {
3787 * If reqid of SPD is non-zero, unique SA is required.
3788 * The result must be of same reqid in this case.
3790 if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
3794 if (flag == CMP_MODE_REQID) {
3795 if (saidx0->mode != IPSEC_MODE_ANY
3796 && saidx0->mode != saidx1->mode)
3800 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0) {
3803 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0) {
3812 * compare two secindex structure exactly.
3814 * spidx0: source, it is often in SPD.
3815 * spidx1: object, it is often from PFKEY message.
3821 key_cmpspidx_exactly(
3822 struct secpolicyindex *spidx0,
3823 struct secpolicyindex *spidx1)
3826 if (spidx0 == NULL && spidx1 == NULL)
3829 if (spidx0 == NULL || spidx1 == NULL)
3832 if (spidx0->prefs != spidx1->prefs
3833 || spidx0->prefd != spidx1->prefd
3834 || spidx0->ul_proto != spidx1->ul_proto)
3837 return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
3838 key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
3842 * compare two secindex structure with mask.
3844 * spidx0: source, it is often in SPD.
3845 * spidx1: object, it is often from IP header.
3851 key_cmpspidx_withmask(
3852 struct secpolicyindex *spidx0,
3853 struct secpolicyindex *spidx1)
3856 if (spidx0 == NULL && spidx1 == NULL)
3859 if (spidx0 == NULL || spidx1 == NULL)
3862 if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
3863 spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
3864 spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
3865 spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
3868 /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
3869 if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
3870 && spidx0->ul_proto != spidx1->ul_proto)
3873 switch (spidx0->src.sa.sa_family) {
3875 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
3876 && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
3878 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
3879 &spidx1->src.sin.sin_addr, spidx0->prefs))
3883 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
3884 && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
3887 * scope_id check. if sin6_scope_id is 0, we regard it
3888 * as a wildcard scope, which matches any scope zone ID.
3890 if (spidx0->src.sin6.sin6_scope_id &&
3891 spidx1->src.sin6.sin6_scope_id &&
3892 spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
3894 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
3895 &spidx1->src.sin6.sin6_addr, spidx0->prefs))
3900 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
3905 switch (spidx0->dst.sa.sa_family) {
3907 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
3908 && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
3910 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
3911 &spidx1->dst.sin.sin_addr, spidx0->prefd))
3915 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
3916 && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
3919 * scope_id check. if sin6_scope_id is 0, we regard it
3920 * as a wildcard scope, which matches any scope zone ID.
3922 if (spidx0->dst.sin6.sin6_scope_id &&
3923 spidx1->dst.sin6.sin6_scope_id &&
3924 spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
3926 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
3927 &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
3932 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
3937 /* XXX Do we check other field ? e.g. flowinfo */
3942 /* returns 0 on match */
3945 const struct sockaddr *sa1,
3946 const struct sockaddr *sa2,
3952 #define satosin(s) ((const struct sockaddr_in *)s)
3956 #define satosin6(s) ((const struct sockaddr_in6 *)s)
3957 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
3960 switch (sa1->sa_family) {
3962 if (sa1->sa_len != sizeof(struct sockaddr_in))
3964 if (satosin(sa1)->sin_addr.s_addr !=
3965 satosin(sa2)->sin_addr.s_addr) {
3968 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
3972 if (sa1->sa_len != sizeof(struct sockaddr_in6))
3973 return 1; /*EINVAL*/
3974 if (satosin6(sa1)->sin6_scope_id !=
3975 satosin6(sa2)->sin6_scope_id) {
3978 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
3979 &satosin6(sa2)->sin6_addr)) {
3983 satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
3988 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
3999 * compare two buffers with mask.
4003 * bits: Number of bits to compare
4009 key_bbcmp(const void *a1, const void *a2, u_int bits)
4011 const unsigned char *p1 = a1;
4012 const unsigned char *p2 = a2;
4014 /* XXX: This could be considerably faster if we compare a word
4015 * at a time, but it is complicated on LSB Endian machines */
4017 /* Handle null pointers */
4018 if (p1 == NULL || p2 == NULL)
4028 u_int8_t mask = ~((1<<(8-bits))-1);
4029 if ((*p1 & mask) != (*p2 & mask))
4032 return 1; /* Match! */
4036 key_flush_spd(time_t now)
4038 static u_int16_t sptree_scangen = 0;
4039 u_int16_t gen = sptree_scangen++;
4040 struct secpolicy *sp;
4044 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4047 LIST_FOREACH(sp, &sptree[dir], chain) {
4048 if (sp->scangen == gen) /* previously handled */
4051 if (sp->state == IPSEC_SPSTATE_DEAD) {
4052 /* NB: clean entries created by key_spdflush */
4057 if (sp->lifetime == 0 && sp->validtime == 0)
4059 if ((sp->lifetime && now - sp->created > sp->lifetime)
4060 || (sp->validtime && now - sp->lastused > sp->validtime)) {
4061 sp->state = IPSEC_SPSTATE_DEAD;
4073 key_flush_sad(time_t now)
4075 struct secashead *sah, *nextsah;
4076 struct secasvar *sav, *nextsav;
4080 LIST_FOREACH_SAFE(sah, &sahtree, chain, nextsah) {
4081 /* if sah has been dead, then delete it and process next sah. */
4082 if (sah->state == SADB_SASTATE_DEAD) {
4087 /* if LARVAL entry doesn't become MATURE, delete it. */
4088 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_LARVAL], chain, nextsav) {
4089 if (now - sav->created > key_larval_lifetime)
4094 * check MATURE entry to start to send expire message
4097 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_MATURE], chain, nextsav) {
4098 /* we don't need to check. */
4099 if (sav->lft_s == NULL)
4103 if (sav->lft_c == NULL) {
4104 ipseclog((LOG_DEBUG,"%s: there is no CURRENT "
4105 "time, why?\n", __func__));
4109 /* check SOFT lifetime */
4110 if (sav->lft_s->addtime != 0 &&
4111 now - sav->created > sav->lft_s->addtime) {
4112 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4114 * Actually, only send expire message if
4115 * SA has been used, as it was done before,
4116 * but should we always send such message,
4117 * and let IKE daemon decide if it should be
4118 * renegotiated or not ?
4119 * XXX expire message will actually NOT be
4120 * sent if SA is only used after soft
4121 * lifetime has been reached, see below
4124 if (sav->lft_c->usetime != 0)
4127 /* check SOFT lifetime by bytes */
4129 * XXX I don't know the way to delete this SA
4130 * when new SA is installed. Caution when it's
4131 * installed too big lifetime by time.
4133 else if (sav->lft_s->bytes != 0 &&
4134 sav->lft_s->bytes < sav->lft_c->bytes) {
4136 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4138 * XXX If we keep to send expire
4139 * message in the status of
4140 * DYING. Do remove below code.
4146 /* check DYING entry to change status to DEAD. */
4147 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DYING], chain, nextsav) {
4148 /* we don't need to check. */
4149 if (sav->lft_h == NULL)
4153 if (sav->lft_c == NULL) {
4154 ipseclog((LOG_DEBUG, "%s: there is no CURRENT "
4155 "time, why?\n", __func__));
4159 if (sav->lft_h->addtime != 0 &&
4160 now - sav->created > sav->lft_h->addtime) {
4161 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4164 #if 0 /* XXX Should we keep to send expire message until HARD lifetime ? */
4165 else if (sav->lft_s != NULL
4166 && sav->lft_s->addtime != 0
4167 && now - sav->created > sav->lft_s->addtime) {
4169 * XXX: should be checked to be
4170 * installed the valid SA.
4174 * If there is no SA then sending
4180 /* check HARD lifetime by bytes */
4181 else if (sav->lft_h->bytes != 0 &&
4182 sav->lft_h->bytes < sav->lft_c->bytes) {
4183 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4188 /* delete entry in DEAD */
4189 LIST_FOREACH_SAFE(sav, &sah->savtree[SADB_SASTATE_DEAD], chain, nextsav) {
4191 if (sav->state != SADB_SASTATE_DEAD) {
4192 ipseclog((LOG_DEBUG, "%s: invalid sav->state "
4193 "(queue: %d SA: %d): kill it anyway\n",
4195 SADB_SASTATE_DEAD, sav->state));
4198 * do not call key_freesav() here.
4199 * sav should already be freed, and sav->refcnt
4200 * shows other references to sav
4201 * (such as from SPD).
4209 key_flush_acq(time_t now)
4211 struct secacq *acq, *nextacq;
4215 for (acq = LIST_FIRST(&acqtree); acq != NULL; acq = nextacq) {
4216 nextacq = LIST_NEXT(acq, chain);
4217 if (now - acq->created > key_blockacq_lifetime
4218 && __LIST_CHAINED(acq)) {
4219 LIST_REMOVE(acq, chain);
4220 free(acq, M_IPSEC_SAQ);
4227 key_flush_spacq(time_t now)
4229 struct secspacq *acq, *nextacq;
4233 for (acq = LIST_FIRST(&spacqtree); acq != NULL; acq = nextacq) {
4234 nextacq = LIST_NEXT(acq, chain);
4235 if (now - acq->created > key_blockacq_lifetime
4236 && __LIST_CHAINED(acq)) {
4237 LIST_REMOVE(acq, chain);
4238 free(acq, M_IPSEC_SAQ);
4246 * scanning SPD and SAD to check status for each entries,
4247 * and do to remove or to expire.
4248 * XXX: year 2038 problem may remain.
4251 key_timehandler(void)
4253 time_t now = time_second;
4258 key_flush_spacq(now);
4260 #ifndef IPSEC_DEBUG2
4261 /* do exchange to tick time !! */
4262 (void)timeout((void *)key_timehandler, (void *)0, hz);
4263 #endif /* IPSEC_DEBUG2 */
4271 key_randomfill(&value, sizeof(value));
4276 key_randomfill(p, l)
4282 static int warn = 1;
4285 n = (size_t)read_random(p, (u_int)l);
4289 bcopy(&v, (u_int8_t *)p + n,
4290 l - n < sizeof(v) ? l - n : sizeof(v));
4294 printf("WARNING: pseudo-random number generator "
4295 "used for IPsec processing\n");
4302 * map SADB_SATYPE_* to IPPROTO_*.
4303 * if satype == SADB_SATYPE then satype is mapped to ~0.
4305 * 0: invalid satype.
4308 key_satype2proto(u_int8_t satype)
4311 case SADB_SATYPE_UNSPEC:
4312 return IPSEC_PROTO_ANY;
4313 case SADB_SATYPE_AH:
4315 case SADB_SATYPE_ESP:
4317 case SADB_X_SATYPE_IPCOMP:
4318 return IPPROTO_IPCOMP;
4319 case SADB_X_SATYPE_TCPSIGNATURE:
4328 * map IPPROTO_* to SADB_SATYPE_*
4330 * 0: invalid protocol type.
4333 key_proto2satype(u_int16_t proto)
4337 return SADB_SATYPE_AH;
4339 return SADB_SATYPE_ESP;
4340 case IPPROTO_IPCOMP:
4341 return SADB_X_SATYPE_IPCOMP;
4343 return SADB_X_SATYPE_TCPSIGNATURE;
4352 * SADB_GETSPI processing is to receive
4353 * <base, (SA2), src address, dst address, (SPI range)>
4354 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4355 * tree with the status of LARVAL, and send
4356 * <base, SA(*), address(SD)>
4359 * IN: mhp: pointer to the pointer to each header.
4360 * OUT: NULL if fail.
4361 * other if success, return pointer to the message to send.
4364 key_getspi(so, m, mhp)
4367 const struct sadb_msghdr *mhp;
4369 struct sadb_address *src0, *dst0;
4370 struct secasindex saidx;
4371 struct secashead *newsah;
4372 struct secasvar *newsav;
4379 IPSEC_ASSERT(so != NULL, ("null socket"));
4380 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4381 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4382 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4384 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4385 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4386 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4388 return key_senderror(so, m, EINVAL);
4390 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4391 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4392 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4394 return key_senderror(so, m, EINVAL);
4396 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4397 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4398 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4400 mode = IPSEC_MODE_ANY;
4404 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4405 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4407 /* map satype to proto */
4408 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4409 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4411 return key_senderror(so, m, EINVAL);
4414 /* make sure if port number is zero. */
4415 switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4417 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4418 sizeof(struct sockaddr_in))
4419 return key_senderror(so, m, EINVAL);
4420 ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4423 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4424 sizeof(struct sockaddr_in6))
4425 return key_senderror(so, m, EINVAL);
4426 ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4431 switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4433 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4434 sizeof(struct sockaddr_in))
4435 return key_senderror(so, m, EINVAL);
4436 ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4439 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4440 sizeof(struct sockaddr_in6))
4441 return key_senderror(so, m, EINVAL);
4442 ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4448 /* XXX boundary check against sa_len */
4449 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4451 /* SPI allocation */
4452 spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4455 return key_senderror(so, m, EINVAL);
4457 /* get a SA index */
4458 if ((newsah = key_getsah(&saidx)) == NULL) {
4459 /* create a new SA index */
4460 if ((newsah = key_newsah(&saidx)) == NULL) {
4461 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4462 return key_senderror(so, m, ENOBUFS);
4468 newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4469 if (newsav == NULL) {
4470 /* XXX don't free new SA index allocated in above. */
4471 return key_senderror(so, m, error);
4475 newsav->spi = htonl(spi);
4477 /* delete the entry in acqtree */
4478 if (mhp->msg->sadb_msg_seq != 0) {
4480 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4481 /* reset counter in order to deletion by timehandler. */
4482 acq->created = time_second;
4488 struct mbuf *n, *nn;
4489 struct sadb_sa *m_sa;
4490 struct sadb_msg *newmsg;
4493 /* create new sadb_msg to reply. */
4494 len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4495 PFKEY_ALIGN8(sizeof(struct sadb_sa));
4497 MGETHDR(n, M_DONTWAIT, MT_DATA);
4499 MCLGET(n, M_DONTWAIT);
4500 if ((n->m_flags & M_EXT) == 0) {
4506 return key_senderror(so, m, ENOBUFS);
4512 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4513 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4515 m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4516 m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4517 m_sa->sadb_sa_exttype = SADB_EXT_SA;
4518 m_sa->sadb_sa_spi = htonl(spi);
4519 off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4521 IPSEC_ASSERT(off == len,
4522 ("length inconsistency (off %u len %u)", off, len));
4524 n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
4525 SADB_EXT_ADDRESS_DST);
4528 return key_senderror(so, m, ENOBUFS);
4531 if (n->m_len < sizeof(struct sadb_msg)) {
4532 n = m_pullup(n, sizeof(struct sadb_msg));
4534 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4537 n->m_pkthdr.len = 0;
4538 for (nn = n; nn; nn = nn->m_next)
4539 n->m_pkthdr.len += nn->m_len;
4541 newmsg = mtod(n, struct sadb_msg *);
4542 newmsg->sadb_msg_seq = newsav->seq;
4543 newmsg->sadb_msg_errno = 0;
4544 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4547 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4552 * allocating new SPI
4553 * called by key_getspi().
4559 key_do_getnewspi(spirange, saidx)
4560 struct sadb_spirange *spirange;
4561 struct secasindex *saidx;
4565 int count = key_spi_trycnt;
4567 /* set spi range to allocate */
4568 if (spirange != NULL) {
4569 min = spirange->sadb_spirange_min;
4570 max = spirange->sadb_spirange_max;
4572 min = key_spi_minval;
4573 max = key_spi_maxval;
4575 /* IPCOMP needs 2-byte SPI */
4576 if (saidx->proto == IPPROTO_IPCOMP) {
4583 t = min; min = max; max = t;
4588 if (key_checkspidup(saidx, min) != NULL) {
4589 ipseclog((LOG_DEBUG, "%s: SPI %u exists already.\n",
4594 count--; /* taking one cost. */
4602 /* when requesting to allocate spi ranged */
4604 /* generate pseudo-random SPI value ranged. */
4605 newspi = min + (key_random() % (max - min + 1));
4607 if (key_checkspidup(saidx, newspi) == NULL)
4611 if (count == 0 || newspi == 0) {
4612 ipseclog((LOG_DEBUG, "%s: to allocate spi is failed.\n",
4619 keystat.getspi_count =
4620 (keystat.getspi_count + key_spi_trycnt - count) / 2;
4626 * SADB_UPDATE processing
4628 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4629 * key(AE), (identity(SD),) (sensitivity)>
4630 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
4632 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4633 * (identity(SD),) (sensitivity)>
4636 * m will always be freed.
4639 key_update(so, m, mhp)
4642 const struct sadb_msghdr *mhp;
4644 struct sadb_sa *sa0;
4645 struct sadb_address *src0, *dst0;
4646 struct secasindex saidx;
4647 struct secashead *sah;
4648 struct secasvar *sav;
4654 IPSEC_ASSERT(so != NULL, ("null socket"));
4655 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4656 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4657 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4659 /* map satype to proto */
4660 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4661 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4663 return key_senderror(so, m, EINVAL);
4666 if (mhp->ext[SADB_EXT_SA] == NULL ||
4667 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4668 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4669 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4670 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4671 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4672 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4673 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4674 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4675 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4676 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4677 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4679 return key_senderror(so, m, EINVAL);
4681 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4682 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4683 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4684 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4686 return key_senderror(so, m, EINVAL);
4688 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4689 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4690 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4692 mode = IPSEC_MODE_ANY;
4695 /* XXX boundary checking for other extensions */
4697 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4698 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4699 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4701 /* XXX boundary check against sa_len */
4702 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4704 /* get a SA header */
4705 if ((sah = key_getsah(&saidx)) == NULL) {
4706 ipseclog((LOG_DEBUG, "%s: no SA index found.\n", __func__));
4707 return key_senderror(so, m, ENOENT);
4710 /* set spidx if there */
4712 error = key_setident(sah, m, mhp);
4714 return key_senderror(so, m, error);
4716 /* find a SA with sequence number. */
4717 #ifdef IPSEC_DOSEQCHECK
4718 if (mhp->msg->sadb_msg_seq != 0
4719 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
4720 ipseclog((LOG_DEBUG, "%s: no larval SA with sequence %u "
4721 "exists.\n", __func__, mhp->msg->sadb_msg_seq));
4722 return key_senderror(so, m, ENOENT);
4726 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
4729 ipseclog((LOG_DEBUG, "%s: no such a SA found (spi:%u)\n",
4730 __func__, (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4731 return key_senderror(so, m, EINVAL);
4735 /* validity check */
4736 if (sav->sah->saidx.proto != proto) {
4737 ipseclog((LOG_DEBUG, "%s: protocol mismatched "
4738 "(DB=%u param=%u)\n", __func__,
4739 sav->sah->saidx.proto, proto));
4740 return key_senderror(so, m, EINVAL);
4742 #ifdef IPSEC_DOSEQCHECK
4743 if (sav->spi != sa0->sadb_sa_spi) {
4744 ipseclog((LOG_DEBUG, "%s: SPI mismatched (DB:%u param:%u)\n",
4746 (u_int32_t)ntohl(sav->spi),
4747 (u_int32_t)ntohl(sa0->sadb_sa_spi)));
4748 return key_senderror(so, m, EINVAL);
4751 if (sav->pid != mhp->msg->sadb_msg_pid) {
4752 ipseclog((LOG_DEBUG, "%s: pid mismatched (DB:%u param:%u)\n",
4753 __func__, sav->pid, mhp->msg->sadb_msg_pid));
4754 return key_senderror(so, m, EINVAL);
4757 /* copy sav values */
4758 error = key_setsaval(sav, m, mhp);
4761 return key_senderror(so, m, error);
4764 /* check SA values to be mature. */
4765 if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
4767 return key_senderror(so, m, 0);
4773 /* set msg buf from mhp */
4774 n = key_getmsgbuf_x1(m, mhp);
4776 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4777 return key_senderror(so, m, ENOBUFS);
4781 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4786 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
4787 * only called by key_update().
4790 * others : found, pointer to a SA.
4792 #ifdef IPSEC_DOSEQCHECK
4793 static struct secasvar *
4794 key_getsavbyseq(sah, seq)
4795 struct secashead *sah;
4798 struct secasvar *sav;
4801 state = SADB_SASTATE_LARVAL;
4803 /* search SAD with sequence number ? */
4804 LIST_FOREACH(sav, &sah->savtree[state], chain) {
4806 KEY_CHKSASTATE(state, sav->state, __func__);
4808 if (sav->seq == seq) {
4810 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
4811 printf("DP %s cause refcnt++:%d SA:%p\n",
4812 __func__, sav->refcnt, sav));
4822 * SADB_ADD processing
4823 * add an entry to SA database, when received
4824 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4825 * key(AE), (identity(SD),) (sensitivity)>
4828 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
4829 * (identity(SD),) (sensitivity)>
4832 * IGNORE identity and sensitivity messages.
4834 * m will always be freed.
4840 const struct sadb_msghdr *mhp;
4842 struct sadb_sa *sa0;
4843 struct sadb_address *src0, *dst0;
4844 struct secasindex saidx;
4845 struct secashead *newsah;
4846 struct secasvar *newsav;
4852 IPSEC_ASSERT(so != NULL, ("null socket"));
4853 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4854 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4855 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4857 /* map satype to proto */
4858 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4859 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
4861 return key_senderror(so, m, EINVAL);
4864 if (mhp->ext[SADB_EXT_SA] == NULL ||
4865 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4866 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
4867 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
4868 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
4869 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
4870 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
4871 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
4872 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
4873 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
4874 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
4875 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4877 return key_senderror(so, m, EINVAL);
4879 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
4880 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4881 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4883 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
4885 return key_senderror(so, m, EINVAL);
4887 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4888 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4889 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4891 mode = IPSEC_MODE_ANY;
4895 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
4896 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
4897 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
4899 /* XXX boundary check against sa_len */
4900 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4902 /* get a SA header */
4903 if ((newsah = key_getsah(&saidx)) == NULL) {
4904 /* create a new SA header */
4905 if ((newsah = key_newsah(&saidx)) == NULL) {
4906 ipseclog((LOG_DEBUG, "%s: No more memory.\n",__func__));
4907 return key_senderror(so, m, ENOBUFS);
4911 /* set spidx if there */
4913 error = key_setident(newsah, m, mhp);
4915 return key_senderror(so, m, error);
4918 /* create new SA entry. */
4919 /* We can create new SA only if SPI is differenct. */
4921 newsav = key_getsavbyspi(newsah, sa0->sadb_sa_spi);
4923 if (newsav != NULL) {
4924 ipseclog((LOG_DEBUG, "%s: SA already exists.\n", __func__));
4925 return key_senderror(so, m, EEXIST);
4927 newsav = KEY_NEWSAV(m, mhp, newsah, &error);
4928 if (newsav == NULL) {
4929 return key_senderror(so, m, error);
4932 /* check SA values to be mature. */
4933 if ((error = key_mature(newsav)) != 0) {
4934 KEY_FREESAV(&newsav);
4935 return key_senderror(so, m, error);
4939 * don't call key_freesav() here, as we would like to keep the SA
4940 * in the database on success.
4946 /* set msg buf from mhp */
4947 n = key_getmsgbuf_x1(m, mhp);
4949 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
4950 return key_senderror(so, m, ENOBUFS);
4954 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
4960 key_setident(sah, m, mhp)
4961 struct secashead *sah;
4963 const struct sadb_msghdr *mhp;
4965 const struct sadb_ident *idsrc, *iddst;
4966 int idsrclen, iddstlen;
4968 IPSEC_ASSERT(sah != NULL, ("null secashead"));
4969 IPSEC_ASSERT(m != NULL, ("null mbuf"));
4970 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
4971 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
4973 /* don't make buffer if not there */
4974 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
4975 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4981 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
4982 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
4983 ipseclog((LOG_DEBUG, "%s: invalid identity.\n", __func__));
4987 idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
4988 iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
4989 idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
4990 iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
4992 /* validity check */
4993 if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
4994 ipseclog((LOG_DEBUG, "%s: ident type mismatch.\n", __func__));
4998 switch (idsrc->sadb_ident_type) {
4999 case SADB_IDENTTYPE_PREFIX:
5000 case SADB_IDENTTYPE_FQDN:
5001 case SADB_IDENTTYPE_USERFQDN:
5003 /* XXX do nothing */
5009 /* make structure */
5010 sah->idents = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5011 if (sah->idents == NULL) {
5012 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5015 sah->identd = malloc(sizeof(struct secident), M_IPSEC_MISC, M_NOWAIT);
5016 if (sah->identd == NULL) {
5017 free(sah->idents, M_IPSEC_MISC);
5019 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5022 sah->idents->type = idsrc->sadb_ident_type;
5023 sah->idents->id = idsrc->sadb_ident_id;
5025 sah->identd->type = iddst->sadb_ident_type;
5026 sah->identd->id = iddst->sadb_ident_id;
5032 * m will not be freed on return.
5033 * it is caller's responsibility to free the result.
5035 static struct mbuf *
5036 key_getmsgbuf_x1(m, mhp)
5038 const struct sadb_msghdr *mhp;
5042 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5043 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5044 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5046 /* create new sadb_msg to reply. */
5047 n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
5048 SADB_EXT_SA, SADB_X_EXT_SA2,
5049 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
5050 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
5051 SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
5055 if (n->m_len < sizeof(struct sadb_msg)) {
5056 n = m_pullup(n, sizeof(struct sadb_msg));
5060 mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5061 mtod(n, struct sadb_msg *)->sadb_msg_len =
5062 PFKEY_UNIT64(n->m_pkthdr.len);
5067 static int key_delete_all __P((struct socket *, struct mbuf *,
5068 const struct sadb_msghdr *, u_int16_t));
5071 * SADB_DELETE processing
5073 * <base, SA(*), address(SD)>
5074 * from the ikmpd, and set SADB_SASTATE_DEAD,
5076 * <base, SA(*), address(SD)>
5079 * m will always be freed.
5082 key_delete(so, m, mhp)
5085 const struct sadb_msghdr *mhp;
5087 struct sadb_sa *sa0;
5088 struct sadb_address *src0, *dst0;
5089 struct secasindex saidx;
5090 struct secashead *sah;
5091 struct secasvar *sav = NULL;
5094 IPSEC_ASSERT(so != NULL, ("null socket"));
5095 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5096 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5097 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5099 /* map satype to proto */
5100 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5101 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5103 return key_senderror(so, m, EINVAL);
5106 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5107 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5108 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5110 return key_senderror(so, m, EINVAL);
5113 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5114 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5115 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5117 return key_senderror(so, m, EINVAL);
5120 if (mhp->ext[SADB_EXT_SA] == NULL) {
5122 * Caller wants us to delete all non-LARVAL SAs
5123 * that match the src/dst. This is used during
5124 * IKE INITIAL-CONTACT.
5126 ipseclog((LOG_DEBUG, "%s: doing delete all.\n", __func__));
5127 return key_delete_all(so, m, mhp, proto);
5128 } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5129 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5131 return key_senderror(so, m, EINVAL);
5134 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5135 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5136 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5138 /* XXX boundary check against sa_len */
5139 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5141 /* get a SA header */
5143 LIST_FOREACH(sah, &sahtree, chain) {
5144 if (sah->state == SADB_SASTATE_DEAD)
5146 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5149 /* get a SA with SPI. */
5150 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5156 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5157 return key_senderror(so, m, ENOENT);
5160 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5166 struct sadb_msg *newmsg;
5168 /* create new sadb_msg to reply. */
5169 n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
5170 SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5172 return key_senderror(so, m, ENOBUFS);
5174 if (n->m_len < sizeof(struct sadb_msg)) {
5175 n = m_pullup(n, sizeof(struct sadb_msg));
5177 return key_senderror(so, m, ENOBUFS);
5179 newmsg = mtod(n, struct sadb_msg *);
5180 newmsg->sadb_msg_errno = 0;
5181 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5184 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5189 * delete all SAs for src/dst. Called from key_delete().
5192 key_delete_all(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp,
5195 struct sadb_address *src0, *dst0;
5196 struct secasindex saidx;
5197 struct secashead *sah;
5198 struct secasvar *sav, *nextsav;
5199 u_int stateidx, state;
5201 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5202 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5204 /* XXX boundary check against sa_len */
5205 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5208 LIST_FOREACH(sah, &sahtree, chain) {
5209 if (sah->state == SADB_SASTATE_DEAD)
5211 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5214 /* Delete all non-LARVAL SAs. */
5216 stateidx < _ARRAYLEN(saorder_state_alive);
5218 state = saorder_state_alive[stateidx];
5219 if (state == SADB_SASTATE_LARVAL)
5221 for (sav = LIST_FIRST(&sah->savtree[state]);
5222 sav != NULL; sav = nextsav) {
5223 nextsav = LIST_NEXT(sav, chain);
5225 if (sav->state != state) {
5226 ipseclog((LOG_DEBUG, "%s: invalid "
5227 "sav->state (queue %d SA %d)\n",
5228 __func__, state, sav->state));
5232 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5240 struct sadb_msg *newmsg;
5242 /* create new sadb_msg to reply. */
5243 n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
5244 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
5246 return key_senderror(so, m, ENOBUFS);
5248 if (n->m_len < sizeof(struct sadb_msg)) {
5249 n = m_pullup(n, sizeof(struct sadb_msg));
5251 return key_senderror(so, m, ENOBUFS);
5253 newmsg = mtod(n, struct sadb_msg *);
5254 newmsg->sadb_msg_errno = 0;
5255 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5258 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5263 * SADB_GET processing
5265 * <base, SA(*), address(SD)>
5266 * from the ikmpd, and get a SP and a SA to respond,
5268 * <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5269 * (identity(SD),) (sensitivity)>
5272 * m will always be freed.
5278 const struct sadb_msghdr *mhp;
5280 struct sadb_sa *sa0;
5281 struct sadb_address *src0, *dst0;
5282 struct secasindex saidx;
5283 struct secashead *sah;
5284 struct secasvar *sav = NULL;
5287 IPSEC_ASSERT(so != NULL, ("null socket"));
5288 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5289 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5290 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5292 /* map satype to proto */
5293 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5294 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5296 return key_senderror(so, m, EINVAL);
5299 if (mhp->ext[SADB_EXT_SA] == NULL ||
5300 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5301 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5302 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5304 return key_senderror(so, m, EINVAL);
5306 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5307 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5308 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5309 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5311 return key_senderror(so, m, EINVAL);
5314 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5315 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5316 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5318 /* XXX boundary check against sa_len */
5319 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5321 /* get a SA header */
5323 LIST_FOREACH(sah, &sahtree, chain) {
5324 if (sah->state == SADB_SASTATE_DEAD)
5326 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5329 /* get a SA with SPI. */
5330 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5336 ipseclog((LOG_DEBUG, "%s: no SA found.\n", __func__));
5337 return key_senderror(so, m, ENOENT);
5344 /* map proto to satype */
5345 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5346 ipseclog((LOG_DEBUG, "%s: there was invalid proto in SAD.\n",
5348 return key_senderror(so, m, EINVAL);
5351 /* create new sadb_msg to reply. */
5352 n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5353 mhp->msg->sadb_msg_pid);
5355 return key_senderror(so, m, ENOBUFS);
5358 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5362 /* XXX make it sysctl-configurable? */
5364 key_getcomb_setlifetime(comb)
5365 struct sadb_comb *comb;
5368 comb->sadb_comb_soft_allocations = 1;
5369 comb->sadb_comb_hard_allocations = 1;
5370 comb->sadb_comb_soft_bytes = 0;
5371 comb->sadb_comb_hard_bytes = 0;
5372 comb->sadb_comb_hard_addtime = 86400; /* 1 day */
5373 comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5374 comb->sadb_comb_soft_usetime = 28800; /* 8 hours */
5375 comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5379 * XXX reorder combinations by preference
5380 * XXX no idea if the user wants ESP authentication or not
5382 static struct mbuf *
5385 struct sadb_comb *comb;
5386 struct enc_xform *algo;
5387 struct mbuf *result = NULL, *m, *n;
5391 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5394 for (i = 1; i <= SADB_EALG_MAX; i++) {
5395 algo = esp_algorithm_lookup(i);
5399 /* discard algorithms with key size smaller than system min */
5400 if (_BITS(algo->maxkey) < ipsec_esp_keymin)
5402 if (_BITS(algo->minkey) < ipsec_esp_keymin)
5403 encmin = ipsec_esp_keymin;
5405 encmin = _BITS(algo->minkey);
5408 m = key_getcomb_ah();
5410 IPSEC_ASSERT(l <= MLEN,
5411 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
5412 MGET(m, M_DONTWAIT, MT_DATA);
5417 bzero(mtod(m, caddr_t), m->m_len);
5424 for (n = m; n; n = n->m_next)
5426 IPSEC_ASSERT((totlen % l) == 0, ("totlen=%u, l=%u", totlen, l));
5428 for (off = 0; off < totlen; off += l) {
5429 n = m_pulldown(m, off, l, &o);
5431 /* m is already freed */
5434 comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5435 bzero(comb, sizeof(*comb));
5436 key_getcomb_setlifetime(comb);
5437 comb->sadb_comb_encrypt = i;
5438 comb->sadb_comb_encrypt_minbits = encmin;
5439 comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
5458 const struct auth_hash *ah,
5463 *min = *max = ah->keysize;
5464 if (ah->keysize == 0) {
5466 * Transform takes arbitrary key size but algorithm
5467 * key size is restricted. Enforce this here.
5470 case SADB_X_AALG_MD5: *min = *max = 16; break;
5471 case SADB_X_AALG_SHA: *min = *max = 20; break;
5472 case SADB_X_AALG_NULL: *min = 1; *max = 256; break;
5474 DPRINTF(("%s: unknown AH algorithm %u\n",
5482 * XXX reorder combinations by preference
5484 static struct mbuf *
5487 struct sadb_comb *comb;
5488 struct auth_hash *algo;
5490 u_int16_t minkeysize, maxkeysize;
5492 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5495 for (i = 1; i <= SADB_AALG_MAX; i++) {
5497 /* we prefer HMAC algorithms, not old algorithms */
5498 if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5501 algo = ah_algorithm_lookup(i);
5504 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
5505 /* discard algorithms with key size smaller than system min */
5506 if (_BITS(minkeysize) < ipsec_ah_keymin)
5510 IPSEC_ASSERT(l <= MLEN,
5511 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
5512 MGET(m, M_DONTWAIT, MT_DATA);
5519 M_PREPEND(m, l, M_DONTWAIT);
5523 comb = mtod(m, struct sadb_comb *);
5524 bzero(comb, sizeof(*comb));
5525 key_getcomb_setlifetime(comb);
5526 comb->sadb_comb_auth = i;
5527 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
5528 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
5535 * not really an official behavior. discussed in pf_key@inner.net in Sep2000.
5536 * XXX reorder combinations by preference
5538 static struct mbuf *
5539 key_getcomb_ipcomp()
5541 struct sadb_comb *comb;
5542 struct comp_algo *algo;
5545 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5548 for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5549 algo = ipcomp_algorithm_lookup(i);
5554 IPSEC_ASSERT(l <= MLEN,
5555 ("l=%u > MLEN=%lu", l, (u_long) MLEN));
5556 MGET(m, M_DONTWAIT, MT_DATA);
5563 M_PREPEND(m, l, M_DONTWAIT);
5567 comb = mtod(m, struct sadb_comb *);
5568 bzero(comb, sizeof(*comb));
5569 key_getcomb_setlifetime(comb);
5570 comb->sadb_comb_encrypt = i;
5571 /* what should we set into sadb_comb_*_{min,max}bits? */
5578 * XXX no way to pass mode (transport/tunnel) to userland
5579 * XXX replay checking?
5580 * XXX sysctl interface to ipsec_{ah,esp}_keymin
5582 static struct mbuf *
5584 const struct secasindex *saidx;
5586 struct sadb_prop *prop;
5588 const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5591 switch (saidx->proto) {
5593 m = key_getcomb_esp();
5596 m = key_getcomb_ah();
5598 case IPPROTO_IPCOMP:
5599 m = key_getcomb_ipcomp();
5607 M_PREPEND(m, l, M_DONTWAIT);
5612 for (n = m; n; n = n->m_next)
5615 prop = mtod(m, struct sadb_prop *);
5616 bzero(prop, sizeof(*prop));
5617 prop->sadb_prop_len = PFKEY_UNIT64(totlen);
5618 prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5619 prop->sadb_prop_replay = 32; /* XXX */
5625 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5627 * <base, SA, address(SD), (address(P)), x_policy,
5628 * (identity(SD),) (sensitivity,) proposal>
5629 * to KMD, and expect to receive
5630 * <base> with SADB_ACQUIRE if error occured,
5632 * <base, src address, dst address, (SPI range)> with SADB_GETSPI
5633 * from KMD by PF_KEY.
5635 * XXX x_policy is outside of RFC2367 (KAME extension).
5636 * XXX sensitivity is not supported.
5637 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5638 * see comment for key_getcomb_ipcomp().
5642 * others: error number
5645 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
5647 struct mbuf *result = NULL, *m;
5648 struct secacq *newacq;
5653 IPSEC_ASSERT(saidx != NULL, ("null saidx"));
5654 satype = key_proto2satype(saidx->proto);
5655 IPSEC_ASSERT(satype != 0, ("null satype, protocol %u", saidx->proto));
5658 * We never do anything about acquirng SA. There is anather
5659 * solution that kernel blocks to send SADB_ACQUIRE message until
5660 * getting something message from IKEd. In later case, to be
5661 * managed with ACQUIRING list.
5663 /* Get an entry to check whether sending message or not. */
5664 if ((newacq = key_getacq(saidx)) != NULL) {
5665 if (key_blockacq_count < newacq->count) {
5666 /* reset counter and do send message. */
5669 /* increment counter and do nothing. */
5674 /* make new entry for blocking to send SADB_ACQUIRE. */
5675 if ((newacq = key_newacq(saidx)) == NULL)
5681 m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
5688 /* set sadb_address for saidx's. */
5689 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
5690 &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5697 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
5698 &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
5705 /* XXX proxy address (optional) */
5707 /* set sadb_x_policy */
5709 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
5717 /* XXX identity (optional) */
5719 if (idexttype && fqdn) {
5720 /* create identity extension (FQDN) */
5721 struct sadb_ident *id;
5724 fqdnlen = strlen(fqdn) + 1; /* +1 for terminating-NUL */
5725 id = (struct sadb_ident *)p;
5726 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5727 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
5728 id->sadb_ident_exttype = idexttype;
5729 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
5730 bcopy(fqdn, id + 1, fqdnlen);
5731 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
5735 /* create identity extension (USERFQDN) */
5736 struct sadb_ident *id;
5740 /* +1 for terminating-NUL */
5741 userfqdnlen = strlen(userfqdn) + 1;
5744 id = (struct sadb_ident *)p;
5745 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5746 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
5747 id->sadb_ident_exttype = idexttype;
5748 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
5749 /* XXX is it correct? */
5750 if (curproc && curproc->p_cred)
5751 id->sadb_ident_id = curproc->p_cred->p_ruid;
5752 if (userfqdn && userfqdnlen)
5753 bcopy(userfqdn, id + 1, userfqdnlen);
5754 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
5758 /* XXX sensitivity (optional) */
5760 /* create proposal/combination extension */
5761 m = key_getprop(saidx);
5764 * spec conformant: always attach proposal/combination extension,
5765 * the problem is that we have no way to attach it for ipcomp,
5766 * due to the way sadb_comb is declared in RFC2367.
5775 * outside of spec; make proposal/combination extension optional.
5781 if ((result->m_flags & M_PKTHDR) == 0) {
5786 if (result->m_len < sizeof(struct sadb_msg)) {
5787 result = m_pullup(result, sizeof(struct sadb_msg));
5788 if (result == NULL) {
5794 result->m_pkthdr.len = 0;
5795 for (m = result; m; m = m->m_next)
5796 result->m_pkthdr.len += m->m_len;
5798 mtod(result, struct sadb_msg *)->sadb_msg_len =
5799 PFKEY_UNIT64(result->m_pkthdr.len);
5801 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
5809 static struct secacq *
5810 key_newacq(const struct secasindex *saidx)
5812 struct secacq *newacq;
5815 newacq = malloc(sizeof(struct secacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5816 if (newacq == NULL) {
5817 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5822 bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
5823 newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
5824 newacq->created = time_second;
5827 /* add to acqtree */
5829 LIST_INSERT_HEAD(&acqtree, newacq, chain);
5835 static struct secacq *
5836 key_getacq(const struct secasindex *saidx)
5841 LIST_FOREACH(acq, &acqtree, chain) {
5842 if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
5850 static struct secacq *
5851 key_getacqbyseq(seq)
5857 LIST_FOREACH(acq, &acqtree, chain) {
5858 if (acq->seq == seq)
5866 static struct secspacq *
5868 struct secpolicyindex *spidx;
5870 struct secspacq *acq;
5873 acq = malloc(sizeof(struct secspacq), M_IPSEC_SAQ, M_NOWAIT|M_ZERO);
5875 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
5880 bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
5881 acq->created = time_second;
5884 /* add to spacqtree */
5886 LIST_INSERT_HEAD(&spacqtree, acq, chain);
5892 static struct secspacq *
5894 struct secpolicyindex *spidx;
5896 struct secspacq *acq;
5899 LIST_FOREACH(acq, &spacqtree, chain) {
5900 if (key_cmpspidx_exactly(spidx, &acq->spidx)) {
5901 /* NB: return holding spacq_lock */
5911 * SADB_ACQUIRE processing,
5912 * in first situation, is receiving
5914 * from the ikmpd, and clear sequence of its secasvar entry.
5916 * In second situation, is receiving
5917 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5918 * from a user land process, and return
5919 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
5922 * m will always be freed.
5925 key_acquire2(so, m, mhp)
5928 const struct sadb_msghdr *mhp;
5930 const struct sadb_address *src0, *dst0;
5931 struct secasindex saidx;
5932 struct secashead *sah;
5936 IPSEC_ASSERT(so != NULL, ("null socket"));
5937 IPSEC_ASSERT(m != NULL, ("null mbuf"));
5938 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
5939 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
5942 * Error message from KMd.
5943 * We assume that if error was occured in IKEd, the length of PFKEY
5944 * message is equal to the size of sadb_msg structure.
5945 * We do not raise error even if error occured in this function.
5947 if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
5950 /* check sequence number */
5951 if (mhp->msg->sadb_msg_seq == 0) {
5952 ipseclog((LOG_DEBUG, "%s: must specify sequence "
5953 "number.\n", __func__));
5958 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
5960 * the specified larval SA is already gone, or we got
5961 * a bogus sequence number. we can silently ignore it.
5967 /* reset acq counter in order to deletion by timehander. */
5968 acq->created = time_second;
5975 * This message is from user land.
5978 /* map satype to proto */
5979 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5980 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
5982 return key_senderror(so, m, EINVAL);
5985 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5986 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5987 mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
5989 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5991 return key_senderror(so, m, EINVAL);
5993 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5994 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
5995 mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
5997 ipseclog((LOG_DEBUG, "%s: invalid message is passed.\n",
5999 return key_senderror(so, m, EINVAL);
6002 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6003 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6005 /* XXX boundary check against sa_len */
6006 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6008 /* get a SA index */
6010 LIST_FOREACH(sah, &sahtree, chain) {
6011 if (sah->state == SADB_SASTATE_DEAD)
6013 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6018 ipseclog((LOG_DEBUG, "%s: a SA exists already.\n", __func__));
6019 return key_senderror(so, m, EEXIST);
6022 error = key_acquire(&saidx, NULL);
6024 ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
6025 __func__, mhp->msg->sadb_msg_errno));
6026 return key_senderror(so, m, error);
6029 return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6033 * SADB_REGISTER processing.
6034 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6037 * from the ikmpd, and register a socket to send PF_KEY messages,
6041 * If socket is detached, must free from regnode.
6043 * m will always be freed.
6046 key_register(so, m, mhp)
6049 const struct sadb_msghdr *mhp;
6051 struct secreg *reg, *newreg = 0;
6053 IPSEC_ASSERT(so != NULL, ("null socket"));
6054 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6055 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6056 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6058 /* check for invalid register message */
6059 if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
6060 return key_senderror(so, m, EINVAL);
6062 /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6063 if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6066 /* check whether existing or not */
6068 LIST_FOREACH(reg, ®tree[mhp->msg->sadb_msg_satype], chain) {
6069 if (reg->so == so) {
6071 ipseclog((LOG_DEBUG, "%s: socket exists already.\n",
6073 return key_senderror(so, m, EEXIST);
6077 /* create regnode */
6078 newreg = malloc(sizeof(struct secreg), M_IPSEC_SAR, M_NOWAIT|M_ZERO);
6079 if (newreg == NULL) {
6081 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6082 return key_senderror(so, m, ENOBUFS);
6086 ((struct keycb *)sotorawcb(so))->kp_registered++;
6088 /* add regnode to regtree. */
6089 LIST_INSERT_HEAD(®tree[mhp->msg->sadb_msg_satype], newreg, chain);
6095 struct sadb_msg *newmsg;
6096 struct sadb_supported *sup;
6097 u_int len, alen, elen;
6100 struct sadb_alg *alg;
6102 /* create new sadb_msg to reply. */
6104 for (i = 1; i <= SADB_AALG_MAX; i++) {
6105 if (ah_algorithm_lookup(i))
6106 alen += sizeof(struct sadb_alg);
6109 alen += sizeof(struct sadb_supported);
6111 for (i = 1; i <= SADB_EALG_MAX; i++) {
6112 if (esp_algorithm_lookup(i))
6113 elen += sizeof(struct sadb_alg);
6116 elen += sizeof(struct sadb_supported);
6118 len = sizeof(struct sadb_msg) + alen + elen;
6121 return key_senderror(so, m, ENOBUFS);
6123 MGETHDR(n, M_DONTWAIT, MT_DATA);
6125 MCLGET(n, M_DONTWAIT);
6126 if ((n->m_flags & M_EXT) == 0) {
6132 return key_senderror(so, m, ENOBUFS);
6134 n->m_pkthdr.len = n->m_len = len;
6138 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6139 newmsg = mtod(n, struct sadb_msg *);
6140 newmsg->sadb_msg_errno = 0;
6141 newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6142 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6144 /* for authentication algorithm */
6146 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6147 sup->sadb_supported_len = PFKEY_UNIT64(alen);
6148 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6149 off += PFKEY_ALIGN8(sizeof(*sup));
6151 for (i = 1; i <= SADB_AALG_MAX; i++) {
6152 struct auth_hash *aalgo;
6153 u_int16_t minkeysize, maxkeysize;
6155 aalgo = ah_algorithm_lookup(i);
6158 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6159 alg->sadb_alg_id = i;
6160 alg->sadb_alg_ivlen = 0;
6161 key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
6162 alg->sadb_alg_minbits = _BITS(minkeysize);
6163 alg->sadb_alg_maxbits = _BITS(maxkeysize);
6164 off += PFKEY_ALIGN8(sizeof(*alg));
6168 /* for encryption algorithm */
6170 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6171 sup->sadb_supported_len = PFKEY_UNIT64(elen);
6172 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6173 off += PFKEY_ALIGN8(sizeof(*sup));
6175 for (i = 1; i <= SADB_EALG_MAX; i++) {
6176 struct enc_xform *ealgo;
6178 ealgo = esp_algorithm_lookup(i);
6181 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6182 alg->sadb_alg_id = i;
6183 alg->sadb_alg_ivlen = ealgo->blocksize;
6184 alg->sadb_alg_minbits = _BITS(ealgo->minkey);
6185 alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
6186 off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6190 IPSEC_ASSERT(off == len,
6191 ("length assumption failed (off %u len %u)", off, len));
6194 return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6199 * free secreg entry registered.
6200 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6203 key_freereg(struct socket *so)
6208 IPSEC_ASSERT(so != NULL, ("NULL so"));
6211 * check whether existing or not.
6212 * check all type of SA, because there is a potential that
6213 * one socket is registered to multiple type of SA.
6216 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6217 LIST_FOREACH(reg, ®tree[i], chain) {
6218 if (reg->so == so && __LIST_CHAINED(reg)) {
6219 LIST_REMOVE(reg, chain);
6220 free(reg, M_IPSEC_SAR);
6229 * SADB_EXPIRE processing
6231 * <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6233 * NOTE: We send only soft lifetime extension.
6236 * others : error number
6239 key_expire(struct secasvar *sav)
6243 struct mbuf *result = NULL, *m;
6246 struct sadb_lifetime *lt;
6248 /* XXX: Why do we lock ? */
6249 s = splnet(); /*called from softclock()*/
6251 IPSEC_ASSERT (sav != NULL, ("null sav"));
6252 IPSEC_ASSERT (sav->sah != NULL, ("null sa header"));
6254 /* set msg header */
6255 satype = key_proto2satype(sav->sah->saidx.proto);
6256 IPSEC_ASSERT(satype != 0, ("invalid proto, satype %u", satype));
6257 m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6264 /* create SA extension */
6265 m = key_setsadbsa(sav);
6272 /* create SA extension */
6273 m = key_setsadbxsa2(sav->sah->saidx.mode,
6274 sav->replay ? sav->replay->count : 0,
6275 sav->sah->saidx.reqid);
6282 /* create lifetime extension (current and soft) */
6283 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6284 m = key_alloc_mbuf(len);
6285 if (!m || m->m_next) { /*XXX*/
6291 bzero(mtod(m, caddr_t), len);
6292 lt = mtod(m, struct sadb_lifetime *);
6293 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6294 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6295 lt->sadb_lifetime_allocations = sav->lft_c->allocations;
6296 lt->sadb_lifetime_bytes = sav->lft_c->bytes;
6297 lt->sadb_lifetime_addtime = sav->lft_c->addtime;
6298 lt->sadb_lifetime_usetime = sav->lft_c->usetime;
6299 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6300 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6301 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
6302 lt->sadb_lifetime_allocations = sav->lft_s->allocations;
6303 lt->sadb_lifetime_bytes = sav->lft_s->bytes;
6304 lt->sadb_lifetime_addtime = sav->lft_s->addtime;
6305 lt->sadb_lifetime_usetime = sav->lft_s->usetime;
6308 /* set sadb_address for source */
6309 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6310 &sav->sah->saidx.src.sa,
6311 FULLMASK, IPSEC_ULPROTO_ANY);
6318 /* set sadb_address for destination */
6319 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6320 &sav->sah->saidx.dst.sa,
6321 FULLMASK, IPSEC_ULPROTO_ANY);
6328 if ((result->m_flags & M_PKTHDR) == 0) {
6333 if (result->m_len < sizeof(struct sadb_msg)) {
6334 result = m_pullup(result, sizeof(struct sadb_msg));
6335 if (result == NULL) {
6341 result->m_pkthdr.len = 0;
6342 for (m = result; m; m = m->m_next)
6343 result->m_pkthdr.len += m->m_len;
6345 mtod(result, struct sadb_msg *)->sadb_msg_len =
6346 PFKEY_UNIT64(result->m_pkthdr.len);
6349 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6359 * SADB_FLUSH processing
6362 * from the ikmpd, and free all entries in secastree.
6366 * NOTE: to do is only marking SADB_SASTATE_DEAD.
6368 * m will always be freed.
6371 key_flush(so, m, mhp)
6374 const struct sadb_msghdr *mhp;
6376 struct sadb_msg *newmsg;
6377 struct secashead *sah, *nextsah;
6378 struct secasvar *sav, *nextsav;
6383 IPSEC_ASSERT(so != NULL, ("null socket"));
6384 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6385 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6387 /* map satype to proto */
6388 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6389 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6391 return key_senderror(so, m, EINVAL);
6394 /* no SATYPE specified, i.e. flushing all SA. */
6396 for (sah = LIST_FIRST(&sahtree);
6399 nextsah = LIST_NEXT(sah, chain);
6401 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6402 && proto != sah->saidx.proto)
6406 stateidx < _ARRAYLEN(saorder_state_alive);
6408 state = saorder_state_any[stateidx];
6409 for (sav = LIST_FIRST(&sah->savtree[state]);
6413 nextsav = LIST_NEXT(sav, chain);
6415 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6420 sah->state = SADB_SASTATE_DEAD;
6424 if (m->m_len < sizeof(struct sadb_msg) ||
6425 sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6426 ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
6427 return key_senderror(so, m, ENOBUFS);
6433 m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6434 newmsg = mtod(m, struct sadb_msg *);
6435 newmsg->sadb_msg_errno = 0;
6436 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6438 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6442 * SADB_DUMP processing
6443 * dump all entries including status of DEAD in SAD.
6446 * from the ikmpd, and dump all secasvar leaves
6451 * m will always be freed.
6454 key_dump(so, m, mhp)
6457 const struct sadb_msghdr *mhp;
6459 struct secashead *sah;
6460 struct secasvar *sav;
6466 struct sadb_msg *newmsg;
6469 IPSEC_ASSERT(so != NULL, ("null socket"));
6470 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6471 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6472 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6474 /* map satype to proto */
6475 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6476 ipseclog((LOG_DEBUG, "%s: invalid satype is passed.\n",
6478 return key_senderror(so, m, EINVAL);
6481 /* count sav entries to be sent to the userland. */
6484 LIST_FOREACH(sah, &sahtree, chain) {
6485 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6486 && proto != sah->saidx.proto)
6490 stateidx < _ARRAYLEN(saorder_state_any);
6492 state = saorder_state_any[stateidx];
6493 LIST_FOREACH(sav, &sah->savtree[state], chain) {
6501 return key_senderror(so, m, ENOENT);
6504 /* send this to the userland, one at a time. */
6506 LIST_FOREACH(sah, &sahtree, chain) {
6507 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6508 && proto != sah->saidx.proto)
6511 /* map proto to satype */
6512 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6514 ipseclog((LOG_DEBUG, "%s: there was invalid proto in "
6515 "SAD.\n", __func__));
6516 return key_senderror(so, m, EINVAL);
6520 stateidx < _ARRAYLEN(saorder_state_any);
6522 state = saorder_state_any[stateidx];
6523 LIST_FOREACH(sav, &sah->savtree[state], chain) {
6524 n = key_setdumpsa(sav, SADB_DUMP, satype,
6525 --cnt, mhp->msg->sadb_msg_pid);
6528 return key_senderror(so, m, ENOBUFS);
6530 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6541 * SADB_X_PROMISC processing
6543 * m will always be freed.
6546 key_promisc(so, m, mhp)
6549 const struct sadb_msghdr *mhp;
6553 IPSEC_ASSERT(so != NULL, ("null socket"));
6554 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6555 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6556 IPSEC_ASSERT(mhp->msg != NULL, ("null msg"));
6558 olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6560 if (olen < sizeof(struct sadb_msg)) {
6562 return key_senderror(so, m, EINVAL);
6567 } else if (olen == sizeof(struct sadb_msg)) {
6568 /* enable/disable promisc mode */
6571 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6572 return key_senderror(so, m, EINVAL);
6573 mhp->msg->sadb_msg_errno = 0;
6574 switch (mhp->msg->sadb_msg_satype) {
6577 kp->kp_promisc = mhp->msg->sadb_msg_satype;
6580 return key_senderror(so, m, EINVAL);
6583 /* send the original message back to everyone */
6584 mhp->msg->sadb_msg_errno = 0;
6585 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6587 /* send packet as is */
6589 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6591 /* TODO: if sadb_msg_seq is specified, send to specific pid */
6592 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6596 static int (*key_typesw[]) __P((struct socket *, struct mbuf *,
6597 const struct sadb_msghdr *)) = {
6598 NULL, /* SADB_RESERVED */
6599 key_getspi, /* SADB_GETSPI */
6600 key_update, /* SADB_UPDATE */
6601 key_add, /* SADB_ADD */
6602 key_delete, /* SADB_DELETE */
6603 key_get, /* SADB_GET */
6604 key_acquire2, /* SADB_ACQUIRE */
6605 key_register, /* SADB_REGISTER */
6606 NULL, /* SADB_EXPIRE */
6607 key_flush, /* SADB_FLUSH */
6608 key_dump, /* SADB_DUMP */
6609 key_promisc, /* SADB_X_PROMISC */
6610 NULL, /* SADB_X_PCHANGE */
6611 key_spdadd, /* SADB_X_SPDUPDATE */
6612 key_spdadd, /* SADB_X_SPDADD */
6613 key_spddelete, /* SADB_X_SPDDELETE */
6614 key_spdget, /* SADB_X_SPDGET */
6615 NULL, /* SADB_X_SPDACQUIRE */
6616 key_spddump, /* SADB_X_SPDDUMP */
6617 key_spdflush, /* SADB_X_SPDFLUSH */
6618 key_spdadd, /* SADB_X_SPDSETIDX */
6619 NULL, /* SADB_X_SPDEXPIRE */
6620 key_spddelete2, /* SADB_X_SPDDELETE2 */
6624 * parse sadb_msg buffer to process PFKEYv2,
6625 * and create a data to response if needed.
6626 * I think to be dealed with mbuf directly.
6628 * msgp : pointer to pointer to a received buffer pulluped.
6629 * This is rewrited to response.
6630 * so : pointer to socket.
6632 * length for buffer to send to user process.
6639 struct sadb_msg *msg;
6640 struct sadb_msghdr mh;
6645 IPSEC_ASSERT(so != NULL, ("null socket"));
6646 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6648 #if 0 /*kdebug_sadb assumes msg in linear buffer*/
6649 KEYDEBUG(KEYDEBUG_KEY_DUMP,
6650 ipseclog((LOG_DEBUG, "%s: passed sadb_msg\n", __func__));
6654 if (m->m_len < sizeof(struct sadb_msg)) {
6655 m = m_pullup(m, sizeof(struct sadb_msg));
6659 msg = mtod(m, struct sadb_msg *);
6660 orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
6661 target = KEY_SENDUP_ONE;
6663 if ((m->m_flags & M_PKTHDR) == 0 ||
6664 m->m_pkthdr.len != m->m_pkthdr.len) {
6665 ipseclog((LOG_DEBUG, "%s: invalid message length.\n",__func__));
6666 pfkeystat.out_invlen++;
6671 if (msg->sadb_msg_version != PF_KEY_V2) {
6672 ipseclog((LOG_DEBUG, "%s: PF_KEY version %u is mismatched.\n",
6673 __func__, msg->sadb_msg_version));
6674 pfkeystat.out_invver++;
6679 if (msg->sadb_msg_type > SADB_MAX) {
6680 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6681 __func__, msg->sadb_msg_type));
6682 pfkeystat.out_invmsgtype++;
6687 /* for old-fashioned code - should be nuked */
6688 if (m->m_pkthdr.len > MCLBYTES) {
6695 MGETHDR(n, M_DONTWAIT, MT_DATA);
6696 if (n && m->m_pkthdr.len > MHLEN) {
6697 MCLGET(n, M_DONTWAIT);
6698 if ((n->m_flags & M_EXT) == 0) {
6707 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
6708 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
6714 /* align the mbuf chain so that extensions are in contiguous region. */
6715 error = key_align(m, &mh);
6722 switch (msg->sadb_msg_satype) {
6723 case SADB_SATYPE_UNSPEC:
6724 switch (msg->sadb_msg_type) {
6732 ipseclog((LOG_DEBUG, "%s: must specify satype "
6733 "when msg type=%u.\n", __func__,
6734 msg->sadb_msg_type));
6735 pfkeystat.out_invsatype++;
6740 case SADB_SATYPE_AH:
6741 case SADB_SATYPE_ESP:
6742 case SADB_X_SATYPE_IPCOMP:
6743 case SADB_X_SATYPE_TCPSIGNATURE:
6744 switch (msg->sadb_msg_type) {
6746 case SADB_X_SPDDELETE:
6748 case SADB_X_SPDDUMP:
6749 case SADB_X_SPDFLUSH:
6750 case SADB_X_SPDSETIDX:
6751 case SADB_X_SPDUPDATE:
6752 case SADB_X_SPDDELETE2:
6753 ipseclog((LOG_DEBUG, "%s: illegal satype=%u\n",
6754 __func__, msg->sadb_msg_type));
6755 pfkeystat.out_invsatype++;
6760 case SADB_SATYPE_RSVP:
6761 case SADB_SATYPE_OSPFV2:
6762 case SADB_SATYPE_RIPV2:
6763 case SADB_SATYPE_MIP:
6764 ipseclog((LOG_DEBUG, "%s: type %u isn't supported.\n",
6765 __func__, msg->sadb_msg_satype));
6766 pfkeystat.out_invsatype++;
6769 case 1: /* XXX: What does it do? */
6770 if (msg->sadb_msg_type == SADB_X_PROMISC)
6774 ipseclog((LOG_DEBUG, "%s: invalid type %u is passed.\n",
6775 __func__, msg->sadb_msg_satype));
6776 pfkeystat.out_invsatype++;
6781 /* check field of upper layer protocol and address family */
6782 if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
6783 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
6784 struct sadb_address *src0, *dst0;
6787 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
6788 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
6790 /* check upper layer protocol */
6791 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
6792 ipseclog((LOG_DEBUG, "%s: upper layer protocol "
6793 "mismatched.\n", __func__));
6794 pfkeystat.out_invaddr++;
6800 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
6801 PFKEY_ADDR_SADDR(dst0)->sa_family) {
6802 ipseclog((LOG_DEBUG, "%s: address family mismatched.\n",
6804 pfkeystat.out_invaddr++;
6808 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6809 PFKEY_ADDR_SADDR(dst0)->sa_len) {
6810 ipseclog((LOG_DEBUG, "%s: address struct size "
6811 "mismatched.\n", __func__));
6812 pfkeystat.out_invaddr++;
6817 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6819 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6820 sizeof(struct sockaddr_in)) {
6821 pfkeystat.out_invaddr++;
6827 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
6828 sizeof(struct sockaddr_in6)) {
6829 pfkeystat.out_invaddr++;
6835 ipseclog((LOG_DEBUG, "%s: unsupported address family\n",
6837 pfkeystat.out_invaddr++;
6838 error = EAFNOSUPPORT;
6842 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
6844 plen = sizeof(struct in_addr) << 3;
6847 plen = sizeof(struct in6_addr) << 3;
6850 plen = 0; /*fool gcc*/
6854 /* check max prefix length */
6855 if (src0->sadb_address_prefixlen > plen ||
6856 dst0->sadb_address_prefixlen > plen) {
6857 ipseclog((LOG_DEBUG, "%s: illegal prefixlen.\n",
6859 pfkeystat.out_invaddr++;
6865 * prefixlen == 0 is valid because there can be a case when
6866 * all addresses are matched.
6870 if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
6871 key_typesw[msg->sadb_msg_type] == NULL) {
6872 pfkeystat.out_invmsgtype++;
6877 return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
6880 msg->sadb_msg_errno = error;
6881 return key_sendup_mbuf(so, m, target);
6885 key_senderror(so, m, code)
6890 struct sadb_msg *msg;
6892 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
6893 ("mbuf too small, len %u", m->m_len));
6895 msg = mtod(m, struct sadb_msg *);
6896 msg->sadb_msg_errno = code;
6897 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
6901 * set the pointer to each header into message buffer.
6902 * m will be freed on error.
6903 * XXX larger-than-MCLBYTES extension?
6908 struct sadb_msghdr *mhp;
6911 struct sadb_ext *ext;
6916 IPSEC_ASSERT(m != NULL, ("null mbuf"));
6917 IPSEC_ASSERT(mhp != NULL, ("null msghdr"));
6918 IPSEC_ASSERT(m->m_len >= sizeof(struct sadb_msg),
6919 ("mbuf too small, len %u", m->m_len));
6922 bzero(mhp, sizeof(*mhp));
6924 mhp->msg = mtod(m, struct sadb_msg *);
6925 mhp->ext[0] = (struct sadb_ext *)mhp->msg; /*XXX backward compat */
6927 end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6928 extlen = end; /*just in case extlen is not updated*/
6929 for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
6930 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
6932 /* m is already freed */
6935 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6938 switch (ext->sadb_ext_type) {
6940 case SADB_EXT_ADDRESS_SRC:
6941 case SADB_EXT_ADDRESS_DST:
6942 case SADB_EXT_ADDRESS_PROXY:
6943 case SADB_EXT_LIFETIME_CURRENT:
6944 case SADB_EXT_LIFETIME_HARD:
6945 case SADB_EXT_LIFETIME_SOFT:
6946 case SADB_EXT_KEY_AUTH:
6947 case SADB_EXT_KEY_ENCRYPT:
6948 case SADB_EXT_IDENTITY_SRC:
6949 case SADB_EXT_IDENTITY_DST:
6950 case SADB_EXT_SENSITIVITY:
6951 case SADB_EXT_PROPOSAL:
6952 case SADB_EXT_SUPPORTED_AUTH:
6953 case SADB_EXT_SUPPORTED_ENCRYPT:
6954 case SADB_EXT_SPIRANGE:
6955 case SADB_X_EXT_POLICY:
6956 case SADB_X_EXT_SA2:
6957 /* duplicate check */
6959 * XXX Are there duplication payloads of either
6960 * KEY_AUTH or KEY_ENCRYPT ?
6962 if (mhp->ext[ext->sadb_ext_type] != NULL) {
6963 ipseclog((LOG_DEBUG, "%s: duplicate ext_type "
6964 "%u\n", __func__, ext->sadb_ext_type));
6966 pfkeystat.out_dupext++;
6971 ipseclog((LOG_DEBUG, "%s: invalid ext_type %u\n",
6972 __func__, ext->sadb_ext_type));
6974 pfkeystat.out_invexttype++;
6978 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
6980 if (key_validate_ext(ext, extlen)) {
6982 pfkeystat.out_invlen++;
6986 n = m_pulldown(m, off, extlen, &toff);
6988 /* m is already freed */
6991 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
6993 mhp->ext[ext->sadb_ext_type] = ext;
6994 mhp->extoff[ext->sadb_ext_type] = off;
6995 mhp->extlen[ext->sadb_ext_type] = extlen;
7000 pfkeystat.out_invlen++;
7008 key_validate_ext(ext, len)
7009 const struct sadb_ext *ext;
7012 const struct sockaddr *sa;
7013 enum { NONE, ADDR } checktype = NONE;
7015 const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7017 if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7020 /* if it does not match minimum/maximum length, bail */
7021 if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7022 ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7024 if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7026 if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7029 /* more checks based on sadb_ext_type XXX need more */
7030 switch (ext->sadb_ext_type) {
7031 case SADB_EXT_ADDRESS_SRC:
7032 case SADB_EXT_ADDRESS_DST:
7033 case SADB_EXT_ADDRESS_PROXY:
7034 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7037 case SADB_EXT_IDENTITY_SRC:
7038 case SADB_EXT_IDENTITY_DST:
7039 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
7040 SADB_X_IDENTTYPE_ADDR) {
7041 baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7051 switch (checktype) {
7055 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
7056 if (len < baselen + sal)
7058 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7072 REGTREE_LOCK_INIT();
7073 SAHTREE_LOCK_INIT();
7077 for (i = 0; i < IPSEC_DIR_MAX; i++)
7078 LIST_INIT(&sptree[i]);
7080 LIST_INIT(&sahtree);
7082 for (i = 0; i <= SADB_SATYPE_MAX; i++)
7083 LIST_INIT(®tree[i]);
7085 LIST_INIT(&acqtree);
7086 LIST_INIT(&spacqtree);
7088 /* system default */
7089 ip4_def_policy.policy = IPSEC_POLICY_NONE;
7090 ip4_def_policy.refcnt++; /*never reclaim this*/
7092 #ifndef IPSEC_DEBUG2
7093 timeout((void *)key_timehandler, (void *)0, hz);
7094 #endif /*IPSEC_DEBUG2*/
7096 /* initialize key statistics */
7097 keystat.getspi_count = 1;
7099 printf("IPsec: Initialized Security Association Processing.\n");
7105 * XXX: maybe This function is called after INBOUND IPsec processing.
7107 * Special check for tunnel-mode packets.
7108 * We must make some checks for consistency between inner and outer IP header.
7110 * xxx more checks to be provided
7113 key_checktunnelsanity(sav, family, src, dst)
7114 struct secasvar *sav;
7119 IPSEC_ASSERT(sav->sah != NULL, ("null SA header"));
7121 /* XXX: check inner IP header */
7126 /* record data transfer on SA, and update timestamps */
7128 key_sa_recordxfer(sav, m)
7129 struct secasvar *sav;
7132 IPSEC_ASSERT(sav != NULL, ("Null secasvar"));
7133 IPSEC_ASSERT(m != NULL, ("Null mbuf"));
7138 * XXX Currently, there is a difference of bytes size
7139 * between inbound and outbound processing.
7141 sav->lft_c->bytes += m->m_pkthdr.len;
7142 /* to check bytes lifetime is done in key_timehandler(). */
7145 * We use the number of packets as the unit of
7146 * allocations. We increment the variable
7147 * whenever {esp,ah}_{in,out}put is called.
7149 sav->lft_c->allocations++;
7150 /* XXX check for expires? */
7153 * NOTE: We record CURRENT usetime by using wall clock,
7154 * in seconds. HARD and SOFT lifetime are measured by the time
7155 * difference (again in seconds) from usetime.
7159 * -----+-----+--------+---> t
7160 * <--------------> HARD
7163 sav->lft_c->usetime = time_second;
7164 /* XXX check for expires? */
7171 key_sa_routechange(dst)
7172 struct sockaddr *dst;
7174 struct secashead *sah;
7178 LIST_FOREACH(sah, &sahtree, chain) {
7179 ro = &sah->sa_route;
7180 if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7181 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7183 ro->ro_rt = (struct rtentry *)NULL;
7190 key_sa_chgstate(struct secasvar *sav, u_int8_t state)
7192 IPSEC_ASSERT(sav != NULL, ("NULL sav"));
7193 SAHTREE_LOCK_ASSERT();
7195 if (sav->state != state) {
7196 if (__LIST_CHAINED(sav))
7197 LIST_REMOVE(sav, chain);
7199 LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7205 struct secasvar *sav;
7208 IPSEC_ASSERT(sav->iv != NULL, ("null IV"));
7209 key_randomfill(sav->iv, sav->ivlen);
7213 static struct mbuf *
7217 struct mbuf *m = NULL, *n;
7222 MGET(n, M_DONTWAIT, MT_DATA);
7223 if (n && len > MLEN)
7224 MCLGET(n, M_DONTWAIT);
7232 n->m_len = M_TRAILINGSPACE(n);
7233 /* use the bottom of mbuf, hoping we can prepend afterwards */
7234 if (n->m_len > len) {
7235 t = (n->m_len - len) & ~(sizeof(long) - 1);
7252 * Take one of the kernel's security keys and convert it into a PF_KEY
7253 * structure within an mbuf, suitable for sending up to a waiting
7254 * application in user land.
7257 * src: A pointer to a kernel security key.
7258 * exttype: Which type of key this is. Refer to the PF_KEY data structures.
7260 * a valid mbuf or NULL indicating an error
7264 static struct mbuf *
7265 key_setkey(struct seckey *src, u_int16_t exttype)
7274 len = PFKEY_ALIGN8(sizeof(struct sadb_key) + _KEYLEN(src));
7275 m = key_alloc_mbuf(len);
7278 p = mtod(m, struct sadb_key *);
7280 p->sadb_key_len = PFKEY_UNIT64(len);
7281 p->sadb_key_exttype = exttype;
7282 p->sadb_key_bits = src->bits;
7283 bcopy(src->key_data, _KEYBUF(p), _KEYLEN(src));
7289 * Take one of the kernel's lifetime data structures and convert it
7290 * into a PF_KEY structure within an mbuf, suitable for sending up to
7291 * a waiting application in user land.
7294 * src: A pointer to a kernel lifetime structure.
7295 * exttype: Which type of lifetime this is. Refer to the PF_KEY
7296 * data structures for more information.
7298 * a valid mbuf or NULL indicating an error
7302 static struct mbuf *
7303 key_setlifetime(struct seclifetime *src, u_int16_t exttype)
7305 struct mbuf *m = NULL;
7306 struct sadb_lifetime *p;
7307 int len = PFKEY_ALIGN8(sizeof(struct sadb_lifetime));
7312 m = key_alloc_mbuf(len);
7315 p = mtod(m, struct sadb_lifetime *);
7318 p->sadb_lifetime_len = PFKEY_UNIT64(len);
7319 p->sadb_lifetime_exttype = exttype;
7320 p->sadb_lifetime_allocations = src->allocations;
7321 p->sadb_lifetime_bytes = src->bytes;
7322 p->sadb_lifetime_addtime = src->addtime;
7323 p->sadb_lifetime_usetime = src->usetime;