The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

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

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*      $NetBSD: key.c,v 1.11.2.7 2004/06/17 09:26:57 tron Exp $        */
    2 /*      $FreeBSD: /usr/local/www/cvsroot/FreeBSD/src/sys/netipsec/key.c,v 1.3.2.2 2003/07/01 01:38:13 sam Exp $ */
    3 /*      $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $   */
    4 
    5 /*
    6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
    7  * All rights reserved.
    8  *
    9  * Redistribution and use in source and binary forms, with or without
   10  * modification, are permitted provided that the following conditions
   11  * are met:
   12  * 1. Redistributions of source code must retain the above copyright
   13  *    notice, this list of conditions and the following disclaimer.
   14  * 2. Redistributions in binary form must reproduce the above copyright
   15  *    notice, this list of conditions and the following disclaimer in the
   16  *    documentation and/or other materials provided with the distribution.
   17  * 3. Neither the name of the project nor the names of its contributors
   18  *    may be used to endorse or promote products derived from this software
   19  *    without specific prior written permission.
   20  *
   21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
   22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
   25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   31  * SUCH DAMAGE.
   32  */
   33 
   34 #include <sys/cdefs.h>
   35 __KERNEL_RCSID(0, "$NetBSD: key.c,v 1.11.2.7 2004/06/17 09:26:57 tron Exp $");
   36 
   37 /*
   38  * This code is referd to RFC 2367
   39  */
   40 
   41 #include "opt_inet.h"
   42 #ifdef __FreeBSD__
   43 #include "opt_inet6.h"
   44 #endif
   45 #include "opt_ipsec.h"
   46 #ifdef __NetBSD__
   47 #include "opt_gateway.h"
   48 #endif
   49 
   50 #include <sys/types.h>
   51 #include <sys/param.h>
   52 #include <sys/systm.h>
   53 #include <sys/callout.h>
   54 #include <sys/kernel.h>
   55 #include <sys/mbuf.h>
   56 #include <sys/domain.h>
   57 #include <sys/protosw.h>
   58 #include <sys/malloc.h>
   59 #include <sys/socket.h>
   60 #include <sys/socketvar.h>
   61 #include <sys/sysctl.h>
   62 #include <sys/errno.h>
   63 #include <sys/proc.h>
   64 #include <sys/queue.h>
   65 #include <sys/syslog.h>
   66 
   67 #include <net/if.h>
   68 #include <net/route.h>
   69 #include <net/raw_cb.h>
   70 
   71 #include <netinet/in.h>
   72 #include <netinet/in_systm.h>
   73 #include <netinet/ip.h>
   74 #include <netinet/in_var.h>
   75 #ifdef INET
   76 #include <netinet/ip_var.h>
   77 #endif
   78 
   79 #ifdef INET6
   80 #include <netinet/ip6.h>
   81 #include <netinet6/in6_var.h>
   82 #include <netinet6/ip6_var.h>
   83 #endif /* INET6 */
   84 
   85 #ifdef INET
   86 #include <netinet/in_pcb.h>
   87 #endif
   88 #ifdef INET6
   89 #include <netinet6/in6_pcb.h>
   90 #endif /* INET6 */
   91 
   92 #include <net/pfkeyv2.h>
   93 #include <netipsec/keydb.h>
   94 #include <netipsec/key.h>
   95 #include <netipsec/keysock.h>
   96 #include <netipsec/key_debug.h>
   97 
   98 #include <netipsec/ipsec.h>
   99 #ifdef INET6
  100 #include <netipsec/ipsec6.h>
  101 #endif
  102 
  103 #include <netipsec/xform.h>
  104 #include <netipsec/ipsec_osdep.h>
  105 
  106 #include <machine/stdarg.h>
  107 
  108 
  109 #include <net/net_osdep.h>
  110 
  111 #define FULLMASK        0xff
  112 #define _BITS(bytes)    ((bytes) << 3)
  113 
  114 /*
  115  * Note on SA reference counting:
  116  * - SAs that are not in DEAD state will have (total external reference + 1)
  117  *   following value in reference count field.  they cannot be freed and are
  118  *   referenced from SA header.
  119  * - SAs that are in DEAD state will have (total external reference)
  120  *   in reference count field.  they are ready to be freed.  reference from
  121  *   SA header will be removed in key_delsav(), when the reference count
  122  *   field hits 0 (= no external reference other than from SA header.
  123  */
  124 
  125 u_int32_t key_debug_level = 0;
  126 static u_int key_spi_trycnt = 1000;
  127 static u_int32_t key_spi_minval = 0x100;
  128 static u_int32_t key_spi_maxval = 0x0fffffff;   /* XXX */
  129 static u_int32_t policy_id = 0;
  130 static u_int key_int_random = 60;       /*interval to initialize randseed,1(m)*/
  131 static u_int key_larval_lifetime = 30;  /* interval to expire acquiring, 30(s)*/
  132 static int key_blockacq_count = 10;     /* counter for blocking SADB_ACQUIRE.*/
  133 static int key_blockacq_lifetime = 20;  /* lifetime for blocking SADB_ACQUIRE.*/
  134 static int key_prefered_oldsa = 0;      /* prefered old sa rather than new sa.*/
  135 
  136 static u_int32_t acq_seq = 0;
  137 static int key_tick_init_random = 0;
  138 
  139 static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];     /* SPD */
  140 static LIST_HEAD(_sahtree, secashead) sahtree;                  /* SAD */
  141 static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
  142                                                         /* registed list */
  143 #ifndef IPSEC_NONBLOCK_ACQUIRE
  144 static LIST_HEAD(_acqtree, secacq) acqtree;             /* acquiring list */
  145 #endif
  146 static LIST_HEAD(_spacqtree, secspacq) spacqtree;       /* SP acquiring list */
  147 
  148 /* search order for SAs */
  149 static u_int saorder_state_valid[] = {
  150         SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
  151         /*
  152          * This order is important because we must select the oldest SA
  153          * for outbound processing.  For inbound, This is not important.
  154          */
  155 };
  156 static u_int saorder_state_alive[] = {
  157         /* except DEAD */
  158         SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
  159 };
  160 static u_int saorder_state_any[] = {
  161         SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
  162         SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
  163 };
  164 
  165 static const int minsize[] = {
  166         sizeof(struct sadb_msg),        /* SADB_EXT_RESERVED */
  167         sizeof(struct sadb_sa),         /* SADB_EXT_SA */
  168         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_CURRENT */
  169         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_HARD */
  170         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_SOFT */
  171         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_SRC */
  172         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_DST */
  173         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_PROXY */
  174         sizeof(struct sadb_key),        /* SADB_EXT_KEY_AUTH */
  175         sizeof(struct sadb_key),        /* SADB_EXT_KEY_ENCRYPT */
  176         sizeof(struct sadb_ident),      /* SADB_EXT_IDENTITY_SRC */
  177         sizeof(struct sadb_ident),      /* SADB_EXT_IDENTITY_DST */
  178         sizeof(struct sadb_sens),       /* SADB_EXT_SENSITIVITY */
  179         sizeof(struct sadb_prop),       /* SADB_EXT_PROPOSAL */
  180         sizeof(struct sadb_supported),  /* SADB_EXT_SUPPORTED_AUTH */
  181         sizeof(struct sadb_supported),  /* SADB_EXT_SUPPORTED_ENCRYPT */
  182         sizeof(struct sadb_spirange),   /* SADB_EXT_SPIRANGE */
  183         0,                              /* SADB_X_EXT_KMPRIVATE */
  184         sizeof(struct sadb_x_policy),   /* SADB_X_EXT_POLICY */
  185         sizeof(struct sadb_x_sa2),      /* SADB_X_SA2 */
  186 };
  187 static const int maxsize[] = {
  188         sizeof(struct sadb_msg),        /* SADB_EXT_RESERVED */
  189         sizeof(struct sadb_sa),         /* SADB_EXT_SA */
  190         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_CURRENT */
  191         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_HARD */
  192         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_SOFT */
  193         0,                              /* SADB_EXT_ADDRESS_SRC */
  194         0,                              /* SADB_EXT_ADDRESS_DST */
  195         0,                              /* SADB_EXT_ADDRESS_PROXY */
  196         0,                              /* SADB_EXT_KEY_AUTH */
  197         0,                              /* SADB_EXT_KEY_ENCRYPT */
  198         0,                              /* SADB_EXT_IDENTITY_SRC */
  199         0,                              /* SADB_EXT_IDENTITY_DST */
  200         0,                              /* SADB_EXT_SENSITIVITY */
  201         0,                              /* SADB_EXT_PROPOSAL */
  202         0,                              /* SADB_EXT_SUPPORTED_AUTH */
  203         0,                              /* SADB_EXT_SUPPORTED_ENCRYPT */
  204         sizeof(struct sadb_spirange),   /* SADB_EXT_SPIRANGE */
  205         0,                              /* SADB_X_EXT_KMPRIVATE */
  206         0,                              /* SADB_X_EXT_POLICY */
  207         sizeof(struct sadb_x_sa2),      /* SADB_X_SA2 */
  208 };
  209 
  210 static int ipsec_esp_keymin = 256;
  211 static int ipsec_esp_auth = 0;
  212 static int ipsec_ah_keymin = 128;
  213 
  214 #ifdef SYSCTL_DECL
  215 SYSCTL_DECL(_net_key);
  216 #endif
  217 
  218 #ifdef SYSCTL_INT
  219 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL,        debug,  CTLFLAG_RW, \
  220         &key_debug_level,       0,      "");
  221 
  222 /* max count of trial for the decision of spi value */
  223 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY,            spi_trycnt,     CTLFLAG_RW, \
  224         &key_spi_trycnt,        0,      "");
  225 
  226 /* minimum spi value to allocate automatically. */
  227 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE,      spi_minval,     CTLFLAG_RW, \
  228         &key_spi_minval,        0,      "");
  229 
  230 /* maximun spi value to allocate automatically. */
  231 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE,      spi_maxval,     CTLFLAG_RW, \
  232         &key_spi_maxval,        0,      "");
  233 
  234 /* interval to initialize randseed */
  235 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random,     CTLFLAG_RW, \
  236         &key_int_random,        0,      "");
  237 
  238 /* lifetime for larval SA */
  239 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME,    larval_lifetime, CTLFLAG_RW, \
  240         &key_larval_lifetime,   0,      "");
  241 
  242 /* counter for blocking to send SADB_ACQUIRE to IKEd */
  243 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,     blockacq_count, CTLFLAG_RW, \
  244         &key_blockacq_count,    0,      "");
  245 
  246 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
  247 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,  blockacq_lifetime, CTLFLAG_RW, \
  248         &key_blockacq_lifetime, 0,      "");
  249 
  250 /* ESP auth */
  251 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH,   esp_auth, CTLFLAG_RW, \
  252         &ipsec_esp_auth,        0,      "");
  253 
  254 /* minimum ESP key length */
  255 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin, CTLFLAG_RW, \
  256         &ipsec_esp_keymin,      0,      "");
  257 
  258 /* minimum AH key length */
  259 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN,  ah_keymin, CTLFLAG_RW, \
  260         &ipsec_ah_keymin,       0,      "");
  261 
  262 /* perfered old SA rather than new SA */
  263 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA,     prefered_oldsa, CTLFLAG_RW,\
  264         &key_prefered_oldsa,    0,      "");
  265 #endif /* SYSCTL_INT */
  266 
  267 #ifndef LIST_FOREACH
  268 #define LIST_FOREACH(elm, head, field)                                     \
  269         for (elm = LIST_FIRST(head); elm; elm = LIST_NEXT(elm, field))
  270 #endif
  271 #define __LIST_CHAINED(elm) \
  272         (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
  273 #define LIST_INSERT_TAIL(head, elm, type, field) \
  274 do {\
  275         struct type *curelm = LIST_FIRST(head); \
  276         if (curelm == NULL) {\
  277                 LIST_INSERT_HEAD(head, elm, field); \
  278         } else { \
  279                 while (LIST_NEXT(curelm, field)) \
  280                         curelm = LIST_NEXT(curelm, field);\
  281                 LIST_INSERT_AFTER(curelm, elm, field);\
  282         }\
  283 } while (0)
  284 
  285 #define KEY_CHKSASTATE(head, sav, name) \
  286 do { \
  287         if ((head) != (sav)) {                                          \
  288                 ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
  289                         (name), (head), (sav)));                        \
  290                 continue;                                               \
  291         }                                                               \
  292 } while (0)
  293 
  294 #define KEY_CHKSPDIR(head, sp, name) \
  295 do { \
  296         if ((head) != (sp)) {                                           \
  297                 ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
  298                         "anyway continue.\n",                           \
  299                         (name), (head), (sp)));                         \
  300         }                                                               \
  301 } while (0)
  302 
  303 MALLOC_DEFINE(M_SECA, "key mgmt", "security associations, key management");
  304 
  305 #if 1
  306 #define KMALLOC(p, t, n)                                                     \
  307         ((p) = (t) malloc((unsigned long)(n), M_SECA, M_NOWAIT))
  308 #define KFREE(p)                                                             \
  309         free((caddr_t)(p), M_SECA)
  310 #else
  311 #define KMALLOC(p, t, n) \
  312 do { \
  313         ((p) = (t)malloc((unsigned long)(n), M_SECA, M_NOWAIT));             \
  314         printf("%s %d: %p <- KMALLOC(%s, %d)\n",                             \
  315                 __FILE__, __LINE__, (p), #t, n);                             \
  316 } while (0)
  317 
  318 #define KFREE(p)                                                             \
  319         do {                                                                 \
  320                 printf("%s %d: %p -> KFREE()\n", __FILE__, __LINE__, (p));   \
  321                 free((caddr_t)(p), M_SECA);                                  \
  322         } while (0)
  323 #endif
  324 
  325 /*
  326  * set parameters into secpolicyindex buffer.
  327  * Must allocate secpolicyindex buffer passed to this function.
  328  */
  329 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
  330 do { \
  331         bzero((idx), sizeof(struct secpolicyindex));                         \
  332         (idx)->dir = (_dir);                                                 \
  333         (idx)->prefs = (ps);                                                 \
  334         (idx)->prefd = (pd);                                                 \
  335         (idx)->ul_proto = (ulp);                                             \
  336         bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
  337         bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
  338 } while (0)
  339 
  340 /*
  341  * set parameters into secasindex buffer.
  342  * Must allocate secasindex buffer before calling this function.
  343  */
  344 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
  345 do { \
  346         bzero((idx), sizeof(struct secasindex));                             \
  347         (idx)->proto = (p);                                                  \
  348         (idx)->mode = (m);                                                   \
  349         (idx)->reqid = (r);                                                  \
  350         bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
  351         bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
  352 } while (0)
  353 
  354 /* key statistics */
  355 struct _keystat {
  356         u_long getspi_count; /* the avarage of count to try to get new SPI */
  357 } keystat;
  358 
  359 struct sadb_msghdr {
  360         struct sadb_msg *msg;
  361         struct sadb_ext *ext[SADB_EXT_MAX + 1];
  362         int extoff[SADB_EXT_MAX + 1];
  363         int extlen[SADB_EXT_MAX + 1];
  364 };
  365 
  366 static struct secasvar *key_allocsa_policy __P((const struct secasindex *));
  367 static void key_freesp_so __P((struct secpolicy **));
  368 static struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
  369 static void key_delsp __P((struct secpolicy *));
  370 static struct secpolicy *key_getsp __P((struct secpolicyindex *));
  371 static struct secpolicy *key_getspbyid __P((u_int32_t));
  372 static u_int32_t key_newreqid __P((void));
  373 static struct mbuf *key_gather_mbuf __P((struct mbuf *,
  374         const struct sadb_msghdr *, int, int, ...));
  375 static int key_spdadd __P((struct socket *, struct mbuf *,
  376         const struct sadb_msghdr *));
  377 static u_int32_t key_getnewspid __P((void));
  378 static int key_spddelete __P((struct socket *, struct mbuf *,
  379         const struct sadb_msghdr *));
  380 static int key_spddelete2 __P((struct socket *, struct mbuf *,
  381         const struct sadb_msghdr *));
  382 static int key_spdget __P((struct socket *, struct mbuf *,
  383         const struct sadb_msghdr *));
  384 static int key_spdflush __P((struct socket *, struct mbuf *,
  385         const struct sadb_msghdr *));
  386 static int key_spddump __P((struct socket *, struct mbuf *,
  387         const struct sadb_msghdr *));
  388 static struct mbuf * key_setspddump __P((int *errorp, pid_t));
  389 static struct mbuf * key_setspddump_chain __P((int *errorp, int *lenp, pid_t pid));
  390 static struct mbuf *key_setdumpsp __P((struct secpolicy *,
  391         u_int8_t, u_int32_t, pid_t));
  392 static u_int key_getspreqmsglen __P((struct secpolicy *));
  393 static int key_spdexpire __P((struct secpolicy *));
  394 static struct secashead *key_newsah __P((struct secasindex *));
  395 static void key_delsah __P((struct secashead *));
  396 static struct secasvar *key_newsav __P((struct mbuf *,
  397         const struct sadb_msghdr *, struct secashead *, int *,
  398         const char*, int));
  399 #define KEY_NEWSAV(m, sadb, sah, e)                             \
  400         key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
  401 static void key_delsav __P((struct secasvar *));
  402 static struct secashead *key_getsah __P((struct secasindex *));
  403 static struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
  404 static struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
  405 static int key_setsaval __P((struct secasvar *, struct mbuf *,
  406         const struct sadb_msghdr *));
  407 static int key_mature __P((struct secasvar *));
  408 static struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
  409         u_int8_t, u_int32_t, u_int32_t));
  410 static struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
  411         u_int32_t, pid_t, u_int16_t));
  412 static struct mbuf *key_setsadbsa __P((struct secasvar *));
  413 static struct mbuf *key_setsadbaddr __P((u_int16_t,
  414         const struct sockaddr *, u_int8_t, u_int16_t));
  415 #if 0
  416 static struct mbuf *key_setsadbident __P((u_int16_t, u_int16_t, caddr_t,
  417         int, u_int64_t));
  418 #endif
  419 static struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
  420 static struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
  421         u_int32_t));
  422 static void *key_newbuf __P((const void *, u_int));
  423 #ifdef INET6
  424 static int key_ismyaddr6 __P((struct sockaddr_in6 *));
  425 #endif
  426 
  427 /* flags for key_cmpsaidx() */
  428 #define CMP_HEAD        1       /* protocol, addresses. */
  429 #define CMP_MODE_REQID  2       /* additionally HEAD, reqid, mode. */
  430 #define CMP_REQID       3       /* additionally HEAD, reaid. */
  431 #define CMP_EXACTLY     4       /* all elements. */
  432 static int key_cmpsaidx
  433         __P((const struct secasindex *, const struct secasindex *, int));
  434 
  435 static int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
  436 static int key_bbcmp __P((const void *, const void *, u_int));
  437 static void key_srandom __P((void));
  438 static u_int16_t key_satype2proto __P((u_int8_t));
  439 static u_int8_t key_proto2satype __P((u_int16_t));
  440 
  441 static int key_getspi __P((struct socket *, struct mbuf *,
  442         const struct sadb_msghdr *));
  443 static u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
  444                                         struct secasindex *));
  445 static int key_update __P((struct socket *, struct mbuf *,
  446         const struct sadb_msghdr *));
  447 #ifdef IPSEC_DOSEQCHECK
  448 static struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
  449 #endif
  450 static int key_add __P((struct socket *, struct mbuf *,
  451         const struct sadb_msghdr *));
  452 static int key_setident __P((struct secashead *, struct mbuf *,
  453         const struct sadb_msghdr *));
  454 static struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
  455         const struct sadb_msghdr *));
  456 static int key_delete __P((struct socket *, struct mbuf *,
  457         const struct sadb_msghdr *));
  458 static int key_get __P((struct socket *, struct mbuf *,
  459         const struct sadb_msghdr *));
  460 
  461 static void key_getcomb_setlifetime __P((struct sadb_comb *));
  462 static struct mbuf *key_getcomb_esp __P((void));
  463 static struct mbuf *key_getcomb_ah __P((void));
  464 static struct mbuf *key_getcomb_ipcomp __P((void));
  465 static struct mbuf *key_getprop __P((const struct secasindex *));
  466 
  467 static int key_acquire __P((const struct secasindex *, struct secpolicy *));
  468 #ifndef IPSEC_NONBLOCK_ACQUIRE
  469 static struct secacq *key_newacq __P((const struct secasindex *));
  470 static struct secacq *key_getacq __P((const struct secasindex *));
  471 static struct secacq *key_getacqbyseq __P((u_int32_t));
  472 #endif
  473 static struct secspacq *key_newspacq __P((struct secpolicyindex *));
  474 static struct secspacq *key_getspacq __P((struct secpolicyindex *));
  475 static int key_acquire2 __P((struct socket *, struct mbuf *,
  476         const struct sadb_msghdr *));
  477 static int key_register __P((struct socket *, struct mbuf *,
  478         const struct sadb_msghdr *));
  479 static int key_expire __P((struct secasvar *));
  480 static int key_flush __P((struct socket *, struct mbuf *,
  481         const struct sadb_msghdr *));
  482 static struct mbuf *key_setdump_chain __P((u_int8_t req_satype, int *errorp,
  483         int *lenp, pid_t pid));
  484 static int key_dump __P((struct socket *, struct mbuf *,
  485         const struct sadb_msghdr *));
  486 static int key_promisc __P((struct socket *, struct mbuf *,
  487         const struct sadb_msghdr *));
  488 static int key_senderror __P((struct socket *, struct mbuf *, int));
  489 static int key_validate_ext __P((const struct sadb_ext *, int));
  490 static int key_align __P((struct mbuf *, struct sadb_msghdr *));
  491 #if 0
  492 static const char *key_getfqdn __P((void));
  493 static const char *key_getuserfqdn __P((void));
  494 #endif
  495 static void key_sa_chgstate __P((struct secasvar *, u_int8_t));
  496 static  __inline void key_sp_dead __P((struct secpolicy *));
  497 static void key_sp_unlink __P((struct secpolicy *sp));
  498 
  499 static struct mbuf *key_alloc_mbuf __P((int));
  500 struct callout key_timehandler_ch;
  501 
  502 #define SA_ADDREF(p) do {                                               \
  503         (p)->refcnt++;                                                  \
  504         IPSEC_ASSERT((p)->refcnt != 0,                                  \
  505                 ("SA refcnt overflow at %s:%u", __FILE__, __LINE__));   \
  506 } while (0)
  507 #define SA_DELREF(p) do {                                               \
  508         IPSEC_ASSERT((p)->refcnt > 0,                                   \
  509                 ("SA refcnt underflow at %s:%u", __FILE__, __LINE__));  \
  510         (p)->refcnt--;                                                  \
  511 } while (0)
  512 
  513 #define SP_ADDREF(p) do {                                               \
  514         (p)->refcnt++;                                                  \
  515         IPSEC_ASSERT((p)->refcnt != 0,                                  \
  516                 ("SP refcnt overflow at %s:%u", __FILE__, __LINE__));   \
  517 } while (0)
  518 #define SP_DELREF(p) do {                                               \
  519         IPSEC_ASSERT((p)->refcnt > 0,                                   \
  520                 ("SP refcnt underflow at %s:%u", __FILE__, __LINE__));  \
  521         (p)->refcnt--;                                                  \
  522 } while (0)
  523 
  524 
  525 static __inline void
  526 key_sp_dead(struct secpolicy *sp)
  527 {
  528 
  529         /* mark the SP dead */
  530         sp->state = IPSEC_SPSTATE_DEAD;
  531 }
  532 
  533 static void
  534 key_sp_unlink(struct secpolicy *sp)
  535 {
  536 
  537         /* remove from SP index */
  538         if (__LIST_CHAINED(sp)) {
  539                 LIST_REMOVE(sp, chain);
  540                 /* Release refcount held just for being on chain */
  541                 KEY_FREESP(&sp);
  542         }
  543 }
  544 
  545 
  546 /*
  547  * Return 0 when there are known to be no SP's for the specified
  548  * direction.  Otherwise return 1.  This is used by IPsec code
  549  * to optimize performance.
  550  */
  551 int
  552 key_havesp(u_int dir)
  553 {
  554         return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
  555                 LIST_FIRST(&sptree[dir]) != NULL : 1);
  556 }
  557 
  558 /* %%% IPsec policy management */
  559 /*
  560  * allocating a SP for OUTBOUND or INBOUND packet.
  561  * Must call key_freesp() later.
  562  * OUT: NULL:   not found
  563  *      others: found and return the pointer.
  564  */
  565 struct secpolicy *
  566 key_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
  567 {
  568         struct secpolicy *sp;
  569         int s;
  570 
  571         IPSEC_ASSERT(spidx != NULL, ("key_allocsp: null spidx"));
  572         IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
  573                 ("key_allocsp: invalid direction %u", dir));
  574 
  575         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  576                 printf("DP key_allocsp from %s:%u\n", where, tag));
  577 
  578         /* get a SP entry */
  579         s = splsoftnet();       /*called from softclock()*/
  580         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
  581                 printf("*** objects\n");
  582                 kdebug_secpolicyindex(spidx));
  583 
  584         LIST_FOREACH(sp, &sptree[dir], chain) {
  585                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
  586                         printf("*** in SPD\n");
  587                         kdebug_secpolicyindex(&sp->spidx));
  588 
  589                 if (sp->state == IPSEC_SPSTATE_DEAD)
  590                         continue;
  591                 if (key_cmpspidx_withmask(&sp->spidx, spidx))
  592                         goto found;
  593         }
  594         sp = NULL;
  595 found:
  596         if (sp) {
  597                 /* sanity check */
  598                 KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp");
  599 
  600                 /* found a SPD entry */
  601                 sp->lastused = time_second;
  602                 SP_ADDREF(sp);
  603         }
  604         splx(s);
  605 
  606         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  607                 printf("DP key_allocsp return SP:%p (ID=%u) refcnt %u\n",
  608                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
  609         return sp;
  610 }
  611 
  612 /*
  613  * allocating a SP for OUTBOUND or INBOUND packet.
  614  * Must call key_freesp() later.
  615  * OUT: NULL:   not found
  616  *      others: found and return the pointer.
  617  */
  618 struct secpolicy *
  619 key_allocsp2(u_int32_t spi,
  620              union sockaddr_union *dst,
  621              u_int8_t proto,
  622              u_int dir,
  623              const char* where, int tag)
  624 {
  625         struct secpolicy *sp;
  626         int s;
  627 
  628         IPSEC_ASSERT(dst != NULL, ("key_allocsp2: null dst"));
  629         IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
  630                 ("key_allocsp2: invalid direction %u", dir));
  631 
  632         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  633                 printf("DP key_allocsp2 from %s:%u\n", where, tag));
  634 
  635         /* get a SP entry */
  636         s = splsoftnet();       /*called from softclock()*/
  637         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
  638                 printf("*** objects\n");
  639                 printf("spi %u proto %u dir %u\n", spi, proto, dir);
  640                 kdebug_sockaddr(&dst->sa));
  641 
  642         LIST_FOREACH(sp, &sptree[dir], chain) {
  643                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
  644                         printf("*** in SPD\n");
  645                         kdebug_secpolicyindex(&sp->spidx));
  646 
  647                 if (sp->state == IPSEC_SPSTATE_DEAD)
  648                         continue;
  649                 /* compare simple values, then dst address */
  650                 if (sp->spidx.ul_proto != proto)
  651                         continue;
  652                 /* NB: spi's must exist and match */
  653                 if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
  654                         continue;
  655                 if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
  656                         goto found;
  657         }
  658         sp = NULL;
  659 found:
  660         if (sp) {
  661                 /* sanity check */
  662                 KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp2");
  663 
  664                 /* found a SPD entry */
  665                 sp->lastused = time_second;
  666                 SP_ADDREF(sp);
  667         }
  668         splx(s);
  669 
  670         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  671                 printf("DP key_allocsp2 return SP:%p (ID=%u) refcnt %u\n",
  672                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
  673         return sp;
  674 }
  675 
  676 /*
  677  * return a policy that matches this particular inbound packet.
  678  * XXX slow
  679  */
  680 struct secpolicy *
  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)
  686 {
  687         struct secpolicy *sp;
  688         const int dir = IPSEC_DIR_INBOUND;
  689         int s;
  690         struct ipsecrequest *r1, *r2, *p;
  691         struct secpolicyindex spidx;
  692 
  693         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  694                 printf("DP key_gettunnel from %s:%u\n", where, tag));
  695 
  696         if (isrc->sa_family != idst->sa_family) {
  697                 ipseclog((LOG_ERR, "protocol family mismatched %d != %d\n.",
  698                         isrc->sa_family, idst->sa_family));
  699                 sp = NULL;
  700                 goto done;
  701         }
  702 
  703         s = splsoftnet();       /*called from softclock()*/
  704         LIST_FOREACH(sp, &sptree[dir], chain) {
  705                 if (sp->state == IPSEC_SPSTATE_DEAD)
  706                         continue;
  707 
  708                 r1 = r2 = NULL;
  709                 for (p = sp->req; p; p = p->next) {
  710                         if (p->saidx.mode != IPSEC_MODE_TUNNEL)
  711                                 continue;
  712 
  713                         r1 = r2;
  714                         r2 = p;
  715 
  716                         if (!r1) {
  717                                 /* here we look at address matches only */
  718                                 spidx = sp->spidx;
  719                                 if (isrc->sa_len > sizeof(spidx.src) ||
  720                                     idst->sa_len > sizeof(spidx.dst))
  721                                         continue;
  722                                 bcopy(isrc, &spidx.src, isrc->sa_len);
  723                                 bcopy(idst, &spidx.dst, idst->sa_len);
  724                                 if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
  725                                         continue;
  726                         } else {
  727                                 if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
  728                                     key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
  729                                         continue;
  730                         }
  731 
  732                         if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
  733                             key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
  734                                 continue;
  735 
  736                         goto found;
  737                 }
  738         }
  739         sp = NULL;
  740 found:
  741         if (sp) {
  742                 sp->lastused = time_second;
  743                 SP_ADDREF(sp);
  744         }
  745         splx(s);
  746 done:
  747         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  748                 printf("DP key_gettunnel return SP:%p (ID=%u) refcnt %u\n",
  749                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
  750         return sp;
  751 }
  752 
  753 /*
  754  * allocating an SA entry for an *OUTBOUND* packet.
  755  * checking each request entries in SP, and acquire an SA if need.
  756  * OUT: 0: there are valid requests.
  757  *      ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
  758  */
  759 int
  760 key_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
  761 {
  762         u_int level;
  763         int error;
  764 
  765         IPSEC_ASSERT(isr != NULL, ("key_checkrequest: null isr"));
  766         IPSEC_ASSERT(saidx != NULL, ("key_checkrequest: null saidx"));
  767         IPSEC_ASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
  768                 saidx->mode == IPSEC_MODE_TUNNEL,
  769                 ("key_checkrequest: unexpected policy %u", saidx->mode));
  770 
  771         /* get current level */
  772         level = ipsec_get_reqlevel(isr);
  773 
  774         /*
  775          * XXX guard against protocol callbacks from the crypto
  776          * thread as they reference ipsecrequest.sav which we
  777          * temporarily null out below.  Need to rethink how we
  778          * handle bundled SA's in the callback thread.
  779          */
  780         IPSEC_SPLASSERT_SOFTNET("key_checkrequest");
  781 #if 0
  782         /*
  783          * We do allocate new SA only if the state of SA in the holder is
  784          * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
  785          */
  786         if (isr->sav != NULL) {
  787                 if (isr->sav->sah == NULL)
  788                         panic("key_checkrequest: sah is null.\n");
  789                 if (isr->sav == (struct secasvar *)LIST_FIRST(
  790                             &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
  791                         KEY_FREESAV(&isr->sav);
  792                         isr->sav = NULL;
  793                 }
  794         }
  795 #else
  796         /*
  797          * we free any SA stashed in the IPsec request because a different
  798          * SA may be involved each time this request is checked, either
  799          * because new SAs are being configured, or this request is
  800          * associated with an unconnected datagram socket, or this request
  801          * is associated with a system default policy.
  802          *
  803          * The operation may have negative impact to performance.  We may
  804          * want to check cached SA carefully, rather than picking new SA
  805          * every time.
  806          */
  807         if (isr->sav != NULL) {
  808                 KEY_FREESAV(&isr->sav);
  809                 isr->sav = NULL;
  810         }
  811 #endif
  812 
  813         /*
  814          * new SA allocation if no SA found.
  815          * key_allocsa_policy should allocate the oldest SA available.
  816          * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
  817          */
  818         if (isr->sav == NULL)
  819                 isr->sav = key_allocsa_policy(saidx);
  820 
  821         /* When there is SA. */
  822         if (isr->sav != NULL) {
  823                 if (isr->sav->state != SADB_SASTATE_MATURE &&
  824                     isr->sav->state != SADB_SASTATE_DYING)
  825                         return EINVAL;
  826                 return 0;
  827         }
  828 
  829         /* there is no SA */
  830         error = key_acquire(saidx, isr->sp);
  831         if (error != 0) {
  832                 /* XXX What should I do ? */
  833                 ipseclog((LOG_DEBUG, "key_checkrequest: error %d returned "
  834                         "from key_acquire.\n", error));
  835                 return error;
  836         }
  837 
  838         if (level != IPSEC_LEVEL_REQUIRE) {
  839                 /* XXX sigh, the interface to this routine is botched */
  840                 IPSEC_ASSERT(isr->sav == NULL, ("key_checkrequest: unexpected SA"));
  841                 return 0;
  842         } else {
  843                 return ENOENT;
  844         }
  845 }
  846 
  847 /*
  848  * allocating a SA for policy entry from SAD.
  849  * NOTE: searching SAD of aliving state.
  850  * OUT: NULL:   not found.
  851  *      others: found and return the pointer.
  852  */
  853 static struct secasvar *
  854 key_allocsa_policy(const struct secasindex *saidx)
  855 {
  856         struct secashead *sah;
  857         struct secasvar *sav;
  858         u_int stateidx, state;
  859 
  860         LIST_FOREACH(sah, &sahtree, chain) {
  861                 if (sah->state == SADB_SASTATE_DEAD)
  862                         continue;
  863                 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID))
  864                         goto found;
  865         }
  866 
  867         return NULL;
  868 
  869     found:
  870 
  871         /* search valid state */
  872         for (stateidx = 0;
  873              stateidx < _ARRAYLEN(saorder_state_valid);
  874              stateidx++) {
  875 
  876                 state = saorder_state_valid[stateidx];
  877 
  878                 sav = key_do_allocsa_policy(sah, state);
  879                 if (sav != NULL)
  880                         return sav;
  881         }
  882 
  883         return NULL;
  884 }
  885 
  886 /*
  887  * searching SAD with direction, protocol, mode and state.
  888  * called by key_allocsa_policy().
  889  * OUT:
  890  *      NULL    : not found
  891  *      others  : found, pointer to a SA.
  892  */
  893 static struct secasvar *
  894 key_do_allocsa_policy(struct secashead *sah, u_int state)
  895 {
  896         struct secasvar *sav, *nextsav, *candidate, *d;
  897 
  898         /* initilize */
  899         candidate = NULL;
  900 
  901         for (sav = LIST_FIRST(&sah->savtree[state]);
  902              sav != NULL;
  903              sav = nextsav) {
  904 
  905                 nextsav = LIST_NEXT(sav, chain);
  906 
  907                 /* sanity check */
  908                 KEY_CHKSASTATE(sav->state, state, "key_do_allocsa_policy");
  909 
  910                 /* initialize */
  911                 if (candidate == NULL) {
  912                         candidate = sav;
  913                         continue;
  914                 }
  915 
  916                 /* Which SA is the better ? */
  917 
  918                 /* sanity check 2 */
  919                 if (candidate->lft_c == NULL || sav->lft_c == NULL)
  920                         panic("key_do_allocsa_policy: "
  921                                 "lifetime_current is NULL.\n");
  922 
  923                 /* What the best method is to compare ? */
  924                 if (key_prefered_oldsa) {
  925                         if (candidate->lft_c->sadb_lifetime_addtime >
  926                                         sav->lft_c->sadb_lifetime_addtime) {
  927                                 candidate = sav;
  928                         }
  929                         continue;
  930                         /*NOTREACHED*/
  931                 }
  932 
  933                 /* prefered new sa rather than old sa */
  934                 if (candidate->lft_c->sadb_lifetime_addtime <
  935                                 sav->lft_c->sadb_lifetime_addtime) {
  936                         d = candidate;
  937                         candidate = sav;
  938                 } else
  939                         d = sav;
  940 
  941                 /*
  942                  * prepared to delete the SA when there is more
  943                  * suitable candidate and the lifetime of the SA is not
  944                  * permanent.
  945                  */
  946                 if (d->lft_c->sadb_lifetime_addtime != 0) {
  947                         struct mbuf *m, *result;
  948 
  949                         key_sa_chgstate(d, SADB_SASTATE_DEAD);
  950 
  951                         IPSEC_ASSERT(d->refcnt > 0,
  952                                 ("key_do_allocsa_policy: bogus ref count"));
  953                         m = key_setsadbmsg(SADB_DELETE, 0,
  954                             d->sah->saidx.proto, 0, 0, d->refcnt - 1);
  955                         if (!m)
  956                                 goto msgfail;
  957                         result = m;
  958 
  959                         /* set sadb_address for saidx's. */
  960                         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
  961                                 &d->sah->saidx.src.sa,
  962                                 d->sah->saidx.src.sa.sa_len << 3,
  963                                 IPSEC_ULPROTO_ANY);
  964                         if (!m)
  965                                 goto msgfail;
  966                         m_cat(result, m);
  967 
  968                         /* set sadb_address for saidx's. */
  969                         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
  970                                 &d->sah->saidx.src.sa,
  971                                 d->sah->saidx.src.sa.sa_len << 3,
  972                                 IPSEC_ULPROTO_ANY);
  973                         if (!m)
  974                                 goto msgfail;
  975                         m_cat(result, m);
  976 
  977                         /* create SA extension */
  978                         m = key_setsadbsa(d);
  979                         if (!m)
  980                                 goto msgfail;
  981                         m_cat(result, m);
  982 
  983                         if (result->m_len < sizeof(struct sadb_msg)) {
  984                                 result = m_pullup(result,
  985                                                 sizeof(struct sadb_msg));
  986                                 if (result == NULL)
  987                                         goto msgfail;
  988                         }
  989 
  990                         result->m_pkthdr.len = 0;
  991                         for (m = result; m; m = m->m_next)
  992                                 result->m_pkthdr.len += m->m_len;
  993                         mtod(result, struct sadb_msg *)->sadb_msg_len =
  994                                 PFKEY_UNIT64(result->m_pkthdr.len);
  995 
  996                         if (key_sendup_mbuf(NULL, result,
  997                                         KEY_SENDUP_REGISTERED))
  998                                 goto msgfail;
  999                  msgfail:
 1000                         KEY_FREESAV(&d);
 1001                 }
 1002         }
 1003 
 1004         if (candidate) {
 1005                 SA_ADDREF(candidate);
 1006                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1007                         printf("DP allocsa_policy cause "
 1008                                 "refcnt++:%d SA:%p\n",
 1009                                 candidate->refcnt, candidate));
 1010         }
 1011         return candidate;
 1012 }
 1013 
 1014 /*
 1015  * allocating a usable SA entry for a *INBOUND* packet.
 1016  * Must call key_freesav() later.
 1017  * OUT: positive:       pointer to a usable sav (i.e. MATURE or DYING state).
 1018  *      NULL:           not found, or error occurred.
 1019  *
 1020  * In the comparison, no source address is used--for RFC2401 conformance.
 1021  * To quote, from section 4.1:
 1022  *      A security association is uniquely identified by a triple consisting
 1023  *      of a Security Parameter Index (SPI), an IP Destination Address, and a
 1024  *      security protocol (AH or ESP) identifier.
 1025  * Note that, however, we do need to keep source address in IPsec SA.
 1026  * IKE specification and PF_KEY specification do assume that we
 1027  * keep source address in IPsec SA.  We see a tricky situation here.
 1028  */
 1029 struct secasvar *
 1030 key_allocsa(
 1031         union sockaddr_union *dst,
 1032         u_int proto,
 1033         u_int32_t spi,
 1034         const char* where, int tag)
 1035 {
 1036         struct secashead *sah;
 1037         struct secasvar *sav;
 1038         u_int stateidx, state;
 1039         int s;
 1040 
 1041         IPSEC_ASSERT(dst != NULL, ("key_allocsa: null dst address"));
 1042 
 1043         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1044                 printf("DP key_allocsa from %s:%u\n", where, tag));
 1045 
 1046         /*
 1047          * searching SAD.
 1048          * XXX: to be checked internal IP header somewhere.  Also when
 1049          * IPsec tunnel packet is received.  But ESP tunnel mode is
 1050          * encrypted so we can't check internal IP header.
 1051          */
 1052         s = splsoftnet();       /*called from softclock()*/
 1053         LIST_FOREACH(sah, &sahtree, chain) {
 1054                 /* search valid state */
 1055                 for (stateidx = 0;
 1056                      stateidx < _ARRAYLEN(saorder_state_valid);
 1057                      stateidx++) {
 1058                         state = saorder_state_valid[stateidx];
 1059                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
 1060                                 /* sanity check */
 1061                                 KEY_CHKSASTATE(sav->state, state, "key_allocsav");
 1062                                 /* do not return entries w/ unusable state */
 1063                                 if (sav->state != SADB_SASTATE_MATURE &&
 1064                                     sav->state != SADB_SASTATE_DYING)
 1065                                         continue;
 1066                                 if (proto != sav->sah->saidx.proto)
 1067                                         continue;
 1068                                 if (spi != sav->spi)
 1069                                         continue;
 1070 #if 0   /* don't check src */
 1071                                 /* check src address */
 1072                                 if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, 0) != 0)
 1073                                         continue;
 1074 #endif
 1075                                 /* check dst address */
 1076                                 if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, 0) != 0)
 1077                                         continue;
 1078                                 SA_ADDREF(sav);
 1079                                 goto done;
 1080                         }
 1081                 }
 1082         }
 1083         sav = NULL;
 1084 done:
 1085         splx(s);
 1086 
 1087         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1088                 printf("DP key_allocsa return SA:%p; refcnt %u\n",
 1089                         sav, sav ? sav->refcnt : 0));
 1090         return sav;
 1091 }
 1092 
 1093 /*
 1094  * Must be called after calling key_allocsp().
 1095  * For both the packet without socket and key_freeso().
 1096  */
 1097 void
 1098 _key_freesp(struct secpolicy **spp, const char* where, int tag)
 1099 {
 1100         struct secpolicy *sp = *spp;
 1101 
 1102         IPSEC_ASSERT(sp != NULL, ("key_freesp: null sp"));
 1103 
 1104         SP_DELREF(sp);
 1105 
 1106         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1107                 printf("DP key_freesp SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
 1108                         sp, sp->id, where, tag, sp->refcnt));
 1109 
 1110         if (sp->refcnt == 0) {
 1111                 *spp = NULL;
 1112                 key_delsp(sp);
 1113         }
 1114 }
 1115 
 1116 /*
 1117  * Must be called after calling key_allocsp().
 1118  * For the packet with socket.
 1119  */
 1120 void
 1121 key_freeso(struct socket *so)
 1122 {
 1123         /* sanity check */
 1124         IPSEC_ASSERT(so != NULL, ("key_freeso: null so"));
 1125 
 1126         switch (so->so_proto->pr_domain->dom_family) {
 1127 #ifdef INET
 1128         case PF_INET:
 1129             {
 1130                 struct inpcb *pcb = sotoinpcb(so);
 1131 
 1132                 /* Does it have a PCB ? */
 1133                 if (pcb == NULL)
 1134                         return;
 1135                 key_freesp_so(&pcb->inp_sp->sp_in);
 1136                 key_freesp_so(&pcb->inp_sp->sp_out);
 1137             }
 1138                 break;
 1139 #endif
 1140 #ifdef INET6
 1141         case PF_INET6:
 1142             {
 1143 #ifdef HAVE_NRL_INPCB
 1144                 struct inpcb *pcb  = sotoinpcb(so);
 1145 
 1146                 /* Does it have a PCB ? */
 1147                 if (pcb == NULL)
 1148                         return;
 1149                 key_freesp_so(&pcb->inp_sp->sp_in);
 1150                 key_freesp_so(&pcb->inp_sp->sp_out);
 1151 #else
 1152                 struct in6pcb *pcb  = sotoin6pcb(so);
 1153 
 1154                 /* Does it have a PCB ? */
 1155                 if (pcb == NULL)
 1156                         return;
 1157                 key_freesp_so(&pcb->in6p_sp->sp_in);
 1158                 key_freesp_so(&pcb->in6p_sp->sp_out);
 1159 #endif
 1160             }
 1161                 break;
 1162 #endif /* INET6 */
 1163         default:
 1164                 ipseclog((LOG_DEBUG, "key_freeso: unknown address family=%d.\n",
 1165                     so->so_proto->pr_domain->dom_family));
 1166                 return;
 1167         }
 1168 }
 1169 
 1170 static void
 1171 key_freesp_so(struct secpolicy **sp)
 1172 {
 1173         IPSEC_ASSERT(sp != NULL && *sp != NULL, ("key_freesp_so: null sp"));
 1174 
 1175         if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
 1176             (*sp)->policy == IPSEC_POLICY_BYPASS)
 1177                 return;
 1178 
 1179         IPSEC_ASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
 1180                 ("key_freesp_so: invalid policy %u", (*sp)->policy));
 1181         KEY_FREESP(sp);
 1182 }
 1183 
 1184 /*
 1185  * Must be called after calling key_allocsa().
 1186  * This function is called by key_freesp() to free some SA allocated
 1187  * for a policy.
 1188  */
 1189 void
 1190 key_freesav(struct secasvar **psav, const char* where, int tag)
 1191 {
 1192         struct secasvar *sav = *psav;
 1193 
 1194         IPSEC_ASSERT(sav != NULL, ("key_freesav: null sav"));
 1195 
 1196         SA_DELREF(sav);
 1197 
 1198         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1199                 printf("DP key_freesav SA:%p (SPI %lu) from %s:%u; refcnt now %u\n",
 1200                         sav, (u_long)ntohl(sav->spi),
 1201                        where, tag, sav->refcnt));
 1202 
 1203         if (sav->refcnt == 0) {
 1204                 *psav = NULL;
 1205                 key_delsav(sav);
 1206         }
 1207 }
 1208 
 1209 /* %%% SPD management */
 1210 /*
 1211  * free security policy entry.
 1212  */
 1213 static void
 1214 key_delsp(struct secpolicy *sp)
 1215 {
 1216         int s;
 1217 
 1218         IPSEC_ASSERT(sp != NULL, ("key_delsp: null sp"));
 1219 
 1220         key_sp_dead(sp);
 1221 
 1222         IPSEC_ASSERT(sp->refcnt == 0,
 1223                 ("key_delsp: SP with references deleted (refcnt %u)",
 1224                 sp->refcnt));
 1225 
 1226         s = splsoftnet();       /*called from softclock()*/
 1227 
 1228     {
 1229         struct ipsecrequest *isr = sp->req, *nextisr;
 1230 
 1231         while (isr != NULL) {
 1232                 if (isr->sav != NULL) {
 1233                         KEY_FREESAV(&isr->sav);
 1234                         isr->sav = NULL;
 1235                 }
 1236 
 1237                 nextisr = isr->next;
 1238                 KFREE(isr);
 1239                 isr = nextisr;
 1240         }
 1241     }
 1242 
 1243         KFREE(sp);
 1244 
 1245         splx(s);
 1246 }
 1247 
 1248 /*
 1249  * search SPD
 1250  * OUT: NULL    : not found
 1251  *      others  : found, pointer to a SP.
 1252  */
 1253 static struct secpolicy *
 1254 key_getsp(struct secpolicyindex *spidx)
 1255 {
 1256         struct secpolicy *sp;
 1257 
 1258         IPSEC_ASSERT(spidx != NULL, ("key_getsp: null spidx"));
 1259 
 1260         LIST_FOREACH(sp, &sptree[spidx->dir], chain) {
 1261                 if (sp->state == IPSEC_SPSTATE_DEAD)
 1262                         continue;
 1263                 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
 1264                         SP_ADDREF(sp);
 1265                         return sp;
 1266                 }
 1267         }
 1268 
 1269         return NULL;
 1270 }
 1271 
 1272 /*
 1273  * get SP by index.
 1274  * OUT: NULL    : not found
 1275  *      others  : found, pointer to a SP.
 1276  */
 1277 static struct secpolicy *
 1278 key_getspbyid(u_int32_t id)
 1279 {
 1280         struct secpolicy *sp;
 1281 
 1282         LIST_FOREACH(sp, &sptree[IPSEC_DIR_INBOUND], chain) {
 1283                 if (sp->state == IPSEC_SPSTATE_DEAD)
 1284                         continue;
 1285                 if (sp->id == id) {
 1286                         SP_ADDREF(sp);
 1287                         return sp;
 1288                 }
 1289         }
 1290 
 1291         LIST_FOREACH(sp, &sptree[IPSEC_DIR_OUTBOUND], chain) {
 1292                 if (sp->state == IPSEC_SPSTATE_DEAD)
 1293                         continue;
 1294                 if (sp->id == id) {
 1295                         SP_ADDREF(sp);
 1296                         return sp;
 1297                 }
 1298         }
 1299 
 1300         return NULL;
 1301 }
 1302 
 1303 struct secpolicy *
 1304 key_newsp(const char* where, int tag)
 1305 {
 1306         struct secpolicy *newsp = NULL;
 1307 
 1308         newsp = (struct secpolicy *)
 1309                 malloc(sizeof(struct secpolicy), M_SECA, M_NOWAIT|M_ZERO);
 1310         if (newsp) {
 1311                 newsp->refcnt = 1;
 1312                 newsp->req = NULL;
 1313         }
 1314 
 1315         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1316                 printf("DP key_newsp from %s:%u return SP:%p\n",
 1317                         where, tag, newsp));
 1318         return newsp;
 1319 }
 1320 
 1321 /*
 1322  * create secpolicy structure from sadb_x_policy structure.
 1323  * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
 1324  * so must be set properly later.
 1325  */
 1326 struct secpolicy *
 1327 key_msg2sp(xpl0, len, error)
 1328         struct sadb_x_policy *xpl0;
 1329         size_t len;
 1330         int *error;
 1331 {
 1332         struct secpolicy *newsp;
 1333 
 1334         /* sanity check */
 1335         if (xpl0 == NULL)
 1336                 panic("key_msg2sp: NULL pointer was passed.\n");
 1337         if (len < sizeof(*xpl0))
 1338                 panic("key_msg2sp: invalid length.\n");
 1339         if (len != PFKEY_EXTLEN(xpl0)) {
 1340                 ipseclog((LOG_DEBUG, "key_msg2sp: Invalid msg length.\n"));
 1341                 *error = EINVAL;
 1342                 return NULL;
 1343         }
 1344 
 1345         if ((newsp = KEY_NEWSP()) == NULL) {
 1346                 *error = ENOBUFS;
 1347                 return NULL;
 1348         }
 1349 
 1350         newsp->spidx.dir = xpl0->sadb_x_policy_dir;
 1351         newsp->policy = xpl0->sadb_x_policy_type;
 1352 
 1353         /* check policy */
 1354         switch (xpl0->sadb_x_policy_type) {
 1355         case IPSEC_POLICY_DISCARD:
 1356         case IPSEC_POLICY_NONE:
 1357         case IPSEC_POLICY_ENTRUST:
 1358         case IPSEC_POLICY_BYPASS:
 1359                 newsp->req = NULL;
 1360                 break;
 1361 
 1362         case IPSEC_POLICY_IPSEC:
 1363             {
 1364                 int tlen;
 1365                 struct sadb_x_ipsecrequest *xisr;
 1366                 struct ipsecrequest **p_isr = &newsp->req;
 1367 
 1368                 /* validity check */
 1369                 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
 1370                         ipseclog((LOG_DEBUG,
 1371                             "key_msg2sp: Invalid msg length.\n"));
 1372                         KEY_FREESP(&newsp);
 1373                         *error = EINVAL;
 1374                         return NULL;
 1375                 }
 1376 
 1377                 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
 1378                 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
 1379 
 1380                 while (tlen > 0) {
 1381                         /* length check */
 1382                         if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
 1383                                 ipseclog((LOG_DEBUG, "key_msg2sp: "
 1384                                         "invalid ipsecrequest length.\n"));
 1385                                 KEY_FREESP(&newsp);
 1386                                 *error = EINVAL;
 1387                                 return NULL;
 1388                         }
 1389 
 1390                         /* allocate request buffer */
 1391                         KMALLOC(*p_isr, struct ipsecrequest *, sizeof(**p_isr));
 1392                         if ((*p_isr) == NULL) {
 1393                                 ipseclog((LOG_DEBUG,
 1394                                     "key_msg2sp: No more memory.\n"));
 1395                                 KEY_FREESP(&newsp);
 1396                                 *error = ENOBUFS;
 1397                                 return NULL;
 1398                         }
 1399                         bzero(*p_isr, sizeof(**p_isr));
 1400 
 1401                         /* set values */
 1402                         (*p_isr)->next = NULL;
 1403 
 1404                         switch (xisr->sadb_x_ipsecrequest_proto) {
 1405                         case IPPROTO_ESP:
 1406                         case IPPROTO_AH:
 1407                         case IPPROTO_IPCOMP:
 1408                                 break;
 1409                         default:
 1410                                 ipseclog((LOG_DEBUG,
 1411                                     "key_msg2sp: invalid proto type=%u\n",
 1412                                     xisr->sadb_x_ipsecrequest_proto));
 1413                                 KEY_FREESP(&newsp);
 1414                                 *error = EPROTONOSUPPORT;
 1415                                 return NULL;
 1416                         }
 1417                         (*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
 1418 
 1419                         switch (xisr->sadb_x_ipsecrequest_mode) {
 1420                         case IPSEC_MODE_TRANSPORT:
 1421                         case IPSEC_MODE_TUNNEL:
 1422                                 break;
 1423                         case IPSEC_MODE_ANY:
 1424                         default:
 1425                                 ipseclog((LOG_DEBUG,
 1426                                     "key_msg2sp: invalid mode=%u\n",
 1427                                     xisr->sadb_x_ipsecrequest_mode));
 1428                                 KEY_FREESP(&newsp);
 1429                                 *error = EINVAL;
 1430                                 return NULL;
 1431                         }
 1432                         (*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
 1433 
 1434                         switch (xisr->sadb_x_ipsecrequest_level) {
 1435                         case IPSEC_LEVEL_DEFAULT:
 1436                         case IPSEC_LEVEL_USE:
 1437                         case IPSEC_LEVEL_REQUIRE:
 1438                                 break;
 1439                         case IPSEC_LEVEL_UNIQUE:
 1440                                 /* validity check */
 1441                                 /*
 1442                                  * If range violation of reqid, kernel will
 1443                                  * update it, don't refuse it.
 1444                                  */
 1445                                 if (xisr->sadb_x_ipsecrequest_reqid
 1446                                                 > IPSEC_MANUAL_REQID_MAX) {
 1447                                         ipseclog((LOG_DEBUG,
 1448                                             "key_msg2sp: reqid=%d range "
 1449                                             "violation, updated by kernel.\n",
 1450                                             xisr->sadb_x_ipsecrequest_reqid));
 1451                                         xisr->sadb_x_ipsecrequest_reqid = 0;
 1452                                 }
 1453 
 1454                                 /* allocate new reqid id if reqid is zero. */
 1455                                 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
 1456                                         u_int32_t reqid;
 1457                                         if ((reqid = key_newreqid()) == 0) {
 1458                                                 KEY_FREESP(&newsp);
 1459                                                 *error = ENOBUFS;
 1460                                                 return NULL;
 1461                                         }
 1462                                         (*p_isr)->saidx.reqid = reqid;
 1463                                         xisr->sadb_x_ipsecrequest_reqid = reqid;
 1464                                 } else {
 1465                                 /* set it for manual keying. */
 1466                                         (*p_isr)->saidx.reqid =
 1467                                                 xisr->sadb_x_ipsecrequest_reqid;
 1468                                 }
 1469                                 break;
 1470 
 1471                         default:
 1472                                 ipseclog((LOG_DEBUG, "key_msg2sp: invalid level=%u\n",
 1473                                         xisr->sadb_x_ipsecrequest_level));
 1474                                 KEY_FREESP(&newsp);
 1475                                 *error = EINVAL;
 1476                                 return NULL;
 1477                         }
 1478                         (*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
 1479 
 1480                         /* set IP addresses if there */
 1481                         if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
 1482                                 struct sockaddr *paddr;
 1483 
 1484                                 paddr = (struct sockaddr *)(xisr + 1);
 1485 
 1486                                 /* validity check */
 1487                                 if (paddr->sa_len
 1488                                     > sizeof((*p_isr)->saidx.src)) {
 1489                                         ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
 1490                                                 "address length.\n"));
 1491                                         KEY_FREESP(&newsp);
 1492                                         *error = EINVAL;
 1493                                         return NULL;
 1494                                 }
 1495                                 bcopy(paddr, &(*p_isr)->saidx.src,
 1496                                         paddr->sa_len);
 1497 
 1498                                 paddr = (struct sockaddr *)((caddr_t)paddr
 1499                                                         + paddr->sa_len);
 1500 
 1501                                 /* validity check */
 1502                                 if (paddr->sa_len
 1503                                     > sizeof((*p_isr)->saidx.dst)) {
 1504                                         ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
 1505                                                 "address length.\n"));
 1506                                         KEY_FREESP(&newsp);
 1507                                         *error = EINVAL;
 1508                                         return NULL;
 1509                                 }
 1510                                 bcopy(paddr, &(*p_isr)->saidx.dst,
 1511                                         paddr->sa_len);
 1512                         }
 1513 
 1514                         (*p_isr)->sav = NULL;
 1515                         (*p_isr)->sp = newsp;
 1516 
 1517                         /* initialization for the next. */
 1518                         p_isr = &(*p_isr)->next;
 1519                         tlen -= xisr->sadb_x_ipsecrequest_len;
 1520 
 1521                         /* validity check */
 1522                         if (tlen < 0) {
 1523                                 ipseclog((LOG_DEBUG, "key_msg2sp: becoming tlen < 0.\n"));
 1524                                 KEY_FREESP(&newsp);
 1525                                 *error = EINVAL;
 1526                                 return NULL;
 1527                         }
 1528 
 1529                         xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
 1530                                          + xisr->sadb_x_ipsecrequest_len);
 1531                 }
 1532             }
 1533                 break;
 1534         default:
 1535                 ipseclog((LOG_DEBUG, "key_msg2sp: invalid policy type.\n"));
 1536                 KEY_FREESP(&newsp);
 1537                 *error = EINVAL;
 1538                 return NULL;
 1539         }
 1540 
 1541         *error = 0;
 1542         return newsp;
 1543 }
 1544 
 1545 static u_int32_t
 1546 key_newreqid()
 1547 {
 1548         static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
 1549 
 1550         auto_reqid = (auto_reqid == ~0
 1551                         ? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
 1552 
 1553         /* XXX should be unique check */
 1554 
 1555         return auto_reqid;
 1556 }
 1557 
 1558 /*
 1559  * copy secpolicy struct to sadb_x_policy structure indicated.
 1560  */
 1561 struct mbuf *
 1562 key_sp2msg(sp)
 1563         struct secpolicy *sp;
 1564 {
 1565         struct sadb_x_policy *xpl;
 1566         int tlen;
 1567         caddr_t p;
 1568         struct mbuf *m;
 1569 
 1570         /* sanity check. */
 1571         if (sp == NULL)
 1572                 panic("key_sp2msg: NULL pointer was passed.\n");
 1573 
 1574         tlen = key_getspreqmsglen(sp);
 1575 
 1576         m = key_alloc_mbuf(tlen);
 1577         if (!m || m->m_next) {  /*XXX*/
 1578                 if (m)
 1579                         m_freem(m);
 1580                 return NULL;
 1581         }
 1582 
 1583         m->m_len = tlen;
 1584         m->m_next = NULL;
 1585         xpl = mtod(m, struct sadb_x_policy *);
 1586         bzero(xpl, tlen);
 1587 
 1588         xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
 1589         xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
 1590         xpl->sadb_x_policy_type = sp->policy;
 1591         xpl->sadb_x_policy_dir = sp->spidx.dir;
 1592         xpl->sadb_x_policy_id = sp->id;
 1593         p = (caddr_t)xpl + sizeof(*xpl);
 1594 
 1595         /* if is the policy for ipsec ? */
 1596         if (sp->policy == IPSEC_POLICY_IPSEC) {
 1597                 struct sadb_x_ipsecrequest *xisr;
 1598                 struct ipsecrequest *isr;
 1599 
 1600                 for (isr = sp->req; isr != NULL; isr = isr->next) {
 1601 
 1602                         xisr = (struct sadb_x_ipsecrequest *)p;
 1603 
 1604                         xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
 1605                         xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
 1606                         xisr->sadb_x_ipsecrequest_level = isr->level;
 1607                         xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
 1608 
 1609                         p += sizeof(*xisr);
 1610                         bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
 1611                         p += isr->saidx.src.sa.sa_len;
 1612                         bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
 1613                         p += isr->saidx.src.sa.sa_len;
 1614 
 1615                         xisr->sadb_x_ipsecrequest_len =
 1616                                 PFKEY_ALIGN8(sizeof(*xisr)
 1617                                         + isr->saidx.src.sa.sa_len
 1618                                         + isr->saidx.dst.sa.sa_len);
 1619                 }
 1620         }
 1621 
 1622         return m;
 1623 }
 1624 
 1625 /* m will not be freed nor modified */
 1626 static struct mbuf *
 1627 #ifdef __STDC__
 1628 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
 1629         int ndeep, int nitem, ...)
 1630 #else
 1631 key_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
 1632         struct mbuf *m;
 1633         const struct sadb_msghdr *mhp;
 1634         int ndeep;
 1635         int nitem;
 1636         va_dcl
 1637 #endif
 1638 {
 1639         va_list ap;
 1640         int idx;
 1641         int i;
 1642         struct mbuf *result = NULL, *n;
 1643         int len;
 1644 
 1645         if (m == NULL || mhp == NULL)
 1646                 panic("null pointer passed to key_gather");
 1647 
 1648         va_start(ap, nitem);
 1649         for (i = 0; i < nitem; i++) {
 1650                 idx = va_arg(ap, int);
 1651                 if (idx < 0 || idx > SADB_EXT_MAX)
 1652                         goto fail;
 1653                 /* don't attempt to pull empty extension */
 1654                 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
 1655                         continue;
 1656                 if (idx != SADB_EXT_RESERVED  &&
 1657                     (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
 1658                         continue;
 1659 
 1660                 if (idx == SADB_EXT_RESERVED) {
 1661                         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
 1662 #ifdef DIAGNOSTIC
 1663                         if (len > MHLEN)
 1664                                 panic("assumption failed");
 1665 #endif
 1666                         MGETHDR(n, M_DONTWAIT, MT_DATA);
 1667                         if (!n)
 1668                                 goto fail;
 1669                         n->m_len = len;
 1670                         n->m_next = NULL;
 1671                         m_copydata(m, 0, sizeof(struct sadb_msg),
 1672                             mtod(n, caddr_t));
 1673                 } else if (i < ndeep) {
 1674                         len = mhp->extlen[idx];
 1675                         n = key_alloc_mbuf(len);
 1676                         if (!n || n->m_next) {  /*XXX*/
 1677                                 if (n)
 1678                                         m_freem(n);
 1679                                 goto fail;
 1680                         }
 1681                         m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
 1682                             mtod(n, caddr_t));
 1683                 } else {
 1684                         n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
 1685                             M_DONTWAIT);
 1686                 }
 1687                 if (n == NULL)
 1688                         goto fail;
 1689 
 1690                 if (result)
 1691                         m_cat(result, n);
 1692                 else
 1693                         result = n;
 1694         }
 1695         va_end(ap);
 1696 
 1697         if ((result->m_flags & M_PKTHDR) != 0) {
 1698                 result->m_pkthdr.len = 0;
 1699                 for (n = result; n; n = n->m_next)
 1700                         result->m_pkthdr.len += n->m_len;
 1701         }
 1702 
 1703         return result;
 1704 
 1705 fail:
 1706         va_end(ap);
 1707         m_freem(result);
 1708         return NULL;
 1709 }
 1710 
 1711 /*
 1712  * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
 1713  * add an entry to SP database, when received
 1714  *   <base, address(SD), (lifetime(H),) policy>
 1715  * from the user(?).
 1716  * Adding to SP database,
 1717  * and send
 1718  *   <base, address(SD), (lifetime(H),) policy>
 1719  * to the socket which was send.
 1720  *
 1721  * SPDADD set a unique policy entry.
 1722  * SPDSETIDX like SPDADD without a part of policy requests.
 1723  * SPDUPDATE replace a unique policy entry.
 1724  *
 1725  * m will always be freed.
 1726  */
 1727 static int
 1728 key_spdadd(so, m, mhp)
 1729         struct socket *so;
 1730         struct mbuf *m;
 1731         const struct sadb_msghdr *mhp;
 1732 {
 1733         struct sadb_address *src0, *dst0;
 1734         struct sadb_x_policy *xpl0, *xpl;
 1735         struct sadb_lifetime *lft = NULL;
 1736         struct secpolicyindex spidx;
 1737         struct secpolicy *newsp;
 1738         int error;
 1739 
 1740         /* sanity check */
 1741         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 1742                 panic("key_spdadd: NULL pointer is passed.\n");
 1743 
 1744         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 1745             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
 1746             mhp->ext[SADB_X_EXT_POLICY] == NULL) {
 1747                 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
 1748                 return key_senderror(so, m, EINVAL);
 1749         }
 1750         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 1751             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
 1752             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
 1753                 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
 1754                 return key_senderror(so, m, EINVAL);
 1755         }
 1756         if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
 1757                 if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
 1758                         < sizeof(struct sadb_lifetime)) {
 1759                         ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
 1760                         return key_senderror(so, m, EINVAL);
 1761                 }
 1762                 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
 1763         }
 1764 
 1765         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
 1766         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 1767         xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
 1768 
 1769 #if defined(__NetBSD__) && defined(INET6)
 1770         /*
 1771          * On NetBSD, FAST_IPSEC and INET6 can be configured together,
 1772          * but FAST_IPSEC does not protect IPv6 traffic.
 1773          * Rather than silently leaking IPv6 traffic for which IPsec
 1774          * is configured, forbid  specifying IPsec for IPv6 traffic.
 1775          *
 1776          * (On FreeBSD, both FAST_IPSEC and INET6 gives a compile-time error.)
 1777          */
 1778         if (((const struct sockaddr *)(src0 + 1))->sa_family == AF_INET6 ||
 1779             ((const struct sockaddr *)(dst0 + 1))->sa_family == AF_INET6) {
 1780                 static int v6_warned = 0;
 1781 
 1782                 if (v6_warned == 0) {
 1783                         printf("key_spdadd: FAST_IPSEC does not support IPv6.");
 1784                         printf("Check syslog for more per-SPD warnings.\n");
 1785                         v6_warned++;
 1786                 }
 1787                 log(LOG_WARNING,
 1788                     "FAST_IPSEC does not support PF_INET6 SPDs. "
 1789                     "Request refused.\n");
 1790 
 1791                 return EOPNOTSUPP;      /* EPROTOTYPE?  EAFNOSUPPORT? */
 1792         }
 1793 #endif /* __NetBSD__ && INET6 */
 1794 
 1795         /* make secindex */
 1796         /* XXX boundary check against sa_len */
 1797         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
 1798                         src0 + 1,
 1799                         dst0 + 1,
 1800                         src0->sadb_address_prefixlen,
 1801                         dst0->sadb_address_prefixlen,
 1802                         src0->sadb_address_proto,
 1803                         &spidx);
 1804 
 1805         /* checking the direciton. */
 1806         switch (xpl0->sadb_x_policy_dir) {
 1807         case IPSEC_DIR_INBOUND:
 1808         case IPSEC_DIR_OUTBOUND:
 1809                 break;
 1810         default:
 1811                 ipseclog((LOG_DEBUG, "key_spdadd: Invalid SP direction.\n"));
 1812                 mhp->msg->sadb_msg_errno = EINVAL;
 1813                 return 0;
 1814         }
 1815 
 1816         /* check policy */
 1817         /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
 1818         if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
 1819          || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
 1820                 ipseclog((LOG_DEBUG, "key_spdadd: Invalid policy type.\n"));
 1821                 return key_senderror(so, m, EINVAL);
 1822         }
 1823 
 1824         /* policy requests are mandatory when action is ipsec. */
 1825         if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
 1826          && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
 1827          && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
 1828                 ipseclog((LOG_DEBUG, "key_spdadd: some policy requests part required.\n"));
 1829                 return key_senderror(so, m, EINVAL);
 1830         }
 1831 
 1832         /*
 1833          * checking there is SP already or not.
 1834          * SPDUPDATE doesn't depend on whether there is a SP or not.
 1835          * If the type is either SPDADD or SPDSETIDX AND a SP is found,
 1836          * then error.
 1837          */
 1838         newsp = key_getsp(&spidx);
 1839         if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
 1840                 if (newsp) {
 1841                         key_sp_dead(newsp);
 1842                         key_sp_unlink(newsp);   /* XXX jrs ordering */
 1843                         KEY_FREESP(&newsp);
 1844                         newsp = NULL;
 1845                 }
 1846         } else {
 1847                 if (newsp != NULL) {
 1848                         KEY_FREESP(&newsp);
 1849                         ipseclog((LOG_DEBUG, "key_spdadd: a SP entry exists already.\n"));
 1850                         return key_senderror(so, m, EEXIST);
 1851                 }
 1852         }
 1853 
 1854         /* allocation new SP entry */
 1855         if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
 1856                 return key_senderror(so, m, error);
 1857         }
 1858 
 1859         if ((newsp->id = key_getnewspid()) == 0) {
 1860                 KFREE(newsp);
 1861                 return key_senderror(so, m, ENOBUFS);
 1862         }
 1863 
 1864         /* XXX boundary check against sa_len */
 1865         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
 1866                         src0 + 1,
 1867                         dst0 + 1,
 1868                         src0->sadb_address_prefixlen,
 1869                         dst0->sadb_address_prefixlen,
 1870                         src0->sadb_address_proto,
 1871                         &newsp->spidx);
 1872 
 1873         /* sanity check on addr pair */
 1874         if (((struct sockaddr *)(src0 + 1))->sa_family !=
 1875                         ((struct sockaddr *)(dst0+ 1))->sa_family) {
 1876                 KFREE(newsp);
 1877                 return key_senderror(so, m, EINVAL);
 1878         }
 1879         if (((struct sockaddr *)(src0 + 1))->sa_len !=
 1880                         ((struct sockaddr *)(dst0+ 1))->sa_len) {
 1881                 KFREE(newsp);
 1882                 return key_senderror(so, m, EINVAL);
 1883         }
 1884 #if 1
 1885         if (newsp->req && newsp->req->saidx.src.sa.sa_family) {
 1886                 struct sockaddr *sa;
 1887                 sa = (struct sockaddr *)(src0 + 1);
 1888                 if (sa->sa_family != newsp->req->saidx.src.sa.sa_family) {
 1889                         KFREE(newsp);
 1890                         return key_senderror(so, m, EINVAL);
 1891                 }
 1892         }
 1893         if (newsp->req && newsp->req->saidx.dst.sa.sa_family) {
 1894                 struct sockaddr *sa;
 1895                 sa = (struct sockaddr *)(dst0 + 1);
 1896                 if (sa->sa_family != newsp->req->saidx.dst.sa.sa_family) {
 1897                         KFREE(newsp);
 1898                         return key_senderror(so, m, EINVAL);
 1899                 }
 1900         }
 1901 #endif
 1902 
 1903         newsp->created = time_second;
 1904         newsp->lastused = newsp->created;
 1905         newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
 1906         newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
 1907 
 1908         newsp->refcnt = 1;      /* do not reclaim until I say I do */
 1909         newsp->state = IPSEC_SPSTATE_ALIVE;
 1910         LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain);
 1911 
 1912         /* delete the entry in spacqtree */
 1913         if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
 1914                 struct secspacq *spacq;
 1915                 if ((spacq = key_getspacq(&spidx)) != NULL) {
 1916                         /* reset counter in order to deletion by timehandler. */
 1917                         spacq->created = time_second;
 1918                         spacq->count = 0;
 1919                 }
 1920         }
 1921 
 1922 #if defined(__NetBSD__)
 1923         /* Invalidate all cached SPD pointers in the PCBs. */
 1924         ipsec_invalpcbcacheall();
 1925 
 1926 #if defined(GATEWAY)
 1927         /* Invalidate the ipflow cache, as well. */
 1928         ipflow_invalidate_all();
 1929 #endif
 1930 #endif /* __NetBSD__ */
 1931 
 1932     {
 1933         struct mbuf *n, *mpolicy;
 1934         struct sadb_msg *newmsg;
 1935         int off;
 1936 
 1937         /* create new sadb_msg to reply. */
 1938         if (lft) {
 1939                 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
 1940                     SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
 1941                     SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 1942         } else {
 1943                 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
 1944                     SADB_X_EXT_POLICY,
 1945                     SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 1946         }
 1947         if (!n)
 1948                 return key_senderror(so, m, ENOBUFS);
 1949 
 1950         if (n->m_len < sizeof(*newmsg)) {
 1951                 n = m_pullup(n, sizeof(*newmsg));
 1952                 if (!n)
 1953                         return key_senderror(so, m, ENOBUFS);
 1954         }
 1955         newmsg = mtod(n, struct sadb_msg *);
 1956         newmsg->sadb_msg_errno = 0;
 1957         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 1958 
 1959         off = 0;
 1960         mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
 1961             sizeof(*xpl), &off);
 1962         if (mpolicy == NULL) {
 1963                 /* n is already freed */
 1964                 return key_senderror(so, m, ENOBUFS);
 1965         }
 1966         xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
 1967         if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
 1968                 m_freem(n);
 1969                 return key_senderror(so, m, EINVAL);
 1970         }
 1971         xpl->sadb_x_policy_id = newsp->id;
 1972 
 1973         m_freem(m);
 1974         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 1975     }
 1976 }
 1977 
 1978 /*
 1979  * get new policy id.
 1980  * OUT:
 1981  *      0:      failure.
 1982  *      others: success.
 1983  */
 1984 static u_int32_t
 1985 key_getnewspid()
 1986 {
 1987         u_int32_t newid = 0;
 1988         int count = key_spi_trycnt;     /* XXX */
 1989         struct secpolicy *sp;
 1990 
 1991         /* when requesting to allocate spi ranged */
 1992         while (count--) {
 1993                 newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
 1994 
 1995                 if ((sp = key_getspbyid(newid)) == NULL)
 1996                         break;
 1997 
 1998                 KEY_FREESP(&sp);
 1999         }
 2000 
 2001         if (count == 0 || newid == 0) {
 2002                 ipseclog((LOG_DEBUG, "key_getnewspid: to allocate policy id is failed.\n"));
 2003                 return 0;
 2004         }
 2005 
 2006         return newid;
 2007 }
 2008 
 2009 /*
 2010  * SADB_SPDDELETE processing
 2011  * receive
 2012  *   <base, address(SD), policy(*)>
 2013  * from the user(?), and set SADB_SASTATE_DEAD,
 2014  * and send,
 2015  *   <base, address(SD), policy(*)>
 2016  * to the ikmpd.
 2017  * policy(*) including direction of policy.
 2018  *
 2019  * m will always be freed.
 2020  */
 2021 static int
 2022 key_spddelete(so, m, mhp)
 2023         struct socket *so;
 2024         struct mbuf *m;
 2025         const struct sadb_msghdr *mhp;
 2026 {
 2027         struct sadb_address *src0, *dst0;
 2028         struct sadb_x_policy *xpl0;
 2029         struct secpolicyindex spidx;
 2030         struct secpolicy *sp;
 2031 
 2032         /* sanity check */
 2033         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 2034                 panic("key_spddelete: NULL pointer is passed.\n");
 2035 
 2036         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 2037             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
 2038             mhp->ext[SADB_X_EXT_POLICY] == NULL) {
 2039                 ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
 2040                 return key_senderror(so, m, EINVAL);
 2041         }
 2042         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 2043             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
 2044             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
 2045                 ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
 2046                 return key_senderror(so, m, EINVAL);
 2047         }
 2048 
 2049         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
 2050         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 2051         xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
 2052 
 2053         /* make secindex */
 2054         /* XXX boundary check against sa_len */
 2055         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
 2056                         src0 + 1,
 2057                         dst0 + 1,
 2058                         src0->sadb_address_prefixlen,
 2059                         dst0->sadb_address_prefixlen,
 2060                         src0->sadb_address_proto,
 2061                         &spidx);
 2062 
 2063         /* checking the direciton. */
 2064         switch (xpl0->sadb_x_policy_dir) {
 2065         case IPSEC_DIR_INBOUND:
 2066         case IPSEC_DIR_OUTBOUND:
 2067                 break;
 2068         default:
 2069                 ipseclog((LOG_DEBUG, "key_spddelete: Invalid SP direction.\n"));
 2070                 return key_senderror(so, m, EINVAL);
 2071         }
 2072 
 2073         /* Is there SP in SPD ? */
 2074         if ((sp = key_getsp(&spidx)) == NULL) {
 2075                 ipseclog((LOG_DEBUG, "key_spddelete: no SP found.\n"));
 2076                 return key_senderror(so, m, EINVAL);
 2077         }
 2078 
 2079         /* save policy id to buffer to be returned. */
 2080         xpl0->sadb_x_policy_id = sp->id;
 2081 
 2082         key_sp_dead(sp);
 2083         key_sp_unlink(sp);      /* XXX jrs ordering */
 2084         KEY_FREESP(&sp);        /* ref gained by key_getspbyid */
 2085 
 2086 #if defined(__NetBSD__)
 2087         /* Invalidate all cached SPD pointers in the PCBs. */
 2088         ipsec_invalpcbcacheall();
 2089 
 2090         /* We're deleting policy; no need to invalidate the ipflow cache. */
 2091 #endif /* __NetBSD__ */
 2092 
 2093     {
 2094         struct mbuf *n;
 2095         struct sadb_msg *newmsg;
 2096 
 2097         /* create new sadb_msg to reply. */
 2098         n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
 2099             SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 2100         if (!n)
 2101                 return key_senderror(so, m, ENOBUFS);
 2102 
 2103         newmsg = mtod(n, struct sadb_msg *);
 2104         newmsg->sadb_msg_errno = 0;
 2105         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 2106 
 2107         m_freem(m);
 2108         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 2109     }
 2110 }
 2111 
 2112 /*
 2113  * SADB_SPDDELETE2 processing
 2114  * receive
 2115  *   <base, policy(*)>
 2116  * from the user(?), and set SADB_SASTATE_DEAD,
 2117  * and send,
 2118  *   <base, policy(*)>
 2119  * to the ikmpd.
 2120  * policy(*) including direction of policy.
 2121  *
 2122  * m will always be freed.
 2123  */
 2124 static int
 2125 key_spddelete2(so, m, mhp)
 2126         struct socket *so;
 2127         struct mbuf *m;
 2128         const struct sadb_msghdr *mhp;
 2129 {
 2130         u_int32_t id;
 2131         struct secpolicy *sp;
 2132 
 2133         /* sanity check */
 2134         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 2135                 panic("key_spddelete2: NULL pointer is passed.\n");
 2136 
 2137         if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
 2138             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
 2139                 ipseclog((LOG_DEBUG, "key_spddelete2: invalid message is passed.\n"));
 2140                 key_senderror(so, m, EINVAL);
 2141                 return 0;
 2142         }
 2143 
 2144         id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
 2145 
 2146         /* Is there SP in SPD ? */
 2147         if ((sp = key_getspbyid(id)) == NULL) {
 2148                 ipseclog((LOG_DEBUG, "key_spddelete2: no SP found id:%u.\n", id));
 2149                 key_senderror(so, m, EINVAL);
 2150         }
 2151 
 2152         key_sp_dead(sp);
 2153         key_sp_unlink(sp);      /* XXX jrs ordering */
 2154         KEY_FREESP(&sp);        /* ref gained by key_getsp */
 2155         sp = NULL;
 2156 
 2157 #if defined(__NetBSD__)
 2158         /* Invalidate all cached SPD pointers in the PCBs. */
 2159         ipsec_invalpcbcacheall();
 2160 
 2161         /* We're deleting policy; no need to invalidate the ipflow cache. */
 2162 #endif /* __NetBSD__ */
 2163 
 2164     {
 2165         struct mbuf *n, *nn;
 2166         struct sadb_msg *newmsg;
 2167         int off, len;
 2168 
 2169         /* create new sadb_msg to reply. */
 2170         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
 2171 
 2172         if (len > MCLBYTES)
 2173                 return key_senderror(so, m, ENOBUFS);
 2174         MGETHDR(n, M_DONTWAIT, MT_DATA);
 2175         if (n && len > MHLEN) {
 2176                 MCLGET(n, M_DONTWAIT);
 2177                 if ((n->m_flags & M_EXT) == 0) {
 2178                         m_freem(n);
 2179                         n = NULL;
 2180                 }
 2181         }
 2182         if (!n)
 2183                 return key_senderror(so, m, ENOBUFS);
 2184 
 2185         n->m_len = len;
 2186         n->m_next = NULL;
 2187         off = 0;
 2188 
 2189         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
 2190         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
 2191 
 2192 #ifdef DIAGNOSTIC
 2193         if (off != len)
 2194                 panic("length inconsistency in key_spddelete2");
 2195 #endif
 2196 
 2197         n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
 2198             mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
 2199         if (!n->m_next) {
 2200                 m_freem(n);
 2201                 return key_senderror(so, m, ENOBUFS);
 2202         }
 2203 
 2204         n->m_pkthdr.len = 0;
 2205         for (nn = n; nn; nn = nn->m_next)
 2206                 n->m_pkthdr.len += nn->m_len;
 2207 
 2208         newmsg = mtod(n, struct sadb_msg *);
 2209         newmsg->sadb_msg_errno = 0;
 2210         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 2211 
 2212         m_freem(m);
 2213         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 2214     }
 2215 }
 2216 
 2217 /*
 2218  * SADB_X_GET processing
 2219  * receive
 2220  *   <base, policy(*)>
 2221  * from the user(?),
 2222  * and send,
 2223  *   <base, address(SD), policy>
 2224  * to the ikmpd.
 2225  * policy(*) including direction of policy.
 2226  *
 2227  * m will always be freed.
 2228  */
 2229 static int
 2230 key_spdget(so, m, mhp)
 2231         struct socket *so;
 2232         struct mbuf *m;
 2233         const struct sadb_msghdr *mhp;
 2234 {
 2235         u_int32_t id;
 2236         struct secpolicy *sp;
 2237         struct mbuf *n;
 2238 
 2239         /* sanity check */
 2240         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 2241                 panic("key_spdget: NULL pointer is passed.\n");
 2242 
 2243         if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
 2244             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
 2245                 ipseclog((LOG_DEBUG, "key_spdget: invalid message is passed.\n"));
 2246                 return key_senderror(so, m, EINVAL);
 2247         }
 2248 
 2249         id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
 2250 
 2251         /* Is there SP in SPD ? */
 2252         if ((sp = key_getspbyid(id)) == NULL) {
 2253                 ipseclog((LOG_DEBUG, "key_spdget: no SP found id:%u.\n", id));
 2254                 return key_senderror(so, m, ENOENT);
 2255         }
 2256 
 2257         n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
 2258         if (n != NULL) {
 2259                 m_freem(m);
 2260                 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
 2261         } else
 2262                 return key_senderror(so, m, ENOBUFS);
 2263 }
 2264 
 2265 /*
 2266  * SADB_X_SPDACQUIRE processing.
 2267  * Acquire policy and SA(s) for a *OUTBOUND* packet.
 2268  * send
 2269  *   <base, policy(*)>
 2270  * to KMD, and expect to receive
 2271  *   <base> with SADB_X_SPDACQUIRE if error occurred,
 2272  * or
 2273  *   <base, policy>
 2274  * with SADB_X_SPDUPDATE from KMD by PF_KEY.
 2275  * policy(*) is without policy requests.
 2276  *
 2277  *    0     : succeed
 2278  *    others: error number
 2279  */
 2280 int
 2281 key_spdacquire(sp)
 2282         struct secpolicy *sp;
 2283 {
 2284         struct mbuf *result = NULL, *m;
 2285         struct secspacq *newspacq;
 2286         int error;
 2287 
 2288         /* sanity check */
 2289         if (sp == NULL)
 2290                 panic("key_spdacquire: NULL pointer is passed.\n");
 2291         if (sp->req != NULL)
 2292                 panic("key_spdacquire: called but there is request.\n");
 2293         if (sp->policy != IPSEC_POLICY_IPSEC)
 2294                 panic("key_spdacquire: policy mismathed. IPsec is expected.\n");
 2295 
 2296         /* Get an entry to check whether sent message or not. */
 2297         if ((newspacq = key_getspacq(&sp->spidx)) != NULL) {
 2298                 if (key_blockacq_count < newspacq->count) {
 2299                         /* reset counter and do send message. */
 2300                         newspacq->count = 0;
 2301                 } else {
 2302                         /* increment counter and do nothing. */
 2303                         newspacq->count++;
 2304                         return 0;
 2305                 }
 2306         } else {
 2307                 /* make new entry for blocking to send SADB_ACQUIRE. */
 2308                 if ((newspacq = key_newspacq(&sp->spidx)) == NULL)
 2309                         return ENOBUFS;
 2310 
 2311                 /* add to acqtree */
 2312                 LIST_INSERT_HEAD(&spacqtree, newspacq, chain);
 2313         }
 2314 
 2315         /* create new sadb_msg to reply. */
 2316         m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
 2317         if (!m) {
 2318                 error = ENOBUFS;
 2319                 goto fail;
 2320         }
 2321         result = m;
 2322 
 2323         result->m_pkthdr.len = 0;
 2324         for (m = result; m; m = m->m_next)
 2325                 result->m_pkthdr.len += m->m_len;
 2326 
 2327         mtod(result, struct sadb_msg *)->sadb_msg_len =
 2328             PFKEY_UNIT64(result->m_pkthdr.len);
 2329 
 2330         return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
 2331 
 2332 fail:
 2333         if (result)
 2334                 m_freem(result);
 2335         return error;
 2336 }
 2337 
 2338 /*
 2339  * SADB_SPDFLUSH processing
 2340  * receive
 2341  *   <base>
 2342  * from the user, and free all entries in secpctree.
 2343  * and send,
 2344  *   <base>
 2345  * to the user.
 2346  * NOTE: what to do is only marking SADB_SASTATE_DEAD.
 2347  *
 2348  * m will always be freed.
 2349  */
 2350 static int
 2351 key_spdflush(so, m, mhp)
 2352         struct socket *so;
 2353         struct mbuf *m;
 2354         const struct sadb_msghdr *mhp;
 2355 {
 2356         struct sadb_msg *newmsg;
 2357         struct secpolicy *sp;
 2358         u_int dir;
 2359 
 2360         /* sanity check */
 2361         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 2362                 panic("key_spdflush: NULL pointer is passed.\n");
 2363 
 2364         if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
 2365                 return key_senderror(so, m, EINVAL);
 2366 
 2367         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
 2368                 struct secpolicy * nextsp;
 2369                 for (sp = LIST_FIRST(&sptree[dir]);
 2370                      sp != NULL;
 2371                      sp = nextsp) {
 2372 
 2373                         nextsp = LIST_NEXT(sp, chain);
 2374                         if (sp->state == IPSEC_SPSTATE_DEAD)
 2375                                 continue;
 2376                         key_sp_dead(sp);
 2377                         key_sp_unlink(sp);
 2378                         /* 'sp' dead; continue transfers to 'sp = nextsp' */
 2379                         continue;
 2380                 }
 2381         }
 2382 
 2383 #if defined(__NetBSD__)
 2384         /* Invalidate all cached SPD pointers in the PCBs. */
 2385         ipsec_invalpcbcacheall();
 2386 
 2387         /* We're deleting policy; no need to invalidate the ipflow cache. */
 2388 #endif /* __NetBSD__ */
 2389 
 2390         if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
 2391                 ipseclog((LOG_DEBUG, "key_spdflush: No more memory.\n"));
 2392                 return key_senderror(so, m, ENOBUFS);
 2393         }
 2394 
 2395         if (m->m_next)
 2396                 m_freem(m->m_next);
 2397         m->m_next = NULL;
 2398         m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
 2399         newmsg = mtod(m, struct sadb_msg *);
 2400         newmsg->sadb_msg_errno = 0;
 2401         newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
 2402 
 2403         return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
 2404 }
 2405 
 2406 static struct sockaddr key_src = { 2, PF_KEY, };
 2407 
 2408 static struct mbuf *
 2409 key_setspddump_chain(int *errorp, int *lenp, pid_t pid)
 2410 {
 2411         struct secpolicy *sp;
 2412         int cnt;
 2413         u_int dir;
 2414         struct mbuf *m, *n, *prev;
 2415         int totlen;
 2416 
 2417         *lenp = 0;
 2418 
 2419         /* search SPD entry and get buffer size. */
 2420         cnt = 0;
 2421         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
 2422                 LIST_FOREACH(sp, &sptree[dir], chain) {
 2423                         cnt++;
 2424                 }
 2425         }
 2426 
 2427         if (cnt == 0) {
 2428                 *errorp = ENOENT;
 2429                 return (NULL);
 2430         }
 2431 
 2432         m = NULL;
 2433         prev = m;
 2434         totlen = 0;
 2435         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
 2436                 LIST_FOREACH(sp, &sptree[dir], chain) {
 2437                         --cnt;
 2438                         n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
 2439 
 2440                         if (!n) {
 2441                                 *errorp = ENOBUFS;
 2442                                 if (m) m_freem(m);
 2443                                 return (NULL);
 2444                         }
 2445 
 2446                         totlen += n->m_pkthdr.len;
 2447                         if (!m) {
 2448                                 m = n;
 2449                         } else {
 2450                                 prev->m_nextpkt = n;
 2451                         }
 2452                         prev = n;
 2453                 }
 2454         }
 2455 
 2456         *lenp = totlen;
 2457         *errorp = 0;
 2458         return (m);
 2459 }
 2460 
 2461 /*
 2462  * SADB_SPDDUMP processing
 2463  * receive
 2464  *   <base>
 2465  * from the user, and dump all SP leaves
 2466  * and send,
 2467  *   <base> .....
 2468  * to the ikmpd.
 2469  *
 2470  * m will always be freed.
 2471  */
 2472 static int
 2473 key_spddump(so, m0, mhp)
 2474         struct socket *so;
 2475         struct mbuf *m0;
 2476         const struct sadb_msghdr *mhp;
 2477 {
 2478         struct mbuf *n;
 2479         int error, len;
 2480         int ok, s;
 2481         pid_t pid;
 2482 
 2483         /* sanity check */
 2484         if (so == NULL || m0 == NULL || mhp == NULL || mhp->msg == NULL)
 2485                 panic("key_spddump: NULL pointer is passed.\n");
 2486 
 2487 
 2488         pid = mhp->msg->sadb_msg_pid;
 2489         /*
 2490          * If the requestor has insufficient socket-buffer space
 2491          * for the entire chain, nobody gets any response to the DUMP.
 2492          * XXX For now, only the requestor ever gets anything.
 2493          * Moreover, if the requestor has any space at all, they receive
 2494          * the entire chain, otherwise the request is refused with  ENOBUFS.
 2495          */
 2496         if (sbspace(&so->so_rcv) <= 0) {
 2497                 return key_senderror(so, m0, ENOBUFS);
 2498         }
 2499 
 2500         s = splsoftnet();
 2501         n = key_setspddump_chain(&error, &len, pid);
 2502         splx(s);
 2503 
 2504         if (n == NULL) {
 2505                 return key_senderror(so, m0, ENOENT);
 2506         }
 2507         pfkeystat.in_total++;
 2508         pfkeystat.in_bytes += len;
 2509 
 2510         /*
 2511          * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
 2512          * The requestor receives either the entire chain, or an
 2513          * error message with ENOBUFS.
 2514          */
 2515 
 2516         /*
 2517          * sbappendchainwith record takes the chain of entries, one
 2518          * packet-record per SPD entry, prepends the key_src sockaddr
 2519          * to each packet-record, links the sockaddr mbufs into a new
 2520          * list of records, then   appends the entire resulting
 2521          * list to the requesting socket.
 2522          */
 2523         ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src,
 2524                 n, SB_PRIO_ONESHOT_OVERFLOW);
 2525 
 2526         if (!ok) {
 2527                 pfkeystat.in_nomem++;
 2528                 m_freem(n);
 2529                 return key_senderror(so, m0, ENOBUFS);
 2530         }
 2531 
 2532         m_freem(m0);
 2533         return error;
 2534 }
 2535 
 2536 static struct mbuf *
 2537 key_setdumpsp(sp, type, seq, pid)
 2538         struct secpolicy *sp;
 2539         u_int8_t type;
 2540         u_int32_t seq;
 2541         pid_t pid;
 2542 {
 2543         struct mbuf *result = NULL, *m;
 2544 
 2545         m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
 2546         if (!m)
 2547                 goto fail;
 2548         result = m;
 2549 
 2550         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
 2551             &sp->spidx.src.sa, sp->spidx.prefs,
 2552             sp->spidx.ul_proto);
 2553         if (!m)
 2554                 goto fail;
 2555         m_cat(result, m);
 2556 
 2557         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
 2558             &sp->spidx.dst.sa, sp->spidx.prefd,
 2559             sp->spidx.ul_proto);
 2560         if (!m)
 2561                 goto fail;
 2562         m_cat(result, m);
 2563 
 2564         m = key_sp2msg(sp);
 2565         if (!m)
 2566                 goto fail;
 2567         m_cat(result, m);
 2568 
 2569         if ((result->m_flags & M_PKTHDR) == 0)
 2570                 goto fail;
 2571 
 2572         if (result->m_len < sizeof(struct sadb_msg)) {
 2573                 result = m_pullup(result, sizeof(struct sadb_msg));
 2574                 if (result == NULL)
 2575                         goto fail;
 2576         }
 2577 
 2578         result->m_pkthdr.len = 0;
 2579         for (m = result; m; m = m->m_next)
 2580                 result->m_pkthdr.len += m->m_len;
 2581 
 2582         mtod(result, struct sadb_msg *)->sadb_msg_len =
 2583             PFKEY_UNIT64(result->m_pkthdr.len);
 2584 
 2585         return result;
 2586 
 2587 fail:
 2588         m_freem(result);
 2589         return NULL;
 2590 }
 2591 
 2592 /*
 2593  * get PFKEY message length for security policy and request.
 2594  */
 2595 static u_int
 2596 key_getspreqmsglen(sp)
 2597         struct secpolicy *sp;
 2598 {
 2599         u_int tlen;
 2600 
 2601         tlen = sizeof(struct sadb_x_policy);
 2602 
 2603         /* if is the policy for ipsec ? */
 2604         if (sp->policy != IPSEC_POLICY_IPSEC)
 2605                 return tlen;
 2606 
 2607         /* get length of ipsec requests */
 2608     {
 2609         struct ipsecrequest *isr;
 2610         int len;
 2611 
 2612         for (isr = sp->req; isr != NULL; isr = isr->next) {
 2613                 len = sizeof(struct sadb_x_ipsecrequest)
 2614                         + isr->saidx.src.sa.sa_len
 2615                         + isr->saidx.dst.sa.sa_len;
 2616 
 2617                 tlen += PFKEY_ALIGN8(len);
 2618         }
 2619     }
 2620 
 2621         return tlen;
 2622 }
 2623 
 2624 /*
 2625  * SADB_SPDEXPIRE processing
 2626  * send
 2627  *   <base, address(SD), lifetime(CH), policy>
 2628  * to KMD by PF_KEY.
 2629  *
 2630  * OUT: 0       : succeed
 2631  *      others  : error number
 2632  */
 2633 static int
 2634 key_spdexpire(sp)
 2635         struct secpolicy *sp;
 2636 {
 2637         int s;
 2638         struct mbuf *result = NULL, *m;
 2639         int len;
 2640         int error = -1;
 2641         struct sadb_lifetime *lt;
 2642 
 2643         /* XXX: Why do we lock ? */
 2644         s = splsoftnet();       /*called from softclock()*/
 2645 
 2646         /* sanity check */
 2647         if (sp == NULL)
 2648                 panic("key_spdexpire: NULL pointer is passed.\n");
 2649 
 2650         /* set msg header */
 2651         m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
 2652         if (!m) {
 2653                 error = ENOBUFS;
 2654                 goto fail;
 2655         }
 2656         result = m;
 2657 
 2658         /* create lifetime extension (current and hard) */
 2659         len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
 2660         m = key_alloc_mbuf(len);
 2661         if (!m || m->m_next) {  /*XXX*/
 2662                 if (m)
 2663                         m_freem(m);
 2664                 error = ENOBUFS;
 2665                 goto fail;
 2666         }
 2667         bzero(mtod(m, caddr_t), len);
 2668         lt = mtod(m, struct sadb_lifetime *);
 2669         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
 2670         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
 2671         lt->sadb_lifetime_allocations = 0;
 2672         lt->sadb_lifetime_bytes = 0;
 2673         lt->sadb_lifetime_addtime = sp->created;
 2674         lt->sadb_lifetime_usetime = sp->lastused;
 2675         lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
 2676         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
 2677         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
 2678         lt->sadb_lifetime_allocations = 0;
 2679         lt->sadb_lifetime_bytes = 0;
 2680         lt->sadb_lifetime_addtime = sp->lifetime;
 2681         lt->sadb_lifetime_usetime = sp->validtime;
 2682         m_cat(result, m);
 2683 
 2684         /* set sadb_address for source */
 2685         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
 2686             &sp->spidx.src.sa,
 2687             sp->spidx.prefs, sp->spidx.ul_proto);
 2688         if (!m) {
 2689                 error = ENOBUFS;
 2690                 goto fail;
 2691         }
 2692         m_cat(result, m);
 2693 
 2694         /* set sadb_address for destination */
 2695         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
 2696             &sp->spidx.dst.sa,
 2697             sp->spidx.prefd, sp->spidx.ul_proto);
 2698         if (!m) {
 2699                 error = ENOBUFS;
 2700                 goto fail;
 2701         }
 2702         m_cat(result, m);
 2703 
 2704         /* set secpolicy */
 2705         m = key_sp2msg(sp);
 2706         if (!m) {
 2707                 error = ENOBUFS;
 2708                 goto fail;
 2709         }
 2710         m_cat(result, m);
 2711 
 2712         if ((result->m_flags & M_PKTHDR) == 0) {
 2713                 error = EINVAL;
 2714                 goto fail;
 2715         }
 2716 
 2717         if (result->m_len < sizeof(struct sadb_msg)) {
 2718                 result = m_pullup(result, sizeof(struct sadb_msg));
 2719                 if (result == NULL) {
 2720                         error = ENOBUFS;
 2721                         goto fail;
 2722                 }
 2723         }
 2724 
 2725         result->m_pkthdr.len = 0;
 2726         for (m = result; m; m = m->m_next)
 2727                 result->m_pkthdr.len += m->m_len;
 2728 
 2729         mtod(result, struct sadb_msg *)->sadb_msg_len =
 2730             PFKEY_UNIT64(result->m_pkthdr.len);
 2731 
 2732         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
 2733 
 2734  fail:
 2735         if (result)
 2736                 m_freem(result);
 2737         splx(s);
 2738         return error;
 2739 }
 2740 
 2741 /* %%% SAD management */
 2742 /*
 2743  * allocating a memory for new SA head, and copy from the values of mhp.
 2744  * OUT: NULL    : failure due to the lack of memory.
 2745  *      others  : pointer to new SA head.
 2746  */
 2747 static struct secashead *
 2748 key_newsah(saidx)
 2749         struct secasindex *saidx;
 2750 {
 2751         struct secashead *newsah;
 2752 
 2753         IPSEC_ASSERT(saidx != NULL, ("key_newsaidx: null saidx"));
 2754 
 2755         newsah = (struct secashead *)
 2756                 malloc(sizeof(struct secashead), M_SECA, M_NOWAIT|M_ZERO);
 2757         if (newsah != NULL) {
 2758                 int i;
 2759                 for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
 2760                         LIST_INIT(&newsah->savtree[i]);
 2761                 newsah->saidx = *saidx;
 2762 
 2763                 /* add to saidxtree */
 2764                 newsah->state = SADB_SASTATE_MATURE;
 2765                 LIST_INSERT_HEAD(&sahtree, newsah, chain);
 2766         }
 2767         return(newsah);
 2768 }
 2769 
 2770 /*
 2771  * delete SA index and all SA registerd.
 2772  */
 2773 static void
 2774 key_delsah(sah)
 2775         struct secashead *sah;
 2776 {
 2777         struct secasvar *sav, *nextsav;
 2778         u_int stateidx, state;
 2779         int s;
 2780         int zombie = 0;
 2781 
 2782         /* sanity check */
 2783         if (sah == NULL)
 2784                 panic("key_delsah: NULL pointer is passed.\n");
 2785 
 2786         s = splsoftnet();       /*called from softclock()*/
 2787 
 2788         /* searching all SA registerd in the secindex. */
 2789         for (stateidx = 0;
 2790              stateidx < _ARRAYLEN(saorder_state_any);
 2791              stateidx++) {
 2792 
 2793                 state = saorder_state_any[stateidx];
 2794                 for (sav = (struct secasvar *)LIST_FIRST(&sah->savtree[state]);
 2795                      sav != NULL;
 2796                      sav = nextsav) {
 2797 
 2798                         nextsav = LIST_NEXT(sav, chain);
 2799 
 2800                         if (sav->refcnt == 0) {
 2801                                 /* sanity check */
 2802                                 KEY_CHKSASTATE(state, sav->state, "key_delsah");
 2803                                 KEY_FREESAV(&sav);
 2804                         } else {
 2805                                 /* give up to delete this sa */
 2806                                 zombie++;
 2807                         }
 2808                 }
 2809         }
 2810 
 2811         /* don't delete sah only if there are savs. */
 2812         if (zombie) {
 2813                 splx(s);
 2814                 return;
 2815         }
 2816 
 2817         if (sah->sa_route.ro_rt) {
 2818                 RTFREE(sah->sa_route.ro_rt);
 2819                 sah->sa_route.ro_rt = (struct rtentry *)NULL;
 2820         }
 2821 
 2822         /* remove from tree of SA index */
 2823         if (__LIST_CHAINED(sah))
 2824                 LIST_REMOVE(sah, chain);
 2825 
 2826         KFREE(sah);
 2827 
 2828         splx(s);
 2829         return;
 2830 }
 2831 
 2832 /*
 2833  * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
 2834  * and copy the values of mhp into new buffer.
 2835  * When SAD message type is GETSPI:
 2836  *      to set sequence number from acq_seq++,
 2837  *      to set zero to SPI.
 2838  *      not to call key_setsava().
 2839  * OUT: NULL    : fail
 2840  *      others  : pointer to new secasvar.
 2841  *
 2842  * does not modify mbuf.  does not free mbuf on error.
 2843  */
 2844 static struct secasvar *
 2845 key_newsav(m, mhp, sah, errp, where, tag)
 2846         struct mbuf *m;
 2847         const struct sadb_msghdr *mhp;
 2848         struct secashead *sah;
 2849         int *errp;
 2850         const char* where;
 2851         int tag;
 2852 {
 2853         struct secasvar *newsav;
 2854         const struct sadb_sa *xsa;
 2855 
 2856         /* sanity check */
 2857         if (m == NULL || mhp == NULL || mhp->msg == NULL || sah == NULL)
 2858                 panic("key_newsa: NULL pointer is passed.\n");
 2859 
 2860         KMALLOC(newsav, struct secasvar *, sizeof(struct secasvar));
 2861         if (newsav == NULL) {
 2862                 ipseclog((LOG_DEBUG, "key_newsa: No more memory.\n"));
 2863                 *errp = ENOBUFS;
 2864                 goto done;
 2865         }
 2866         bzero((caddr_t)newsav, sizeof(struct secasvar));
 2867 
 2868         switch (mhp->msg->sadb_msg_type) {
 2869         case SADB_GETSPI:
 2870                 newsav->spi = 0;
 2871 
 2872 #ifdef IPSEC_DOSEQCHECK
 2873                 /* sync sequence number */
 2874                 if (mhp->msg->sadb_msg_seq == 0)
 2875                         newsav->seq =
 2876                                 (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
 2877                 else
 2878 #endif
 2879                         newsav->seq = mhp->msg->sadb_msg_seq;
 2880                 break;
 2881 
 2882         case SADB_ADD:
 2883                 /* sanity check */
 2884                 if (mhp->ext[SADB_EXT_SA] == NULL) {
 2885                         KFREE(newsav), newsav = NULL;
 2886                         ipseclog((LOG_DEBUG, "key_newsa: invalid message is passed.\n"));
 2887                         *errp = EINVAL;
 2888                         goto done;
 2889                 }
 2890                 xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 2891                 newsav->spi = xsa->sadb_sa_spi;
 2892                 newsav->seq = mhp->msg->sadb_msg_seq;
 2893                 break;
 2894         default:
 2895                 KFREE(newsav), newsav = NULL;
 2896                 *errp = EINVAL;
 2897                 goto done;
 2898         }
 2899 
 2900         /* copy sav values */
 2901         if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
 2902                 *errp = key_setsaval(newsav, m, mhp);
 2903                 if (*errp) {
 2904                         KFREE(newsav), newsav = NULL;
 2905                         goto done;
 2906                 }
 2907         }
 2908 
 2909         /* reset created */
 2910         newsav->created = time_second;
 2911         newsav->pid = mhp->msg->sadb_msg_pid;
 2912 
 2913         /* add to satree */
 2914         newsav->sah = sah;
 2915         newsav->refcnt = 1;
 2916         newsav->state = SADB_SASTATE_LARVAL;
 2917         LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
 2918                         secasvar, chain);
 2919 done:
 2920         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 2921                 printf("DP key_newsav from %s:%u return SP:%p\n",
 2922                         where, tag, newsav));
 2923 
 2924         return newsav;
 2925 }
 2926 
 2927 /*
 2928  * free() SA variable entry.
 2929  */
 2930 static void
 2931 key_delsav(sav)
 2932         struct secasvar *sav;
 2933 {
 2934         IPSEC_ASSERT(sav != NULL, ("key_delsav: null sav"));
 2935         IPSEC_ASSERT(sav->refcnt == 0,
 2936                 ("key_delsav: reference count %u > 0", sav->refcnt));
 2937 
 2938         /* remove from SA header */
 2939         if (__LIST_CHAINED(sav))
 2940                 LIST_REMOVE(sav, chain);
 2941 
 2942         /*
 2943          * Cleanup xform state.  Note that zeroize'ing causes the
 2944          * keys to be cleared; otherwise we must do it ourself.
 2945          */
 2946         if (sav->tdb_xform != NULL) {
 2947                 sav->tdb_xform->xf_zeroize(sav);
 2948                 sav->tdb_xform = NULL;
 2949         } else {
 2950                 if (sav->key_auth != NULL)
 2951                         bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
 2952                 if (sav->key_enc != NULL)
 2953                         bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc));
 2954         }
 2955         if (sav->key_auth != NULL) {
 2956                 KFREE(sav->key_auth);
 2957                 sav->key_auth = NULL;
 2958         }
 2959         if (sav->key_enc != NULL) {
 2960                 KFREE(sav->key_enc);
 2961                 sav->key_enc = NULL;
 2962         }
 2963         if (sav->sched) {
 2964                 bzero(sav->sched, sav->schedlen);
 2965                 KFREE(sav->sched);
 2966                 sav->sched = NULL;
 2967         }
 2968         if (sav->replay != NULL) {
 2969                 KFREE(sav->replay);
 2970                 sav->replay = NULL;
 2971         }
 2972         if (sav->lft_c != NULL) {
 2973                 KFREE(sav->lft_c);
 2974                 sav->lft_c = NULL;
 2975         }
 2976         if (sav->lft_h != NULL) {
 2977                 KFREE(sav->lft_h);
 2978                 sav->lft_h = NULL;
 2979         }
 2980         if (sav->lft_s != NULL) {
 2981                 KFREE(sav->lft_s);
 2982                 sav->lft_s = NULL;
 2983         }
 2984         if (sav->iv != NULL) {
 2985                 KFREE(sav->iv);
 2986                 sav->iv = NULL;
 2987         }
 2988 
 2989         KFREE(sav);
 2990 
 2991         return;
 2992 }
 2993 
 2994 /*
 2995  * search SAD.
 2996  * OUT:
 2997  *      NULL    : not found
 2998  *      others  : found, pointer to a SA.
 2999  */
 3000 static struct secashead *
 3001 key_getsah(saidx)
 3002         struct secasindex *saidx;
 3003 {
 3004         struct secashead *sah;
 3005 
 3006         LIST_FOREACH(sah, &sahtree, chain) {
 3007                 if (sah->state == SADB_SASTATE_DEAD)
 3008                         continue;
 3009                 if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
 3010                         return sah;
 3011         }
 3012 
 3013         return NULL;
 3014 }
 3015 
 3016 /*
 3017  * check not to be duplicated SPI.
 3018  * NOTE: this function is too slow due to searching all SAD.
 3019  * OUT:
 3020  *      NULL    : not found
 3021  *      others  : found, pointer to a SA.
 3022  */
 3023 static struct secasvar *
 3024 key_checkspidup(saidx, spi)
 3025         struct secasindex *saidx;
 3026         u_int32_t spi;
 3027 {
 3028         struct secashead *sah;
 3029         struct secasvar *sav;
 3030 
 3031         /* check address family */
 3032         if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
 3033                 ipseclog((LOG_DEBUG, "key_checkspidup: address family mismatched.\n"));
 3034                 return NULL;
 3035         }
 3036 
 3037         /* check all SAD */
 3038         LIST_FOREACH(sah, &sahtree, chain) {
 3039                 if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
 3040                         continue;
 3041                 sav = key_getsavbyspi(sah, spi);
 3042                 if (sav != NULL)
 3043                         return sav;
 3044         }
 3045 
 3046         return NULL;
 3047 }
 3048 
 3049 /*
 3050  * search SAD litmited alive SA, protocol, SPI.
 3051  * OUT:
 3052  *      NULL    : not found
 3053  *      others  : found, pointer to a SA.
 3054  */
 3055 static struct secasvar *
 3056 key_getsavbyspi(sah, spi)
 3057         struct secashead *sah;
 3058         u_int32_t spi;
 3059 {
 3060         struct secasvar *sav;
 3061         u_int stateidx, state;
 3062 
 3063         /* search all status */
 3064         for (stateidx = 0;
 3065              stateidx < _ARRAYLEN(saorder_state_alive);
 3066              stateidx++) {
 3067 
 3068                 state = saorder_state_alive[stateidx];
 3069                 LIST_FOREACH(sav, &sah->savtree[state], chain) {
 3070 
 3071                         /* sanity check */
 3072                         if (sav->state != state) {
 3073                                 ipseclog((LOG_DEBUG, "key_getsavbyspi: "
 3074                                     "invalid sav->state (queue: %d SA: %d)\n",
 3075                                     state, sav->state));
 3076                                 continue;
 3077                         }
 3078 
 3079                         if (sav->spi == spi)
 3080                                 return sav;
 3081                 }
 3082         }
 3083 
 3084         return NULL;
 3085 }
 3086 
 3087 /*
 3088  * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
 3089  * You must update these if need.
 3090  * OUT: 0:      success.
 3091  *      !0:     failure.
 3092  *
 3093  * does not modify mbuf.  does not free mbuf on error.
 3094  */
 3095 static int
 3096 key_setsaval(sav, m, mhp)
 3097         struct secasvar *sav;
 3098         struct mbuf *m;
 3099         const struct sadb_msghdr *mhp;
 3100 {
 3101         int error = 0;
 3102 
 3103         /* sanity check */
 3104         if (m == NULL || mhp == NULL || mhp->msg == NULL)
 3105                 panic("key_setsaval: NULL pointer is passed.\n");
 3106 
 3107         /* initialization */
 3108         sav->replay = NULL;
 3109         sav->key_auth = NULL;
 3110         sav->key_enc = NULL;
 3111         sav->sched = NULL;
 3112         sav->schedlen = 0;
 3113         sav->iv = NULL;
 3114         sav->lft_c = NULL;
 3115         sav->lft_h = NULL;
 3116         sav->lft_s = NULL;
 3117         sav->tdb_xform = NULL;          /* transform */
 3118         sav->tdb_encalgxform = NULL;    /* encoding algorithm */
 3119         sav->tdb_authalgxform = NULL;   /* authentication algorithm */
 3120         sav->tdb_compalgxform = NULL;   /* compression algorithm */
 3121 
 3122         /* SA */
 3123         if (mhp->ext[SADB_EXT_SA] != NULL) {
 3124                 const struct sadb_sa *sa0;
 3125 
 3126                 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 3127                 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
 3128                         error = EINVAL;
 3129                         goto fail;
 3130                 }
 3131 
 3132                 sav->alg_auth = sa0->sadb_sa_auth;
 3133                 sav->alg_enc = sa0->sadb_sa_encrypt;
 3134                 sav->flags = sa0->sadb_sa_flags;
 3135 
 3136                 /* replay window */
 3137                 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
 3138                         sav->replay = (struct secreplay *)
 3139                                 malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_SECA, M_NOWAIT|M_ZERO);
 3140                         if (sav->replay == NULL) {
 3141                                 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
 3142                                 error = ENOBUFS;
 3143                                 goto fail;
 3144                         }
 3145                         if (sa0->sadb_sa_replay != 0)
 3146                                 sav->replay->bitmap = (caddr_t)(sav->replay+1);
 3147                         sav->replay->wsize = sa0->sadb_sa_replay;
 3148                 }
 3149         }
 3150 
 3151         /* Authentication keys */
 3152         if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
 3153                 const struct sadb_key *key0;
 3154                 int len;
 3155 
 3156                 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
 3157                 len = mhp->extlen[SADB_EXT_KEY_AUTH];
 3158 
 3159                 error = 0;
 3160                 if (len < sizeof(*key0)) {
 3161                         error = EINVAL;
 3162                         goto fail;
 3163                 }
 3164                 switch (mhp->msg->sadb_msg_satype) {
 3165                 case SADB_SATYPE_AH:
 3166                 case SADB_SATYPE_ESP:
 3167                         if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
 3168                             sav->alg_auth != SADB_X_AALG_NULL)
 3169                                 error = EINVAL;
 3170                         break;
 3171                 case SADB_X_SATYPE_IPCOMP:
 3172                 default:
 3173                         error = EINVAL;
 3174                         break;
 3175                 }
 3176                 if (error) {
 3177                         ipseclog((LOG_DEBUG, "key_setsaval: invalid key_auth values.\n"));
 3178                         goto fail;
 3179                 }
 3180 
 3181                 sav->key_auth = (struct sadb_key *)key_newbuf(key0, len);
 3182                 if (sav->key_auth == NULL) {
 3183                         ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
 3184                         error = ENOBUFS;
 3185                         goto fail;
 3186                 }
 3187         }
 3188 
 3189         /* Encryption key */
 3190         if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
 3191                 const struct sadb_key *key0;
 3192                 int len;
 3193 
 3194                 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
 3195                 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
 3196 
 3197                 error = 0;
 3198                 if (len < sizeof(*key0)) {
 3199                         error = EINVAL;
 3200                         goto fail;
 3201                 }
 3202                 switch (mhp->msg->sadb_msg_satype) {
 3203                 case SADB_SATYPE_ESP:
 3204                         if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
 3205                             sav->alg_enc != SADB_EALG_NULL) {
 3206                                 error = EINVAL;
 3207                                 break;
 3208                         }
 3209                         sav->key_enc = (struct sadb_key *)key_newbuf(key0, len);
 3210                         if (sav->key_enc == NULL) {
 3211                                 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
 3212                                 error = ENOBUFS;
 3213                                 goto fail;
 3214                         }
 3215                         break;
 3216                 case SADB_X_SATYPE_IPCOMP:
 3217                         if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
 3218                                 error = EINVAL;
 3219                         sav->key_enc = NULL;    /*just in case*/
 3220                         break;
 3221                 case SADB_SATYPE_AH:
 3222                 default:
 3223                         error = EINVAL;
 3224                         break;
 3225                 }
 3226                 if (error) {
 3227                         ipseclog((LOG_DEBUG, "key_setsatval: invalid key_enc value.\n"));
 3228                         goto fail;
 3229                 }
 3230         }
 3231 
 3232         /* set iv */
 3233         sav->ivlen = 0;
 3234 
 3235         switch (mhp->msg->sadb_msg_satype) {
 3236         case SADB_SATYPE_AH:
 3237                 error = xform_init(sav, XF_AH);
 3238                 break;
 3239         case SADB_SATYPE_ESP:
 3240                 error = xform_init(sav, XF_ESP);
 3241                 break;
 3242         case SADB_X_SATYPE_IPCOMP:
 3243                 error = xform_init(sav, XF_IPCOMP);
 3244                 break;
 3245         }
 3246         if (error) {
 3247                 ipseclog((LOG_DEBUG,
 3248                         "key_setsaval: unable to initialize SA type %u.\n",
 3249                         mhp->msg->sadb_msg_satype));
 3250                 goto fail;
 3251         }
 3252 
 3253         /* reset created */
 3254         sav->created = time_second;
 3255 
 3256         /* make lifetime for CURRENT */
 3257         KMALLOC(sav->lft_c, struct sadb_lifetime *,
 3258             sizeof(struct sadb_lifetime));
 3259         if (sav->lft_c == NULL) {
 3260                 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
 3261                 error = ENOBUFS;
 3262                 goto fail;
 3263         }
 3264 
 3265         sav->lft_c->sadb_lifetime_len =
 3266             PFKEY_UNIT64(sizeof(struct sadb_lifetime));
 3267         sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
 3268         sav->lft_c->sadb_lifetime_allocations = 0;
 3269         sav->lft_c->sadb_lifetime_bytes = 0;
 3270         sav->lft_c->sadb_lifetime_addtime = time_second;
 3271         sav->lft_c->sadb_lifetime_usetime = 0;
 3272 
 3273         /* lifetimes for HARD and SOFT */
 3274     {
 3275         const struct sadb_lifetime *lft0;
 3276 
 3277         lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
 3278         if (lft0 != NULL) {
 3279                 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
 3280                         error = EINVAL;
 3281                         goto fail;
 3282                 }
 3283                 sav->lft_h = (struct sadb_lifetime *)key_newbuf(lft0,
 3284                     sizeof(*lft0));
 3285                 if (sav->lft_h == NULL) {
 3286                         ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
 3287                         error = ENOBUFS;
 3288                         goto fail;
 3289                 }
 3290                 /* to be initialize ? */
 3291         }
 3292 
 3293         lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
 3294         if (lft0 != NULL) {
 3295                 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
 3296                         error = EINVAL;
 3297                         goto fail;
 3298                 }
 3299                 sav->lft_s = (struct sadb_lifetime *)key_newbuf(lft0,
 3300                     sizeof(*lft0));
 3301                 if (sav->lft_s == NULL) {
 3302                         ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
 3303                         error = ENOBUFS;
 3304                         goto fail;
 3305                 }
 3306                 /* to be initialize ? */
 3307         }
 3308     }
 3309 
 3310         return 0;
 3311 
 3312  fail:
 3313         /* initialization */
 3314         if (sav->replay != NULL) {
 3315                 KFREE(sav->replay);
 3316                 sav->replay = NULL;
 3317         }
 3318         if (sav->key_auth != NULL) {
 3319                 KFREE(sav->key_auth);
 3320                 sav->key_auth = NULL;
 3321         }
 3322         if (sav->key_enc != NULL) {
 3323                 KFREE(sav->key_enc);
 3324                 sav->key_enc = NULL;
 3325         }
 3326         if (sav->sched) {
 3327                 KFREE(sav->sched);
 3328                 sav->sched = NULL;
 3329         }
 3330         if (sav->iv != NULL) {
 3331                 KFREE(sav->iv);
 3332                 sav->iv = NULL;
 3333         }
 3334         if (sav->lft_c != NULL) {
 3335                 KFREE(sav->lft_c);
 3336                 sav->lft_c = NULL;
 3337         }
 3338         if (sav->lft_h != NULL) {
 3339                 KFREE(sav->lft_h);
 3340                 sav->lft_h = NULL;
 3341         }
 3342         if (sav->lft_s != NULL) {
 3343                 KFREE(sav->lft_s);
 3344                 sav->lft_s = NULL;
 3345         }
 3346 
 3347         return error;
 3348 }
 3349 
 3350 /*
 3351  * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
 3352  * OUT: 0:      valid
 3353  *      other:  errno
 3354  */
 3355 static int
 3356 key_mature(sav)
 3357         struct secasvar *sav;
 3358 {
 3359         int error;
 3360 
 3361         /* check SPI value */
 3362         switch (sav->sah->saidx.proto) {
 3363         case IPPROTO_ESP:
 3364         case IPPROTO_AH:
 3365                 if (ntohl(sav->spi) >= 0 && ntohl(sav->spi) <= 255) {
 3366                         ipseclog((LOG_DEBUG,
 3367                             "key_mature: illegal range of SPI %u.\n",
 3368                             (u_int32_t)ntohl(sav->spi)));
 3369                         return EINVAL;
 3370                 }
 3371                 break;
 3372         }
 3373 
 3374         /* check satype */
 3375         switch (sav->sah->saidx.proto) {
 3376         case IPPROTO_ESP:
 3377                 /* check flags */
 3378                 if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
 3379                     (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
 3380                         ipseclog((LOG_DEBUG, "key_mature: "
 3381                             "invalid flag (derived) given to old-esp.\n"));
 3382                         return EINVAL;
 3383                 }
 3384                 error = xform_init(sav, XF_ESP);
 3385                 break;
 3386         case IPPROTO_AH:
 3387                 /* check flags */
 3388                 if (sav->flags & SADB_X_EXT_DERIV) {
 3389                         ipseclog((LOG_DEBUG, "key_mature: "
 3390                             "invalid flag (derived) given to AH SA.\n"));
 3391                         return EINVAL;
 3392                 }
 3393                 if (sav->alg_enc != SADB_EALG_NONE) {
 3394                         ipseclog((LOG_DEBUG, "key_mature: "
 3395                             "protocol and algorithm mismated.\n"));
 3396                         return(EINVAL);
 3397                 }
 3398                 error = xform_init(sav, XF_AH);
 3399                 break;
 3400         case IPPROTO_IPCOMP:
 3401                 if (sav->alg_auth != SADB_AALG_NONE) {
 3402                         ipseclog((LOG_DEBUG, "key_mature: "
 3403                                 "protocol and algorithm mismated.\n"));
 3404                         return(EINVAL);
 3405                 }
 3406                 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
 3407                  && ntohl(sav->spi) >= 0x10000) {
 3408                         ipseclog((LOG_DEBUG, "key_mature: invalid cpi for IPComp.\n"));
 3409                         return(EINVAL);
 3410                 }
 3411                 error = xform_init(sav, XF_IPCOMP);
 3412                 break;
 3413         default:
 3414                 ipseclog((LOG_DEBUG, "key_mature: Invalid satype.\n"));
 3415                 error = EPROTONOSUPPORT;
 3416                 break;
 3417         }
 3418         if (error == 0)
 3419                 key_sa_chgstate(sav, SADB_SASTATE_MATURE);
 3420         return (error);
 3421 }
 3422 
 3423 /*
 3424  * subroutine for SADB_GET and SADB_DUMP.
 3425  */
 3426 static struct mbuf *
 3427 key_setdumpsa(sav, type, satype, seq, pid)
 3428         struct secasvar *sav;
 3429         u_int8_t type, satype;
 3430         u_int32_t seq, pid;
 3431 {
 3432         struct mbuf *result = NULL, *tres = NULL, *m;
 3433         int l = 0;
 3434         int i;
 3435         void *p;
 3436         int dumporder[] = {
 3437                 SADB_EXT_SA, SADB_X_EXT_SA2,
 3438                 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
 3439                 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
 3440                 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
 3441                 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
 3442                 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
 3443         };
 3444 
 3445         m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
 3446         if (m == NULL)
 3447                 goto fail;
 3448         result = m;
 3449 
 3450         for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
 3451                 m = NULL;
 3452                 p = NULL;
 3453                 switch (dumporder[i]) {
 3454                 case SADB_EXT_SA:
 3455                         m = key_setsadbsa(sav);
 3456                         if (!m)
 3457                                 goto fail;
 3458                         break;
 3459 
 3460                 case SADB_X_EXT_SA2:
 3461                         m = key_setsadbxsa2(sav->sah->saidx.mode,
 3462                                         sav->replay ? sav->replay->count : 0,
 3463                                         sav->sah->saidx.reqid);
 3464                         if (!m)
 3465                                 goto fail;
 3466                         break;
 3467 
 3468                 case SADB_EXT_ADDRESS_SRC:
 3469                         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
 3470                             &sav->sah->saidx.src.sa,
 3471                             FULLMASK, IPSEC_ULPROTO_ANY);
 3472                         if (!m)
 3473                                 goto fail;
 3474                         break;
 3475 
 3476                 case SADB_EXT_ADDRESS_DST:
 3477                         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
 3478                             &sav->sah->saidx.dst.sa,
 3479                             FULLMASK, IPSEC_ULPROTO_ANY);
 3480                         if (!m)
 3481                                 goto fail;
 3482                         break;
 3483 
 3484                 case SADB_EXT_KEY_AUTH:
 3485                         if (!sav->key_auth)
 3486                                 continue;
 3487                         l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
 3488                         p = sav->key_auth;
 3489                         break;
 3490 
 3491                 case SADB_EXT_KEY_ENCRYPT:
 3492                         if (!sav->key_enc)
 3493                                 continue;
 3494                         l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
 3495                         p = sav->key_enc;
 3496                         break;
 3497 
 3498                 case SADB_EXT_LIFETIME_CURRENT:
 3499                         if (!sav->lft_c)
 3500                                 continue;
 3501                         l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
 3502                         p = sav->lft_c;
 3503                         break;
 3504 
 3505                 case SADB_EXT_LIFETIME_HARD:
 3506                         if (!sav->lft_h)
 3507                                 continue;
 3508                         l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
 3509                         p = sav->lft_h;
 3510                         break;
 3511 
 3512                 case SADB_EXT_LIFETIME_SOFT:
 3513                         if (!sav->lft_s)
 3514                                 continue;
 3515                         l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
 3516                         p = sav->lft_s;
 3517                         break;
 3518 
 3519                 case SADB_EXT_ADDRESS_PROXY:
 3520                 case SADB_EXT_IDENTITY_SRC:
 3521                 case SADB_EXT_IDENTITY_DST:
 3522                         /* XXX: should we brought from SPD ? */
 3523                 case SADB_EXT_SENSITIVITY:
 3524                 default:
 3525                         continue;
 3526                 }
 3527 
 3528                 if ((!m && !p) || (m && p))
 3529                         goto fail;
 3530                 if (p && tres) {
 3531                         M_PREPEND(tres, l, M_DONTWAIT);
 3532                         if (!tres)
 3533                                 goto fail;
 3534                         bcopy(p, mtod(tres, caddr_t), l);
 3535                         continue;
 3536                 }
 3537                 if (p) {
 3538                         m = key_alloc_mbuf(l);
 3539                         if (!m)
 3540                                 goto fail;
 3541                         m_copyback(m, 0, l, p);
 3542                 }
 3543 
 3544                 if (tres)
 3545                         m_cat(m, tres);
 3546                 tres = m;
 3547         }
 3548 
 3549         m_cat(result, tres);
 3550 
 3551         if (result->m_len < sizeof(struct sadb_msg)) {
 3552                 result = m_pullup(result, sizeof(struct sadb_msg));
 3553                 if (result == NULL)
 3554                         goto fail;
 3555         }
 3556 
 3557         result->m_pkthdr.len = 0;
 3558         for (m = result; m; m = m->m_next)
 3559                 result->m_pkthdr.len += m->m_len;
 3560 
 3561         mtod(result, struct sadb_msg *)->sadb_msg_len =
 3562             PFKEY_UNIT64(result->m_pkthdr.len);
 3563 
 3564         return result;
 3565 
 3566 fail:
 3567         m_freem(result);
 3568         m_freem(tres);
 3569         return NULL;
 3570 }
 3571 
 3572 /*
 3573  * set data into sadb_msg.
 3574  */
 3575 static struct mbuf *
 3576 key_setsadbmsg(type, tlen, satype, seq, pid, reserved)
 3577         u_int8_t type, satype;
 3578         u_int16_t tlen;
 3579         u_int32_t seq;
 3580         pid_t pid;
 3581         u_int16_t reserved;
 3582 {
 3583         struct mbuf *m;
 3584         struct sadb_msg *p;
 3585         int len;
 3586 
 3587         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
 3588         if (len > MCLBYTES)
 3589                 return NULL;
 3590         MGETHDR(m, M_DONTWAIT, MT_DATA);
 3591         if (m && len > MHLEN) {
 3592                 MCLGET(m, M_DONTWAIT);
 3593                 if ((m->m_flags & M_EXT) == 0) {
 3594                         m_freem(m);
 3595                         m = NULL;
 3596                 }
 3597         }
 3598         if (!m)
 3599                 return NULL;
 3600         m->m_pkthdr.len = m->m_len = len;
 3601         m->m_next = NULL;
 3602 
 3603         p = mtod(m, struct sadb_msg *);
 3604 
 3605         bzero(p, len);
 3606         p->sadb_msg_version = PF_KEY_V2;
 3607         p->sadb_msg_type = type;
 3608         p->sadb_msg_errno = 0;
 3609         p->sadb_msg_satype = satype;
 3610         p->sadb_msg_len = PFKEY_UNIT64(tlen);
 3611         p->sadb_msg_reserved = reserved;
 3612         p->sadb_msg_seq = seq;
 3613         p->sadb_msg_pid = (u_int32_t)pid;
 3614 
 3615         return m;
 3616 }
 3617 
 3618 /*
 3619  * copy secasvar data into sadb_address.
 3620  */
 3621 static struct mbuf *
 3622 key_setsadbsa(sav)
 3623         struct secasvar *sav;
 3624 {
 3625         struct mbuf *m;
 3626         struct sadb_sa *p;
 3627         int len;
 3628 
 3629         len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
 3630         m = key_alloc_mbuf(len);
 3631         if (!m || m->m_next) {  /*XXX*/
 3632                 if (m)
 3633                         m_freem(m);
 3634                 return NULL;
 3635         }
 3636 
 3637         p = mtod(m, struct sadb_sa *);
 3638 
 3639         bzero(p, len);
 3640         p->sadb_sa_len = PFKEY_UNIT64(len);
 3641         p->sadb_sa_exttype = SADB_EXT_SA;
 3642         p->sadb_sa_spi = sav->spi;
 3643         p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
 3644         p->sadb_sa_state = sav->state;
 3645         p->sadb_sa_auth = sav->alg_auth;
 3646         p->sadb_sa_encrypt = sav->alg_enc;
 3647         p->sadb_sa_flags = sav->flags;
 3648 
 3649         return m;
 3650 }
 3651 
 3652 /*
 3653  * set data into sadb_address.
 3654  */
 3655 static struct mbuf *
 3656 key_setsadbaddr(exttype, saddr, prefixlen, ul_proto)
 3657         u_int16_t exttype;
 3658         const struct sockaddr *saddr;
 3659         u_int8_t prefixlen;
 3660         u_int16_t ul_proto;
 3661 {
 3662         struct mbuf *m;
 3663         struct sadb_address *p;
 3664         size_t len;
 3665 
 3666         len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
 3667             PFKEY_ALIGN8(saddr->sa_len);
 3668         m = key_alloc_mbuf(len);
 3669         if (!m || m->m_next) {  /*XXX*/
 3670                 if (m)
 3671                         m_freem(m);
 3672                 return NULL;
 3673         }
 3674 
 3675         p = mtod(m, struct sadb_address *);
 3676 
 3677         bzero(p, len);
 3678         p->sadb_address_len = PFKEY_UNIT64(len);
 3679         p->sadb_address_exttype = exttype;
 3680         p->sadb_address_proto = ul_proto;
 3681         if (prefixlen == FULLMASK) {
 3682                 switch (saddr->sa_family) {
 3683                 case AF_INET:
 3684                         prefixlen = sizeof(struct in_addr) << 3;
 3685                         break;
 3686                 case AF_INET6:
 3687                         prefixlen = sizeof(struct in6_addr) << 3;
 3688                         break;
 3689                 default:
 3690                         ; /*XXX*/
 3691                 }
 3692         }
 3693         p->sadb_address_prefixlen = prefixlen;
 3694         p->sadb_address_reserved = 0;
 3695 
 3696         bcopy(saddr,
 3697             mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
 3698             saddr->sa_len);
 3699 
 3700         return m;
 3701 }
 3702 
 3703 #if 0
 3704 /*
 3705  * set data into sadb_ident.
 3706  */
 3707 static struct mbuf *
 3708 key_setsadbident(exttype, idtype, string, stringlen, id)
 3709         u_int16_t exttype, idtype;
 3710         caddr_t string;
 3711         int stringlen;
 3712         u_int64_t id;
 3713 {
 3714         struct mbuf *m;
 3715         struct sadb_ident *p;
 3716         size_t len;
 3717 
 3718         len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
 3719         m = key_alloc_mbuf(len);
 3720         if (!m || m->m_next) {  /*XXX*/
 3721                 if (m)
 3722                         m_freem(m);
 3723                 return NULL;
 3724         }
 3725 
 3726         p = mtod(m, struct sadb_ident *);
 3727 
 3728         bzero(p, len);
 3729         p->sadb_ident_len = PFKEY_UNIT64(len);
 3730         p->sadb_ident_exttype = exttype;
 3731         p->sadb_ident_type = idtype;
 3732         p->sadb_ident_reserved = 0;
 3733         p->sadb_ident_id = id;
 3734 
 3735         bcopy(string,
 3736             mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
 3737             stringlen);
 3738 
 3739         return m;
 3740 }
 3741 #endif
 3742 
 3743 /*
 3744  * set data into sadb_x_sa2.
 3745  */
 3746 static struct mbuf *
 3747 key_setsadbxsa2(mode, seq, reqid)
 3748         u_int8_t mode;
 3749         u_int32_t seq, reqid;
 3750 {
 3751         struct mbuf *m;
 3752         struct sadb_x_sa2 *p;
 3753         size_t len;
 3754 
 3755         len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
 3756         m = key_alloc_mbuf(len);
 3757         if (!m || m->m_next) {  /*XXX*/
 3758                 if (m)
 3759                         m_freem(m);
 3760                 return NULL;
 3761         }
 3762 
 3763         p = mtod(m, struct sadb_x_sa2 *);
 3764 
 3765         bzero(p, len);
 3766         p->sadb_x_sa2_len = PFKEY_UNIT64(len);
 3767         p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
 3768         p->sadb_x_sa2_mode = mode;
 3769         p->sadb_x_sa2_reserved1 = 0;
 3770         p->sadb_x_sa2_reserved2 = 0;
 3771         p->sadb_x_sa2_sequence = seq;
 3772         p->sadb_x_sa2_reqid = reqid;
 3773 
 3774         return m;
 3775 }
 3776 
 3777 /*
 3778  * set data into sadb_x_policy
 3779  */
 3780 static struct mbuf *
 3781 key_setsadbxpolicy(type, dir, id)
 3782         u_int16_t type;
 3783         u_int8_t dir;
 3784         u_int32_t id;
 3785 {
 3786         struct mbuf *m;
 3787         struct sadb_x_policy *p;
 3788         size_t len;
 3789 
 3790         len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
 3791         m = key_alloc_mbuf(len);
 3792         if (!m || m->m_next) {  /*XXX*/
 3793                 if (m)
 3794                         m_freem(m);
 3795                 return NULL;
 3796         }
 3797 
 3798         p = mtod(m, struct sadb_x_policy *);
 3799 
 3800         bzero(p, len);
 3801         p->sadb_x_policy_len = PFKEY_UNIT64(len);
 3802         p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
 3803         p->sadb_x_policy_type = type;
 3804         p->sadb_x_policy_dir = dir;
 3805         p->sadb_x_policy_id = id;
 3806 
 3807         return m;
 3808 }
 3809 
 3810 /* %%% utilities */
 3811 /*
 3812  * copy a buffer into the new buffer allocated.
 3813  */
 3814 static void *
 3815 key_newbuf(src, len)
 3816         const void *src;
 3817         u_int len;
 3818 {
 3819         caddr_t new;
 3820 
 3821         KMALLOC(new, caddr_t, len);
 3822         if (new == NULL) {
 3823                 ipseclog((LOG_DEBUG, "key_newbuf: No more memory.\n"));
 3824                 return NULL;
 3825         }
 3826         bcopy(src, new, len);
 3827 
 3828         return new;
 3829 }
 3830 
 3831 /* compare my own address
 3832  * OUT: 1: true, i.e. my address.
 3833  *      0: false
 3834  */
 3835 int
 3836 key_ismyaddr(sa)
 3837         struct sockaddr *sa;
 3838 {
 3839 #ifdef INET
 3840         struct sockaddr_in *sin;
 3841         struct in_ifaddr *ia;
 3842 #endif
 3843 
 3844         /* sanity check */
 3845         if (sa == NULL)
 3846                 panic("key_ismyaddr: NULL pointer is passed.\n");
 3847 
 3848         switch (sa->sa_family) {
 3849 #ifdef INET
 3850         case AF_INET:
 3851                 sin = (struct sockaddr_in *)sa;
 3852                 for (ia = in_ifaddrhead.tqh_first; ia;
 3853                      ia = ia->ia_link.tqe_next)
 3854                 {
 3855                         if (sin->sin_family == ia->ia_addr.sin_family &&
 3856                             sin->sin_len == ia->ia_addr.sin_len &&
 3857                             sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
 3858                         {
 3859                                 return 1;
 3860                         }
 3861                 }
 3862                 break;
 3863 #endif
 3864 #ifdef INET6
 3865         case AF_INET6:
 3866                 return key_ismyaddr6((struct sockaddr_in6 *)sa);
 3867 #endif
 3868         }
 3869 
 3870         return 0;
 3871 }
 3872 
 3873 #ifdef INET6
 3874 /*
 3875  * compare my own address for IPv6.
 3876  * 1: ours
 3877  * 0: other
 3878  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
 3879  */
 3880 #include <netinet6/in6_var.h>
 3881 
 3882 static int
 3883 key_ismyaddr6(sin6)
 3884         struct sockaddr_in6 *sin6;
 3885 {
 3886         struct in6_ifaddr *ia;
 3887         struct in6_multi *in6m;
 3888 
 3889         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
 3890                 if (key_sockaddrcmp((struct sockaddr *)&sin6,
 3891                     (struct sockaddr *)&ia->ia_addr, 0) == 0)
 3892                         return 1;
 3893 
 3894                 /*
 3895                  * XXX Multicast
 3896                  * XXX why do we care about multlicast here while we don't care
 3897                  * about IPv4 multicast??
 3898                  * XXX scope
 3899                  */
 3900                 in6m = NULL;
 3901 #ifdef __FreeBSD__
 3902                 IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
 3903 #else
 3904                 for ((in6m) = ia->ia6_multiaddrs.lh_first;
 3905                      (in6m) != NULL &&
 3906                      !IN6_ARE_ADDR_EQUAL(&(in6m)->in6m_addr, &sin6->sin6_addr);
 3907                      (in6m) = in6m->in6m_entry.le_next)
 3908                         continue;
 3909 #endif
 3910                 if (in6m)
 3911                         return 1;
 3912         }
 3913 
 3914         /* loopback, just for safety */
 3915         if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
 3916                 return 1;
 3917 
 3918         return 0;
 3919 }
 3920 #endif /*INET6*/
 3921 
 3922 /*
 3923  * compare two secasindex structure.
 3924  * flag can specify to compare 2 saidxes.
 3925  * compare two secasindex structure without both mode and reqid.
 3926  * don't compare port.
 3927  * IN:  
 3928  *      saidx0: source, it can be in SAD.
 3929  *      saidx1: object.
 3930  * OUT: 
 3931  *      1 : equal
 3932  *      0 : not equal
 3933  */
 3934 static int
 3935 key_cmpsaidx(
 3936         const struct secasindex *saidx0,
 3937         const struct secasindex *saidx1,
 3938         int flag)
 3939 {
 3940         /* sanity */
 3941         if (saidx0 == NULL && saidx1 == NULL)
 3942                 return 1;
 3943 
 3944         if (saidx0 == NULL || saidx1 == NULL)
 3945                 return 0;
 3946 
 3947         if (saidx0->proto != saidx1->proto)
 3948                 return 0;
 3949 
 3950         if (flag == CMP_EXACTLY) {
 3951                 if (saidx0->mode != saidx1->mode)
 3952                         return 0;
 3953                 if (saidx0->reqid != saidx1->reqid)
 3954                         return 0;
 3955                 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
 3956                     bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
 3957                         return 0;
 3958         } else {
 3959 
 3960                 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
 3961                 if (flag == CMP_MODE_REQID
 3962                   ||flag == CMP_REQID) {
 3963                         /*
 3964                          * If reqid of SPD is non-zero, unique SA is required.
 3965                          * The result must be of same reqid in this case.
 3966                          */
 3967                         if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
 3968                                 return 0;
 3969                 }
 3970 
 3971                 if (flag == CMP_MODE_REQID) {
 3972                         if (saidx0->mode != IPSEC_MODE_ANY
 3973                          && saidx0->mode != saidx1->mode)
 3974                                 return 0;
 3975                 }
 3976 
 3977                 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0) {
 3978                         return 0;
 3979                 }
 3980                 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0) {
 3981                         return 0;
 3982                 }
 3983         }
 3984 
 3985         return 1;
 3986 }
 3987 
 3988 /*
 3989  * compare two secindex structure exactly.
 3990  * IN:
 3991  *      spidx0: source, it is often in SPD.
 3992  *      spidx1: object, it is often from PFKEY message.
 3993  * OUT:
 3994  *      1 : equal
 3995  *      0 : not equal
 3996  */
 3997 int
 3998 key_cmpspidx_exactly(
 3999         struct secpolicyindex *spidx0,
 4000         struct secpolicyindex *spidx1)
 4001 {
 4002         /* sanity */
 4003         if (spidx0 == NULL && spidx1 == NULL)
 4004                 return 1;
 4005 
 4006         if (spidx0 == NULL || spidx1 == NULL)
 4007                 return 0;
 4008 
 4009         if (spidx0->prefs != spidx1->prefs
 4010          || spidx0->prefd != spidx1->prefd
 4011          || spidx0->ul_proto != spidx1->ul_proto)
 4012                 return 0;
 4013 
 4014         return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
 4015                key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
 4016 }
 4017 
 4018 /*
 4019  * compare two secindex structure with mask.
 4020  * IN:
 4021  *      spidx0: source, it is often in SPD.
 4022  *      spidx1: object, it is often from IP header.
 4023  * OUT:
 4024  *      1 : equal
 4025  *      0 : not equal
 4026  */
 4027 int
 4028 key_cmpspidx_withmask(
 4029         struct secpolicyindex *spidx0,
 4030         struct secpolicyindex *spidx1)
 4031 {
 4032         /* sanity */
 4033         if (spidx0 == NULL && spidx1 == NULL)
 4034                 return 1;
 4035 
 4036         if (spidx0 == NULL || spidx1 == NULL)
 4037                 return 0;
 4038 
 4039         if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
 4040             spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
 4041             spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
 4042             spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
 4043                 return 0;
 4044 
 4045         /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
 4046         if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
 4047          && spidx0->ul_proto != spidx1->ul_proto)
 4048                 return 0;
 4049 
 4050         switch (spidx0->src.sa.sa_family) {
 4051         case AF_INET:
 4052                 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
 4053                  && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
 4054                         return 0;
 4055                 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
 4056                     &spidx1->src.sin.sin_addr, spidx0->prefs))
 4057                         return 0;
 4058                 break;
 4059         case AF_INET6:
 4060                 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
 4061                  && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
 4062                         return 0;
 4063                 /*
 4064                  * scope_id check. if sin6_scope_id is 0, we regard it
 4065                  * as a wildcard scope, which matches any scope zone ID. 
 4066                  */
 4067                 if (spidx0->src.sin6.sin6_scope_id &&
 4068                     spidx1->src.sin6.sin6_scope_id &&
 4069                     spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
 4070                         return 0;
 4071                 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
 4072                     &spidx1->src.sin6.sin6_addr, spidx0->prefs))
 4073                         return 0;
 4074                 break;
 4075         default:
 4076                 /* XXX */
 4077                 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
 4078                         return 0;
 4079                 break;
 4080         }
 4081 
 4082         switch (spidx0->dst.sa.sa_family) {
 4083         case AF_INET:
 4084                 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
 4085                  && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
 4086                         return 0;
 4087                 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
 4088                     &spidx1->dst.sin.sin_addr, spidx0->prefd))
 4089                         return 0;
 4090                 break;
 4091         case AF_INET6:
 4092                 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
 4093                  && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
 4094                         return 0;
 4095                 /*
 4096                  * scope_id check. if sin6_scope_id is 0, we regard it
 4097                  * as a wildcard scope, which matches any scope zone ID. 
 4098                  */
 4099                 if (spidx0->src.sin6.sin6_scope_id &&
 4100                     spidx1->src.sin6.sin6_scope_id &&
 4101                     spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
 4102                         return 0;
 4103                 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
 4104                     &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
 4105                         return 0;
 4106                 break;
 4107         default:
 4108                 /* XXX */
 4109                 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
 4110                         return 0;
 4111                 break;
 4112         }
 4113 
 4114         /* XXX Do we check other field ?  e.g. flowinfo */
 4115 
 4116         return 1;
 4117 }
 4118 
 4119 /* returns 0 on match */
 4120 static int
 4121 key_sockaddrcmp(
 4122         const struct sockaddr *sa1,
 4123         const struct sockaddr *sa2,
 4124         int port)
 4125 {
 4126 #ifdef satosin
 4127 #undef satosin
 4128 #endif
 4129 #define satosin(s) ((const struct sockaddr_in *)s)
 4130 #ifdef satosin6
 4131 #undef satosin6
 4132 #endif
 4133 #define satosin6(s) ((const struct sockaddr_in6 *)s)
 4134         if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
 4135                 return 1;
 4136 
 4137         switch (sa1->sa_family) {
 4138         case AF_INET:
 4139                 if (sa1->sa_len != sizeof(struct sockaddr_in))
 4140                         return 1;
 4141                 if (satosin(sa1)->sin_addr.s_addr !=
 4142                     satosin(sa2)->sin_addr.s_addr) {
 4143                         return 1;
 4144                 }
 4145                 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
 4146                         return 1;
 4147                 break;
 4148         case AF_INET6:
 4149                 if (sa1->sa_len != sizeof(struct sockaddr_in6))
 4150                         return 1;       /*EINVAL*/
 4151                 if (satosin6(sa1)->sin6_scope_id !=
 4152                     satosin6(sa2)->sin6_scope_id) {
 4153                         return 1;
 4154                 }
 4155                 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
 4156                     &satosin6(sa2)->sin6_addr)) {
 4157                         return 1;
 4158                 }
 4159                 if (port &&
 4160                     satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
 4161                         return 1;
 4162                 }
 4163         default:
 4164                 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
 4165                         return 1;
 4166                 break;
 4167         }
 4168 
 4169         return 0;
 4170 #undef satosin
 4171 #undef satosin6
 4172 }
 4173 
 4174 /*
 4175  * compare two buffers with mask.
 4176  * IN:
 4177  *      addr1: source
 4178  *      addr2: object
 4179  *      bits:  Number of bits to compare
 4180  * OUT:
 4181  *      1 : equal
 4182  *      0 : not equal
 4183  */
 4184 static int
 4185 key_bbcmp(const void *a1, const void *a2, u_int bits)
 4186 {
 4187         const unsigned char *p1 = a1;
 4188         const unsigned char *p2 = a2;
 4189 
 4190         /* XXX: This could be considerably faster if we compare a word
 4191          * at a time, but it is complicated on LSB Endian machines */
 4192 
 4193         /* Handle null pointers */
 4194         if (p1 == NULL || p2 == NULL)
 4195                 return (p1 == p2);
 4196 
 4197         while (bits >= 8) {
 4198                 if (*p1++ != *p2++)
 4199                         return 0;
 4200                 bits -= 8;
 4201         }
 4202 
 4203         if (bits > 0) {
 4204                 u_int8_t mask = ~((1<<(8-bits))-1);
 4205                 if ((*p1 & mask) != (*p2 & mask))
 4206                         return 0;
 4207         }
 4208         return 1;       /* Match! */
 4209 }
 4210 
 4211 /*
 4212  * time handler.
 4213  * scanning SPD and SAD to check status for each entries,
 4214  * and do to remove or to expire.
 4215  * XXX: year 2038 problem may remain.
 4216  */
 4217 void
 4218 key_timehandler(void* arg)
 4219 {
 4220         u_int dir;
 4221         int s;
 4222         time_t now = time_second;
 4223 
 4224         s = splsoftnet();       /*called from softclock()*/
 4225 
 4226         /* SPD */
 4227     {
 4228         struct secpolicy *sp, *nextsp;
 4229 
 4230         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
 4231                 for (sp = LIST_FIRST(&sptree[dir]);
 4232                      sp != NULL;
 4233                      sp = nextsp) {
 4234 
 4235                         nextsp = LIST_NEXT(sp, chain);
 4236 
 4237                         if (sp->state == IPSEC_SPSTATE_DEAD) {
 4238                                 key_sp_unlink(sp);      /*XXX*/
 4239 
 4240                                 /* 'sp' dead; continue transfers to
 4241                                  * 'sp = nextsp'
 4242                                  */
 4243                                 continue;
 4244                         }
 4245 
 4246                         if (sp->lifetime == 0 && sp->validtime == 0)
 4247                                 continue;
 4248 
 4249                         /* the deletion will occur next time */
 4250                         if ((sp->lifetime && now - sp->created > sp->lifetime)
 4251                          || (sp->validtime && now - sp->lastused > sp->validtime)) {
 4252                                 key_sp_dead(sp);
 4253                                 key_spdexpire(sp);
 4254                                 continue;
 4255                         }
 4256                 }
 4257         }
 4258     }
 4259 
 4260         /* SAD */
 4261     {
 4262         struct secashead *sah, *nextsah;
 4263         struct secasvar *sav, *nextsav;
 4264 
 4265         for (sah = LIST_FIRST(&sahtree);
 4266              sah != NULL;
 4267              sah = nextsah) {
 4268 
 4269                 nextsah = LIST_NEXT(sah, chain);
 4270 
 4271                 /* if sah has been dead, then delete it and process next sah. */
 4272                 if (sah->state == SADB_SASTATE_DEAD) {
 4273                         key_delsah(sah);
 4274                         continue;
 4275                 }
 4276 
 4277                 /* if LARVAL entry doesn't become MATURE, delete it. */
 4278                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]);
 4279                      sav != NULL;
 4280                      sav = nextsav) {
 4281 
 4282                         nextsav = LIST_NEXT(sav, chain);
 4283 
 4284                         if (now - sav->created > key_larval_lifetime) {
 4285                                 KEY_FREESAV(&sav);
 4286                         }
 4287                 }
 4288 
 4289                 /*
 4290                  * check MATURE entry to start to send expire message
 4291                  * whether or not.
 4292                  */
 4293                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
 4294                      sav != NULL;
 4295                      sav = nextsav) {
 4296 
 4297                         nextsav = LIST_NEXT(sav, chain);
 4298 
 4299                         /* we don't need to check. */
 4300                         if (sav->lft_s == NULL)
 4301                                 continue;
 4302 
 4303                         /* sanity check */
 4304                         if (sav->lft_c == NULL) {
 4305                                 ipseclog((LOG_DEBUG,"key_timehandler: "
 4306                                         "There is no CURRENT time, why?\n"));
 4307                                 continue;
 4308                         }
 4309 
 4310                         /* check SOFT lifetime */
 4311                         if (sav->lft_s->sadb_lifetime_addtime != 0
 4312                          && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
 4313                                 /*
 4314                                  * check SA to be used whether or not.
 4315                                  * when SA hasn't been used, delete it.
 4316                                  */
 4317                                 if (sav->lft_c->sadb_lifetime_usetime == 0) {
 4318                                         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 4319                                         KEY_FREESAV(&sav);
 4320                                 } else {
 4321                                         key_sa_chgstate(sav, SADB_SASTATE_DYING);
 4322                                         /*
 4323                                          * XXX If we keep to send expire
 4324                                          * message in the status of
 4325                                          * DYING. Do remove below code.
 4326                                          */
 4327                                         key_expire(sav);
 4328                                 }
 4329                         }
 4330                         /* check SOFT lifetime by bytes */
 4331                         /*
 4332                          * XXX I don't know the way to delete this SA
 4333                          * when new SA is installed.  Caution when it's
 4334                          * installed too big lifetime by time.
 4335                          */
 4336                         else if (sav->lft_s->sadb_lifetime_bytes != 0
 4337                               && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
 4338 
 4339                                 key_sa_chgstate(sav, SADB_SASTATE_DYING);
 4340                                 /*
 4341                                  * XXX If we keep to send expire
 4342                                  * message in the status of
 4343                                  * DYING. Do remove below code.
 4344                                  */
 4345                                 key_expire(sav);
 4346                         }
 4347                 }
 4348 
 4349                 /* check DYING entry to change status to DEAD. */
 4350                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]);
 4351                      sav != NULL;
 4352                      sav = nextsav) {
 4353 
 4354                         nextsav = LIST_NEXT(sav, chain);
 4355 
 4356                         /* we don't need to check. */
 4357                         if (sav->lft_h == NULL)
 4358                                 continue;
 4359 
 4360                         /* sanity check */
 4361                         if (sav->lft_c == NULL) {
 4362                                 ipseclog((LOG_DEBUG, "key_timehandler: "
 4363                                         "There is no CURRENT time, why?\n"));
 4364                                 continue;
 4365                         }
 4366 
 4367                         if (sav->lft_h->sadb_lifetime_addtime != 0
 4368                          && now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
 4369                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 4370                                 KEY_FREESAV(&sav);
 4371                         }
 4372 #if 0   /* XXX Should we keep to send expire message until HARD lifetime ? */
 4373                         else if (sav->lft_s != NULL
 4374                               && sav->lft_s->sadb_lifetime_addtime != 0
 4375                               && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
 4376                                 /*
 4377                                  * XXX: should be checked to be
 4378                                  * installed the valid SA.
 4379                                  */
 4380 
 4381                                 /*
 4382                                  * If there is no SA then sending
 4383                                  * expire message.
 4384                                  */
 4385                                 key_expire(sav);
 4386                         }
 4387 #endif
 4388                         /* check HARD lifetime by bytes */
 4389                         else if (sav->lft_h->sadb_lifetime_bytes != 0
 4390                               && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
 4391                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 4392                                 KEY_FREESAV(&sav);
 4393                         }
 4394                 }
 4395 
 4396                 /* delete entry in DEAD */
 4397                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]);
 4398                      sav != NULL;
 4399                      sav = nextsav) {
 4400 
 4401                         nextsav = LIST_NEXT(sav, chain);
 4402 
 4403                         /* sanity check */
 4404                         if (sav->state != SADB_SASTATE_DEAD) {
 4405                                 ipseclog((LOG_DEBUG, "key_timehandler: "
 4406                                         "invalid sav->state "
 4407                                         "(queue: %d SA: %d): "
 4408                                         "kill it anyway\n",
 4409                                         SADB_SASTATE_DEAD, sav->state));
 4410                         }
 4411 
 4412                         /*
 4413                          * do not call key_freesav() here.
 4414                          * sav should already be freed, and sav->refcnt
 4415                          * shows other references to sav
 4416                          * (such as from SPD).
 4417                          */
 4418                 }
 4419         }
 4420     }
 4421 
 4422 #ifndef IPSEC_NONBLOCK_ACQUIRE
 4423         /* ACQ tree */
 4424     {
 4425         struct secacq *acq, *nextacq;
 4426 
 4427         for (acq = LIST_FIRST(&acqtree);
 4428              acq != NULL;
 4429              acq = nextacq) {
 4430 
 4431                 nextacq = LIST_NEXT(acq, chain);
 4432 
 4433                 if (now - acq->created > key_blockacq_lifetime
 4434                  && __LIST_CHAINED(acq)) {
 4435                         LIST_REMOVE(acq, chain);
 4436                         KFREE(acq);
 4437                 }
 4438         }
 4439     }
 4440 #endif
 4441 
 4442         /* SP ACQ tree */
 4443     {
 4444         struct secspacq *acq, *nextacq;
 4445 
 4446         for (acq = LIST_FIRST(&spacqtree);
 4447              acq != NULL;
 4448              acq = nextacq) {
 4449 
 4450                 nextacq = LIST_NEXT(acq, chain);
 4451 
 4452                 if (now - acq->created > key_blockacq_lifetime
 4453                  && __LIST_CHAINED(acq)) {
 4454                         LIST_REMOVE(acq, chain);
 4455                         KFREE(acq);
 4456                 }
 4457         }
 4458     }
 4459 
 4460         /* initialize random seed */
 4461         if (key_tick_init_random++ > key_int_random) {
 4462                 key_tick_init_random = 0;
 4463                 key_srandom();
 4464         }
 4465 
 4466 #ifndef IPSEC_DEBUG2
 4467         /* do exchange to tick time !! */
 4468         callout_reset(&key_timehandler_ch, hz, key_timehandler, (void *)0);
 4469 #endif /* IPSEC_DEBUG2 */
 4470 
 4471         splx(s);
 4472         return;
 4473 }
 4474 
 4475 #ifdef __NetBSD__
 4476 void srandom(int arg); 
 4477 void srandom(int arg) {return;}
 4478 #endif
 4479 
 4480 /*
 4481  * to initialize a seed for random()
 4482  */
 4483 static void
 4484 key_srandom()
 4485 {
 4486         srandom(time_second);
 4487 }
 4488 
 4489 u_long
 4490 key_random()
 4491 {
 4492         u_long value;
 4493 
 4494         key_randomfill(&value, sizeof(value));
 4495         return value;
 4496 }
 4497 
 4498 void
 4499 key_randomfill(p, l)
 4500         void *p;
 4501         size_t l;
 4502 {
 4503         size_t n;
 4504         u_long v;
 4505         static int warn = 1;
 4506 
 4507         n = 0;
 4508         n = (size_t)read_random(p, (u_int)l);
 4509         /* last resort */
 4510         while (n < l) {
 4511                 v = random();
 4512                 bcopy(&v, (u_int8_t *)p + n,
 4513                     l - n < sizeof(v) ? l - n : sizeof(v));
 4514                 n += sizeof(v);
 4515 
 4516                 if (warn) {
 4517                         printf("WARNING: pseudo-random number generator "
 4518                             "used for IPsec processing\n");
 4519                         warn = 0;
 4520                 }
 4521         }
 4522 }
 4523 
 4524 /*
 4525  * map SADB_SATYPE_* to IPPROTO_*.
 4526  * if satype == SADB_SATYPE then satype is mapped to ~0.
 4527  * OUT:
 4528  *      0: invalid satype.
 4529  */
 4530 static u_int16_t
 4531 key_satype2proto(satype)
 4532         u_int8_t satype;
 4533 {
 4534         switch (satype) {
 4535         case SADB_SATYPE_UNSPEC:
 4536                 return IPSEC_PROTO_ANY;
 4537         case SADB_SATYPE_AH:
 4538                 return IPPROTO_AH;
 4539         case SADB_SATYPE_ESP:
 4540                 return IPPROTO_ESP;
 4541         case SADB_X_SATYPE_IPCOMP:
 4542                 return IPPROTO_IPCOMP;
 4543         default:
 4544                 return 0;
 4545         }
 4546         /* NOTREACHED */
 4547 }
 4548 
 4549 /*
 4550  * map IPPROTO_* to SADB_SATYPE_*
 4551  * OUT:
 4552  *      0: invalid protocol type.
 4553  */
 4554 static u_int8_t
 4555 key_proto2satype(proto)
 4556         u_int16_t proto;
 4557 {
 4558         switch (proto) {
 4559         case IPPROTO_AH:
 4560                 return SADB_SATYPE_AH;
 4561         case IPPROTO_ESP:
 4562                 return SADB_SATYPE_ESP;
 4563         case IPPROTO_IPCOMP:
 4564                 return SADB_X_SATYPE_IPCOMP;
 4565         default:
 4566                 return 0;
 4567         }
 4568         /* NOTREACHED */
 4569 }
 4570 
 4571 /* %%% PF_KEY */
 4572 /*
 4573  * SADB_GETSPI processing is to receive
 4574  *      <base, (SA2), src address, dst address, (SPI range)>
 4575  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
 4576  * tree with the status of LARVAL, and send
 4577  *      <base, SA(*), address(SD)>
 4578  * to the IKMPd.
 4579  *
 4580  * IN:  mhp: pointer to the pointer to each header.
 4581  * OUT: NULL if fail.
 4582  *      other if success, return pointer to the message to send.
 4583  */
 4584 static int
 4585 key_getspi(so, m, mhp)
 4586         struct socket *so;
 4587         struct mbuf *m;
 4588         const struct sadb_msghdr *mhp;
 4589 {
 4590         struct sadb_address *src0, *dst0;
 4591         struct secasindex saidx;
 4592         struct secashead *newsah;
 4593         struct secasvar *newsav;
 4594         u_int8_t proto;
 4595         u_int32_t spi;
 4596         u_int8_t mode;
 4597         u_int32_t reqid;
 4598         int error;
 4599 
 4600         /* sanity check */
 4601         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 4602                 panic("key_getspi: NULL pointer is passed.\n");
 4603 
 4604         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 4605             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
 4606                 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
 4607                 return key_senderror(so, m, EINVAL);
 4608         }
 4609         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 4610             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 4611                 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
 4612                 return key_senderror(so, m, EINVAL);
 4613         }
 4614         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
 4615                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
 4616                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
 4617         } else {
 4618                 mode = IPSEC_MODE_ANY;
 4619                 reqid = 0;
 4620         }
 4621 
 4622         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
 4623         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
 4624 
 4625         /* map satype to proto */
 4626         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 4627                 ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
 4628                 return key_senderror(so, m, EINVAL);
 4629         }
 4630 
 4631         /* make sure if port number is zero. */
 4632         switch (((struct sockaddr *)(src0 + 1))->sa_family) {
 4633         case AF_INET:
 4634                 if (((struct sockaddr *)(src0 + 1))->sa_len !=
 4635                     sizeof(struct sockaddr_in))
 4636                         return key_senderror(so, m, EINVAL);
 4637                 ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
 4638                 break;
 4639         case AF_INET6:
 4640                 if (((struct sockaddr *)(src0 + 1))->sa_len !=
 4641                     sizeof(struct sockaddr_in6))
 4642                         return key_senderror(so, m, EINVAL);
 4643                 ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
 4644                 break;
 4645         default:
 4646                 ; /*???*/
 4647         }
 4648         switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
 4649         case AF_INET:
 4650                 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
 4651                     sizeof(struct sockaddr_in))
 4652                         return key_senderror(so, m, EINVAL);
 4653                 ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
 4654                 break;
 4655         case AF_INET6:
 4656                 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
 4657                     sizeof(struct sockaddr_in6))
 4658                         return key_senderror(so, m, EINVAL);
 4659                 ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
 4660                 break;
 4661         default:
 4662                 ; /*???*/
 4663         }
 4664 
 4665         /* XXX boundary check against sa_len */
 4666         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
 4667 
 4668         /* SPI allocation */
 4669         spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
 4670                                &saidx);
 4671         if (spi == 0)
 4672                 return key_senderror(so, m, EINVAL);
 4673 
 4674         /* get a SA index */
 4675         if ((newsah = key_getsah(&saidx)) == NULL) {
 4676                 /* create a new SA index */
 4677                 if ((newsah = key_newsah(&saidx)) == NULL) {
 4678                         ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
 4679                         return key_senderror(so, m, ENOBUFS);
 4680                 }
 4681         }
 4682 
 4683         /* get a new SA */
 4684         /* XXX rewrite */
 4685         newsav = KEY_NEWSAV(m, mhp, newsah, &error);
 4686         if (newsav == NULL) {
 4687                 /* XXX don't free new SA index allocated in above. */
 4688                 return key_senderror(so, m, error);
 4689         }
 4690 
 4691         /* set spi */
 4692         newsav->spi = htonl(spi);
 4693 
 4694 #ifndef IPSEC_NONBLOCK_ACQUIRE
 4695         /* delete the entry in acqtree */
 4696         if (mhp->msg->sadb_msg_seq != 0) {
 4697                 struct secacq *acq;
 4698                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
 4699                         /* reset counter in order to deletion by timehandler. */
 4700                         acq->created = time_second;
 4701                         acq->count = 0;
 4702                 }
 4703         }
 4704 #endif
 4705 
 4706     {
 4707         struct mbuf *n, *nn;
 4708         struct sadb_sa *m_sa;
 4709         struct sadb_msg *newmsg;
 4710         int off, len;
 4711 
 4712         /* create new sadb_msg to reply. */
 4713         len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
 4714             PFKEY_ALIGN8(sizeof(struct sadb_sa));
 4715         if (len > MCLBYTES)
 4716                 return key_senderror(so, m, ENOBUFS);
 4717 
 4718         MGETHDR(n, M_DONTWAIT, MT_DATA);
 4719         if (len > MHLEN) {
 4720                 MCLGET(n, M_DONTWAIT);
 4721                 if ((n->m_flags & M_EXT) == 0) {
 4722                         m_freem(n);
 4723                         n = NULL;
 4724                 }
 4725         }
 4726         if (!n)
 4727                 return key_senderror(so, m, ENOBUFS);
 4728 
 4729         n->m_len = len;
 4730         n->m_next = NULL;
 4731         off = 0;
 4732 
 4733         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
 4734         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
 4735 
 4736         m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
 4737         m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
 4738         m_sa->sadb_sa_exttype = SADB_EXT_SA;
 4739         m_sa->sadb_sa_spi = htonl(spi);
 4740         off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
 4741 
 4742 #ifdef DIAGNOSTIC
 4743         if (off != len)
 4744                 panic("length inconsistency in key_getspi");
 4745 #endif
 4746 
 4747         n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
 4748             SADB_EXT_ADDRESS_DST);
 4749         if (!n->m_next) {
 4750                 m_freem(n);
 4751                 return key_senderror(so, m, ENOBUFS);
 4752         }
 4753 
 4754         if (n->m_len < sizeof(struct sadb_msg)) {
 4755                 n = m_pullup(n, sizeof(struct sadb_msg));
 4756                 if (n == NULL)
 4757                         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
 4758         }
 4759 
 4760         n->m_pkthdr.len = 0;
 4761         for (nn = n; nn; nn = nn->m_next)
 4762                 n->m_pkthdr.len += nn->m_len;
 4763 
 4764         newmsg = mtod(n, struct sadb_msg *);
 4765         newmsg->sadb_msg_seq = newsav->seq;
 4766         newmsg->sadb_msg_errno = 0;
 4767         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 4768 
 4769         m_freem(m);
 4770         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
 4771     }
 4772 }
 4773 
 4774 /*
 4775  * allocating new SPI
 4776  * called by key_getspi().
 4777  * OUT:
 4778  *      0:      failure.
 4779  *      others: success.
 4780  */
 4781 static u_int32_t
 4782 key_do_getnewspi(spirange, saidx)
 4783         struct sadb_spirange *spirange;
 4784         struct secasindex *saidx;
 4785 {
 4786         u_int32_t newspi;
 4787         u_int32_t min, max;
 4788         int count = key_spi_trycnt;
 4789 
 4790         /* set spi range to allocate */
 4791         if (spirange != NULL) {
 4792                 min = spirange->sadb_spirange_min;
 4793                 max = spirange->sadb_spirange_max;
 4794         } else {
 4795                 min = key_spi_minval;
 4796                 max = key_spi_maxval;
 4797         }
 4798         /* IPCOMP needs 2-byte SPI */
 4799         if (saidx->proto == IPPROTO_IPCOMP) {
 4800                 u_int32_t t;
 4801                 if (min >= 0x10000)
 4802                         min = 0xffff;
 4803                 if (max >= 0x10000)
 4804                         max = 0xffff;
 4805                 if (min > max) {
 4806                         t = min; min = max; max = t;
 4807                 }
 4808         }
 4809 
 4810         if (min == max) {
 4811                 if (key_checkspidup(saidx, min) != NULL) {
 4812                         ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", min));
 4813                         return 0;
 4814                 }
 4815 
 4816                 count--; /* taking one cost. */
 4817                 newspi = min;
 4818 
 4819         } else {
 4820 
 4821                 /* init SPI */
 4822                 newspi = 0;
 4823 
 4824                 /* when requesting to allocate spi ranged */
 4825                 while (count--) {
 4826                         /* generate pseudo-random SPI value ranged. */
 4827                         newspi = min + (key_random() % (max - min + 1));
 4828 
 4829                         if (key_checkspidup(saidx, newspi) == NULL)
 4830                                 break;
 4831                 }
 4832 
 4833                 if (count == 0 || newspi == 0) {
 4834                         ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
 4835                         return 0;
 4836                 }
 4837         }
 4838 
 4839         /* statistics */
 4840         keystat.getspi_count =
 4841                 (keystat.getspi_count + key_spi_trycnt - count) / 2;
 4842 
 4843         return newspi;
 4844 }
 4845 
 4846 /*
 4847  * SADB_UPDATE processing
 4848  * receive
 4849  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
 4850  *       key(AE), (identity(SD),) (sensitivity)>
 4851  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
 4852  * and send
 4853  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
 4854  *       (identity(SD),) (sensitivity)>
 4855  * to the ikmpd.
 4856  *
 4857  * m will always be freed.
 4858  */
 4859 static int
 4860 key_update(so, m, mhp)
 4861         struct socket *so;
 4862         struct mbuf *m;
 4863         const struct sadb_msghdr *mhp;
 4864 {
 4865         struct sadb_sa *sa0;
 4866         struct sadb_address *src0, *dst0;
 4867         struct secasindex saidx;
 4868         struct secashead *sah;
 4869         struct secasvar *sav;
 4870         u_int16_t proto;
 4871         u_int8_t mode;
 4872         u_int32_t reqid;
 4873         int error;
 4874 
 4875         /* sanity check */
 4876         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 4877                 panic("key_update: NULL pointer is passed.\n");
 4878 
 4879         /* map satype to proto */
 4880         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 4881                 ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
 4882                 return key_senderror(so, m, EINVAL);
 4883         }
 4884 
 4885         if (mhp->ext[SADB_EXT_SA] == NULL ||
 4886             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 4887             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
 4888             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
 4889              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
 4890             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
 4891              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
 4892             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
 4893              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
 4894             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
 4895              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
 4896                 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
 4897                 return key_senderror(so, m, EINVAL);
 4898         }
 4899         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
 4900             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 4901             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 4902                 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
 4903                 return key_senderror(so, m, EINVAL);
 4904         }
 4905         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
 4906                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
 4907                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
 4908         } else {
 4909                 mode = IPSEC_MODE_ANY;
 4910                 reqid = 0;
 4911         }
 4912         /* XXX boundary checking for other extensions */
 4913 
 4914         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 4915         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
 4916         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
 4917 
 4918         /* XXX boundary check against sa_len */
 4919         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
 4920 
 4921         /* get a SA header */
 4922         if ((sah = key_getsah(&saidx)) == NULL) {
 4923                 ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
 4924                 return key_senderror(so, m, ENOENT);
 4925         }
 4926 
 4927         /* set spidx if there */
 4928         /* XXX rewrite */
 4929         error = key_setident(sah, m, mhp);
 4930         if (error)
 4931                 return key_senderror(so, m, error);
 4932 
 4933         /* find a SA with sequence number. */
 4934 #ifdef IPSEC_DOSEQCHECK
 4935         if (mhp->msg->sadb_msg_seq != 0
 4936          && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
 4937                 ipseclog((LOG_DEBUG,
 4938                     "key_update: no larval SA with sequence %u exists.\n",
 4939                     mhp->msg->sadb_msg_seq));
 4940                 return key_senderror(so, m, ENOENT);
 4941         }
 4942 #else
 4943         if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
 4944                 ipseclog((LOG_DEBUG,
 4945                     "key_update: no such a SA found (spi:%u)\n",
 4946                     (u_int32_t)ntohl(sa0->sadb_sa_spi)));
 4947                 return key_senderror(so, m, EINVAL);
 4948         }
 4949 #endif
 4950 
 4951         /* validity check */
 4952         if (sav->sah->saidx.proto != proto) {
 4953                 ipseclog((LOG_DEBUG,
 4954                     "key_update: protocol mismatched (DB=%u param=%u)\n",
 4955                     sav->sah->saidx.proto, proto));
 4956                 return key_senderror(so, m, EINVAL);
 4957         }
 4958 #ifdef IPSEC_DOSEQCHECK
 4959         if (sav->spi != sa0->sadb_sa_spi) {
 4960                 ipseclog((LOG_DEBUG,
 4961                     "key_update: SPI mismatched (DB:%u param:%u)\n",
 4962                     (u_int32_t)ntohl(sav->spi),
 4963                     (u_int32_t)ntohl(sa0->sadb_sa_spi)));
 4964                 return key_senderror(so, m, EINVAL);
 4965         }
 4966 #endif
 4967         if (sav->pid != mhp->msg->sadb_msg_pid) {
 4968                 ipseclog((LOG_DEBUG,
 4969                     "key_update: pid mismatched (DB:%u param:%u)\n",
 4970                     sav->pid, mhp->msg->sadb_msg_pid));
 4971                 return key_senderror(so, m, EINVAL);
 4972         }
 4973 
 4974         /* copy sav values */
 4975         error = key_setsaval(sav, m, mhp);
 4976         if (error) {
 4977                 KEY_FREESAV(&sav);
 4978                 return key_senderror(so, m, error);
 4979         }
 4980 
 4981         /* check SA values to be mature. */
 4982         if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
 4983                 KEY_FREESAV(&sav);
 4984                 return key_senderror(so, m, 0);
 4985         }
 4986 
 4987     {
 4988         struct mbuf *n;
 4989 
 4990         /* set msg buf from mhp */
 4991         n = key_getmsgbuf_x1(m, mhp);
 4992         if (n == NULL) {
 4993                 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
 4994                 return key_senderror(so, m, ENOBUFS);
 4995         }
 4996 
 4997         m_freem(m);
 4998         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 4999     }
 5000 }
 5001 
 5002 /*
 5003  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
 5004  * only called by key_update().
 5005  * OUT:
 5006  *      NULL    : not found
 5007  *      others  : found, pointer to a SA.
 5008  */
 5009 #ifdef IPSEC_DOSEQCHECK
 5010 static struct secasvar *
 5011 key_getsavbyseq(sah, seq)
 5012         struct secashead *sah;
 5013         u_int32_t seq;
 5014 {
 5015         struct secasvar *sav;
 5016         u_int state;
 5017 
 5018         state = SADB_SASTATE_LARVAL;
 5019 
 5020         /* search SAD with sequence number ? */
 5021         LIST_FOREACH(sav, &sah->savtree[state], chain) {
 5022 
 5023                 KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");
 5024 
 5025                 if (sav->seq == seq) {
 5026                         SA_ADDREF(sav);
 5027                         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 5028                                 printf("DP key_getsavbyseq cause "
 5029                                         "refcnt++:%d SA:%p\n",
 5030                                         sav->refcnt, sav));
 5031                         return sav;
 5032                 }
 5033         }
 5034 
 5035         return NULL;
 5036 }
 5037 #endif
 5038 
 5039 /*
 5040  * SADB_ADD processing
 5041  * add an entry to SA database, when received
 5042  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
 5043  *       key(AE), (identity(SD),) (sensitivity)>
 5044  * from the ikmpd,
 5045  * and send
 5046  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
 5047  *       (identity(SD),) (sensitivity)>
 5048  * to the ikmpd.
 5049  *
 5050  * IGNORE identity and sensitivity messages.
 5051  *
 5052  * m will always be freed.
 5053  */
 5054 static int
 5055 key_add(so, m, mhp)
 5056         struct socket *so;
 5057         struct mbuf *m;
 5058         const struct sadb_msghdr *mhp;
 5059 {
 5060         struct sadb_sa *sa0;
 5061         struct sadb_address *src0, *dst0;
 5062         struct secasindex saidx;
 5063         struct secashead *newsah;
 5064         struct secasvar *newsav;
 5065         u_int16_t proto;
 5066         u_int8_t mode;
 5067         u_int32_t reqid;
 5068         int error;
 5069 
 5070         /* sanity check */
 5071         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 5072                 panic("key_add: NULL pointer is passed.\n");
 5073 
 5074         /* map satype to proto */
 5075         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 5076                 ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
 5077                 return key_senderror(so, m, EINVAL);
 5078         }
 5079 
 5080         if (mhp->ext[SADB_EXT_SA] == NULL ||
 5081             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 5082             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
 5083             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
 5084              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
 5085             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
 5086              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
 5087             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
 5088              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
 5089             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
 5090              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
 5091                 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
 5092                 return key_senderror(so, m, EINVAL);
 5093         }
 5094         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
 5095             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 5096             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 5097                 /* XXX need more */
 5098                 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
 5099                 return key_senderror(so, m, EINVAL);
 5100         }
 5101         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
 5102                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
 5103                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
 5104         } else {
 5105                 mode = IPSEC_MODE_ANY;
 5106                 reqid = 0;
 5107         }
 5108 
 5109         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 5110         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
 5111         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 5112 
 5113         /* XXX boundary check against sa_len */
 5114         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
 5115 
 5116         /* get a SA header */
 5117         if ((newsah = key_getsah(&saidx)) == NULL) {
 5118                 /* create a new SA header */
 5119                 if ((newsah = key_newsah(&saidx)) == NULL) {
 5120                         ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
 5121                         return key_senderror(so, m, ENOBUFS);
 5122                 }
 5123         }
 5124 
 5125         /* set spidx if there */
 5126         /* XXX rewrite */
 5127         error = key_setident(newsah, m, mhp);
 5128         if (error) {
 5129                 return key_senderror(so, m, error);
 5130         }
 5131 
 5132         /* create new SA entry. */
 5133         /* We can create new SA only if SPI is differenct. */
 5134         if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
 5135                 ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
 5136                 return key_senderror(so, m, EEXIST);
 5137         }
 5138         newsav = KEY_NEWSAV(m, mhp, newsah, &error);
 5139         if (newsav == NULL) {
 5140                 return key_senderror(so, m, error);
 5141         }
 5142 
 5143         /* check SA values to be mature. */
 5144         if ((error = key_mature(newsav)) != 0) {
 5145                 KEY_FREESAV(&newsav);
 5146                 return key_senderror(so, m, error);
 5147         }
 5148 
 5149         /*
 5150          * don't call key_freesav() here, as we would like to keep the SA
 5151          * in the database on success.
 5152          */
 5153 
 5154     {
 5155         struct mbuf *n;
 5156 
 5157         /* set msg buf from mhp */
 5158         n = key_getmsgbuf_x1(m, mhp);
 5159         if (n == NULL) {
 5160                 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
 5161                 return key_senderror(so, m, ENOBUFS);
 5162         }
 5163 
 5164         m_freem(m);
 5165         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 5166     }
 5167 }
 5168 
 5169 /* m is retained */
 5170 static int
 5171 key_setident(sah, m, mhp)
 5172         struct secashead *sah;
 5173         struct mbuf *m;
 5174         const struct sadb_msghdr *mhp;
 5175 {
 5176         const struct sadb_ident *idsrc, *iddst;
 5177         int idsrclen, iddstlen;
 5178 
 5179         /* sanity check */
 5180         if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 5181                 panic("key_setident: NULL pointer is passed.\n");
 5182 
 5183         /* don't make buffer if not there */
 5184         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
 5185             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
 5186                 sah->idents = NULL;
 5187                 sah->identd = NULL;
 5188                 return 0;
 5189         }
 5190         
 5191         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
 5192             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
 5193                 ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
 5194                 return EINVAL;
 5195         }
 5196 
 5197         idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
 5198         iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
 5199         idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
 5200         iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
 5201 
 5202         /* validity check */
 5203         if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
 5204                 ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
 5205                 return EINVAL;
 5206         }
 5207 
 5208         switch (idsrc->sadb_ident_type) {
 5209         case SADB_IDENTTYPE_PREFIX:
 5210         case SADB_IDENTTYPE_FQDN:
 5211         case SADB_IDENTTYPE_USERFQDN:
 5212         default:
 5213                 /* XXX do nothing */
 5214                 sah->idents = NULL;
 5215                 sah->identd = NULL;
 5216                 return 0;
 5217         }
 5218 
 5219         /* make structure */
 5220         KMALLOC(sah->idents, struct sadb_ident *, idsrclen);
 5221         if (sah->idents == NULL) {
 5222                 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
 5223                 return ENOBUFS;
 5224         }
 5225         KMALLOC(sah->identd, struct sadb_ident *, iddstlen);
 5226         if (sah->identd == NULL) {
 5227                 KFREE(sah->idents);
 5228                 sah->idents = NULL;
 5229                 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
 5230                 return ENOBUFS;
 5231         }
 5232         bcopy(idsrc, sah->idents, idsrclen);
 5233         bcopy(iddst, sah->identd, iddstlen);
 5234 
 5235         return 0;
 5236 }
 5237 
 5238 /*
 5239  * m will not be freed on return.
 5240  * it is caller's responsibility to free the result. 
 5241  */
 5242 static struct mbuf *
 5243 key_getmsgbuf_x1(m, mhp)
 5244         struct mbuf *m;
 5245         const struct sadb_msghdr *mhp;
 5246 {
 5247         struct mbuf *n;
 5248 
 5249         /* sanity check */
 5250         if (m == NULL || mhp == NULL || mhp->msg == NULL)
 5251                 panic("key_getmsgbuf_x1: NULL pointer is passed.\n");
 5252 
 5253         /* create new sadb_msg to reply. */
 5254         n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
 5255             SADB_EXT_SA, SADB_X_EXT_SA2,
 5256             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
 5257             SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
 5258             SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
 5259         if (!n)
 5260                 return NULL;
 5261 
 5262         if (n->m_len < sizeof(struct sadb_msg)) {
 5263                 n = m_pullup(n, sizeof(struct sadb_msg));
 5264                 if (n == NULL)
 5265                         return NULL;
 5266         }
 5267         mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
 5268         mtod(n, struct sadb_msg *)->sadb_msg_len =
 5269             PFKEY_UNIT64(n->m_pkthdr.len);
 5270 
 5271         return n;
 5272 }
 5273 
 5274 static int key_delete_all __P((struct socket *, struct mbuf *,
 5275         const struct sadb_msghdr *, u_int16_t));
 5276 
 5277 /*
 5278  * SADB_DELETE processing
 5279  * receive
 5280  *   <base, SA(*), address(SD)>
 5281  * from the ikmpd, and set SADB_SASTATE_DEAD,
 5282  * and send,
 5283  *   <base, SA(*), address(SD)>
 5284  * to the ikmpd.
 5285  *
 5286  * m will always be freed.
 5287  */
 5288 static int
 5289 key_delete(so, m, mhp)
 5290         struct socket *so;
 5291         struct mbuf *m;
 5292         const struct sadb_msghdr *mhp;
 5293 {
 5294         struct sadb_sa *sa0;
 5295         struct sadb_address *src0, *dst0;
 5296         struct secasindex saidx;
 5297         struct secashead *sah;
 5298         struct secasvar *sav = NULL;
 5299         u_int16_t proto;
 5300 
 5301         /* sanity check */
 5302         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 5303                 panic("key_delete: NULL pointer is passed.\n");
 5304 
 5305         /* map satype to proto */
 5306         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 5307                 ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
 5308                 return key_senderror(so, m, EINVAL);
 5309         }
 5310 
 5311         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 5312             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
 5313                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
 5314                 return key_senderror(so, m, EINVAL);
 5315         }
 5316 
 5317         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 5318             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 5319                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
 5320                 return key_senderror(so, m, EINVAL);
 5321         }
 5322 
 5323         if (mhp->ext[SADB_EXT_SA] == NULL) {
 5324                 /*
 5325                  * Caller wants us to delete all non-LARVAL SAs
 5326                  * that match the src/dst.  This is used during
 5327                  * IKE INITIAL-CONTACT.
 5328                  */
 5329                 ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
 5330                 return key_delete_all(so, m, mhp, proto);
 5331         } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
 5332                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
 5333                 return key_senderror(so, m, EINVAL);
 5334         }
 5335 
 5336         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 5337         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
 5338         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
 5339 
 5340         /* XXX boundary check against sa_len */
 5341         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
 5342 
 5343         /* get a SA header */
 5344         LIST_FOREACH(sah, &sahtree, chain) {
 5345                 if (sah->state == SADB_SASTATE_DEAD)
 5346                         continue;
 5347                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
 5348                         continue;
 5349 
 5350                 /* get a SA with SPI. */
 5351                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
 5352                 if (sav)
 5353                         break;
 5354         }
 5355         if (sah == NULL) {
 5356                 ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
 5357                 return key_senderror(so, m, ENOENT);
 5358         }
 5359 
 5360         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 5361         KEY_FREESAV(&sav);
 5362 
 5363     {
 5364         struct mbuf *n;
 5365         struct sadb_msg *newmsg;
 5366 
 5367         /* create new sadb_msg to reply. */
 5368         n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
 5369             SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 5370         if (!n)
 5371                 return key_senderror(so, m, ENOBUFS);
 5372 
 5373         if (n->m_len < sizeof(struct sadb_msg)) {
 5374                 n = m_pullup(n, sizeof(struct sadb_msg));
 5375                 if (n == NULL)
 5376                         return key_senderror(so, m, ENOBUFS);
 5377         }
 5378         newmsg = mtod(n, struct sadb_msg *);
 5379         newmsg->sadb_msg_errno = 0;
 5380         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 5381 
 5382         m_freem(m);
 5383         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 5384     }
 5385 }
 5386 
 5387 /*
 5388  * delete all SAs for src/dst.  Called from key_delete().
 5389  */
 5390 static int
 5391 key_delete_all(so, m, mhp, proto)
 5392         struct socket *so;
 5393         struct mbuf *m;
 5394         const struct sadb_msghdr *mhp;
 5395         u_int16_t proto;
 5396 {
 5397         struct sadb_address *src0, *dst0;
 5398         struct secasindex saidx;
 5399         struct secashead *sah;
 5400         struct secasvar *sav, *nextsav;
 5401         u_int stateidx, state;
 5402 
 5403         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
 5404         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
 5405 
 5406         /* XXX boundary check against sa_len */
 5407         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
 5408 
 5409         LIST_FOREACH(sah, &sahtree, chain) {
 5410                 if (sah->state == SADB_SASTATE_DEAD)
 5411                         continue;
 5412                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
 5413                         continue;
 5414 
 5415                 /* Delete all non-LARVAL SAs. */
 5416                 for (stateidx = 0;
 5417                      stateidx < _ARRAYLEN(saorder_state_alive);
 5418                      stateidx++) {
 5419                         state = saorder_state_alive[stateidx];
 5420                         if (state == SADB_SASTATE_LARVAL)
 5421                                 continue;
 5422                         for (sav = LIST_FIRST(&sah->savtree[state]);
 5423                              sav != NULL; sav = nextsav) {
 5424                                 nextsav = LIST_NEXT(sav, chain);
 5425                                 /* sanity check */
 5426                                 if (sav->state != state) {
 5427                                         ipseclog((LOG_DEBUG, "key_delete_all: "
 5428                                                "invalid sav->state "
 5429                                                "(queue: %d SA: %d)\n",
 5430                                                state, sav->state));
 5431                                         continue;
 5432                                 }
 5433                                 
 5434                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 5435                                 KEY_FREESAV(&sav);
 5436                         }
 5437                 }
 5438         }
 5439     {
 5440         struct mbuf *n;
 5441         struct sadb_msg *newmsg;
 5442 
 5443         /* create new sadb_msg to reply. */
 5444         n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
 5445             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 5446         if (!n)
 5447                 return key_senderror(so, m, ENOBUFS);
 5448 
 5449         if (n->m_len < sizeof(struct sadb_msg)) {
 5450                 n = m_pullup(n, sizeof(struct sadb_msg));
 5451                 if (n == NULL)
 5452                         return key_senderror(so, m, ENOBUFS);
 5453         }
 5454         newmsg = mtod(n, struct sadb_msg *);
 5455         newmsg->sadb_msg_errno = 0;
 5456         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 5457 
 5458         m_freem(m);
 5459         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 5460     }
 5461 }
 5462 
 5463 /*
 5464  * SADB_GET processing
 5465  * receive
 5466  *   <base, SA(*), address(SD)>
 5467  * from the ikmpd, and get a SP and a SA to respond,
 5468  * and send,
 5469  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
 5470  *       (identity(SD),) (sensitivity)>
 5471  * to the ikmpd.
 5472  *
 5473  * m will always be freed.
 5474  */
 5475 static int
 5476 key_get(so, m, mhp)
 5477         struct socket *so;
 5478         struct mbuf *m;
 5479         const struct sadb_msghdr *mhp;
 5480 {
 5481         struct sadb_sa *sa0;
 5482         struct sadb_address *src0, *dst0;
 5483         struct secasindex saidx;
 5484         struct secashead *sah;
 5485         struct secasvar *sav = NULL;
 5486         u_int16_t proto;
 5487 
 5488         /* sanity check */
 5489         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 5490                 panic("key_get: NULL pointer is passed.\n");
 5491 
 5492         /* map satype to proto */
 5493         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 5494                 ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
 5495                 return key_senderror(so, m, EINVAL);
 5496         }
 5497 
 5498         if (mhp->ext[SADB_EXT_SA] == NULL ||
 5499             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 5500             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
 5501                 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
 5502                 return key_senderror(so, m, EINVAL);
 5503         }
 5504         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
 5505             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 5506             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 5507                 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
 5508                 return key_senderror(so, m, EINVAL);
 5509         }
 5510 
 5511         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 5512         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
 5513         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 5514 
 5515         /* XXX boundary check against sa_len */
 5516         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
 5517 
 5518         /* get a SA header */
 5519         LIST_FOREACH(sah, &sahtree, chain) {
 5520                 if (sah->state == SADB_SASTATE_DEAD)
 5521                         continue;
 5522                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
 5523                         continue;
 5524 
 5525                 /* get a SA with SPI. */
 5526                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
 5527                 if (sav)
 5528                         break;
 5529         }
 5530         if (sah == NULL) {
 5531                 ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
 5532                 return key_senderror(so, m, ENOENT);
 5533         }
 5534 
 5535     {
 5536         struct mbuf *n;
 5537         u_int8_t satype;
 5538 
 5539         /* map proto to satype */
 5540         if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
 5541                 ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
 5542                 return key_senderror(so, m, EINVAL);
 5543         }
 5544 
 5545         /* create new sadb_msg to reply. */
 5546         n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
 5547             mhp->msg->sadb_msg_pid);
 5548         if (!n)
 5549                 return key_senderror(so, m, ENOBUFS);
 5550 
 5551         m_freem(m);
 5552         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
 5553     }
 5554 }
 5555 
 5556 /* XXX make it sysctl-configurable? */
 5557 static void
 5558 key_getcomb_setlifetime(comb)
 5559         struct sadb_comb *comb;
 5560 {
 5561 
 5562         comb->sadb_comb_soft_allocations = 1;
 5563         comb->sadb_comb_hard_allocations = 1;
 5564         comb->sadb_comb_soft_bytes = 0;
 5565         comb->sadb_comb_hard_bytes = 0;
 5566         comb->sadb_comb_hard_addtime = 86400;   /* 1 day */
 5567         comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
 5568         comb->sadb_comb_soft_usetime = 28800;   /* 8 hours */
 5569         comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
 5570 }
 5571 
 5572 /*
 5573  * XXX reorder combinations by preference
 5574  * XXX no idea if the user wants ESP authentication or not
 5575  */
 5576 static struct mbuf *
 5577 key_getcomb_esp()
 5578 {
 5579         struct sadb_comb *comb;
 5580         struct enc_xform *algo;
 5581         struct mbuf *result = NULL, *m, *n;
 5582         int encmin;
 5583         int i, off, o;
 5584         int totlen;
 5585         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
 5586 
 5587         m = NULL;
 5588         for (i = 1; i <= SADB_EALG_MAX; i++) {
 5589                 algo = esp_algorithm_lookup(i);
 5590                 if (algo == NULL)
 5591                         continue;
 5592 
 5593                 /* discard algorithms with key size smaller than system min */
 5594                 if (_BITS(algo->maxkey) < ipsec_esp_keymin)
 5595                         continue;
 5596                 if (_BITS(algo->minkey) < ipsec_esp_keymin)
 5597                         encmin = ipsec_esp_keymin;
 5598                 else
 5599                         encmin = _BITS(algo->minkey);
 5600 
 5601                 if (ipsec_esp_auth)
 5602                         m = key_getcomb_ah();
 5603                 else {
 5604                         IPSEC_ASSERT(l <= MLEN,
 5605                                 ("key_getcomb_esp: l=%u > MLEN=%lu",
 5606                                 l, (u_long) MLEN));
 5607                         MGET(m, M_DONTWAIT, MT_DATA);
 5608                         if (m) {
 5609                                 M_ALIGN(m, l);
 5610                                 m->m_len = l;
 5611                                 m->m_next = NULL;
 5612                                 bzero(mtod(m, caddr_t), m->m_len);
 5613                         }
 5614                 }
 5615                 if (!m)
 5616                         goto fail;
 5617 
 5618                 totlen = 0;
 5619                 for (n = m; n; n = n->m_next)
 5620                         totlen += n->m_len;
 5621                 IPSEC_ASSERT((totlen % l) == 0,
 5622                         ("key_getcomb_esp: totlen=%u, l=%u", totlen, l));
 5623 
 5624                 for (off = 0; off < totlen; off += l) {
 5625                         n = m_pulldown(m, off, l, &o);
 5626                         if (!n) {
 5627                                 /* m is already freed */
 5628                                 goto fail;
 5629                         }
 5630                         comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
 5631                         bzero(comb, sizeof(*comb));
 5632                         key_getcomb_setlifetime(comb);
 5633                         comb->sadb_comb_encrypt = i;
 5634                         comb->sadb_comb_encrypt_minbits = encmin;
 5635                         comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
 5636                 }
 5637 
 5638                 if (!result)
 5639                         result = m;
 5640                 else
 5641                         m_cat(result, m);
 5642         }
 5643 
 5644         return result;
 5645 
 5646  fail:
 5647         if (result)
 5648                 m_freem(result);
 5649         return NULL;
 5650 }
 5651 
 5652 static void
 5653 key_getsizes_ah(
 5654         const struct auth_hash *ah,
 5655         int alg,
 5656         u_int16_t* min,
 5657         u_int16_t* max)
 5658 {
 5659         *min = *max = ah->keysize;
 5660         if (ah->keysize == 0) {
 5661                 /*
 5662                  * Transform takes arbitrary key size but algorithm
 5663                  * key size is restricted.  Enforce this here.
 5664                  */
 5665                 switch (alg) {
 5666                 case SADB_X_AALG_MD5:   *min = *max = 16; break;
 5667                 case SADB_X_AALG_SHA:   *min = *max = 20; break;
 5668                 case SADB_X_AALG_NULL:  *min = 1; *max = 256; break;
 5669                 default:
 5670                         DPRINTF(("key_getsizes_ah: unknown AH algorithm %u\n",
 5671                                 alg));
 5672                         break;
 5673                 }
 5674         }
 5675 }
 5676 
 5677 /*
 5678  * XXX reorder combinations by preference
 5679  */
 5680 static struct mbuf *
 5681 key_getcomb_ah()
 5682 {
 5683         struct sadb_comb *comb;
 5684         struct auth_hash *algo;
 5685         struct mbuf *m;
 5686         u_int16_t minkeysize, maxkeysize;
 5687         int i;
 5688         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
 5689 
 5690         m = NULL;
 5691         for (i = 1; i <= SADB_AALG_MAX; i++) {
 5692 #if 1
 5693                 /* we prefer HMAC algorithms, not old algorithms */
 5694                 if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
 5695                         continue;
 5696 #endif
 5697                 algo = ah_algorithm_lookup(i);
 5698                 if (!algo)
 5699                         continue;
 5700                 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
 5701                 /* discard algorithms with key size smaller than system min */
 5702                 if (_BITS(minkeysize) < ipsec_ah_keymin)
 5703                         continue;
 5704 
 5705                 if (!m) {
 5706                         IPSEC_ASSERT(l <= MLEN,
 5707                                 ("key_getcomb_ah: l=%u > MLEN=%lu",
 5708                                 l, (u_long) MLEN));
 5709                         MGET(m, M_DONTWAIT, MT_DATA);
 5710                         if (m) {
 5711                                 M_ALIGN(m, l);
 5712                                 m->m_len = l;
 5713                                 m->m_next = NULL;
 5714                         }
 5715                 } else
 5716                         M_PREPEND(m, l, M_DONTWAIT);
 5717                 if (!m)
 5718                         return NULL;
 5719 
 5720                 comb = mtod(m, struct sadb_comb *);
 5721                 bzero(comb, sizeof(*comb));
 5722                 key_getcomb_setlifetime(comb);
 5723                 comb->sadb_comb_auth = i;
 5724                 comb->sadb_comb_auth_minbits = _BITS(minkeysize);
 5725                 comb->sadb_comb_auth_maxbits = _BITS(maxkeysize);
 5726         }
 5727 
 5728         return m;
 5729 }
 5730 
 5731 /*
 5732  * not really an official behavior.  discussed in pf_key@inner.net in Sep2000.
 5733  * XXX reorder combinations by preference
 5734  */
 5735 static struct mbuf *
 5736 key_getcomb_ipcomp()
 5737 {
 5738         struct sadb_comb *comb;
 5739         struct comp_algo *algo;
 5740         struct mbuf *m;
 5741         int i;
 5742         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
 5743 
 5744         m = NULL;
 5745         for (i = 1; i <= SADB_X_CALG_MAX; i++) {
 5746                 algo = ipcomp_algorithm_lookup(i);
 5747                 if (!algo)
 5748                         continue;
 5749 
 5750                 if (!m) {
 5751                         IPSEC_ASSERT(l <= MLEN,
 5752                                 ("key_getcomb_ipcomp: l=%u > MLEN=%lu",
 5753                                 l, (u_long) MLEN));
 5754                         MGET(m, M_DONTWAIT, MT_DATA);
 5755                         if (m) {
 5756                                 M_ALIGN(m, l);
 5757                                 m->m_len = l;
 5758                                 m->m_next = NULL;
 5759                         }
 5760                 } else
 5761                         M_PREPEND(m, l, M_DONTWAIT);
 5762                 if (!m)
 5763                         return NULL;
 5764 
 5765                 comb = mtod(m, struct sadb_comb *);
 5766                 bzero(comb, sizeof(*comb));
 5767                 key_getcomb_setlifetime(comb);
 5768                 comb->sadb_comb_encrypt = i;
 5769                 /* what should we set into sadb_comb_*_{min,max}bits? */
 5770         }
 5771 
 5772         return m;
 5773 }
 5774 
 5775 /*
 5776  * XXX no way to pass mode (transport/tunnel) to userland
 5777  * XXX replay checking?
 5778  * XXX sysctl interface to ipsec_{ah,esp}_keymin
 5779  */
 5780 static struct mbuf *
 5781 key_getprop(saidx)
 5782         const struct secasindex *saidx;
 5783 {
 5784         struct sadb_prop *prop;
 5785         struct mbuf *m, *n;
 5786         const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
 5787         int totlen;
 5788 
 5789         switch (saidx->proto)  {
 5790         case IPPROTO_ESP:
 5791                 m = key_getcomb_esp();
 5792                 break;
 5793         case IPPROTO_AH:
 5794                 m = key_getcomb_ah();
 5795                 break;
 5796         case IPPROTO_IPCOMP:
 5797                 m = key_getcomb_ipcomp();
 5798                 break;
 5799         default:
 5800                 return NULL;
 5801         }
 5802 
 5803         if (!m)
 5804                 return NULL;
 5805         M_PREPEND(m, l, M_DONTWAIT);
 5806         if (!m)
 5807                 return NULL;
 5808 
 5809         totlen = 0;
 5810         for (n = m; n; n = n->m_next)
 5811                 totlen += n->m_len;
 5812 
 5813         prop = mtod(m, struct sadb_prop *);
 5814         bzero(prop, sizeof(*prop));
 5815         prop->sadb_prop_len = PFKEY_UNIT64(totlen);
 5816         prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
 5817         prop->sadb_prop_replay = 32;    /* XXX */
 5818 
 5819         return m;
 5820 }
 5821 
 5822 /*
 5823  * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
 5824  * send
 5825  *   <base, SA, address(SD), (address(P)), x_policy,
 5826  *       (identity(SD),) (sensitivity,) proposal>
 5827  * to KMD, and expect to receive
 5828  *   <base> with SADB_ACQUIRE if error occurred,
 5829  * or
 5830  *   <base, src address, dst address, (SPI range)> with SADB_GETSPI
 5831  * from KMD by PF_KEY.
 5832  *
 5833  * XXX x_policy is outside of RFC2367 (KAME extension).
 5834  * XXX sensitivity is not supported.
 5835  * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
 5836  * see comment for key_getcomb_ipcomp().
 5837  *
 5838  * OUT:
 5839  *    0     : succeed
 5840  *    others: error number
 5841  */
 5842 static int
 5843 key_acquire(const struct secasindex *saidx, struct secpolicy *sp)
 5844 {
 5845         struct mbuf *result = NULL, *m;
 5846 #ifndef IPSEC_NONBLOCK_ACQUIRE
 5847         struct secacq *newacq;
 5848 #endif
 5849         u_int8_t satype;
 5850         int error = -1;
 5851         u_int32_t seq;
 5852 
 5853         /* sanity check */
 5854         IPSEC_ASSERT(saidx != NULL, ("key_acquire: null saidx"));
 5855         satype = key_proto2satype(saidx->proto);
 5856         IPSEC_ASSERT(satype != 0,
 5857                 ("key_acquire: null satype, protocol %u", saidx->proto));
 5858 
 5859 #ifndef IPSEC_NONBLOCK_ACQUIRE
 5860         /*
 5861          * We never do anything about acquirng SA.  There is anather
 5862          * solution that kernel blocks to send SADB_ACQUIRE message until
 5863          * getting something message from IKEd.  In later case, to be
 5864          * managed with ACQUIRING list.
 5865          */
 5866         /* Get an entry to check whether sending message or not. */
 5867         if ((newacq = key_getacq(saidx)) != NULL) {
 5868                 if (key_blockacq_count < newacq->count) {
 5869                         /* reset counter and do send message. */
 5870                         newacq->count = 0;
 5871                 } else {
 5872                         /* increment counter and do nothing. */
 5873                         newacq->count++;
 5874                         return 0;
 5875                 }
 5876         } else {
 5877                 /* make new entry for blocking to send SADB_ACQUIRE. */
 5878                 if ((newacq = key_newacq(saidx)) == NULL)
 5879                         return ENOBUFS;
 5880 
 5881                 /* add to acqtree */
 5882                 LIST_INSERT_HEAD(&acqtree, newacq, chain);
 5883         }
 5884 #endif
 5885 
 5886 
 5887 #ifndef IPSEC_NONBLOCK_ACQUIRE
 5888         seq = newacq->seq;
 5889 #else
 5890         seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
 5891 #endif
 5892         m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
 5893         if (!m) {
 5894                 error = ENOBUFS;
 5895                 goto fail;
 5896         }
 5897         result = m;
 5898 
 5899         /* set sadb_address for saidx's. */
 5900         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
 5901             &saidx->src.sa, FULLMASK, IPSEC_ULPROTO_ANY);
 5902         if (!m) {
 5903                 error = ENOBUFS;
 5904                 goto fail;
 5905         }
 5906         m_cat(result, m);
 5907 
 5908         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
 5909             &saidx->dst.sa, FULLMASK, IPSEC_ULPROTO_ANY);
 5910         if (!m) {
 5911                 error = ENOBUFS;
 5912                 goto fail;
 5913         }
 5914         m_cat(result, m);
 5915 
 5916         /* XXX proxy address (optional) */
 5917 
 5918         /* set sadb_x_policy */
 5919         if (sp) {
 5920                 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
 5921                 if (!m) {
 5922                         error = ENOBUFS;
 5923                         goto fail;
 5924                 }
 5925                 m_cat(result, m);
 5926         }
 5927 
 5928         /* XXX identity (optional) */
 5929 #if 0
 5930         if (idexttype && fqdn) {
 5931                 /* create identity extension (FQDN) */
 5932                 struct sadb_ident *id;
 5933                 int fqdnlen;
 5934 
 5935                 fqdnlen = strlen(fqdn) + 1;     /* +1 for terminating-NUL */
 5936                 id = (struct sadb_ident *)p;
 5937                 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
 5938                 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
 5939                 id->sadb_ident_exttype = idexttype;
 5940                 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
 5941                 bcopy(fqdn, id + 1, fqdnlen);
 5942                 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
 5943         }
 5944 
 5945         if (idexttype) {
 5946                 /* create identity extension (USERFQDN) */
 5947                 struct sadb_ident *id;
 5948                 int userfqdnlen;
 5949 
 5950                 if (userfqdn) {
 5951                         /* +1 for terminating-NUL */
 5952                         userfqdnlen = strlen(userfqdn) + 1;
 5953                 } else
 5954                         userfqdnlen = 0;
 5955                 id = (struct sadb_ident *)p;
 5956                 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
 5957                 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
 5958                 id->sadb_ident_exttype = idexttype;
 5959                 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
 5960                 /* XXX is it correct? */
 5961                 if (curproc && curproc->p_cred)
 5962                         id->sadb_ident_id = curproc->p_cred->p_ruid;
 5963                 if (userfqdn && userfqdnlen)
 5964                         bcopy(userfqdn, id + 1, userfqdnlen);
 5965                 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
 5966         }
 5967 #endif
 5968 
 5969         /* XXX sensitivity (optional) */
 5970 
 5971         /* create proposal/combination extension */
 5972         m = key_getprop(saidx);
 5973 #if 0
 5974         /*
 5975          * spec conformant: always attach proposal/combination extension,
 5976          * the problem is that we have no way to attach it for ipcomp,
 5977          * due to the way sadb_comb is declared in RFC2367.
 5978          */
 5979         if (!m) {
 5980                 error = ENOBUFS;
 5981                 goto fail;
 5982         }
 5983         m_cat(result, m);
 5984 #else
 5985         /*
 5986          * outside of spec; make proposal/combination extension optional.
 5987          */
 5988         if (m)
 5989                 m_cat(result, m);
 5990 #endif
 5991 
 5992         if ((result->m_flags & M_PKTHDR) == 0) {
 5993                 error = EINVAL;
 5994                 goto fail;
 5995         }
 5996 
 5997         if (result->m_len < sizeof(struct sadb_msg)) {
 5998                 result = m_pullup(result, sizeof(struct sadb_msg));
 5999                 if (result == NULL) {
 6000                         error = ENOBUFS;
 6001                         goto fail;
 6002                 }
 6003         }
 6004 
 6005         result->m_pkthdr.len = 0;
 6006         for (m = result; m; m = m->m_next)
 6007                 result->m_pkthdr.len += m->m_len;
 6008 
 6009         mtod(result, struct sadb_msg *)->sadb_msg_len =
 6010             PFKEY_UNIT64(result->m_pkthdr.len);
 6011 
 6012         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
 6013 
 6014  fail:
 6015         if (result)
 6016                 m_freem(result);
 6017         return error;
 6018 }
 6019 
 6020 #ifndef IPSEC_NONBLOCK_ACQUIRE
 6021 static struct secacq *
 6022 key_newacq(const struct secasindex *saidx)
 6023 {
 6024         struct secacq *newacq;
 6025 
 6026         /* get new entry */
 6027         KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
 6028         if (newacq == NULL) {
 6029                 ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
 6030                 return NULL;
 6031         }
 6032         bzero(newacq, sizeof(*newacq));
 6033 
 6034         /* copy secindex */
 6035         bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
 6036         newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
 6037         newacq->created = time_second;
 6038         newacq->count = 0;
 6039 
 6040         return newacq;
 6041 }
 6042 
 6043 static struct secacq *
 6044 key_getacq(const struct secasindex *saidx)
 6045 {
 6046         struct secacq *acq;
 6047 
 6048         LIST_FOREACH(acq, &acqtree, chain) {
 6049                 if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
 6050                         return acq;
 6051         }
 6052 
 6053         return NULL;
 6054 }
 6055 
 6056 static struct secacq *
 6057 key_getacqbyseq(seq)
 6058         u_int32_t seq;
 6059 {
 6060         struct secacq *acq;
 6061 
 6062         LIST_FOREACH(acq, &acqtree, chain) {
 6063                 if (acq->seq == seq)
 6064                         return acq;
 6065         }
 6066 
 6067         return NULL;
 6068 }
 6069 #endif
 6070 
 6071 static struct secspacq *
 6072 key_newspacq(spidx)
 6073         struct secpolicyindex *spidx;
 6074 {
 6075         struct secspacq *acq;
 6076 
 6077         /* get new entry */
 6078         KMALLOC(acq, struct secspacq *, sizeof(struct secspacq));
 6079         if (acq == NULL) {
 6080                 ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
 6081                 return NULL;
 6082         }
 6083         bzero(acq, sizeof(*acq));
 6084 
 6085         /* copy secindex */
 6086         bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
 6087         acq->created = time_second;
 6088         acq->count = 0;
 6089 
 6090         return acq;
 6091 }
 6092 
 6093 static struct secspacq *
 6094 key_getspacq(spidx)
 6095         struct secpolicyindex *spidx;
 6096 {
 6097         struct secspacq *acq;
 6098 
 6099         LIST_FOREACH(acq, &spacqtree, chain) {
 6100                 if (key_cmpspidx_exactly(spidx, &acq->spidx))
 6101                         return acq;
 6102         }
 6103 
 6104         return NULL;
 6105 }
 6106 
 6107 /*
 6108  * SADB_ACQUIRE processing,
 6109  * in first situation, is receiving
 6110  *   <base>
 6111  * from the ikmpd, and clear sequence of its secasvar entry.
 6112  *
 6113  * In second situation, is receiving
 6114  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
 6115  * from a user land process, and return
 6116  *   <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
 6117  * to the socket.
 6118  *
 6119  * m will always be freed.
 6120  */
 6121 static int
 6122 key_acquire2(so, m, mhp)
 6123         struct socket *so;
 6124         struct mbuf *m;
 6125         const struct sadb_msghdr *mhp;
 6126 {
 6127         const struct sadb_address *src0, *dst0;
 6128         struct secasindex saidx;
 6129         struct secashead *sah;
 6130         u_int16_t proto;
 6131         int error;
 6132 
 6133         /* sanity check */
 6134         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 6135                 panic("key_acquire2: NULL pointer is passed.\n");
 6136 
 6137         /*
 6138          * Error message from KMd.
 6139          * We assume that if error was occurred in IKEd, the length of PFKEY
 6140          * message is equal to the size of sadb_msg structure.
 6141          * We do not raise error even if error occurred in this function.
 6142          */
 6143         if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
 6144 #ifndef IPSEC_NONBLOCK_ACQUIRE
 6145                 struct secacq *acq;
 6146 
 6147                 /* check sequence number */
 6148                 if (mhp->msg->sadb_msg_seq == 0) {
 6149                         ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
 6150                         m_freem(m);
 6151                         return 0;
 6152                 }
 6153 
 6154                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
 6155                         /*
 6156                          * the specified larval SA is already gone, or we got
 6157                          * a bogus sequence number.  we can silently ignore it.
 6158                          */
 6159                         m_freem(m);
 6160                         return 0;
 6161                 }
 6162 
 6163                 /* reset acq counter in order to deletion by timehander. */
 6164                 acq->created = time_second;
 6165                 acq->count = 0;
 6166 #endif
 6167                 m_freem(m);
 6168                 return 0;
 6169         }
 6170 
 6171         /*
 6172          * This message is from user land.
 6173          */
 6174 
 6175         /* map satype to proto */
 6176         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 6177                 ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
 6178                 return key_senderror(so, m, EINVAL);
 6179         }
 6180 
 6181         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 6182             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
 6183             mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
 6184                 /* error */
 6185                 ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
 6186                 return key_senderror(so, m, EINVAL);
 6187         }
 6188         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 6189             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
 6190             mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
 6191                 /* error */
 6192                 ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
 6193                 return key_senderror(so, m, EINVAL);
 6194         }
 6195 
 6196         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
 6197         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 6198 
 6199         /* XXX boundary check against sa_len */
 6200         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
 6201 
 6202         /* get a SA index */
 6203         LIST_FOREACH(sah, &sahtree, chain) {
 6204                 if (sah->state == SADB_SASTATE_DEAD)
 6205                         continue;
 6206                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
 6207                         break;
 6208         }
 6209         if (sah != NULL) {
 6210                 ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
 6211                 return key_senderror(so, m, EEXIST);
 6212         }
 6213 
 6214         error = key_acquire(&saidx, NULL);
 6215         if (error != 0) {
 6216                 ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
 6217                         "from key_acquire.\n", mhp->msg->sadb_msg_errno));
 6218                 return key_senderror(so, m, error);
 6219         }
 6220 
 6221         return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
 6222 }
 6223 
 6224 /*
 6225  * SADB_REGISTER processing.
 6226  * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
 6227  * receive
 6228  *   <base>
 6229  * from the ikmpd, and register a socket to send PF_KEY messages,
 6230  * and send
 6231  *   <base, supported>
 6232  * to KMD by PF_KEY.
 6233  * If socket is detached, must free from regnode.
 6234  *
 6235  * m will always be freed.
 6236  */
 6237 static int
 6238 key_register(so, m, mhp)
 6239         struct socket *so;
 6240         struct mbuf *m;
 6241         const struct sadb_msghdr *mhp;
 6242 {
 6243         struct secreg *reg, *newreg = 0;
 6244 
 6245         /* sanity check */
 6246         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 6247                 panic("key_register: NULL pointer is passed.\n");
 6248 
 6249         /* check for invalid register message */
 6250         if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
 6251                 return key_senderror(so, m, EINVAL);
 6252 
 6253         /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
 6254         if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
 6255                 goto setmsg;
 6256 
 6257         /* check whether existing or not */
 6258         LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
 6259                 if (reg->so == so) {
 6260                         ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
 6261                         return key_senderror(so, m, EEXIST);
 6262                 }
 6263         }
 6264 
 6265         /* create regnode */
 6266         KMALLOC(newreg, struct secreg *, sizeof(*newreg));
 6267         if (newreg == NULL) {
 6268                 ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
 6269                 return key_senderror(so, m, ENOBUFS);
 6270         }
 6271         bzero((caddr_t)newreg, sizeof(*newreg));
 6272 
 6273         newreg->so = so;
 6274         ((struct keycb *)sotorawcb(so))->kp_registered++;
 6275 
 6276         /* add regnode to regtree. */
 6277         LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
 6278 
 6279   setmsg:
 6280     {
 6281         struct mbuf *n;
 6282         struct sadb_msg *newmsg;
 6283         struct sadb_supported *sup;
 6284         u_int len, alen, elen;
 6285         int off;
 6286         int i;
 6287         struct sadb_alg *alg;
 6288 
 6289         /* create new sadb_msg to reply. */
 6290         alen = 0;
 6291         for (i = 1; i <= SADB_AALG_MAX; i++) {
 6292                 if (ah_algorithm_lookup(i))
 6293                         alen += sizeof(struct sadb_alg);
 6294         }
 6295         if (alen)
 6296                 alen += sizeof(struct sadb_supported);
 6297         elen = 0;
 6298         for (i = 1; i <= SADB_EALG_MAX; i++) {
 6299                 if (esp_algorithm_lookup(i))
 6300                         elen += sizeof(struct sadb_alg);
 6301         }
 6302         if (elen)
 6303                 elen += sizeof(struct sadb_supported);
 6304 
 6305         len = sizeof(struct sadb_msg) + alen + elen;
 6306 
 6307         if (len > MCLBYTES)
 6308                 return key_senderror(so, m, ENOBUFS);
 6309 
 6310         MGETHDR(n, M_DONTWAIT, MT_DATA);
 6311         if (len > MHLEN) {
 6312                 MCLGET(n, M_DONTWAIT);
 6313                 if ((n->m_flags & M_EXT) == 0) {
 6314                         m_freem(n);
 6315                         n = NULL;
 6316                 }
 6317         }
 6318         if (!n)
 6319                 return key_senderror(so, m, ENOBUFS);
 6320 
 6321         n->m_pkthdr.len = n->m_len = len;
 6322         n->m_next = NULL;
 6323         off = 0;
 6324 
 6325         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
 6326         newmsg = mtod(n, struct sadb_msg *);
 6327         newmsg->sadb_msg_errno = 0;
 6328         newmsg->sadb_msg_len = PFKEY_UNIT64(len);
 6329         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
 6330 
 6331         /* for authentication algorithm */
 6332         if (alen) {
 6333                 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
 6334                 sup->sadb_supported_len = PFKEY_UNIT64(alen);
 6335                 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
 6336                 off += PFKEY_ALIGN8(sizeof(*sup));
 6337 
 6338                 for (i = 1; i <= SADB_AALG_MAX; i++) {
 6339                         struct auth_hash *aalgo;
 6340                         u_int16_t minkeysize, maxkeysize;
 6341 
 6342                         aalgo = ah_algorithm_lookup(i);
 6343                         if (!aalgo)
 6344                                 continue;
 6345                         alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
 6346                         alg->sadb_alg_id = i;
 6347                         alg->sadb_alg_ivlen = 0;
 6348                         key_getsizes_ah(aalgo, i, &minkeysize, &maxkeysize);
 6349                         alg->sadb_alg_minbits = _BITS(minkeysize);
 6350                         alg->sadb_alg_maxbits = _BITS(maxkeysize);
 6351                         off += PFKEY_ALIGN8(sizeof(*alg));
 6352                 }
 6353         }
 6354 
 6355         /* for encryption algorithm */
 6356         if (elen) {
 6357                 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
 6358                 sup->sadb_supported_len = PFKEY_UNIT64(elen);
 6359                 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
 6360                 off += PFKEY_ALIGN8(sizeof(*sup));
 6361 
 6362                 for (i = 1; i <= SADB_EALG_MAX; i++) {
 6363                         struct enc_xform *ealgo;
 6364 
 6365                         ealgo = esp_algorithm_lookup(i);
 6366                         if (!ealgo)
 6367                                 continue;
 6368                         alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
 6369                         alg->sadb_alg_id = i;
 6370                         alg->sadb_alg_ivlen = ealgo->blocksize;
 6371                         alg->sadb_alg_minbits = _BITS(ealgo->minkey);
 6372                         alg->sadb_alg_maxbits = _BITS(ealgo->maxkey);
 6373                         off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
 6374                 }
 6375         }
 6376 
 6377 #ifdef DIGAGNOSTIC
 6378         if (off != len)
 6379                 panic("length assumption failed in key_register");
 6380 #endif
 6381 
 6382         m_freem(m);
 6383         return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
 6384     }
 6385 }
 6386 
 6387 /*
 6388  * free secreg entry registered.
 6389  * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
 6390  */
 6391 void
 6392 key_freereg(so)
 6393         struct socket *so;
 6394 {
 6395         struct secreg *reg;
 6396         int i;
 6397 
 6398         /* sanity check */
 6399         if (so == NULL)
 6400                 panic("key_freereg: NULL pointer is passed.\n");
 6401 
 6402         /*
 6403          * check whether existing or not.
 6404          * check all type of SA, because there is a potential that
 6405          * one socket is registered to multiple type of SA.
 6406          */
 6407         for (i = 0; i <= SADB_SATYPE_MAX; i++) {
 6408                 LIST_FOREACH(reg, &regtree[i], chain) {
 6409                         if (reg->so == so
 6410                          && __LIST_CHAINED(reg)) {
 6411                                 LIST_REMOVE(reg, chain);
 6412                                 KFREE(reg);
 6413                                 break;
 6414                         }
 6415                 }
 6416         }
 6417         
 6418         return;
 6419 }
 6420 
 6421 /*
 6422  * SADB_EXPIRE processing
 6423  * send
 6424  *   <base, SA, SA2, lifetime(C and one of HS), address(SD)>
 6425  * to KMD by PF_KEY.
 6426  * NOTE: We send only soft lifetime extension.
 6427  *
 6428  * OUT: 0       : succeed
 6429  *      others  : error number
 6430  */
 6431 static int
 6432 key_expire(sav)
 6433         struct secasvar *sav;
 6434 {
 6435         int s;
 6436         int satype;
 6437         struct mbuf *result = NULL, *m;
 6438         int len;
 6439         int error = -1;
 6440         struct sadb_lifetime *lt;
 6441 
 6442         /* XXX: Why do we lock ? */
 6443         s = splsoftnet();       /*called from softclock()*/
 6444 
 6445         /* sanity check */
 6446         if (sav == NULL)
 6447                 panic("key_expire: NULL pointer is passed.\n");
 6448         if (sav->sah == NULL)
 6449                 panic("key_expire: Why was SA index in SA NULL.\n");
 6450         if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
 6451                 panic("key_expire: invalid proto is passed.\n");
 6452 
 6453         /* set msg header */
 6454         m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
 6455         if (!m) {
 6456                 error = ENOBUFS;
 6457                 goto fail;
 6458         }
 6459         result = m;
 6460 
 6461         /* create SA extension */
 6462         m = key_setsadbsa(sav);
 6463         if (!m) {
 6464                 error = ENOBUFS;
 6465                 goto fail;
 6466         }
 6467         m_cat(result, m);
 6468 
 6469         /* create SA extension */
 6470         m = key_setsadbxsa2(sav->sah->saidx.mode,
 6471                         sav->replay ? sav->replay->count : 0,
 6472                         sav->sah->saidx.reqid);
 6473         if (!m) {
 6474                 error = ENOBUFS;
 6475                 goto fail;
 6476         }
 6477         m_cat(result, m);
 6478 
 6479         /* create lifetime extension (current and soft) */
 6480         len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
 6481         m = key_alloc_mbuf(len);
 6482         if (!m || m->m_next) {  /*XXX*/
 6483                 if (m)
 6484                         m_freem(m);
 6485                 error = ENOBUFS;
 6486                 goto fail;
 6487         }
 6488         bzero(mtod(m, caddr_t), len);
 6489         lt = mtod(m, struct sadb_lifetime *);
 6490         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
 6491         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
 6492         lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
 6493         lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
 6494         lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
 6495         lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
 6496         lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
 6497         bcopy(sav->lft_s, lt, sizeof(*lt));
 6498         m_cat(result, m);
 6499 
 6500         /* set sadb_address for source */
 6501         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
 6502             &sav->sah->saidx.src.sa,
 6503             FULLMASK, IPSEC_ULPROTO_ANY);
 6504         if (!m) {
 6505                 error = ENOBUFS;
 6506                 goto fail;
 6507         }
 6508         m_cat(result, m);
 6509 
 6510         /* set sadb_address for destination */
 6511         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
 6512             &sav->sah->saidx.dst.sa,
 6513             FULLMASK, IPSEC_ULPROTO_ANY);
 6514         if (!m) {
 6515                 error = ENOBUFS;
 6516                 goto fail;
 6517         }
 6518         m_cat(result, m);
 6519 
 6520         if ((result->m_flags & M_PKTHDR) == 0) {
 6521                 error = EINVAL;
 6522                 goto fail;
 6523         }
 6524 
 6525         if (result->m_len < sizeof(struct sadb_msg)) {
 6526                 result = m_pullup(result, sizeof(struct sadb_msg));
 6527                 if (result == NULL) {
 6528                         error = ENOBUFS;
 6529                         goto fail;
 6530                 }
 6531         }
 6532 
 6533         result->m_pkthdr.len = 0;
 6534         for (m = result; m; m = m->m_next)
 6535                 result->m_pkthdr.len += m->m_len;
 6536 
 6537         mtod(result, struct sadb_msg *)->sadb_msg_len =
 6538             PFKEY_UNIT64(result->m_pkthdr.len);
 6539 
 6540         splx(s);
 6541         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
 6542 
 6543  fail:
 6544         if (result)
 6545                 m_freem(result);
 6546         splx(s);
 6547         return error;
 6548 }
 6549 
 6550 /*
 6551  * SADB_FLUSH processing
 6552  * receive
 6553  *   <base>
 6554  * from the ikmpd, and free all entries in secastree.
 6555  * and send,
 6556  *   <base>
 6557  * to the ikmpd.
 6558  * NOTE: to do is only marking SADB_SASTATE_DEAD.
 6559  *
 6560  * m will always be freed.
 6561  */
 6562 static int
 6563 key_flush(so, m, mhp)
 6564         struct socket *so;
 6565         struct mbuf *m;
 6566         const struct sadb_msghdr *mhp;
 6567 {
 6568         struct sadb_msg *newmsg;
 6569         struct secashead *sah, *nextsah;
 6570         struct secasvar *sav, *nextsav;
 6571         u_int16_t proto;
 6572         u_int8_t state;
 6573         u_int stateidx;
 6574 
 6575         /* sanity check */
 6576         if (so == NULL || mhp == NULL || mhp->msg == NULL)
 6577                 panic("key_flush: NULL pointer is passed.\n");
 6578 
 6579         /* map satype to proto */
 6580         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 6581                 ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
 6582                 return key_senderror(so, m, EINVAL);
 6583         }
 6584 
 6585         /* no SATYPE specified, i.e. flushing all SA. */
 6586         for (sah = LIST_FIRST(&sahtree);
 6587              sah != NULL;
 6588              sah = nextsah) {
 6589                 nextsah = LIST_NEXT(sah, chain);
 6590 
 6591                 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
 6592                  && proto != sah->saidx.proto)
 6593                         continue;
 6594 
 6595                 for (stateidx = 0;
 6596                      stateidx < _ARRAYLEN(saorder_state_alive);
 6597                      stateidx++) {
 6598                         state = saorder_state_any[stateidx];
 6599                         for (sav = LIST_FIRST(&sah->savtree[state]);
 6600                              sav != NULL;
 6601                              sav = nextsav) {
 6602 
 6603                                 nextsav = LIST_NEXT(sav, chain);
 6604 
 6605                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 6606                                 KEY_FREESAV(&sav);
 6607                         }
 6608                 }
 6609 
 6610                 sah->state = SADB_SASTATE_DEAD;
 6611         }
 6612 
 6613         if (m->m_len < sizeof(struct sadb_msg) ||
 6614             sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
 6615                 ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
 6616                 return key_senderror(so, m, ENOBUFS);
 6617         }
 6618 
 6619         if (m->m_next)
 6620                 m_freem(m->m_next);
 6621         m->m_next = NULL;
 6622         m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
 6623         newmsg = mtod(m, struct sadb_msg *);
 6624         newmsg->sadb_msg_errno = 0;
 6625         newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
 6626 
 6627         return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
 6628 }
 6629 
 6630 
 6631 static struct mbuf *
 6632 key_setdump_chain(u_int8_t req_satype, int *errorp, int *lenp, pid_t pid)
 6633 {
 6634         struct secashead *sah;
 6635         struct secasvar *sav;
 6636         u_int16_t proto;
 6637         u_int stateidx;
 6638         u_int8_t satype;
 6639         u_int8_t state;
 6640         int cnt;
 6641         struct mbuf *m, *n, *prev;
 6642         int totlen;
 6643 
 6644         *lenp = 0;
 6645 
 6646         /* map satype to proto */
 6647         if ((proto = key_satype2proto(req_satype)) == 0) {
 6648                 *errorp = EINVAL;
 6649                 return (NULL);
 6650         }
 6651 
 6652         /* count sav entries to be sent to userland. */
 6653         cnt = 0;
 6654         LIST_FOREACH(sah, &sahtree, chain) {
 6655                 if (req_satype != SADB_SATYPE_UNSPEC &&
 6656                     proto != sah->saidx.proto)
 6657                         continue;
 6658 
 6659                 for (stateidx = 0;
 6660                      stateidx < _ARRAYLEN(saorder_state_any);
 6661                      stateidx++) {
 6662                         state = saorder_state_any[stateidx];
 6663                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
 6664                                 cnt++;
 6665                         }
 6666                 }
 6667         }
 6668 
 6669         if (cnt == 0) {
 6670                 *errorp = ENOENT;
 6671                 return (NULL);
 6672         }
 6673 
 6674         /* send this to the userland, one at a time. */
 6675         m = NULL;
 6676         prev = m;
 6677         LIST_FOREACH(sah, &sahtree, chain) {
 6678                 if (req_satype != SADB_SATYPE_UNSPEC &&
 6679                     proto != sah->saidx.proto)
 6680                         continue;
 6681 
 6682                 /* map proto to satype */
 6683                 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
 6684                         m_freem(m);
 6685                         *errorp = EINVAL;
 6686                         return (NULL);
 6687                 }
 6688 
 6689                 for (stateidx = 0;
 6690                      stateidx < _ARRAYLEN(saorder_state_any);
 6691                      stateidx++) {
 6692                         state = saorder_state_any[stateidx];
 6693                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
 6694                                 n = key_setdumpsa(sav, SADB_DUMP, satype,
 6695                                     --cnt, pid);
 6696                                 if (!n) {
 6697                                         m_freem(m);
 6698                                         *errorp = ENOBUFS;
 6699                                         return (NULL);
 6700                                 }
 6701 
 6702                                 totlen += n->m_pkthdr.len;
 6703                                 if (!m)
 6704                                         m = n;
 6705                                 else
 6706                                         prev->m_nextpkt = n;
 6707                                 prev = n;
 6708                         }
 6709                 }
 6710         }
 6711 
 6712         if (!m) {
 6713                 *errorp = EINVAL;
 6714                 return (NULL);
 6715         }
 6716 
 6717         if ((m->m_flags & M_PKTHDR) != 0) {
 6718                 m->m_pkthdr.len = 0;
 6719                 for (n = m; n; n = n->m_next)
 6720                         m->m_pkthdr.len += n->m_len;
 6721         }
 6722 
 6723         *errorp = 0;
 6724         return (m);
 6725 }
 6726 
 6727 /*
 6728  * SADB_DUMP processing
 6729  * dump all entries including status of DEAD in SAD.
 6730  * receive
 6731  *   <base>
 6732  * from the ikmpd, and dump all secasvar leaves
 6733  * and send,
 6734  *   <base> .....
 6735  * to the ikmpd.
 6736  *
 6737  * m will always be freed.
 6738  */
 6739 static int
 6740 key_dump(so, m0, mhp)
 6741         struct socket *so;
 6742         struct mbuf *m0;
 6743         const struct sadb_msghdr *mhp;
 6744 {
 6745         u_int16_t proto;
 6746         u_int8_t satype;
 6747         struct mbuf *n;
 6748         int s;
 6749         int error, len, ok;
 6750 
 6751         /* sanity check */
 6752         if (so == NULL || m0 == NULL || mhp == NULL || mhp->msg == NULL)
 6753                 panic("key_dump: NULL pointer is passed.\n");
 6754 
 6755         /* map satype to proto */
 6756         satype = mhp->msg->sadb_msg_satype;
 6757         if ((proto = key_satype2proto(satype)) == 0) {
 6758                 ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
 6759                 return key_senderror(so, m0, EINVAL);
 6760         }
 6761 
 6762         /*
 6763          * If the requestor has insufficient socket-buffer space
 6764          * for the entire chain, nobody gets any response to the DUMP.
 6765          * XXX For now, only the requestor ever gets anything.
 6766          * Moreover, if the requestor has any space at all, they receive
 6767          * the entire chain, otherwise the request is refused with ENOBUFS.
 6768          */
 6769         if (sbspace(&so->so_rcv) <= 0) {
 6770                 return key_senderror(so, m0, ENOBUFS);
 6771         }
 6772 
 6773         s = splsoftnet();
 6774         n = key_setdump_chain(satype, &error, &len, mhp->msg->sadb_msg_pid);
 6775         splx(s);
 6776 
 6777         if (n == NULL) {
 6778                 return key_senderror(so, m0, ENOENT);
 6779         }
 6780         pfkeystat.in_total++;
 6781         pfkeystat.in_bytes += len;
 6782 
 6783         /*
 6784          * PF_KEY DUMP responses are no longer broadcast to all PF_KEY sockets.
 6785          * The requestor receives either the entire chain, or an
 6786          * error message with ENOBUFS.
 6787          *
 6788          * sbappendaddrchain() takes the chain of entries, one
 6789          * packet-record per SPD entry, prepends the key_src sockaddr
 6790          * to each packet-record, links the sockaddr mbufs into a new
 6791          * list of records, then   appends the entire resulting
 6792          * list to the requesting socket.
 6793          */
 6794         ok = sbappendaddrchain(&so->so_rcv, (struct sockaddr *)&key_src,
 6795                 n, SB_PRIO_ONESHOT_OVERFLOW);
 6796 
 6797         if (!ok) {
 6798                 pfkeystat.in_nomem++;
 6799                 m_freem(n);
 6800                 return key_senderror(so, m0, ENOBUFS);
 6801         }
 6802 
 6803         m_freem(m0);
 6804         return 0;
 6805 }
 6806 
 6807 /*
 6808  * SADB_X_PROMISC processing
 6809  *
 6810  * m will always be freed.
 6811  */
 6812 static int
 6813 key_promisc(so, m, mhp)
 6814         struct socket *so;
 6815         struct mbuf *m;
 6816         const struct sadb_msghdr *mhp;
 6817 {
 6818         int olen;
 6819 
 6820         /* sanity check */
 6821         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 6822                 panic("key_promisc: NULL pointer is passed.\n");
 6823 
 6824         olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
 6825 
 6826         if (olen < sizeof(struct sadb_msg)) {
 6827 #if 1
 6828                 return key_senderror(so, m, EINVAL);
 6829 #else
 6830                 m_freem(m);
 6831                 return 0;
 6832 #endif
 6833         } else if (olen == sizeof(struct sadb_msg)) {
 6834                 /* enable/disable promisc mode */
 6835                 struct keycb *kp;
 6836 
 6837                 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
 6838                         return key_senderror(so, m, EINVAL);
 6839                 mhp->msg->sadb_msg_errno = 0;
 6840                 switch (mhp->msg->sadb_msg_satype) {
 6841                 case 0:
 6842                 case 1:
 6843                         kp->kp_promisc = mhp->msg->sadb_msg_satype;
 6844                         break;
 6845                 default:
 6846                         return key_senderror(so, m, EINVAL);
 6847                 }
 6848 
 6849                 /* send the original message back to everyone */
 6850                 mhp->msg->sadb_msg_errno = 0;
 6851                 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
 6852         } else {
 6853                 /* send packet as is */
 6854 
 6855                 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
 6856 
 6857                 /* TODO: if sadb_msg_seq is specified, send to specific pid */
 6858                 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
 6859         }
 6860 }
 6861 
 6862 static int (*key_typesw[]) __P((struct socket *, struct mbuf *,
 6863                 const struct sadb_msghdr *)) = {
 6864         NULL,           /* SADB_RESERVED */
 6865         key_getspi,     /* SADB_GETSPI */
 6866         key_update,     /* SADB_UPDATE */
 6867         key_add,        /* SADB_ADD */
 6868         key_delete,     /* SADB_DELETE */
 6869         key_get,        /* SADB_GET */
 6870         key_acquire2,   /* SADB_ACQUIRE */
 6871         key_register,   /* SADB_REGISTER */
 6872         NULL,           /* SADB_EXPIRE */
 6873         key_flush,      /* SADB_FLUSH */
 6874         key_dump,       /* SADB_DUMP */
 6875         key_promisc,    /* SADB_X_PROMISC */
 6876         NULL,           /* SADB_X_PCHANGE */
 6877         key_spdadd,     /* SADB_X_SPDUPDATE */
 6878         key_spdadd,     /* SADB_X_SPDADD */
 6879         key_spddelete,  /* SADB_X_SPDDELETE */
 6880         key_spdget,     /* SADB_X_SPDGET */
 6881         NULL,           /* SADB_X_SPDACQUIRE */
 6882         key_spddump,    /* SADB_X_SPDDUMP */
 6883         key_spdflush,   /* SADB_X_SPDFLUSH */
 6884         key_spdadd,     /* SADB_X_SPDSETIDX */
 6885         NULL,           /* SADB_X_SPDEXPIRE */
 6886         key_spddelete2, /* SADB_X_SPDDELETE2 */
 6887 };
 6888 
 6889 /*
 6890  * parse sadb_msg buffer to process PFKEYv2,
 6891  * and create a data to response if needed.
 6892  * I think to be dealed with mbuf directly.
 6893  * IN:
 6894  *     msgp  : pointer to pointer to a received buffer pulluped.
 6895  *             This is rewrited to response.
 6896  *     so    : pointer to socket.
 6897  * OUT:
 6898  *    length for buffer to send to user process.
 6899  */
 6900 int
 6901 key_parse(m, so)
 6902         struct mbuf *m;
 6903         struct socket *so;
 6904 {
 6905         struct sadb_msg *msg;
 6906         struct sadb_msghdr mh;
 6907         u_int orglen;
 6908         int error;
 6909         int target;
 6910 
 6911         /* sanity check */
 6912         if (m == NULL || so == NULL)
 6913                 panic("key_parse: NULL pointer is passed.\n");
 6914 
 6915 #if 0   /*kdebug_sadb assumes msg in linear buffer*/
 6916         KEYDEBUG(KEYDEBUG_KEY_DUMP,
 6917                 ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
 6918                 kdebug_sadb(msg));
 6919 #endif
 6920 
 6921         if (m->m_len < sizeof(struct sadb_msg)) {
 6922                 m = m_pullup(m, sizeof(struct sadb_msg));
 6923                 if (!m)
 6924                         return ENOBUFS;
 6925         }
 6926         msg = mtod(m, struct sadb_msg *);
 6927         orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
 6928         target = KEY_SENDUP_ONE;
 6929 
 6930         if ((m->m_flags & M_PKTHDR) == 0 ||
 6931             m->m_pkthdr.len != m->m_pkthdr.len) {
 6932                 ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
 6933                 pfkeystat.out_invlen++;
 6934                 error = EINVAL;
 6935                 goto senderror;
 6936         }
 6937 
 6938         if (msg->sadb_msg_version != PF_KEY_V2) {
 6939                 ipseclog((LOG_DEBUG,
 6940                     "key_parse: PF_KEY version %u is mismatched.\n",
 6941                     msg->sadb_msg_version));
 6942                 pfkeystat.out_invver++;
 6943                 error = EINVAL;
 6944                 goto senderror;
 6945         }
 6946 
 6947         if (msg->sadb_msg_type > SADB_MAX) {
 6948                 ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
 6949                     msg->sadb_msg_type));
 6950                 pfkeystat.out_invmsgtype++;
 6951                 error = EINVAL;
 6952                 goto senderror;
 6953         }
 6954 
 6955         /* for old-fashioned code - should be nuked */
 6956         if (m->m_pkthdr.len > MCLBYTES) {
 6957                 m_freem(m);
 6958                 return ENOBUFS;
 6959         }
 6960         if (m->m_next) {
 6961                 struct mbuf *n;
 6962 
 6963                 MGETHDR(n, M_DONTWAIT, MT_DATA);
 6964                 if (n && m->m_pkthdr.len > MHLEN) {
 6965                         MCLGET(n, M_DONTWAIT);
 6966                         if ((n->m_flags & M_EXT) == 0) {
 6967                                 m_free(n);
 6968                                 n = NULL;
 6969                         }
 6970                 }
 6971                 if (!n) {
 6972                         m_freem(m);
 6973                         return ENOBUFS;
 6974                 }
 6975                 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
 6976                 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
 6977                 n->m_next = NULL;
 6978                 m_freem(m);
 6979                 m = n;
 6980         }
 6981 
 6982         /* align the mbuf chain so that extensions are in contiguous region. */
 6983         error = key_align(m, &mh);
 6984         if (error)
 6985                 return error;
 6986 
 6987         if (m->m_next) {        /*XXX*/
 6988                 m_freem(m);
 6989                 return ENOBUFS;
 6990         }
 6991 
 6992         msg = mh.msg;
 6993 
 6994         /* check SA type */
 6995         switch (msg->sadb_msg_satype) {
 6996         case SADB_SATYPE_UNSPEC:
 6997                 switch (msg->sadb_msg_type) {
 6998                 case SADB_GETSPI:
 6999                 case SADB_UPDATE:
 7000                 case SADB_ADD:
 7001                 case SADB_DELETE:
 7002                 case SADB_GET:
 7003                 case SADB_ACQUIRE:
 7004                 case SADB_EXPIRE:
 7005                         ipseclog((LOG_DEBUG, "key_parse: must specify satype "
 7006                             "when msg type=%u.\n", msg->sadb_msg_type));
 7007                         pfkeystat.out_invsatype++;
 7008                         error = EINVAL;
 7009                         goto senderror;
 7010                 }
 7011                 break;
 7012         case SADB_SATYPE_AH:
 7013         case SADB_SATYPE_ESP:
 7014         case SADB_X_SATYPE_IPCOMP:
 7015                 switch (msg->sadb_msg_type) {
 7016                 case SADB_X_SPDADD:
 7017                 case SADB_X_SPDDELETE:
 7018                 case SADB_X_SPDGET:
 7019                 case SADB_X_SPDDUMP:
 7020                 case SADB_X_SPDFLUSH:
 7021                 case SADB_X_SPDSETIDX:
 7022                 case SADB_X_SPDUPDATE:
 7023                 case SADB_X_SPDDELETE2:
 7024                         ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
 7025                             msg->sadb_msg_type));
 7026                         pfkeystat.out_invsatype++;
 7027                         error = EINVAL;
 7028                         goto senderror;
 7029                 }
 7030                 break;
 7031         case SADB_SATYPE_RSVP:
 7032         case SADB_SATYPE_OSPFV2:
 7033         case SADB_SATYPE_RIPV2:
 7034         case SADB_SATYPE_MIP:
 7035                 ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
 7036                     msg->sadb_msg_satype));
 7037                 pfkeystat.out_invsatype++;
 7038                 error = EOPNOTSUPP;
 7039                 goto senderror;
 7040         case 1: /* XXX: What does it do? */
 7041                 if (msg->sadb_msg_type == SADB_X_PROMISC)
 7042                         break;
 7043                 /*FALLTHROUGH*/
 7044         default:
 7045                 ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
 7046                     msg->sadb_msg_satype));
 7047                 pfkeystat.out_invsatype++;
 7048                 error = EINVAL;
 7049                 goto senderror;
 7050         }
 7051 
 7052         /* check field of upper layer protocol and address family */
 7053         if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
 7054          && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
 7055                 struct sadb_address *src0, *dst0;
 7056                 u_int plen;
 7057 
 7058                 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
 7059                 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
 7060 
 7061                 /* check upper layer protocol */
 7062                 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
 7063                         ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
 7064                         pfkeystat.out_invaddr++;
 7065                         error = EINVAL;
 7066                         goto senderror;
 7067                 }
 7068 
 7069                 /* check family */
 7070                 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
 7071                     PFKEY_ADDR_SADDR(dst0)->sa_family) {
 7072                         ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
 7073                         pfkeystat.out_invaddr++;
 7074                         error = EINVAL;
 7075                         goto senderror;
 7076                 }
 7077                 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
 7078                     PFKEY_ADDR_SADDR(dst0)->sa_len) {
 7079                         ipseclog((LOG_DEBUG,
 7080                             "key_parse: address struct size mismatched.\n"));
 7081                         pfkeystat.out_invaddr++;
 7082                         error = EINVAL;
 7083                         goto senderror;
 7084                 }
 7085 
 7086                 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
 7087                 case AF_INET:
 7088                         if (PFKEY_ADDR_SADDR(src0)->sa_len !=
 7089                             sizeof(struct sockaddr_in)) {
 7090                                 pfkeystat.out_invaddr++;
 7091                                 error = EINVAL;
 7092                                 goto senderror;
 7093                         }
 7094                         break;
 7095                 case AF_INET6:
 7096                         if (PFKEY_ADDR_SADDR(src0)->sa_len !=
 7097                             sizeof(struct sockaddr_in6)) {
 7098                                 pfkeystat.out_invaddr++;
 7099                                 error = EINVAL;
 7100                                 goto senderror;
 7101                         }
 7102                         break;
 7103                 default:
 7104                         ipseclog((LOG_DEBUG,
 7105                             "key_parse: unsupported address family.\n"));
 7106                         pfkeystat.out_invaddr++;
 7107                         error = EAFNOSUPPORT;
 7108                         goto senderror;
 7109                 }
 7110 
 7111                 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
 7112                 case AF_INET:
 7113                         plen = sizeof(struct in_addr) << 3;
 7114                         break;
 7115                 case AF_INET6:
 7116                         plen = sizeof(struct in6_addr) << 3;
 7117                         break;
 7118                 default:
 7119                         plen = 0;       /*fool gcc*/
 7120                         break;
 7121                 }
 7122 
 7123                 /* check max prefix length */
 7124                 if (src0->sadb_address_prefixlen > plen ||
 7125                     dst0->sadb_address_prefixlen > plen) {
 7126                         ipseclog((LOG_DEBUG,
 7127                             "key_parse: illegal prefixlen.\n"));
 7128                         pfkeystat.out_invaddr++;
 7129                         error = EINVAL;
 7130                         goto senderror;
 7131                 }
 7132 
 7133                 /*
 7134                  * prefixlen == 0 is valid because there can be a case when
 7135                  * all addresses are matched.
 7136                  */
 7137         }
 7138 
 7139         if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
 7140             key_typesw[msg->sadb_msg_type] == NULL) {
 7141                 pfkeystat.out_invmsgtype++;
 7142                 error = EINVAL;
 7143                 goto senderror;
 7144         }
 7145 
 7146         return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
 7147 
 7148 senderror:
 7149         msg->sadb_msg_errno = error;
 7150         return key_sendup_mbuf(so, m, target);
 7151 }
 7152 
 7153 static int
 7154 key_senderror(so, m, code)
 7155         struct socket *so;
 7156         struct mbuf *m;
 7157         int code;
 7158 {
 7159         struct sadb_msg *msg;
 7160 
 7161         if (m->m_len < sizeof(struct sadb_msg))
 7162                 panic("invalid mbuf passed to key_senderror");
 7163 
 7164         msg = mtod(m, struct sadb_msg *);
 7165         msg->sadb_msg_errno = code;
 7166         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
 7167 }
 7168 
 7169 /*
 7170  * set the pointer to each header into message buffer.
 7171  * m will be freed on error.
 7172  * XXX larger-than-MCLBYTES extension?
 7173  */
 7174 static int
 7175 key_align(m, mhp)
 7176         struct mbuf *m;
 7177         struct sadb_msghdr *mhp;
 7178 {
 7179         struct mbuf *n;
 7180         struct sadb_ext *ext;
 7181         size_t off, end;
 7182         int extlen;
 7183         int toff;
 7184 
 7185         /* sanity check */
 7186         if (m == NULL || mhp == NULL)
 7187                 panic("key_align: NULL pointer is passed.\n");
 7188         if (m->m_len < sizeof(struct sadb_msg))
 7189                 panic("invalid mbuf passed to key_align");
 7190 
 7191         /* initialize */
 7192         bzero(mhp, sizeof(*mhp));
 7193 
 7194         mhp->msg = mtod(m, struct sadb_msg *);
 7195         mhp->ext[0] = (struct sadb_ext *)mhp->msg;      /*XXX backward compat */
 7196 
 7197         end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
 7198         extlen = end;   /*just in case extlen is not updated*/
 7199         for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
 7200                 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
 7201                 if (!n) {
 7202                         /* m is already freed */
 7203                         return ENOBUFS;
 7204                 }
 7205                 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
 7206 
 7207                 /* set pointer */
 7208                 switch (ext->sadb_ext_type) {
 7209                 case SADB_EXT_SA:
 7210                 case SADB_EXT_ADDRESS_SRC:
 7211                 case SADB_EXT_ADDRESS_DST:
 7212                 case SADB_EXT_ADDRESS_PROXY:
 7213                 case SADB_EXT_LIFETIME_CURRENT:
 7214                 case SADB_EXT_LIFETIME_HARD:
 7215                 case SADB_EXT_LIFETIME_SOFT:
 7216                 case SADB_EXT_KEY_AUTH:
 7217                 case SADB_EXT_KEY_ENCRYPT:
 7218                 case SADB_EXT_IDENTITY_SRC:
 7219                 case SADB_EXT_IDENTITY_DST:
 7220                 case SADB_EXT_SENSITIVITY:
 7221                 case SADB_EXT_PROPOSAL:
 7222                 case SADB_EXT_SUPPORTED_AUTH:
 7223                 case SADB_EXT_SUPPORTED_ENCRYPT:
 7224                 case SADB_EXT_SPIRANGE:
 7225                 case SADB_X_EXT_POLICY:
 7226                 case SADB_X_EXT_SA2:
 7227                         /* duplicate check */
 7228                         /*
 7229                          * XXX Are there duplication payloads of either
 7230                          * KEY_AUTH or KEY_ENCRYPT ?
 7231                          */
 7232                         if (mhp->ext[ext->sadb_ext_type] != NULL) {
 7233                                 ipseclog((LOG_DEBUG,
 7234                                     "key_align: duplicate ext_type %u "
 7235                                     "is passed.\n", ext->sadb_ext_type));
 7236                                 m_freem(m);
 7237                                 pfkeystat.out_dupext++;
 7238                                 return EINVAL;
 7239                         }
 7240                         break;
 7241                 default:
 7242                         ipseclog((LOG_DEBUG,
 7243                             "key_align: invalid ext_type %u is passed.\n",
 7244                             ext->sadb_ext_type));
 7245                         m_freem(m);
 7246                         pfkeystat.out_invexttype++;
 7247                         return EINVAL;
 7248                 }
 7249 
 7250                 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
 7251 
 7252                 if (key_validate_ext(ext, extlen)) {
 7253                         m_freem(m);
 7254                         pfkeystat.out_invlen++;
 7255                         return EINVAL;
 7256                 }
 7257 
 7258                 n = m_pulldown(m, off, extlen, &toff);
 7259                 if (!n) {
 7260                         /* m is already freed */
 7261                         return ENOBUFS;
 7262                 }
 7263                 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
 7264 
 7265                 mhp->ext[ext->sadb_ext_type] = ext;
 7266                 mhp->extoff[ext->sadb_ext_type] = off;
 7267                 mhp->extlen[ext->sadb_ext_type] = extlen;
 7268         }
 7269 
 7270         if (off != end) {
 7271                 m_freem(m);
 7272                 pfkeystat.out_invlen++;
 7273                 return EINVAL;
 7274         }
 7275 
 7276         return 0;
 7277 }
 7278 
 7279 static int
 7280 key_validate_ext(ext, len)
 7281         const struct sadb_ext *ext;
 7282         int len;
 7283 {
 7284         const struct sockaddr *sa;
 7285         enum { NONE, ADDR } checktype = NONE;
 7286         int baselen = 0;
 7287         const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
 7288 
 7289         if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
 7290                 return EINVAL;
 7291 
 7292         /* if it does not match minimum/maximum length, bail */
 7293         if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
 7294             ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
 7295                 return EINVAL;
 7296         if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
 7297                 return EINVAL;
 7298         if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
 7299                 return EINVAL;
 7300 
 7301         /* more checks based on sadb_ext_type XXX need more */
 7302         switch (ext->sadb_ext_type) {
 7303         case SADB_EXT_ADDRESS_SRC:
 7304         case SADB_EXT_ADDRESS_DST:
 7305         case SADB_EXT_ADDRESS_PROXY:
 7306                 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
 7307                 checktype = ADDR;
 7308                 break;
 7309         case SADB_EXT_IDENTITY_SRC:
 7310         case SADB_EXT_IDENTITY_DST:
 7311                 if (((const struct sadb_ident *)ext)->sadb_ident_type ==
 7312                     SADB_X_IDENTTYPE_ADDR) {
 7313                         baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
 7314                         checktype = ADDR;
 7315                 } else
 7316                         checktype = NONE;
 7317                 break;
 7318         default:
 7319                 checktype = NONE;
 7320                 break;
 7321         }
 7322 
 7323         switch (checktype) {
 7324         case NONE:
 7325                 break;
 7326         case ADDR:
 7327                 sa = (const struct sockaddr *)(((const u_int8_t*)ext)+baselen);
 7328                 if (len < baselen + sal)
 7329                         return EINVAL;
 7330                 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
 7331                         return EINVAL;
 7332                 break;
 7333         }
 7334 
 7335         return 0;
 7336 }
 7337 
 7338 void
 7339 key_init()
 7340 {
 7341         int i;
 7342 
 7343         callout_init(&key_timehandler_ch);
 7344 
 7345         for (i = 0; i < IPSEC_DIR_MAX; i++) {
 7346                 LIST_INIT(&sptree[i]);
 7347         }
 7348 
 7349         LIST_INIT(&sahtree);
 7350 
 7351         for (i = 0; i <= SADB_SATYPE_MAX; i++) {
 7352                 LIST_INIT(&regtree[i]);
 7353         }
 7354 
 7355 #ifndef IPSEC_NONBLOCK_ACQUIRE
 7356         LIST_INIT(&acqtree);
 7357 #endif
 7358         LIST_INIT(&spacqtree);
 7359 
 7360         /* system default */
 7361         ip4_def_policy.policy = IPSEC_POLICY_NONE;
 7362         ip4_def_policy.refcnt++;        /*never reclaim this*/
 7363 
 7364 
 7365 #ifndef IPSEC_DEBUG2
 7366         callout_reset(&key_timehandler_ch, hz, key_timehandler, (void *)0);
 7367 #endif /*IPSEC_DEBUG2*/
 7368 
 7369         /* initialize key statistics */
 7370         keystat.getspi_count = 1;
 7371 
 7372         printf("IPsec: Initialized Security Association Processing.\n");
 7373 
 7374         return;
 7375 }
 7376 
 7377 /*
 7378  * XXX: maybe This function is called after INBOUND IPsec processing.
 7379  *
 7380  * Special check for tunnel-mode packets.
 7381  * We must make some checks for consistency between inner and outer IP header.
 7382  *
 7383  * xxx more checks to be provided
 7384  */
 7385 int
 7386 key_checktunnelsanity(sav, family, src, dst)
 7387         struct secasvar *sav;
 7388         u_int family;
 7389         caddr_t src;
 7390         caddr_t dst;
 7391 {
 7392         /* sanity check */
 7393         if (sav->sah == NULL)
 7394                 panic("sav->sah == NULL at key_checktunnelsanity");
 7395 
 7396         /* XXX: check inner IP header */
 7397 
 7398         return 1;
 7399 }
 7400 
 7401 #if 0
 7402 #define hostnamelen     strlen(hostname)
 7403 
 7404 /*
 7405  * Get FQDN for the host.
 7406  * If the administrator configured hostname (by hostname(1)) without
 7407  * domain name, returns nothing.
 7408  */
 7409 static const char *
 7410 key_getfqdn()
 7411 {
 7412         int i;
 7413         int hasdot;
 7414         static char fqdn[MAXHOSTNAMELEN + 1];
 7415 
 7416         if (!hostnamelen)
 7417                 return NULL;
 7418 
 7419         /* check if it comes with domain name. */
 7420         hasdot = 0;
 7421         for (i = 0; i < hostnamelen; i++) {
 7422                 if (hostname[i] == '.')
 7423                         hasdot++;
 7424         }
 7425         if (!hasdot)
 7426                 return NULL;
 7427 
 7428         /* NOTE: hostname may not be NUL-terminated. */
 7429         bzero(fqdn, sizeof(fqdn));
 7430         bcopy(hostname, fqdn, hostnamelen);
 7431         fqdn[hostnamelen] = '\0';
 7432         return fqdn;
 7433 }
 7434 
 7435 /*
 7436  * get username@FQDN for the host/user.
 7437  */
 7438 static const char *
 7439 key_getuserfqdn()
 7440 {
 7441         const char *host;
 7442         static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
 7443         struct proc *p = curproc;
 7444         char *q;
 7445 
 7446         if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
 7447                 return NULL;
 7448         if (!(host = key_getfqdn()))
 7449                 return NULL;
 7450 
 7451         /* NOTE: s_login may not be-NUL terminated. */
 7452         bzero(userfqdn, sizeof(userfqdn));
 7453         bcopy(p->p_pgrp->pg_session->s_login, userfqdn, MAXLOGNAME);
 7454         userfqdn[MAXLOGNAME] = '\0';    /* safeguard */
 7455         q = userfqdn + strlen(userfqdn);
 7456         *q++ = '@';
 7457         bcopy(host, q, strlen(host));
 7458         q += strlen(host);
 7459         *q++ = '\0';
 7460 
 7461         return userfqdn;
 7462 }
 7463 #endif
 7464 
 7465 /* record data transfer on SA, and update timestamps */
 7466 void
 7467 key_sa_recordxfer(sav, m)
 7468         struct secasvar *sav;
 7469         struct mbuf *m;
 7470 {
 7471         IPSEC_ASSERT(sav != NULL, ("key_sa_recordxfer: Null secasvar"));
 7472         IPSEC_ASSERT(m != NULL, ("key_sa_recordxfer: Null mbuf"));
 7473         if (!sav->lft_c)
 7474                 return;
 7475 
 7476         /*
 7477          * XXX Currently, there is a difference of bytes size
 7478          * between inbound and outbound processing.
 7479          */
 7480         sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
 7481         /* to check bytes lifetime is done in key_timehandler(). */
 7482 
 7483         /*
 7484          * We use the number of packets as the unit of
 7485          * sadb_lifetime_allocations.  We increment the variable
 7486          * whenever {esp,ah}_{in,out}put is called.
 7487          */
 7488         sav->lft_c->sadb_lifetime_allocations++;
 7489         /* XXX check for expires? */
 7490 
 7491         /*
 7492          * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
 7493          * in seconds.  HARD and SOFT lifetime are measured by the time
 7494          * difference (again in seconds) from sadb_lifetime_usetime.
 7495          *
 7496          *      usetime
 7497          *      v     expire   expire
 7498          * -----+-----+--------+---> t
 7499          *      <--------------> HARD
 7500          *      <-----> SOFT
 7501          */
 7502         sav->lft_c->sadb_lifetime_usetime = time_second;
 7503         /* XXX check for expires? */
 7504 
 7505         return;
 7506 }
 7507 
 7508 /* dumb version */
 7509 void
 7510 key_sa_routechange(dst)
 7511         struct sockaddr *dst;
 7512 {
 7513         struct secashead *sah;
 7514         struct route *ro;
 7515 
 7516         LIST_FOREACH(sah, &sahtree, chain) {
 7517                 ro = &sah->sa_route;
 7518                 if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
 7519                  && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
 7520                         RTFREE(ro->ro_rt);
 7521                         ro->ro_rt = (struct rtentry *)NULL;
 7522                 }
 7523         }
 7524 
 7525         return;
 7526 }
 7527 
 7528 static void
 7529 key_sa_chgstate(sav, state)
 7530         struct secasvar *sav;
 7531         u_int8_t state;
 7532 {
 7533         if (sav == NULL)
 7534                 panic("key_sa_chgstate called with sav == NULL");
 7535 
 7536         if (sav->state == state)
 7537                 return;
 7538 
 7539         if (__LIST_CHAINED(sav))
 7540                 LIST_REMOVE(sav, chain);
 7541 
 7542         sav->state = state;
 7543         LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
 7544 }
 7545 
 7546 void
 7547 key_sa_stir_iv(sav)
 7548         struct secasvar *sav;
 7549 {
 7550 
 7551         if (!sav->iv)
 7552                 panic("key_sa_stir_iv called with sav == NULL");
 7553         key_randomfill(sav->iv, sav->ivlen);
 7554 }
 7555 
 7556 /* XXX too much? */
 7557 static struct mbuf *
 7558 key_alloc_mbuf(l)
 7559         int l;
 7560 {
 7561         struct mbuf *m = NULL, *n;
 7562         int len, t;
 7563 
 7564         len = l;
 7565         while (len > 0) {
 7566                 MGET(n, M_DONTWAIT, MT_DATA);
 7567                 if (n && len > MLEN)
 7568                         MCLGET(n, M_DONTWAIT);
 7569                 if (!n) {
 7570                         m_freem(m);
 7571                         return NULL;
 7572                 }
 7573 
 7574                 n->m_next = NULL;
 7575                 n->m_len = 0;
 7576                 n->m_len = M_TRAILINGSPACE(n);
 7577                 /* use the bottom of mbuf, hoping we can prepend afterwards */
 7578                 if (n->m_len > len) {
 7579                         t = (n->m_len - len) & ~(sizeof(long) - 1);
 7580                         n->m_data += t;
 7581                         n->m_len = len;
 7582                 }
 7583 
 7584                 len -= n->m_len;
 7585 
 7586                 if (m)
 7587                         m_cat(m, n);
 7588                 else
 7589                         m = n;
 7590         }
 7591 
 7592         return m;
 7593 }
 7594 
 7595 static struct mbuf *
 7596 key_setdump(u_int8_t req_satype, int *errorp, uint32_t pid)
 7597 {
 7598         struct secashead *sah;
 7599         struct secasvar *sav;
 7600         u_int16_t proto;
 7601         u_int stateidx;
 7602         u_int8_t satype;
 7603         u_int8_t state;
 7604         int cnt;
 7605         struct mbuf *m, *n;
 7606 
 7607         /* map satype to proto */
 7608         if ((proto = key_satype2proto(req_satype)) == 0) {
 7609                 *errorp = EINVAL;
 7610                 return (NULL);
 7611         }
 7612 
 7613         /* count sav entries to be sent to the userland. */
 7614         cnt = 0;
 7615         LIST_FOREACH(sah, &sahtree, chain) {
 7616                 if (req_satype != SADB_SATYPE_UNSPEC &&
 7617                     proto != sah->saidx.proto)
 7618                         continue;
 7619 
 7620                 for (stateidx = 0;
 7621                      stateidx < _ARRAYLEN(saorder_state_any);
 7622                      stateidx++) {
 7623                         state = saorder_state_any[stateidx];
 7624                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
 7625                                 cnt++;
 7626                         }
 7627                 }
 7628         }
 7629 
 7630         if (cnt == 0) {
 7631                 *errorp = ENOENT;
 7632                 return (NULL);
 7633         }
 7634 
 7635         /* send this to the userland, one at a time. */
 7636         m = NULL;
 7637         LIST_FOREACH(sah, &sahtree, chain) {
 7638                 if (req_satype != SADB_SATYPE_UNSPEC &&
 7639                     proto != sah->saidx.proto)
 7640                         continue;
 7641 
 7642                 /* map proto to satype */
 7643                 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
 7644                         m_freem(m);
 7645                         *errorp = EINVAL;
 7646                         return (NULL);
 7647                 }
 7648 
 7649                 for (stateidx = 0;
 7650                      stateidx < _ARRAYLEN(saorder_state_any);
 7651                      stateidx++) {
 7652                         state = saorder_state_any[stateidx];
 7653                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
 7654                                 n = key_setdumpsa(sav, SADB_DUMP, satype,
 7655                                     --cnt, pid);
 7656                                 if (!n) {
 7657                                         m_freem(m);
 7658                                         *errorp = ENOBUFS;
 7659                                         return (NULL);
 7660                                 }
 7661 
 7662                                 if (!m)
 7663                                         m = n;
 7664                                 else
 7665                                         m_cat(m, n);
 7666                         }
 7667                 }
 7668         }
 7669 
 7670         if (!m) {
 7671                 *errorp = EINVAL;
 7672                 return (NULL);
 7673         }
 7674 
 7675         if ((m->m_flags & M_PKTHDR) != 0) {
 7676                 m->m_pkthdr.len = 0;
 7677                 for (n = m; n; n = n->m_next)
 7678                         m->m_pkthdr.len += n->m_len;
 7679         }
 7680 
 7681         *errorp = 0;
 7682         return (m);
 7683 }
 7684 
 7685 static struct mbuf *
 7686 key_setspddump(int *errorp, pid_t pid)
 7687 {
 7688         struct secpolicy *sp;
 7689         int cnt;
 7690         u_int dir;
 7691         struct mbuf *m, *n;
 7692 
 7693         /* search SPD entry and get buffer size. */
 7694         cnt = 0;
 7695         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
 7696                 LIST_FOREACH(sp, &sptree[dir], chain) {
 7697                         cnt++;
 7698                 }
 7699         }
 7700 
 7701         if (cnt == 0) {
 7702                 *errorp = ENOENT;
 7703                 return (NULL);
 7704         }
 7705 
 7706         m = NULL;
 7707         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
 7708                 LIST_FOREACH(sp, &sptree[dir], chain) {
 7709                         --cnt;
 7710                         n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt, pid);
 7711 
 7712                         if (!n) {
 7713                                 *errorp = ENOBUFS;
 7714                                 m_freem(m);
 7715                                 return (NULL);
 7716                         }
 7717                         if (!m)
 7718                                 m = n;
 7719                         else {
 7720                                 m->m_pkthdr.len += n->m_pkthdr.len;
 7721                                 m_cat(m, n);
 7722                         }
 7723                 }
 7724         }
 7725 
 7726         *errorp = 0;
 7727         return (m);
 7728 }
 7729 
 7730 static int
 7731 sysctl_net_key_dumpsa(SYSCTLFN_ARGS)
 7732 {
 7733         struct mbuf *m, *n;
 7734         int err2 = 0;
 7735         char *p, *ep;
 7736         size_t len;
 7737         int s, error;
 7738 
 7739         if (newp)
 7740                 return (EPERM);
 7741         if (namelen != 1)
 7742                 return (EINVAL);
 7743 
 7744         s = splsoftnet();
 7745         m = key_setdump(name[0], &error, l->l_proc->p_pid);
 7746         splx(s);
 7747         if (!m)
 7748                 return (error);
 7749         if (!oldp)
 7750                 *oldlenp = m->m_pkthdr.len;
 7751         else {
 7752                 p = oldp;
 7753                 if (*oldlenp < m->m_pkthdr.len) {
 7754                         err2 = ENOMEM;
 7755                         ep = p + *oldlenp;
 7756                 } else {
 7757                         *oldlenp = m->m_pkthdr.len;
 7758                         ep = p + m->m_pkthdr.len;
 7759                 }
 7760                 for (n = m; n; n = n->m_next) {
 7761                         len =  (ep - p < n->m_len) ?
 7762                                 ep - p : n->m_len;
 7763                         error = copyout(mtod(n, const void *), p, len);
 7764                         p += len;
 7765                         if (error)
 7766                                 break;
 7767                 }
 7768                 if (error == 0)
 7769                         error = err2;
 7770         }
 7771         m_freem(m);
 7772 
 7773         return (error);
 7774 }
 7775 
 7776 static int
 7777 sysctl_net_key_dumpsp(SYSCTLFN_ARGS)
 7778 {
 7779         struct mbuf *m, *n;
 7780         int err2 = 0;
 7781         char *p, *ep;
 7782         size_t len;
 7783         int s, error;
 7784 
 7785         if (newp)
 7786                 return (EPERM);
 7787         if (namelen != 0)
 7788                 return (EINVAL);
 7789 
 7790         s = splsoftnet();
 7791         m = key_setspddump(&error, l->l_proc->p_pid);
 7792         splx(s);
 7793         if (!m)
 7794                 return (error);
 7795         if (!oldp)
 7796                 *oldlenp = m->m_pkthdr.len;
 7797         else {
 7798                 p = oldp;
 7799                 if (*oldlenp < m->m_pkthdr.len) {
 7800                         err2 = ENOMEM;
 7801                         ep = p + *oldlenp;
 7802                 } else {
 7803                         *oldlenp = m->m_pkthdr.len;
 7804                         ep = p + m->m_pkthdr.len;
 7805                 }
 7806                 for (n = m; n; n = n->m_next) {
 7807                         len =  (ep - p < n->m_len) ?
 7808                                 ep - p : n->m_len;
 7809                         error = copyout(mtod(n, const void *), p, len);
 7810                         p += len;
 7811                         if (error)
 7812                                 break;
 7813                 }
 7814                 if (error == 0)
 7815                         error = err2;
 7816         }
 7817         m_freem(m);
 7818 
 7819         return (error);
 7820 }
 7821 
 7822 /*
 7823  * Create sysctl tree for native FAST_IPSEC key knobs, originally
 7824  * under name "net.keyv2"  * with MIB number { CTL_NET, PF_KEY_V2. }.
 7825  * However, sysctl(8) never checked for nodes under { CTL_NET, PF_KEY_V2 };
 7826  * and in any case the part of our sysctl namespace used for dumping the
 7827  * SPD and SA database  *HAS* to be compatible with the KAME sysctl
 7828  * namespace, for API reasons.
 7829  *
 7830  * Pending a consensus on the right way  to fix this, add a level of
 7831  * indirection in how we number the `native' FAST_IPSEC key nodes;
 7832  * and (as requested by Andrew Brown)  move registration of the
 7833  * KAME-compatible names  to a separate function.
 7834  */
 7835 #if 0
 7836 #  define FAST_IPSEC_PFKEY PF_KEY_V2
 7837 # define FAST_IPSEC_PFKEY_NAME "keyv2"
 7838 #else
 7839 #  define FAST_IPSEC_PFKEY PF_KEY
 7840 # define FAST_IPSEC_PFKEY_NAME "key"
 7841 #endif
 7842 
 7843 SYSCTL_SETUP(sysctl_net_keyv2_setup, "sysctl net.keyv2 subtree setup")
 7844 {
 7845 
 7846         sysctl_createv(clog, 0, NULL, NULL,
 7847                        CTLFLAG_PERMANENT,
 7848                        CTLTYPE_NODE, "net", NULL,
 7849                        NULL, 0, NULL, 0,
 7850                        CTL_NET, CTL_EOL);
 7851         sysctl_createv(clog, 0, NULL, NULL,
 7852                        CTLFLAG_PERMANENT,
 7853                        CTLTYPE_NODE, FAST_IPSEC_PFKEY_NAME, NULL,
 7854                        NULL, 0, NULL, 0,
 7855                        CTL_NET, FAST_IPSEC_PFKEY, CTL_EOL);
 7856 
 7857         sysctl_createv(clog, 0, NULL, NULL,
 7858                        CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
 7859                        CTLTYPE_INT, "debug", NULL,
 7860                        NULL, 0, &key_debug_level, 0,
 7861                        CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_DEBUG_LEVEL, CTL_EOL);
 7862         sysctl_createv(clog, 0, NULL, NULL,
 7863                        CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
 7864                        CTLTYPE_INT, "spi_try", NULL,
 7865                        NULL, 0, &key_spi_trycnt, 0,
 7866                        CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_SPI_TRY, CTL_EOL);
 7867         sysctl_createv(clog, 0, NULL, NULL,
 7868                        CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
 7869                        CTLTYPE_INT, "spi_min_value", NULL,
 7870                        NULL, 0, &key_spi_minval, 0,
 7871                        CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_SPI_MIN_VALUE, CTL_EOL);
 7872         sysctl_createv(clog, 0, NULL, NULL,
 7873                        CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
 7874                        CTLTYPE_INT, "spi_max_value", NULL,
 7875                        NULL, 0, &key_spi_maxval, 0,
 7876                        CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_SPI_MAX_VALUE, CTL_EOL);
 7877         sysctl_createv(clog, 0, NULL, NULL,
 7878                        CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
 7879                        CTLTYPE_INT, "random_int", NULL,
 7880                        NULL, 0, &key_int_random, 0,
 7881                        CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_RANDOM_INT, CTL_EOL);
 7882         sysctl_createv(clog, 0, NULL, NULL,
 7883                        CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
 7884                        CTLTYPE_INT, "larval_lifetime", NULL,
 7885                        NULL, 0, &key_larval_lifetime, 0,
 7886                        CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_LARVAL_LIFETIME, CTL_EOL);
 7887         sysctl_createv(clog, 0, NULL, NULL,
 7888                        CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
 7889                        CTLTYPE_INT, "blockacq_count", NULL,
 7890                        NULL, 0, &key_blockacq_count, 0,
 7891                        CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_BLOCKACQ_COUNT, CTL_EOL);
 7892         sysctl_createv(clog, 0, NULL, NULL,
 7893                        CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
 7894                        CTLTYPE_INT, "blockacq_lifetime", NULL,
 7895                        NULL, 0, &key_blockacq_lifetime, 0,
 7896                        CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_BLOCKACQ_LIFETIME, CTL_EOL);
 7897         sysctl_createv(clog, 0, NULL, NULL,
 7898                        CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
 7899                        CTLTYPE_INT, "esp_keymin", NULL,
 7900                        NULL, 0, &ipsec_esp_keymin, 0,
 7901                        CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_ESP_KEYMIN, CTL_EOL);
 7902         sysctl_createv(clog, 0, NULL, NULL,
 7903                        CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
 7904                        CTLTYPE_INT, "prefered_oldsa", NULL,
 7905                        NULL, 0, &key_prefered_oldsa, 0,
 7906                        CTL_NET, PF_KEY, KEYCTL_PREFERED_OLDSA, CTL_EOL);
 7907         sysctl_createv(clog, 0, NULL, NULL,
 7908                        CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
 7909                        CTLTYPE_INT, "esp_auth", NULL,
 7910                        NULL, 0, &ipsec_esp_auth, 0,
 7911                        CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_ESP_AUTH, CTL_EOL);
 7912         sysctl_createv(clog, 0, NULL, NULL,
 7913                        CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
 7914                        CTLTYPE_INT, "ah_keymin", NULL,
 7915                        NULL, 0, &ipsec_ah_keymin, 0,
 7916                        CTL_NET, FAST_IPSEC_PFKEY, KEYCTL_AH_KEYMIN, CTL_EOL);
 7917 }
 7918 
 7919 /*
 7920  * Register sysctl names used by setkey(8). For historical reasons,
 7921  * and to share a single API, these names appear under { CTL_NET, PF_KEY }
 7922  * for both FAST_IPSEC and KAME IPSEC.
 7923  */
 7924 SYSCTL_SETUP(sysctl_net_key_compat_setup, "sysctl net.key subtree setup for FAST_IPSEC")
 7925 {
 7926 
 7927         /* Make sure net.key exists before we register nodes underneath it. */
 7928         sysctl_createv(clog, 0, NULL, NULL,
 7929                        CTLFLAG_PERMANENT,
 7930                        CTLTYPE_NODE, "net", NULL,
 7931                        NULL, 0, NULL, 0,
 7932                        CTL_NET, CTL_EOL);
 7933         sysctl_createv(clog, 0, NULL, NULL,
 7934                        CTLFLAG_PERMANENT,
 7935                        CTLTYPE_NODE, "key", NULL,
 7936                        NULL, 0, NULL, 0,
 7937                        CTL_NET, PF_KEY, CTL_EOL);
 7938 
 7939         /* Register the net.key.dump{sa,sp} nodes used by setkey(8). */
 7940         sysctl_createv(clog, 0, NULL, NULL,
 7941                        CTLFLAG_PERMANENT,
 7942                        CTLTYPE_STRUCT, "dumpsa", NULL,
 7943                        sysctl_net_key_dumpsa, 0, NULL, 0,
 7944                        CTL_NET, PF_KEY, KEYCTL_DUMPSA, CTL_EOL);
 7945         sysctl_createv(clog, 0, NULL, NULL,
 7946                        CTLFLAG_PERMANENT,
 7947                        CTLTYPE_STRUCT, "dumpsp", NULL,
 7948                        sysctl_net_key_dumpsp, 0, NULL, 0,
 7949                        CTL_NET, PF_KEY, KEYCTL_DUMPSP, CTL_EOL);
 7950 }

Cache object: 3c5a1fd12524d5da8fd4f4a98bb33224


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.