[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ]

FreeBSD/Linux Kernel Cross Reference
sys/netipsec/key.c

Version: -  FREEBSD  -  FREEBSD7  -  FREEBSD70  -  FREEBSD6  -  FREEBSD63  -  FREEBSD62  -  FREEBSD61  -  FREEBSD60  -  FREEBSD5  -  FREEBSD55  -  FREEBSD54  -  FREEBSD53  -  FREEBSD52  -  FREEBSD51  -  FREEBSD50  -  FREEBSD4  -  FREEBSD3  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  OPENSOLARIS  -  minix-3-1-1  -  TRUSTEDBSD-SEBSD  -  FREEBSD-LIBC  -  FREEBSD7-LIBC  -  FREEBSD6-LIBC  -  GLIBC27 
SearchContext: -  none  -  excerpts  -  bigexcerpts 

  1 /*      $FreeBSD: src/sys/netipsec/key.c,v 1.36 2008/10/02 15:37:58 zec Exp $   */
  2 /*      $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $   */
  3 
  4 /*-
  5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
  6  * All rights reserved.
  7  *
  8  * Redistribution and use in source and binary forms, with or without
  9  * modification, are permitted provided that the following conditions
 10  * are met:
 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.
 19  *
 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
 30  * SUCH DAMAGE.
 31  */
 32 
 33 /*
 34  * This code is referd to RFC 2367
 35  */
 36 
 37 #include "opt_inet.h"
 38 #include "opt_inet6.h"
 39 #include "opt_ipsec.h"
 40 
 41 #include <sys/types.h>
 42 #include <sys/param.h>
 43 #include <sys/systm.h>
 44 #include <sys/kernel.h>
 45 #include <sys/lock.h>
 46 #include <sys/mutex.h>
 47 #include <sys/mbuf.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>
 55 #include <sys/proc.h>
 56 #include <sys/queue.h>
 57 #include <sys/refcount.h>
 58 #include <sys/syslog.h>
 59 #include <sys/vimage.h>
 60 
 61 #include <net/if.h>
 62 #include <net/route.h>
 63 #include <net/raw_cb.h>
 64 
 65 #include <netinet/in.h>
 66 #include <netinet/in_systm.h>
 67 #include <netinet/ip.h>
 68 #include <netinet/in_var.h>
 69 
 70 #ifdef INET6
 71 #include <netinet/ip6.h>
 72 #include <netinet6/in6_var.h>
 73 #include <netinet6/ip6_var.h>
 74 #endif /* INET6 */
 75 
 76 #ifdef INET
 77 #include <netinet/in_pcb.h>
 78 #endif
 79 #ifdef INET6
 80 #include <netinet6/in6_pcb.h>
 81 #endif /* INET6 */
 82 
 83 #include <net/pfkeyv2.h>
 84 #include <netipsec/keydb.h>
 85 #include <netipsec/key.h>
 86 #include <netipsec/keysock.h>
 87 #include <netipsec/key_debug.h>
 88 
 89 #include <netipsec/ipsec.h>
 90 #ifdef INET6
 91 #include <netipsec/ipsec6.h>
 92 #endif
 93 
 94 #include <netipsec/xform.h>
 95 
 96 #include <machine/stdarg.h>
 97 
 98 /* randomness */
 99 #include <sys/random.h>
100 #include <sys/vimage.h>
101 
102 #define FULLMASK        0xff
103 #define _BITS(bytes)    ((bytes) << 3)
104 
105 /*
106  * Note on SA reference counting:
107  * - SAs that are not in DEAD state will have (total external reference + 1)
108  *   following value in reference count field.  they cannot be freed and are
109  *   referenced from SA header.
110  * - SAs that are in DEAD state will have (total external reference)
111  *   in reference count field.  they are ready to be freed.  reference from
112  *   SA header will be removed in key_delsav(), when the reference count
113  *   field hits 0 (= no external reference other than from SA header.
114  */
115 
116 u_int32_t key_debug_level = 0;
117 static u_int key_spi_trycnt = 1000;
118 static u_int32_t key_spi_minval = 0x100;
119 static u_int32_t key_spi_maxval = 0x0fffffff;   /* XXX */
120 static u_int32_t policy_id = 0;
121 static u_int key_int_random = 60;       /*interval to initialize randseed,1(m)*/
122 static u_int key_larval_lifetime = 30;  /* interval to expire acquiring, 30(s)*/
123 static int key_blockacq_count = 10;     /* counter for blocking SADB_ACQUIRE.*/
124 static int key_blockacq_lifetime = 20;  /* lifetime for blocking SADB_ACQUIRE.*/
125 static int key_preferred_oldsa = 1;     /* preferred old sa rather than new sa.*/
126 
127 static u_int32_t acq_seq = 0;
128 
129 static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];     /* SPD */
130 static struct mtx sptree_lock;
131 #define SPTREE_LOCK_INIT() \
132         mtx_init(&sptree_lock, "sptree", \
133                 "fast ipsec security policy database", MTX_DEF)
134 #define SPTREE_LOCK_DESTROY()   mtx_destroy(&sptree_lock)
135 #define SPTREE_LOCK()           mtx_lock(&sptree_lock)
136 #define SPTREE_UNLOCK() mtx_unlock(&sptree_lock)
137 #define SPTREE_LOCK_ASSERT()    mtx_assert(&sptree_lock, MA_OWNED)
138 
139 static LIST_HEAD(_sahtree, secashead) sahtree;                  /* SAD */
140 static struct mtx sahtree_lock;
141 #define SAHTREE_LOCK_INIT() \
142         mtx_init(&sahtree_lock, "sahtree", \
143                 "fast ipsec security association database", MTX_DEF)
144 #define SAHTREE_LOCK_DESTROY()  mtx_destroy(&sahtree_lock)
145 #define SAHTREE_LOCK()          mtx_lock(&sahtree_lock)
146 #define SAHTREE_UNLOCK()        mtx_unlock(&sahtree_lock)
147 #define SAHTREE_LOCK_ASSERT()   mtx_assert(&sahtree_lock, MA_OWNED)
148 
149                                                         /* registed list */
150 static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
151 static struct mtx regtree_lock;
152 #define REGTREE_LOCK_INIT() \
153         mtx_init(&regtree_lock, "regtree", "fast ipsec regtree", MTX_DEF)
154 #define REGTREE_LOCK_DESTROY()  mtx_destroy(&regtree_lock)
155 #define REGTREE_LOCK()          mtx_lock(&regtree_lock)
156 #define REGTREE_UNLOCK()        mtx_unlock(&regtree_lock)
157 #define REGTREE_LOCK_ASSERT()   mtx_assert(&regtree_lock, MA_OWNED)
158 
159 static LIST_HEAD(_acqtree, secacq) acqtree;             /* acquiring list */
160 static struct mtx acq_lock;
161 #define ACQ_LOCK_INIT() \
162         mtx_init(&acq_lock, "acqtree", "fast ipsec acquire list", MTX_DEF)
163 #define ACQ_LOCK_DESTROY()      mtx_destroy(&acq_lock)
164 #define ACQ_LOCK()              mtx_lock(&acq_lock)
165 #define ACQ_UNLOCK()            mtx_unlock(&acq_lock)
166 #define ACQ_LOCK_ASSERT()       mtx_assert(&acq_lock, MA_OWNED)
167 
168 static LIST_HEAD(_spacqtree, secspacq) spacqtree;       /* SP acquiring list */
169 static struct mtx spacq_lock;
170 #define SPACQ_LOCK_INIT() \
171         mtx_init(&spacq_lock, "spacqtree", \
172                 "fast ipsec security policy acquire list", MTX_DEF)
173 #define SPACQ_LOCK_DESTROY()    mtx_destroy(&spacq_lock)
174 #define SPACQ_LOCK()            mtx_lock(&spacq_lock)
175 #define SPACQ_UNLOCK()          mtx_unlock(&spacq_lock)
176 #define SPACQ_LOCK_ASSERT()     mtx_assert(&spacq_lock, MA_OWNED)
177 
178 /* search order for SAs */
179 static const u_int saorder_state_valid_prefer_old[] = {
180         SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
181 };
182 static const u_int saorder_state_valid_prefer_new[] = {
183         SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
184 };
185 static u_int saorder_state_alive[] = {
186         /* except DEAD */
187         SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
188 };
189 static u_int saorder_state_any[] = {
190         SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
191         SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
192 };
193 
194 static const int minsize[] = {
195         sizeof(struct sadb_msg),        /* SADB_EXT_RESERVED */
196         sizeof(struct sadb_sa),         /* SADB_EXT_SA */
197         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_CURRENT */
198         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_HARD */
199         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_SOFT */
200         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_SRC */
201         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_DST */
202         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_PROXY */
203         sizeof(struct sadb_key),        /* SADB_EXT_KEY_AUTH */
204         sizeof(struct sadb_key),        /* SADB_EXT_KEY_ENCRYPT */
205         sizeof(struct sadb_ident),      /* SADB_EXT_IDENTITY_SRC */
206         sizeof(struct sadb_ident),      /* SADB_EXT_IDENTITY_DST */
207         sizeof(struct sadb_sens),       /* SADB_EXT_SENSITIVITY */
208         sizeof(struct sadb_prop),       /* SADB_EXT_PROPOSAL */
209         sizeof(struct sadb_supported),  /* SADB_EXT_SUPPORTED_AUTH */
210         sizeof(struct sadb_supported),  /* SADB_EXT_SUPPORTED_ENCRYPT */
211         sizeof(struct sadb_spirange),   /* SADB_EXT_SPIRANGE */
212         0,                              /* SADB_X_EXT_KMPRIVATE */
213         sizeof(struct sadb_x_policy),   /* SADB_X_EXT_POLICY */
214         sizeof(struct sadb_x_sa2),      /* SADB_X_SA2 */
215 };
216 static const int maxsize[] = {
217         sizeof(struct sadb_msg),        /* SADB_EXT_RESERVED */
218         sizeof(struct sadb_sa),         /* SADB_EXT_SA */
219         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_CURRENT */
220         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_HARD */
221         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_SOFT */
222         0,                              /* SADB_EXT_ADDRESS_SRC */
223         0,                              /* SADB_EXT_ADDRESS_DST */
224         0,                              /* SADB_EXT_ADDRESS_PROXY */
225         0,                              /* SADB_EXT_KEY_AUTH */
226         0,                              /* SADB_EXT_KEY_ENCRYPT */
227         0,                              /* SADB_EXT_IDENTITY_SRC */
228         0,                              /* SADB_EXT_IDENTITY_DST */
229         0,                              /* SADB_EXT_SENSITIVITY */
230         0,                              /* SADB_EXT_PROPOSAL */
231         0,                              /* SADB_EXT_SUPPORTED_AUTH */
232         0,                              /* SADB_EXT_SUPPORTED_ENCRYPT */
233         sizeof(struct sadb_spirange),   /* SADB_EXT_SPIRANGE */
234         0,                              /* SADB_X_EXT_KMPRIVATE */
235         0,                              /* SADB_X_EXT_POLICY */
236         sizeof(struct sadb_x_sa2),      /* SADB_X_SA2 */
237 };
238 
239 static int ipsec_esp_keymin = 256;
240 static int ipsec_esp_auth = 0;
241 static int ipsec_ah_keymin = 128;
242 
243 #ifdef SYSCTL_DECL
244 SYSCTL_DECL(_net_key);
245 #endif
246 
247 SYSCTL_V_INT(V_NET, vnet_ipsec,_net_key, KEYCTL_DEBUG_LEVEL,    debug,
248         CTLFLAG_RW, key_debug_level,    0,      "");
249 
250 /* max count of trial for the decision of spi value */
251 SYSCTL_V_INT(V_NET, vnet_ipsec,_net_key, KEYCTL_SPI_TRY, spi_trycnt,
252         CTLFLAG_RW, key_spi_trycnt,     0,      "");
253 
254 /* minimum spi value to allocate automatically. */
255 SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_SPI_MIN_VALUE,
256         spi_minval,     CTLFLAG_RW, key_spi_minval,     0,      "");
257 
258 /* maximun spi value to allocate automatically. */
259 SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_SPI_MAX_VALUE,
260         spi_maxval,     CTLFLAG_RW, key_spi_maxval,     0,      "");
261 
262 /* interval to initialize randseed */
263 SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_RANDOM_INT,
264         int_random,     CTLFLAG_RW, key_int_random,     0,      "");
265 
266 /* lifetime for larval SA */
267 SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_LARVAL_LIFETIME,
268         larval_lifetime, CTLFLAG_RW, key_larval_lifetime,       0,      "");
269 
270 /* counter for blocking to send SADB_ACQUIRE to IKEd */
271 SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_BLOCKACQ_COUNT,
272         blockacq_count, CTLFLAG_RW, key_blockacq_count, 0,      "");
273 
274 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
275 SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_BLOCKACQ_LIFETIME,
276         blockacq_lifetime, CTLFLAG_RW, key_blockacq_lifetime,   0, "");
277 
278 /* ESP auth */
279 SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_ESP_AUTH,      esp_auth,
280         CTLFLAG_RW, ipsec_esp_auth,     0,      "");
281 
282 /* minimum ESP key length */
283 SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_ESP_KEYMIN,
284         esp_keymin, CTLFLAG_RW, ipsec_esp_keymin,       0,      "");
285 
286 /* minimum AH key length */
287 SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_AH_KEYMIN,     ah_keymin,
288         CTLFLAG_RW, ipsec_ah_keymin,    0,      "");
289 
290 /* perfered old SA rather than new SA */
291 SYSCTL_V_INT(V_NET, vnet_ipsec, _net_key, KEYCTL_PREFERED_OLDSA,
292         preferred_oldsa, CTLFLAG_RW, key_preferred_oldsa,       0,      "");
293 
294 #define __LIST_CHAINED(elm) \
295         (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
296 #define LIST_INSERT_TAIL(head, elm, type, field) \
297 do {\
298         struct type *curelm = LIST_FIRST(head); \
299         if (curelm == NULL) {\
300                 LIST_INSERT_HEAD(head, elm, field); \
301         } else { \
302                 while (LIST_NEXT(curelm, field)) \
303                         curelm = LIST_NEXT(curelm, field);\
304                 LIST_INSERT_AFTER(curelm, elm, field);\
305         }\
306 } while (0)
307 
308 #define KEY_CHKSASTATE(head, sav, name) \
309 do { \
310         if ((head) != (sav)) {                                          \
311                 ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
312                         (name), (head), (sav)));                        \
313                 continue;                                               \
314         }                                                               \
315 } while (0)
316 
317 #define KEY_CHKSPDIR(head, sp, name) \
318 do { \
319         if ((head) != (sp)) {                                           \
320                 ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
321                         "anyway continue.\n",                           \
322                         (name), (head), (sp)));                         \
323         }                                                               \
324 } while (0)
325 
326 MALLOC_DEFINE(M_IPSEC_SA, "secasvar", "ipsec security association");
327 MALLOC_DEFINE(M_IPSEC_SAH, "sahead", "ipsec sa head");
328 MALLOC_DEFINE(M_IPSEC_SP, "ipsecpolicy", "ipsec security policy");
329 MALLOC_DEFINE(M_IPSEC_SR, "ipsecrequest", "ipsec security request");
330 MALLOC_DEFINE(M_IPSEC_MISC, "ipsec-misc", "ipsec miscellaneous");
331 MALLOC_DEFINE(M_IPSEC_SAQ, "ipsec-saq", "ipsec sa acquire");
332 MALLOC_DEFINE(M_IPSEC_SAR, "ipsec-reg", "ipsec sa acquire");
333 
334 /*
335  * set parameters into secpolicyindex buffer.
336  * Must allocate secpolicyindex buffer passed to this function.
337  */
338 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
339 do { \
340         bzero((idx), sizeof(struct secpolicyindex));                         \
341         (idx)->dir = (_dir);                                                 \
342         (idx)->prefs = (ps);                                                 \
343         (idx)->prefd = (pd);                                                 \
344         (idx)->ul_proto = (ulp);                                             \
345         bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
346         bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
347 } while (0)
348 
349 /*
350  * set parameters into secasindex buffer.
351  * Must allocate secasindex buffer before calling this function.
352  */
353 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
354 do { \
355         bzero((idx), sizeof(struct secasindex));                             \
356         (idx)->proto = (p);                                                  \
357         (idx)->mode = (m);                                                   \
358         (idx)->reqid = (r);                                                  \
359         bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
360         bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
361 } while (0)
362 
363 /* key statistics */
364 struct _keystat {
365         u_long getspi_count; /* the avarage of count to try to get new SPI */
366 } keystat;
367 
368 struct sadb_msghdr {
369         struct sadb_msg *msg;
370         struct sadb_ext *ext[SADB_EXT_MAX + 1];
371         int extoff[SADB_EXT_MAX + 1];
372         int extlen[SADB_EXT_MAX + 1];
373 };
374 
375 static struct secasvar *key_allocsa_policy __P((const struct secasindex *));
376 static void key_freesp_so __P((struct secpolicy **));
377 static struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
378 static void key_delsp __P((struct secpolicy *));
379 static struct secpolicy *key_getsp __P((struct secpolicyindex *));
380 static void _key_delsp(struct secpolicy *sp);
381 static struct secpolicy *key_getspbyid __P((u_int32_t));
382 static u_int32_t key_newreqid __P((void));
383 static struct mbuf *key_gather_mbuf __P((struct mbuf *,
384         const struct sadb_msghdr *, int, int, ...));
385 static int key_spdadd __P((struct socket *, struct mbuf *,
386         const struct sadb_msghdr *));
387 static u_int32_t key_getnewspid __P((void));
388 static int key_spddelete __P((struct socket *, struct mbuf *,
389         const struct sadb_msghdr *));
390 static int key_spddelete2 __P((struct socket *, struct mbuf *,
391         const struct sadb_msghdr *));
392 static int key_spdget __P((struct socket *, struct mbuf *,
393         const struct sadb_msghdr *));
394 static int key_spdflush __P((struct socket *, struct mbuf *,
395         const struct sadb_msghdr *));
396 static int key_spddump __P((struct socket *, struct mbuf *,
397         const struct sadb_msghdr *));
398 static struct mbuf *key_setdumpsp __P((struct secpolicy *,
399         u_int8_t, u_int32_t, u_int32_t));
400 static u_int key_getspreqmsglen __P((struct secpolicy *));
401 static int key_spdexpire __P((struct secpolicy *));
402 static struct secashead *key_newsah __P((struct secasindex *));
403 static void key_delsah __P((struct secashead *));
404 static struct secasvar *key_newsav __P((struct mbuf *,
405         const struct sadb_msghdr *, struct secashead *, int *,
406         const char*, int));
407 #define KEY_NEWSAV(m, sadb, sah, e)                             \
408         key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
409 static void key_delsav __P((struct secasvar *));
410 static struct secashead *key_getsah __P((struct secasindex *));
411 static struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
412 static struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
413 static int key_setsaval __P((struct secasvar *, struct mbuf *,
414         const struct sadb_msghdr *));
415 static int key_mature __P((struct secasvar *));
416 static struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
417         u_int8_t, u_int32_t, u_int32_t));
418 static struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
419         u_int32_t, pid_t, u_int16_t));
420 static struct mbuf *key_setsadbsa __P((struct secasvar *));
421 static struct mbuf *key_setsadbaddr __P((u_int16_t,
422         const struct sockaddr *, u_int8_t, u_int16_t));
423 static struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
424 static struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
425         u_int32_t));
426 static struct seckey *key_dup_keymsg(const struct sadb_key *, u_int, 
427                                      struct malloc_type *);
428 static struct seclifetime *key_dup_lifemsg(const struct sadb_lifetime *src,
429                                             struct malloc_type *type);
430 #ifdef INET6
431 static int key_ismyaddr6 __P((struct sockaddr_in6 *));
432 #endif
433 
434 /* flags for key_cmpsaidx() */
435 #define CMP_HEAD        1       /* protocol, addresses. */
436 #define CMP_MODE_REQID  2       /* additionally HEAD, reqid, mode. */
437 #define CMP_REQID       3       /* additionally HEAD, reaid. */
438 #define CMP_EXACTLY     4       /* all elements. */
439 static int key_cmpsaidx
440         __P((const struct secasindex *, const struct secasindex *, int));
441 
442 static int key_cmpspidx_exactly
443         __P((struct secpolicyindex *, struct secpolicyindex *));
444 static int key_cmpspidx_withmask
445         __P((struct secpolicyindex *, struct secpolicyindex *));
446 static int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
447 static int key_bbcmp __P((const void *, const void *, u_int));
448 static u_int16_t key_satype2proto __P((u_int8_t));
449 static u_int8_t key_proto2satype __P((u_int16_t));
450 
451 static int key_getspi __P((struct socket *, struct mbuf *,
452         const struct sadb_msghdr *));
453 static u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
454                                         struct secasindex *));
455 static int key_update __P((struct socket *, struct mbuf *,
456         const struct sadb_msghdr *));
457 #ifdef IPSEC_DOSEQCHECK
458 static struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
459 #endif
460 static int key_add __P((struct socket *, struct mbuf *,
461         const struct sadb_msghdr *));
462 static int key_setident __P((struct secashead *, struct mbuf *,
463         const struct sadb_msghdr *));
464 static struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
465         const struct sadb_msghdr *));
466 static int key_delete __P((struct socket *, struct mbuf *,
467         const struct sadb_msghdr *));
468 static int key_get __P((struct socket *, struct mbuf *,
469         const struct sadb_msghdr *));
470 
471 static void key_getcomb_setlifetime __P((struct sadb_comb *));
472 static struct mbuf *key_getcomb_esp __P((void));
473 static struct mbuf *key_getcomb_ah __P((void));
474 static struct mbuf *key_getcomb_ipcomp __P((void));
475 static struct mbuf *key_getprop __P((const struct secasindex *));
476 
477 static int key_acquire __P((const struct secasindex *, struct secpolicy *));
478 static struct secacq *key_newacq __P((const struct secasindex *));
479 static struct secacq *key_getacq __P((const struct secasindex *));
480 static struct secacq *key_getacqbyseq __P((u_int32_t));
481 static struct secspacq *key_newspacq __P((struct secpolicyindex *));
482 static struct secspacq *key_getspacq __P((struct secpolicyindex *));
483 static int key_acquire2 __P((struct socket *, struct mbuf *,
484         const struct sadb_msghdr *));
485 static int key_register __P((struct socket *, struct mbuf *,
486         const struct sadb_msghdr *));
487 static int key_expire __P((struct secasvar *));
488 static int key_flush __P((struct socket *, struct mbuf *,
489         const struct sadb_msghdr *));
490 static int key_dump __P((struct socket *, struct mbuf *,
491         const struct sadb_msghdr *));
492 static int key_promisc __P((struct socket *, struct mbuf *,
493         const struct sadb_msghdr *));
494 static int key_senderror __P((struct socket *, struct mbuf *, int));
495 static int key_validate_ext __P((const struct sadb_ext *, int));
496 static int key_align __P((struct mbuf *, struct sadb_msghdr *));
497 static struct mbuf *key_setlifetime(struct seclifetime *src, 
498                                      u_int16_t exttype);
499 static struct mbuf *key_setkey(struct seckey *src, u_int16_t exttype);
500 
501 #if 0
502 static const char *key_getfqdn __P((void));
503 static const char *key_getuserfqdn __P((void));
504 #endif
505 static void key_sa_chgstate __P((struct secasvar *, u_int8_t));
506 static struct mbuf *key_alloc_mbuf __P((int));
507 
508 static __inline void
509 sa_initref(struct secasvar *sav)
510 {
511 
512         refcount_init(&sav->refcnt, 1);
513 }
514 static __inline void
515 sa_addref(struct secasvar *sav)
516 {
517 
518         refcount_acquire(&sav->refcnt);
519         IPSEC_ASSERT(sav->refcnt != 0, ("SA refcnt overflow"));
520 }
521 static __inline int
522 sa_delref(struct secasvar *sav)
523 {
524 
525         IPSEC_ASSERT(sav->refcnt > 0, ("SA refcnt underflow"));
526         return (refcount_release(&sav->refcnt));
527 }
528 
529 #define SP_ADDREF(p) do {                                               \
530         (p)->refcnt++;                                                  \
531         IPSEC_ASSERT((p)->refcnt != 0, ("SP refcnt overflow"));         \
532 } while (0)
533 #define SP_DELREF(p) do {                                               \
534         IPSEC_ASSERT((p)->refcnt > 0, ("SP refcnt underflow"));         \
535         (p)->refcnt--;                                                  \
536 } while (0)
537  
538 
539 /*
540  * Update the refcnt while holding the SPTREE lock.
541  */
542 void
543 key_addref(struct secpolicy *sp)
544 {
545         SPTREE_LOCK();
546         SP_ADDREF(sp);
547         SPTREE_UNLOCK();
548 }
549 
550 /*
551  * Return 0 when there are known to be no SP's for the specified
552  * direction.  Otherwise return 1.  This is used by IPsec code
553  * to optimize performance.
554  */
555 int
556 key_havesp(u_int dir)
557 {
558         INIT_VNET_IPSEC(curvnet);
559 
560         return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
561                 LIST_FIRST(&V_sptree[dir]) != NULL : 1);
562 }
563 
564 /* %%% IPsec policy management */
565 /*
566  * allocating a SP for OUTBOUND or INBOUND packet.
567  * Must call key_freesp() later.
568  * OUT: NULL:   not found
569  *      others: found and return the pointer.
570  */
571 struct secpolicy *
572 key_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
573 {
574         INIT_VNET_IPSEC(curvnet);
575         struct secpolicy *sp;
576 
577         IPSEC_ASSERT(spidx != NULL, ("null spidx"));
578         IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
579                 ("invalid direction %u", dir));
580 
581         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
582                 printf("DP %s from %s:%u\n", __func__, where, tag));
583 
584         /* get a SP entry */
585         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
586                 printf("*** objects\n");
587                 kdebug_secpolicyindex(spidx));
588 
589         SPTREE_LOCK();
590         LIST_FOREACH(sp, &V_sptree[dir], chain) {
591                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
592                         printf("*** in SPD\n");
593                         kdebug_secpolicyindex(&sp->spidx));
594 
595                 if (sp->state == IPSEC_SPSTATE_DEAD)
596                         continue;
597                 if (key_cmpspidx_withmask(&sp->spidx, spidx))
598                         goto found;
599         }
600         sp = NULL;
601 found:
602         if (sp) {
603                 /* sanity check */
604                 KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
605 
606                 /* found a SPD entry */
607                 sp->lastused = time_second;
608                 SP_ADDREF(sp);
609         }
610         SPTREE_UNLOCK();
611 
612         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
613                 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
614                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
615         return sp;
616 }
617 
618 /*
619  * allocating a SP for OUTBOUND or INBOUND packet.
620  * Must call key_freesp() later.
621  * OUT: NULL:   not found
622  *      others: found and return the pointer.
623  */
624 struct secpolicy *
625 key_allocsp2(u_int32_t spi,
626              union sockaddr_union *dst,
627              u_int8_t proto,
628              u_int dir,
629              const char* where, int tag)
630 {
631         INIT_VNET_IPSEC(curvnet);
632         struct secpolicy *sp;
633 
634         IPSEC_ASSERT(dst != NULL, ("null dst"));
635         IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
636                 ("invalid direction %u", dir));
637 
638         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
639                 printf("DP %s from %s:%u\n", __func__, where, tag));
640 
641         /* get a SP entry */
642         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
643                 printf("*** objects\n");
644                 printf("spi %u proto %u dir %u\n", spi, proto, dir);
645                 kdebug_sockaddr(&dst->sa));
646 
647         SPTREE_LOCK();
648         LIST_FOREACH(sp, &V_sptree[dir], chain) {
649                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
650                         printf("*** in SPD\n");
651                         kdebug_secpolicyindex(&sp->spidx));
652 
653                 if (sp->state == IPSEC_SPSTATE_DEAD)
654                         continue;
655                 /* compare simple values, then dst address */
656                 if (sp->spidx.ul_proto != proto)
657                         continue;
658                 /* NB: spi's must exist and match */
659                 if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
660                         continue;
661                 if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
662                         goto found;
663         }
664         sp = NULL;
665 found:
666         if (sp) {
667                 /* sanity check */
668                 KEY_CHKSPDIR(sp->spidx.dir, dir, __func__);
669 
670                 /* found a SPD entry */
671                 sp->lastused = time_second;
672                 SP_ADDREF(sp);
673         }
674         SPTREE_UNLOCK();
675 
676         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
677                 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
678                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
679         return sp;
680 }
681 
682 /*
683  * return a policy that matches this particular inbound packet.
684  * XXX slow
685  */
686 struct secpolicy *
687 key_gettunnel(const struct sockaddr *osrc,
688               const struct sockaddr *odst,
689               const struct sockaddr *isrc,
690               const struct sockaddr *idst,
691               const char* where, int tag)
692 {
693         INIT_VNET_IPSEC(curvnet);
694         struct secpolicy *sp;
695         const int dir = IPSEC_DIR_INBOUND;
696         struct ipsecrequest *r1, *r2, *p;
697         struct secpolicyindex spidx;
698 
699         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
700                 printf("DP %s from %s:%u\n", __func__, where, tag));
701 
702         if (isrc->sa_family != idst->sa_family) {
703                 ipseclog((LOG_ERR, "%s: protocol family mismatched %d != %d\n.",
704                         __func__, isrc->sa_family, idst->sa_family));
705                 sp = NULL;
706                 goto done;
707         }
708 
709         SPTREE_LOCK();
710         LIST_FOREACH(sp, &V_sptree[dir], chain) {
711                 if (sp->state == IPSEC_SPSTATE_DEAD)
712                         continue;
713 
714                 r1 = r2 = NULL;
715                 for (p = sp->req; p; p = p->next) {
716                         if (p->saidx.mode != IPSEC_MODE_TUNNEL)
717                                 continue;
718 
719                         r1 = r2;
720                         r2 = p;
721 
722                         if (!r1) {
723                                 /* here we look at address matches only */
724                                 spidx = sp->spidx;
725                                 if (isrc->sa_len > sizeof(spidx.src) ||
726                                     idst->sa_len > sizeof(spidx.dst))
727                                         continue;
728                                 bcopy(isrc, &spidx.src, isrc->sa_len);
729                                 bcopy(idst, &spidx.dst, idst->sa_len);
730                                 if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
731                                         continue;
732                         } else {
733                                 if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
734                                     key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
735                                         continue;
736                         }
737 
738                         if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
739                             key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
740                                 continue;
741 
742                         goto found;
743                 }
744         }
745         sp = NULL;
746 found:
747         if (sp) {
748                 sp->lastused = time_second;
749                 SP_ADDREF(sp);
750         }
751         SPTREE_UNLOCK();
752 done:
753         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
754                 printf("DP %s return SP:%p (ID=%u) refcnt %u\n", __func__,
755                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
756         return sp;
757 }
758 
759 /*
760  * allocating an SA entry for an *OUTBOUND* packet.
761  * checking each request entries in SP, and acquire an SA if need.
762  * OUT: 0: there are valid requests.
763  *      ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
764  */
765 int
766 key_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
767 {
768         INIT_VNET_IPSEC(curvnet);
769         u_int level;
770         int error;
771 
772         IPSEC_ASSERT(isr != NULL, ("null isr"));
773         IPSEC_ASSERT(saidx != NULL, ("null saidx"));
774         IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
775                 saidx->mode == IPSEC_MODE_TUNNEL,
776                 ("unexpected policy %u", saidx->mode));
777 
778         /*
779          * XXX guard against protocol callbacks from the crypto
780          * thread as they reference ipsecrequest.sav which we
781          * temporarily null out below.  Need to rethink how we
782          * handle bundled SA's in the callback thread.
783          */
784         IPSECREQUEST_LOCK_ASSERT(isr);
785 
786         /* get current level */
787         level = ipsec_get_reqlevel(isr);
788 #if 0
789         /*
790          * We do allocate new SA only if the state of SA in the holder is
791          * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
792          */
793         if (isr->sav != NULL) {
794                 if (isr->sav->sah == NULL)
795                         panic("%s: sah is null.\n", __func__);
796                 if (isr->sav == (struct secasvar *)LIST_FIRST(
797                             &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
798                         KEY_FREESAV(&isr->sav);
799                         isr->sav = NULL;
800                 }
801         }
802 #else
803         /*
804          * we free any SA stashed in the IPsec request because a different
805          * SA may be involved each time this request is checked, either
806          * because new SAs are being configured, or this request is
807          * associated with an unconnected datagram socket, or this request
808          * is associated with a system default policy.
809          *
810          * The operation may have negative impact to performance.  We may
811          * want to check cached SA carefully, rather than picking new SA
812          * every time.
813          */
814         if (isr->sav != NULL) {
815                 KEY_FREESAV(&isr->sav);
816                 isr->sav = NULL;
817         }
818 #endif
819 
820         /*
821          * new SA allocation if no SA found.
822          * key_allocsa_policy should allocate the oldest SA available.
823          * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
824          */
825         if (isr->sav == NULL)
826                 isr->sav = key_allocsa_policy(saidx);
827 
828         /* When there is SA. */
829         if (isr->sav != NULL) {
830                 if (isr->sav->state != SADB_SASTATE_MATURE &&
831                     isr->sav->state != SADB_SASTATE_DYING)
832                         return EINVAL;
833                 return 0;
834         }
835 
836         /* there is no SA */
837         error = key_acquire(saidx, isr->sp);
838         if (error != 0) {
839                 /* XXX What should I do ? */
840                 ipseclog((LOG_DEBUG, "%s: error %d returned from key_acquire\n",
841                         __func__, error));
842                 return error;
843         }
844 
845         if (level != IPSEC_LEVEL_REQUIRE) {
846                 /* XXX sigh, the interface to this routine is botched */
847                 IPSEC_ASSERT(isr->sav == NULL, ("unexpected SA"));
848                 return 0;
849         } else {
850                 return ENOENT;
851         }
852 }
853 
854 /*
855  * allocating a SA for policy entry from SAD.
856  * NOTE: searching SAD of aliving state.
857  * OUT: NULL:   not found.
858  *      others: found and return the pointer.
859  */
860 static struct secasvar *
861 key_allocsa_policy(const struct secasindex *saidx)
862 {
863 #define N(a)    _ARRAYLEN(a)
864         INIT_VNET_IPSEC(curvnet);       
865         struct secashead *sah;
866         struct secasvar *sav;
867         u_int stateidx, arraysize;
868         const u_int *state_valid;
869 
870         SAHTREE_LOCK();
871         LIST_FOREACH(sah, &V_sahtree, chain) {
872                 if (sah->state == SADB_SASTATE_DEAD)
873                         continue;
874                 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID)) {
875                         if (V_key_preferred_oldsa) {
876                                 state_valid = saorder_state_valid_prefer_old;
877                                 arraysize = N(saorder_state_valid_prefer_old);
878                         } else {
879                                 state_valid = saorder_state_valid_prefer_new;
880                                 arraysize = N(saorder_state_valid_prefer_new);
881                         }
882                         SAHTREE_UNLOCK();
883                         goto found;
884                 }
885         }
886         SAHTREE_UNLOCK();
887 
888         return NULL;
889 
890     found:
891         /* search valid state */
892         for (stateidx = 0; stateidx < arraysize; stateidx++) {
893                 sav = key_do_allocsa_policy(sah, state_valid[stateidx]);
894                 if (sav != NULL)
895                         return sav;
896         }
897 
898         return NULL;
899 #undef N
900 }
901 
902 /*
903  * searching SAD with direction, protocol, mode and state.
904  * called by key_allocsa_policy().
905  * OUT:
906  *      NULL    : not found
907  *      others  : found, pointer to a SA.
908  */
909 static struct secasvar *
910 key_d