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-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-2  -  FREEBSD-11-1  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-4  -  FREEBSD-10-3  -  FREEBSD-10-2  -  FREEBSD-10-1  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-3  -  FREEBSD-9-2  -  FREEBSD-9-1  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-4  -  FREEBSD-8-3  -  FREEBSD-8-2  -  FREEBSD-8-1  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-4  -  FREEBSD-7-3  -  FREEBSD-7-2  -  FREEBSD-7-1  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-4  -  FREEBSD-6-3  -  FREEBSD-6-2  -  FREEBSD-6-1  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-5  -  FREEBSD-5-4  -  FREEBSD-5-3  -  FREEBSD-5-2  -  FREEBSD-5-1  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
SearchContext: -  none  -  3  -  10 

    1 /*      $FreeBSD: stable/4/sys/netipsec/key.c 125828 2004-02-14 22:24:09Z bms $ */
    2 /*      $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $   */
    3 
    4 /*
    5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
    6  * All rights reserved.
    7  *
    8  * Redistribution and use in source and binary forms, with or without
    9  * modification, are permitted provided that the following conditions
   10  * are met:
   11  * 1. Redistributions of source code must retain the above copyright
   12  *    notice, this list of conditions and the following disclaimer.
   13  * 2. Redistributions in binary form must reproduce the above copyright
   14  *    notice, this list of conditions and the following disclaimer in the
   15  *    documentation and/or other materials provided with the distribution.
   16  * 3. Neither the name of the project nor the names of its contributors
   17  *    may be used to endorse or promote products derived from this software
   18  *    without specific prior written permission.
   19  *
   20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
   21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
   24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   30  * SUCH DAMAGE.
   31  */
   32 
   33 /*
   34  * This code is referd to RFC 2367
   35  */
   36 
   37 #include "opt_inet.h"
   38 #include "opt_inet6.h"
   39 #include "opt_ipsec.h"
   40 
   41 #include <sys/types.h>
   42 #include <sys/param.h>
   43 #include <sys/systm.h>
   44 #include <sys/kernel.h>
   45 #include <sys/mbuf.h>
   46 #include <sys/domain.h>
   47 #include <sys/protosw.h>
   48 #include <sys/malloc.h>
   49 #include <sys/socket.h>
   50 #include <sys/socketvar.h>
   51 #include <sys/sysctl.h>
   52 #include <sys/errno.h>
   53 #include <sys/proc.h>
   54 #include <sys/queue.h>
   55 #include <sys/syslog.h>
   56 
   57 #include <net/if.h>
   58 #include <net/route.h>
   59 #include <net/raw_cb.h>
   60 
   61 #include <netinet/in.h>
   62 #include <netinet/in_systm.h>
   63 #include <netinet/ip.h>
   64 #include <netinet/in_var.h>
   65 
   66 #ifdef INET6
   67 #include <netinet/ip6.h>
   68 #include <netinet6/in6_var.h>
   69 #include <netinet6/ip6_var.h>
   70 #endif /* INET6 */
   71 
   72 #ifdef INET
   73 #include <netinet/in_pcb.h>
   74 #endif
   75 #ifdef INET6
   76 #include <netinet6/in6_pcb.h>
   77 #endif /* INET6 */
   78 
   79 #include <net/pfkeyv2.h>
   80 #include <netipsec/keydb.h>
   81 #include <netipsec/key.h>
   82 #include <netipsec/keysock.h>
   83 #include <netipsec/key_debug.h>
   84 
   85 #include <netipsec/ipsec.h>
   86 #ifdef INET6
   87 #include <netipsec/ipsec6.h>
   88 #endif
   89 
   90 #include <netipsec/xform.h>
   91 
   92 #include <machine/stdarg.h>
   93 
   94 /* randomness */
   95 #include <sys/random.h>
   96 
   97 #include <net/net_osdep.h>
   98 
   99 #define FULLMASK        0xff
  100 #define _BITS(bytes)    ((bytes) << 3)
  101 
  102 /*
  103  * Note on SA reference counting:
  104  * - SAs that are not in DEAD state will have (total external reference + 1)
  105  *   following value in reference count field.  they cannot be freed and are
  106  *   referenced from SA header.
  107  * - SAs that are in DEAD state will have (total external reference)
  108  *   in reference count field.  they are ready to be freed.  reference from
  109  *   SA header will be removed in key_delsav(), when the reference count
  110  *   field hits 0 (= no external reference other than from SA header.
  111  */
  112 
  113 u_int32_t key_debug_level = 0;
  114 static u_int key_spi_trycnt = 1000;
  115 static u_int32_t key_spi_minval = 0x100;
  116 static u_int32_t key_spi_maxval = 0x0fffffff;   /* XXX */
  117 static u_int32_t policy_id = 0;
  118 static u_int key_int_random = 60;       /*interval to initialize randseed,1(m)*/
  119 static u_int key_larval_lifetime = 30;  /* interval to expire acquiring, 30(s)*/
  120 static int key_blockacq_count = 10;     /* counter for blocking SADB_ACQUIRE.*/
  121 static int key_blockacq_lifetime = 20;  /* lifetime for blocking SADB_ACQUIRE.*/
  122 static int key_prefered_oldsa = 1;      /* prefered old sa rather than new sa.*/
  123 
  124 static u_int32_t acq_seq = 0;
  125 static int key_tick_init_random = 0;
  126 
  127 static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX];     /* SPD */
  128 static LIST_HEAD(_sahtree, secashead) sahtree;                  /* SAD */
  129 static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
  130                                                         /* registed list */
  131 #ifndef IPSEC_NONBLOCK_ACQUIRE
  132 static LIST_HEAD(_acqtree, secacq) acqtree;             /* acquiring list */
  133 #endif
  134 static LIST_HEAD(_spacqtree, secspacq) spacqtree;       /* SP acquiring list */
  135 
  136 /* search order for SAs */
  137 static u_int saorder_state_valid[] = {
  138         SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
  139         /*
  140          * This order is important because we must select the oldest SA
  141          * for outbound processing.  For inbound, This is not important.
  142          */
  143 };
  144 static u_int saorder_state_alive[] = {
  145         /* except DEAD */
  146         SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
  147 };
  148 static u_int saorder_state_any[] = {
  149         SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
  150         SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
  151 };
  152 
  153 static const int minsize[] = {
  154         sizeof(struct sadb_msg),        /* SADB_EXT_RESERVED */
  155         sizeof(struct sadb_sa),         /* SADB_EXT_SA */
  156         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_CURRENT */
  157         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_HARD */
  158         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_SOFT */
  159         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_SRC */
  160         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_DST */
  161         sizeof(struct sadb_address),    /* SADB_EXT_ADDRESS_PROXY */
  162         sizeof(struct sadb_key),        /* SADB_EXT_KEY_AUTH */
  163         sizeof(struct sadb_key),        /* SADB_EXT_KEY_ENCRYPT */
  164         sizeof(struct sadb_ident),      /* SADB_EXT_IDENTITY_SRC */
  165         sizeof(struct sadb_ident),      /* SADB_EXT_IDENTITY_DST */
  166         sizeof(struct sadb_sens),       /* SADB_EXT_SENSITIVITY */
  167         sizeof(struct sadb_prop),       /* SADB_EXT_PROPOSAL */
  168         sizeof(struct sadb_supported),  /* SADB_EXT_SUPPORTED_AUTH */
  169         sizeof(struct sadb_supported),  /* SADB_EXT_SUPPORTED_ENCRYPT */
  170         sizeof(struct sadb_spirange),   /* SADB_EXT_SPIRANGE */
  171         0,                              /* SADB_X_EXT_KMPRIVATE */
  172         sizeof(struct sadb_x_policy),   /* SADB_X_EXT_POLICY */
  173         sizeof(struct sadb_x_sa2),      /* SADB_X_SA2 */
  174 };
  175 static const int maxsize[] = {
  176         sizeof(struct sadb_msg),        /* SADB_EXT_RESERVED */
  177         sizeof(struct sadb_sa),         /* SADB_EXT_SA */
  178         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_CURRENT */
  179         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_HARD */
  180         sizeof(struct sadb_lifetime),   /* SADB_EXT_LIFETIME_SOFT */
  181         0,                              /* SADB_EXT_ADDRESS_SRC */
  182         0,                              /* SADB_EXT_ADDRESS_DST */
  183         0,                              /* SADB_EXT_ADDRESS_PROXY */
  184         0,                              /* SADB_EXT_KEY_AUTH */
  185         0,                              /* SADB_EXT_KEY_ENCRYPT */
  186         0,                              /* SADB_EXT_IDENTITY_SRC */
  187         0,                              /* SADB_EXT_IDENTITY_DST */
  188         0,                              /* SADB_EXT_SENSITIVITY */
  189         0,                              /* SADB_EXT_PROPOSAL */
  190         0,                              /* SADB_EXT_SUPPORTED_AUTH */
  191         0,                              /* SADB_EXT_SUPPORTED_ENCRYPT */
  192         sizeof(struct sadb_spirange),   /* SADB_EXT_SPIRANGE */
  193         0,                              /* SADB_X_EXT_KMPRIVATE */
  194         0,                              /* SADB_X_EXT_POLICY */
  195         sizeof(struct sadb_x_sa2),      /* SADB_X_SA2 */
  196 };
  197 
  198 static int ipsec_esp_keymin = 256;
  199 static int ipsec_esp_auth = 0;
  200 static int ipsec_ah_keymin = 128;
  201 
  202 #ifdef SYSCTL_DECL
  203 SYSCTL_DECL(_net_key);
  204 #endif
  205 
  206 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL,        debug,  CTLFLAG_RW, \
  207         &key_debug_level,       0,      "");
  208 
  209 /* max count of trial for the decision of spi value */
  210 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY,            spi_trycnt,     CTLFLAG_RW, \
  211         &key_spi_trycnt,        0,      "");
  212 
  213 /* minimum spi value to allocate automatically. */
  214 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE,      spi_minval,     CTLFLAG_RW, \
  215         &key_spi_minval,        0,      "");
  216 
  217 /* maximun spi value to allocate automatically. */
  218 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE,      spi_maxval,     CTLFLAG_RW, \
  219         &key_spi_maxval,        0,      "");
  220 
  221 /* interval to initialize randseed */
  222 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random,     CTLFLAG_RW, \
  223         &key_int_random,        0,      "");
  224 
  225 /* lifetime for larval SA */
  226 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME,    larval_lifetime, CTLFLAG_RW, \
  227         &key_larval_lifetime,   0,      "");
  228 
  229 /* counter for blocking to send SADB_ACQUIRE to IKEd */
  230 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT,     blockacq_count, CTLFLAG_RW, \
  231         &key_blockacq_count,    0,      "");
  232 
  233 /* lifetime for blocking to send SADB_ACQUIRE to IKEd */
  234 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME,  blockacq_lifetime, CTLFLAG_RW, \
  235         &key_blockacq_lifetime, 0,      "");
  236 
  237 /* ESP auth */
  238 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH,   esp_auth, CTLFLAG_RW, \
  239         &ipsec_esp_auth,        0,      "");
  240 
  241 /* minimum ESP key length */
  242 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin, CTLFLAG_RW, \
  243         &ipsec_esp_keymin,      0,      "");
  244 
  245 /* minimum AH key length */
  246 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN,  ah_keymin, CTLFLAG_RW, \
  247         &ipsec_ah_keymin,       0,      "");
  248 
  249 /* perfered old SA rather than new SA */
  250 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA,     prefered_oldsa, CTLFLAG_RW,\
  251         &key_prefered_oldsa,    0,      "");
  252 
  253 #ifndef LIST_FOREACH
  254 #define LIST_FOREACH(elm, head, field)                                     \
  255         for (elm = LIST_FIRST(head); elm; elm = LIST_NEXT(elm, field))
  256 #endif
  257 #define __LIST_CHAINED(elm) \
  258         (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
  259 #define LIST_INSERT_TAIL(head, elm, type, field) \
  260 do {\
  261         struct type *curelm = LIST_FIRST(head); \
  262         if (curelm == NULL) {\
  263                 LIST_INSERT_HEAD(head, elm, field); \
  264         } else { \
  265                 while (LIST_NEXT(curelm, field)) \
  266                         curelm = LIST_NEXT(curelm, field);\
  267                 LIST_INSERT_AFTER(curelm, elm, field);\
  268         }\
  269 } while (0)
  270 
  271 #define KEY_CHKSASTATE(head, sav, name) \
  272 do { \
  273         if ((head) != (sav)) {                                          \
  274                 ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
  275                         (name), (head), (sav)));                        \
  276                 continue;                                               \
  277         }                                                               \
  278 } while (0)
  279 
  280 #define KEY_CHKSPDIR(head, sp, name) \
  281 do { \
  282         if ((head) != (sp)) {                                           \
  283                 ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
  284                         "anyway continue.\n",                           \
  285                         (name), (head), (sp)));                         \
  286         }                                                               \
  287 } while (0)
  288 
  289 MALLOC_DEFINE(M_SECA, "key mgmt", "security associations, key management");
  290 
  291 #if 1
  292 #define KMALLOC(p, t, n)                                                     \
  293         ((p) = (t) malloc((unsigned long)(n), M_SECA, M_NOWAIT))
  294 #define KFREE(p)                                                             \
  295         free((caddr_t)(p), M_SECA)
  296 #else
  297 #define KMALLOC(p, t, n) \
  298 do { \
  299         ((p) = (t)malloc((unsigned long)(n), M_SECA, M_NOWAIT));             \
  300         printf("%s %d: %p <- KMALLOC(%s, %d)\n",                             \
  301                 __FILE__, __LINE__, (p), #t, n);                             \
  302 } while (0)
  303 
  304 #define KFREE(p)                                                             \
  305         do {                                                                 \
  306                 printf("%s %d: %p -> KFREE()\n", __FILE__, __LINE__, (p));   \
  307                 free((caddr_t)(p), M_SECA);                                  \
  308         } while (0)
  309 #endif
  310 
  311 /*
  312  * set parameters into secpolicyindex buffer.
  313  * Must allocate secpolicyindex buffer passed to this function.
  314  */
  315 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
  316 do { \
  317         bzero((idx), sizeof(struct secpolicyindex));                         \
  318         (idx)->dir = (_dir);                                                 \
  319         (idx)->prefs = (ps);                                                 \
  320         (idx)->prefd = (pd);                                                 \
  321         (idx)->ul_proto = (ulp);                                             \
  322         bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len);     \
  323         bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len);     \
  324 } while (0)
  325 
  326 /*
  327  * set parameters into secasindex buffer.
  328  * Must allocate secasindex buffer before calling this function.
  329  */
  330 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
  331 do { \
  332         bzero((idx), sizeof(struct secasindex));                             \
  333         (idx)->proto = (p);                                                  \
  334         (idx)->mode = (m);                                                   \
  335         (idx)->reqid = (r);                                                  \
  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 /* key statistics */
  341 struct _keystat {
  342         u_long getspi_count; /* the avarage of count to try to get new SPI */
  343 } keystat;
  344 
  345 struct sadb_msghdr {
  346         struct sadb_msg *msg;
  347         struct sadb_ext *ext[SADB_EXT_MAX + 1];
  348         int extoff[SADB_EXT_MAX + 1];
  349         int extlen[SADB_EXT_MAX + 1];
  350 };
  351 
  352 static struct secasvar *key_allocsa_policy __P((const struct secasindex *));
  353 static void key_freesp_so __P((struct secpolicy **));
  354 static struct secasvar *key_do_allocsa_policy __P((struct secashead *, u_int));
  355 static void key_delsp __P((struct secpolicy *));
  356 static struct secpolicy *key_getsp __P((struct secpolicyindex *));
  357 static struct secpolicy *key_getspbyid __P((u_int32_t));
  358 static u_int32_t key_newreqid __P((void));
  359 static struct mbuf *key_gather_mbuf __P((struct mbuf *,
  360         const struct sadb_msghdr *, int, int, ...));
  361 static int key_spdadd __P((struct socket *, struct mbuf *,
  362         const struct sadb_msghdr *));
  363 static u_int32_t key_getnewspid __P((void));
  364 static int key_spddelete __P((struct socket *, struct mbuf *,
  365         const struct sadb_msghdr *));
  366 static int key_spddelete2 __P((struct socket *, struct mbuf *,
  367         const struct sadb_msghdr *));
  368 static int key_spdget __P((struct socket *, struct mbuf *,
  369         const struct sadb_msghdr *));
  370 static int key_spdflush __P((struct socket *, struct mbuf *,
  371         const struct sadb_msghdr *));
  372 static int key_spddump __P((struct socket *, struct mbuf *,
  373         const struct sadb_msghdr *));
  374 static struct mbuf *key_setdumpsp __P((struct secpolicy *,
  375         u_int8_t, u_int32_t, u_int32_t));
  376 static u_int key_getspreqmsglen __P((struct secpolicy *));
  377 static int key_spdexpire __P((struct secpolicy *));
  378 static struct secashead *key_newsah __P((struct secasindex *));
  379 static void key_delsah __P((struct secashead *));
  380 static struct secasvar *key_newsav __P((struct mbuf *,
  381         const struct sadb_msghdr *, struct secashead *, int *,
  382         const char*, int));
  383 #define KEY_NEWSAV(m, sadb, sah, e)                             \
  384         key_newsav(m, sadb, sah, e, __FILE__, __LINE__)
  385 static void key_delsav __P((struct secasvar *));
  386 static struct secashead *key_getsah __P((struct secasindex *));
  387 static struct secasvar *key_checkspidup __P((struct secasindex *, u_int32_t));
  388 static struct secasvar *key_getsavbyspi __P((struct secashead *, u_int32_t));
  389 static int key_setsaval __P((struct secasvar *, struct mbuf *,
  390         const struct sadb_msghdr *));
  391 static int key_mature __P((struct secasvar *));
  392 static struct mbuf *key_setdumpsa __P((struct secasvar *, u_int8_t,
  393         u_int8_t, u_int32_t, u_int32_t));
  394 static struct mbuf *key_setsadbmsg __P((u_int8_t, u_int16_t, u_int8_t,
  395         u_int32_t, pid_t, u_int16_t));
  396 static struct mbuf *key_setsadbsa __P((struct secasvar *));
  397 static struct mbuf *key_setsadbaddr __P((u_int16_t,
  398         const struct sockaddr *, u_int8_t, u_int16_t));
  399 #if 0
  400 static struct mbuf *key_setsadbident __P((u_int16_t, u_int16_t, caddr_t,
  401         int, u_int64_t));
  402 #endif
  403 static struct mbuf *key_setsadbxsa2 __P((u_int8_t, u_int32_t, u_int32_t));
  404 static struct mbuf *key_setsadbxpolicy __P((u_int16_t, u_int8_t,
  405         u_int32_t));
  406 static void *key_newbuf __P((const void *, u_int));
  407 #ifdef INET6
  408 static int key_ismyaddr6 __P((struct sockaddr_in6 *));
  409 #endif
  410 
  411 /* flags for key_cmpsaidx() */
  412 #define CMP_HEAD        1       /* protocol, addresses. */
  413 #define CMP_MODE_REQID  2       /* additionally HEAD, reqid, mode. */
  414 #define CMP_REQID       3       /* additionally HEAD, reaid. */
  415 #define CMP_EXACTLY     4       /* all elements. */
  416 static int key_cmpsaidx
  417         __P((const struct secasindex *, const struct secasindex *, int));
  418 
  419 static int key_cmpspidx_exactly
  420         __P((struct secpolicyindex *, struct secpolicyindex *));
  421 static int key_cmpspidx_withmask
  422         __P((struct secpolicyindex *, struct secpolicyindex *));
  423 static int key_sockaddrcmp __P((const struct sockaddr *, const struct sockaddr *, int));
  424 static int key_bbcmp __P((const void *, const void *, u_int));
  425 static void key_srandom __P((void));
  426 static u_int16_t key_satype2proto __P((u_int8_t));
  427 static u_int8_t key_proto2satype __P((u_int16_t));
  428 
  429 static int key_getspi __P((struct socket *, struct mbuf *,
  430         const struct sadb_msghdr *));
  431 static u_int32_t key_do_getnewspi __P((struct sadb_spirange *,
  432                                         struct secasindex *));
  433 static int key_update __P((struct socket *, struct mbuf *,
  434         const struct sadb_msghdr *));
  435 #ifdef IPSEC_DOSEQCHECK
  436 static struct secasvar *key_getsavbyseq __P((struct secashead *, u_int32_t));
  437 #endif
  438 static int key_add __P((struct socket *, struct mbuf *,
  439         const struct sadb_msghdr *));
  440 static int key_setident __P((struct secashead *, struct mbuf *,
  441         const struct sadb_msghdr *));
  442 static struct mbuf *key_getmsgbuf_x1 __P((struct mbuf *,
  443         const struct sadb_msghdr *));
  444 static int key_delete __P((struct socket *, struct mbuf *,
  445         const struct sadb_msghdr *));
  446 static int key_get __P((struct socket *, struct mbuf *,
  447         const struct sadb_msghdr *));
  448 
  449 static void key_getcomb_setlifetime __P((struct sadb_comb *));
  450 static struct mbuf *key_getcomb_esp __P((void));
  451 static struct mbuf *key_getcomb_ah __P((void));
  452 static struct mbuf *key_getcomb_ipcomp __P((void));
  453 static struct mbuf *key_getprop __P((const struct secasindex *));
  454 
  455 static int key_acquire __P((const struct secasindex *, struct secpolicy *));
  456 #ifndef IPSEC_NONBLOCK_ACQUIRE
  457 static struct secacq *key_newacq __P((const struct secasindex *));
  458 static struct secacq *key_getacq __P((const struct secasindex *));
  459 static struct secacq *key_getacqbyseq __P((u_int32_t));
  460 #endif
  461 static struct secspacq *key_newspacq __P((struct secpolicyindex *));
  462 static struct secspacq *key_getspacq __P((struct secpolicyindex *));
  463 static int key_acquire2 __P((struct socket *, struct mbuf *,
  464         const struct sadb_msghdr *));
  465 static int key_register __P((struct socket *, struct mbuf *,
  466         const struct sadb_msghdr *));
  467 static int key_expire __P((struct secasvar *));
  468 static int key_flush __P((struct socket *, struct mbuf *,
  469         const struct sadb_msghdr *));
  470 static int key_dump __P((struct socket *, struct mbuf *,
  471         const struct sadb_msghdr *));
  472 static int key_promisc __P((struct socket *, struct mbuf *,
  473         const struct sadb_msghdr *));
  474 static int key_senderror __P((struct socket *, struct mbuf *, int));
  475 static int key_validate_ext __P((const struct sadb_ext *, int));
  476 static int key_align __P((struct mbuf *, struct sadb_msghdr *));
  477 #if 0
  478 static const char *key_getfqdn __P((void));
  479 static const char *key_getuserfqdn __P((void));
  480 #endif
  481 static void key_sa_chgstate __P((struct secasvar *, u_int8_t));
  482 static struct mbuf *key_alloc_mbuf __P((int));
  483 
  484 #define SA_ADDREF(p) do {                                               \
  485         (p)->refcnt++;                                                  \
  486         KASSERT((p)->refcnt != 0,                                       \
  487                 ("SA refcnt overflow at %s:%u", __FILE__, __LINE__));   \
  488 } while (0)
  489 #define SA_DELREF(p) do {                                               \
  490         KASSERT((p)->refcnt > 0,                                        \
  491                 ("SA refcnt underflow at %s:%u", __FILE__, __LINE__));  \
  492         (p)->refcnt--;                                                  \
  493 } while (0)
  494 
  495 #define SP_ADDREF(p) do {                                               \
  496         (p)->refcnt++;                                                  \
  497         KASSERT((p)->refcnt != 0,                                       \
  498                 ("SP refcnt overflow at %s:%u", __FILE__, __LINE__));   \
  499 } while (0)
  500 #define SP_DELREF(p) do {                                               \
  501         KASSERT((p)->refcnt > 0,                                        \
  502                 ("SP refcnt underflow at %s:%u", __FILE__, __LINE__));  \
  503         (p)->refcnt--;                                                  \
  504 } while (0)
  505 
  506 /*
  507  * Return 0 when there are known to be no SP's for the specified
  508  * direction.  Otherwise return 1.  This is used by IPsec code
  509  * to optimize performance.
  510  */
  511 int
  512 key_havesp(u_int dir)
  513 {
  514         return (dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND ?
  515                 LIST_FIRST(&sptree[dir]) != NULL : 1);
  516 }
  517 
  518 /* %%% IPsec policy management */
  519 /*
  520  * allocating a SP for OUTBOUND or INBOUND packet.
  521  * Must call key_freesp() later.
  522  * OUT: NULL:   not found
  523  *      others: found and return the pointer.
  524  */
  525 struct secpolicy *
  526 key_allocsp(struct secpolicyindex *spidx, u_int dir, const char* where, int tag)
  527 {
  528         struct secpolicy *sp;
  529         int s;
  530 
  531         KASSERT(spidx != NULL, ("key_allocsp: null spidx"));
  532         KASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
  533                 ("key_allocsp: invalid direction %u", dir));
  534 
  535         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  536                 printf("DP key_allocsp from %s:%u\n", where, tag));
  537 
  538         /* get a SP entry */
  539         s = splnet();   /*called from softclock()*/
  540         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
  541                 printf("*** objects\n");
  542                 kdebug_secpolicyindex(spidx));
  543 
  544         LIST_FOREACH(sp, &sptree[dir], chain) {
  545                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
  546                         printf("*** in SPD\n");
  547                         kdebug_secpolicyindex(&sp->spidx));
  548 
  549                 if (sp->state == IPSEC_SPSTATE_DEAD)
  550                         continue;
  551                 if (key_cmpspidx_withmask(&sp->spidx, spidx))
  552                         goto found;
  553         }
  554         sp = NULL;
  555 found:
  556         if (sp) {
  557                 /* sanity check */
  558                 KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp");
  559 
  560                 /* found a SPD entry */
  561                 sp->lastused = time_second;
  562                 SP_ADDREF(sp);
  563         }
  564         splx(s);
  565 
  566         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  567                 printf("DP key_allocsp return SP:%p (ID=%u) refcnt %u\n",
  568                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
  569         return sp;
  570 }
  571 
  572 /*
  573  * allocating a SP for OUTBOUND or INBOUND packet.
  574  * Must call key_freesp() later.
  575  * OUT: NULL:   not found
  576  *      others: found and return the pointer.
  577  */
  578 struct secpolicy *
  579 key_allocsp2(u_int32_t spi,
  580              union sockaddr_union *dst,
  581              u_int8_t proto,
  582              u_int dir,
  583              const char* where, int tag)
  584 {
  585         struct secpolicy *sp;
  586         int s;
  587 
  588         KASSERT(dst != NULL, ("key_allocsp2: null dst"));
  589         KASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
  590                 ("key_allocsp2: invalid direction %u", dir));
  591 
  592         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  593                 printf("DP key_allocsp2 from %s:%u\n", where, tag));
  594 
  595         /* get a SP entry */
  596         s = splnet();   /*called from softclock()*/
  597         KEYDEBUG(KEYDEBUG_IPSEC_DATA,
  598                 printf("*** objects\n");
  599                 printf("spi %u proto %u dir %u\n", spi, proto, dir);
  600                 kdebug_sockaddr(&dst->sa));
  601 
  602         LIST_FOREACH(sp, &sptree[dir], chain) {
  603                 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
  604                         printf("*** in SPD\n");
  605                         kdebug_secpolicyindex(&sp->spidx));
  606 
  607                 if (sp->state == IPSEC_SPSTATE_DEAD)
  608                         continue;
  609                 /* compare simple values, then dst address */
  610                 if (sp->spidx.ul_proto != proto)
  611                         continue;
  612                 /* NB: spi's must exist and match */
  613                 if (!sp->req || !sp->req->sav || sp->req->sav->spi != spi)
  614                         continue;
  615                 if (key_sockaddrcmp(&sp->spidx.dst.sa, &dst->sa, 1) == 0)
  616                         goto found;
  617         }
  618         sp = NULL;
  619 found:
  620         if (sp) {
  621                 /* sanity check */
  622                 KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp2");
  623 
  624                 /* found a SPD entry */
  625                 sp->lastused = time_second;
  626                 SP_ADDREF(sp);
  627         }
  628         splx(s);
  629 
  630         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  631                 printf("DP key_allocsp2 return SP:%p (ID=%u) refcnt %u\n",
  632                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
  633         return sp;
  634 }
  635 
  636 /*
  637  * return a policy that matches this particular inbound packet.
  638  * XXX slow
  639  */
  640 struct secpolicy *
  641 key_gettunnel(const struct sockaddr *osrc,
  642               const struct sockaddr *odst,
  643               const struct sockaddr *isrc,
  644               const struct sockaddr *idst,
  645               const char* where, int tag)
  646 {
  647         struct secpolicy *sp;
  648         const int dir = IPSEC_DIR_INBOUND;
  649         int s;
  650         struct ipsecrequest *r1, *r2, *p;
  651         struct secpolicyindex spidx;
  652 
  653         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  654                 printf("DP key_gettunnel from %s:%u\n", where, tag));
  655 
  656         if (isrc->sa_family != idst->sa_family) {
  657                 ipseclog((LOG_ERR, "protocol family mismatched %d != %d\n.",
  658                         isrc->sa_family, idst->sa_family));
  659                 sp = NULL;
  660                 goto done;
  661         }
  662 
  663         s = splnet();   /*called from softclock()*/
  664         LIST_FOREACH(sp, &sptree[dir], chain) {
  665                 if (sp->state == IPSEC_SPSTATE_DEAD)
  666                         continue;
  667 
  668                 r1 = r2 = NULL;
  669                 for (p = sp->req; p; p = p->next) {
  670                         if (p->saidx.mode != IPSEC_MODE_TUNNEL)
  671                                 continue;
  672 
  673                         r1 = r2;
  674                         r2 = p;
  675 
  676                         if (!r1) {
  677                                 /* here we look at address matches only */
  678                                 spidx = sp->spidx;
  679                                 if (isrc->sa_len > sizeof(spidx.src) ||
  680                                     idst->sa_len > sizeof(spidx.dst))
  681                                         continue;
  682                                 bcopy(isrc, &spidx.src, isrc->sa_len);
  683                                 bcopy(idst, &spidx.dst, idst->sa_len);
  684                                 if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
  685                                         continue;
  686                         } else {
  687                                 if (key_sockaddrcmp(&r1->saidx.src.sa, isrc, 0) ||
  688                                     key_sockaddrcmp(&r1->saidx.dst.sa, idst, 0))
  689                                         continue;
  690                         }
  691 
  692                         if (key_sockaddrcmp(&r2->saidx.src.sa, osrc, 0) ||
  693                             key_sockaddrcmp(&r2->saidx.dst.sa, odst, 0))
  694                                 continue;
  695 
  696                         goto found;
  697                 }
  698         }
  699         sp = NULL;
  700 found:
  701         if (sp) {
  702                 sp->lastused = time_second;
  703                 SP_ADDREF(sp);
  704         }
  705         splx(s);
  706 done:
  707         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  708                 printf("DP key_gettunnel return SP:%p (ID=%u) refcnt %u\n",
  709                         sp, sp ? sp->id : 0, sp ? sp->refcnt : 0));
  710         return sp;
  711 }
  712 
  713 /*
  714  * allocating an SA entry for an *OUTBOUND* packet.
  715  * checking each request entries in SP, and acquire an SA if need.
  716  * OUT: 0: there are valid requests.
  717  *      ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
  718  */
  719 int
  720 key_checkrequest(struct ipsecrequest *isr, const struct secasindex *saidx)
  721 {
  722         u_int level;
  723         int error;
  724 
  725         KASSERT(isr != NULL, ("key_checkrequest: null isr"));
  726         KASSERT(saidx != NULL, ("key_checkrequest: null saidx"));
  727         KASSERT(saidx->mode == IPSEC_MODE_TRANSPORT ||
  728                 saidx->mode == IPSEC_MODE_TUNNEL,
  729                 ("key_checkrequest: unexpected policy %u", saidx->mode));
  730 
  731         /* get current level */
  732         level = ipsec_get_reqlevel(isr);
  733 
  734         /*
  735          * XXX guard against protocol callbacks from the crypto
  736          * thread as they reference ipsecrequest.sav which we
  737          * temporarily null out below.  Need to rethink how we
  738          * handle bundled SA's in the callback thread.
  739          */
  740         SPLASSERT(net, "key_checkrequest");
  741 #if 0
  742         /*
  743          * We do allocate new SA only if the state of SA in the holder is
  744          * SADB_SASTATE_DEAD.  The SA for outbound must be the oldest.
  745          */
  746         if (isr->sav != NULL) {
  747                 if (isr->sav->sah == NULL)
  748                         panic("key_checkrequest: sah is null.\n");
  749                 if (isr->sav == (struct secasvar *)LIST_FIRST(
  750                             &isr->sav->sah->savtree[SADB_SASTATE_DEAD])) {
  751                         KEY_FREESAV(&isr->sav);
  752                         isr->sav = NULL;
  753                 }
  754         }
  755 #else
  756         /*
  757          * we free any SA stashed in the IPsec request because a different
  758          * SA may be involved each time this request is checked, either
  759          * because new SAs are being configured, or this request is
  760          * associated with an unconnected datagram socket, or this request
  761          * is associated with a system default policy.
  762          *
  763          * The operation may have negative impact to performance.  We may
  764          * want to check cached SA carefully, rather than picking new SA
  765          * every time.
  766          */
  767         if (isr->sav != NULL) {
  768                 KEY_FREESAV(&isr->sav);
  769                 isr->sav = NULL;
  770         }
  771 #endif
  772 
  773         /*
  774          * new SA allocation if no SA found.
  775          * key_allocsa_policy should allocate the oldest SA available.
  776          * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
  777          */
  778         if (isr->sav == NULL)
  779                 isr->sav = key_allocsa_policy(saidx);
  780 
  781         /* When there is SA. */
  782         if (isr->sav != NULL) {
  783                 if (isr->sav->state != SADB_SASTATE_MATURE &&
  784                     isr->sav->state != SADB_SASTATE_DYING)
  785                         return EINVAL;
  786                 return 0;
  787         }
  788 
  789         /* there is no SA */
  790         error = key_acquire(saidx, isr->sp);
  791         if (error != 0) {
  792                 /* XXX What should I do ? */
  793                 ipseclog((LOG_DEBUG, "key_checkrequest: error %d returned "
  794                         "from key_acquire.\n", error));
  795                 return error;
  796         }
  797 
  798         if (level != IPSEC_LEVEL_REQUIRE) {
  799                 /* XXX sigh, the interface to this routine is botched */
  800                 KASSERT(isr->sav == NULL, ("key_checkrequest: unexpected SA"));
  801                 return 0;
  802         } else {
  803                 return ENOENT;
  804         }
  805 }
  806 
  807 /*
  808  * allocating a SA for policy entry from SAD.
  809  * NOTE: searching SAD of aliving state.
  810  * OUT: NULL:   not found.
  811  *      others: found and return the pointer.
  812  */
  813 static struct secasvar *
  814 key_allocsa_policy(const struct secasindex *saidx)
  815 {
  816         struct secashead *sah;
  817         struct secasvar *sav;
  818         u_int stateidx, state;
  819 
  820         LIST_FOREACH(sah, &sahtree, chain) {
  821                 if (sah->state == SADB_SASTATE_DEAD)
  822                         continue;
  823                 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE_REQID))
  824                         goto found;
  825         }
  826 
  827         return NULL;
  828 
  829     found:
  830 
  831         /* search valid state */
  832         for (stateidx = 0;
  833              stateidx < _ARRAYLEN(saorder_state_valid);
  834              stateidx++) {
  835 
  836                 state = saorder_state_valid[stateidx];
  837 
  838                 sav = key_do_allocsa_policy(sah, state);
  839                 if (sav != NULL)
  840                         return sav;
  841         }
  842 
  843         return NULL;
  844 }
  845 
  846 /*
  847  * searching SAD with direction, protocol, mode and state.
  848  * called by key_allocsa_policy().
  849  * OUT:
  850  *      NULL    : not found
  851  *      others  : found, pointer to a SA.
  852  */
  853 static struct secasvar *
  854 key_do_allocsa_policy(struct secashead *sah, u_int state)
  855 {
  856         struct secasvar *sav, *nextsav, *candidate, *d;
  857 
  858         /* initilize */
  859         candidate = NULL;
  860 
  861         for (sav = LIST_FIRST(&sah->savtree[state]);
  862              sav != NULL;
  863              sav = nextsav) {
  864 
  865                 nextsav = LIST_NEXT(sav, chain);
  866 
  867                 /* sanity check */
  868                 KEY_CHKSASTATE(sav->state, state, "key_do_allocsa_policy");
  869 
  870                 /* initialize */
  871                 if (candidate == NULL) {
  872                         candidate = sav;
  873                         continue;
  874                 }
  875 
  876                 /* Which SA is the better ? */
  877 
  878                 /* sanity check 2 */
  879                 if (candidate->lft_c == NULL || sav->lft_c == NULL)
  880                         panic("key_do_allocsa_policy: "
  881                                 "lifetime_current is NULL.\n");
  882 
  883                 /* What the best method is to compare ? */
  884                 if (key_prefered_oldsa) {
  885                         if (candidate->lft_c->sadb_lifetime_addtime >
  886                                         sav->lft_c->sadb_lifetime_addtime) {
  887                                 candidate = sav;
  888                         }
  889                         continue;
  890                         /*NOTREACHED*/
  891                 }
  892 
  893                 /* prefered new sa rather than old sa */
  894                 if (candidate->lft_c->sadb_lifetime_addtime <
  895                                 sav->lft_c->sadb_lifetime_addtime) {
  896                         d = candidate;
  897                         candidate = sav;
  898                 } else
  899                         d = sav;
  900 
  901                 /*
  902                  * prepared to delete the SA when there is more
  903                  * suitable candidate and the lifetime of the SA is not
  904                  * permanent.
  905                  */
  906                 if (d->lft_c->sadb_lifetime_addtime != 0) {
  907                         struct mbuf *m, *result;
  908 
  909                         key_sa_chgstate(d, SADB_SASTATE_DEAD);
  910 
  911                         KASSERT(d->refcnt > 0,
  912                                 ("key_do_allocsa_policy: bogus ref count"));
  913                         m = key_setsadbmsg(SADB_DELETE, 0,
  914                             d->sah->saidx.proto, 0, 0, d->refcnt - 1);
  915                         if (!m)
  916                                 goto msgfail;
  917                         result = m;
  918 
  919                         /* set sadb_address for saidx's. */
  920                         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
  921                                 &d->sah->saidx.src.sa,
  922                                 d->sah->saidx.src.sa.sa_len << 3,
  923                                 IPSEC_ULPROTO_ANY);
  924                         if (!m)
  925                                 goto msgfail;
  926                         m_cat(result, m);
  927 
  928                         /* set sadb_address for saidx's. */
  929                         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
  930                                 &d->sah->saidx.src.sa,
  931                                 d->sah->saidx.src.sa.sa_len << 3,
  932                                 IPSEC_ULPROTO_ANY);
  933                         if (!m)
  934                                 goto msgfail;
  935                         m_cat(result, m);
  936 
  937                         /* create SA extension */
  938                         m = key_setsadbsa(d);
  939                         if (!m)
  940                                 goto msgfail;
  941                         m_cat(result, m);
  942 
  943                         if (result->m_len < sizeof(struct sadb_msg)) {
  944                                 result = m_pullup(result,
  945                                                 sizeof(struct sadb_msg));
  946                                 if (result == NULL)
  947                                         goto msgfail;
  948                         }
  949 
  950                         result->m_pkthdr.len = 0;
  951                         for (m = result; m; m = m->m_next)
  952                                 result->m_pkthdr.len += m->m_len;
  953                         mtod(result, struct sadb_msg *)->sadb_msg_len =
  954                                 PFKEY_UNIT64(result->m_pkthdr.len);
  955 
  956                         if (key_sendup_mbuf(NULL, result,
  957                                         KEY_SENDUP_REGISTERED))
  958                                 goto msgfail;
  959                  msgfail:
  960                         KEY_FREESAV(&d);
  961                 }
  962         }
  963 
  964         if (candidate) {
  965                 SA_ADDREF(candidate);
  966                 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
  967                         printf("DP allocsa_policy cause "
  968                                 "refcnt++:%d SA:%p\n",
  969                                 candidate->refcnt, candidate));
  970         }
  971         return candidate;
  972 }
  973 
  974 /*
  975  * allocating a usable SA entry for a *INBOUND* packet.
  976  * Must call key_freesav() later.
  977  * OUT: positive:       pointer to a usable sav (i.e. MATURE or DYING state).
  978  *      NULL:           not found, or error occured.
  979  *
  980  * In the comparison, no source address is used--for RFC2401 conformance.
  981  * To quote, from section 4.1:
  982  *      A security association is uniquely identified by a triple consisting
  983  *      of a Security Parameter Index (SPI), an IP Destination Address, and a
  984  *      security protocol (AH or ESP) identifier.
  985  * Note that, however, we do need to keep source address in IPsec SA.
  986  * IKE specification and PF_KEY specification do assume that we
  987  * keep source address in IPsec SA.  We see a tricky situation here.
  988  */
  989 struct secasvar *
  990 key_allocsa(
  991         union sockaddr_union *dst,
  992         u_int proto,
  993         u_int32_t spi,
  994         const char* where, int tag)
  995 {
  996         struct secashead *sah;
  997         struct secasvar *sav;
  998         u_int stateidx, state;
  999         int s;
 1000 
 1001         KASSERT(dst != NULL, ("key_allocsa: null dst address"));
 1002 
 1003         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1004                 printf("DP key_allocsa from %s:%u\n", where, tag));
 1005 
 1006         /*
 1007          * searching SAD.
 1008          * XXX: to be checked internal IP header somewhere.  Also when
 1009          * IPsec tunnel packet is received.  But ESP tunnel mode is
 1010          * encrypted so we can't check internal IP header.
 1011          */
 1012         s = splnet();   /*called from softclock()*/
 1013         LIST_FOREACH(sah, &sahtree, chain) {
 1014                 /* search valid state */
 1015                 for (stateidx = 0;
 1016                      stateidx < _ARRAYLEN(saorder_state_valid);
 1017                      stateidx++) {
 1018                         state = saorder_state_valid[stateidx];
 1019                         LIST_FOREACH(sav, &sah->savtree[state], chain) {
 1020                                 /* sanity check */
 1021                                 KEY_CHKSASTATE(sav->state, state, "key_allocsav");
 1022                                 /* do not return entries w/ unusable state */
 1023                                 if (sav->state != SADB_SASTATE_MATURE &&
 1024                                     sav->state != SADB_SASTATE_DYING)
 1025                                         continue;
 1026                                 if (proto != sav->sah->saidx.proto)
 1027                                         continue;
 1028                                 if (spi != sav->spi)
 1029                                         continue;
 1030 #if 0   /* don't check src */
 1031                                 /* check src address */
 1032                                 if (key_sockaddrcmp(&src->sa, &sav->sah->saidx.src.sa, 0) != 0)
 1033                                         continue;
 1034 #endif
 1035                                 /* check dst address */
 1036                                 if (key_sockaddrcmp(&dst->sa, &sav->sah->saidx.dst.sa, 0) != 0)
 1037                                         continue;
 1038                                 SA_ADDREF(sav);
 1039                                 goto done;
 1040                         }
 1041                 }
 1042         }
 1043         sav = NULL;
 1044 done:
 1045         splx(s);
 1046 
 1047         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1048                 printf("DP key_allocsa return SA:%p; refcnt %u\n",
 1049                         sav, sav ? sav->refcnt : 0));
 1050         return sav;
 1051 }
 1052 
 1053 /*
 1054  * Must be called after calling key_allocsp().
 1055  * For both the packet without socket and key_freeso().
 1056  */
 1057 void
 1058 _key_freesp(struct secpolicy **spp, const char* where, int tag)
 1059 {
 1060         struct secpolicy *sp = *spp;
 1061 
 1062         KASSERT(sp != NULL, ("key_freesp: null sp"));
 1063 
 1064         SP_DELREF(sp);
 1065 
 1066         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1067                 printf("DP key_freesp SP:%p (ID=%u) from %s:%u; refcnt now %u\n",
 1068                         sp, sp->id, where, tag, sp->refcnt));
 1069 
 1070         if (sp->refcnt == 0) {
 1071                 *spp = NULL;
 1072                 key_delsp(sp);
 1073         }
 1074 }
 1075 
 1076 /*
 1077  * Must be called after calling key_allocsp().
 1078  * For the packet with socket.
 1079  */
 1080 void
 1081 key_freeso(struct socket *so)
 1082 {
 1083         /* sanity check */
 1084         KASSERT(so != NULL, ("key_freeso: null so"));
 1085 
 1086         switch (so->so_proto->pr_domain->dom_family) {
 1087 #ifdef INET
 1088         case PF_INET:
 1089             {
 1090                 struct inpcb *pcb = sotoinpcb(so);
 1091 
 1092                 /* Does it have a PCB ? */
 1093                 if (pcb == NULL)
 1094                         return;
 1095                 key_freesp_so(&pcb->inp_sp->sp_in);
 1096                 key_freesp_so(&pcb->inp_sp->sp_out);
 1097             }
 1098                 break;
 1099 #endif
 1100 #ifdef INET6
 1101         case PF_INET6:
 1102             {
 1103 #ifdef HAVE_NRL_INPCB
 1104                 struct inpcb *pcb  = sotoinpcb(so);
 1105 
 1106                 /* Does it have a PCB ? */
 1107                 if (pcb == NULL)
 1108                         return;
 1109                 key_freesp_so(&pcb->inp_sp->sp_in);
 1110                 key_freesp_so(&pcb->inp_sp->sp_out);
 1111 #else
 1112                 struct in6pcb *pcb  = sotoin6pcb(so);
 1113 
 1114                 /* Does it have a PCB ? */
 1115                 if (pcb == NULL)
 1116                         return;
 1117                 key_freesp_so(&pcb->in6p_sp->sp_in);
 1118                 key_freesp_so(&pcb->in6p_sp->sp_out);
 1119 #endif
 1120             }
 1121                 break;
 1122 #endif /* INET6 */
 1123         default:
 1124                 ipseclog((LOG_DEBUG, "key_freeso: unknown address family=%d.\n",
 1125                     so->so_proto->pr_domain->dom_family));
 1126                 return;
 1127         }
 1128 }
 1129 
 1130 static void
 1131 key_freesp_so(struct secpolicy **sp)
 1132 {
 1133         KASSERT(sp != NULL && *sp != NULL, ("key_freesp_so: null sp"));
 1134 
 1135         if ((*sp)->policy == IPSEC_POLICY_ENTRUST ||
 1136             (*sp)->policy == IPSEC_POLICY_BYPASS)
 1137                 return;
 1138 
 1139         KASSERT((*sp)->policy == IPSEC_POLICY_IPSEC,
 1140                 ("key_freesp_so: invalid policy %u", (*sp)->policy));
 1141         KEY_FREESP(sp);
 1142 }
 1143 
 1144 /*
 1145  * Must be called after calling key_allocsa().
 1146  * This function is called by key_freesp() to free some SA allocated
 1147  * for a policy.
 1148  */
 1149 void
 1150 key_freesav(struct secasvar **psav, const char* where, int tag)
 1151 {
 1152         struct secasvar *sav = *psav;
 1153 
 1154         KASSERT(sav != NULL, ("key_freesav: null sav"));
 1155 
 1156         SA_DELREF(sav);
 1157 
 1158         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1159                 printf("DP key_freesav SA:%p (SPI %lu) from %s:%u; refcnt now %u\n",
 1160                         sav, ntohl(sav->spi), where, tag, sav->refcnt));
 1161 
 1162         if (sav->refcnt == 0) {
 1163                 *psav = NULL;
 1164                 key_delsav(sav);
 1165         }
 1166 }
 1167 
 1168 /* %%% SPD management */
 1169 /*
 1170  * free security policy entry.
 1171  */
 1172 static void
 1173 key_delsp(struct secpolicy *sp)
 1174 {
 1175         int s;
 1176 
 1177         KASSERT(sp != NULL, ("key_delsp: null sp"));
 1178 
 1179         sp->state = IPSEC_SPSTATE_DEAD;
 1180 
 1181         KASSERT(sp->refcnt == 0,
 1182                 ("key_delsp: SP with references deleted (refcnt %u)",
 1183                 sp->refcnt));
 1184 
 1185         s = splnet();   /*called from softclock()*/
 1186         /* remove from SP index */
 1187         if (__LIST_CHAINED(sp))
 1188                 LIST_REMOVE(sp, chain);
 1189 
 1190     {
 1191         struct ipsecrequest *isr = sp->req, *nextisr;
 1192 
 1193         while (isr != NULL) {
 1194                 if (isr->sav != NULL) {
 1195                         KEY_FREESAV(&isr->sav);
 1196                         isr->sav = NULL;
 1197                 }
 1198 
 1199                 nextisr = isr->next;
 1200                 KFREE(isr);
 1201                 isr = nextisr;
 1202         }
 1203     }
 1204 
 1205         KFREE(sp);
 1206 
 1207         splx(s);
 1208 }
 1209 
 1210 /*
 1211  * search SPD
 1212  * OUT: NULL    : not found
 1213  *      others  : found, pointer to a SP.
 1214  */
 1215 static struct secpolicy *
 1216 key_getsp(struct secpolicyindex *spidx)
 1217 {
 1218         struct secpolicy *sp;
 1219 
 1220         KASSERT(spidx != NULL, ("key_getsp: null spidx"));
 1221 
 1222         LIST_FOREACH(sp, &sptree[spidx->dir], chain) {
 1223                 if (sp->state == IPSEC_SPSTATE_DEAD)
 1224                         continue;
 1225                 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
 1226                         SP_ADDREF(sp);
 1227                         return sp;
 1228                 }
 1229         }
 1230 
 1231         return NULL;
 1232 }
 1233 
 1234 /*
 1235  * get SP by index.
 1236  * OUT: NULL    : not found
 1237  *      others  : found, pointer to a SP.
 1238  */
 1239 static struct secpolicy *
 1240 key_getspbyid(u_int32_t id)
 1241 {
 1242         struct secpolicy *sp;
 1243 
 1244         LIST_FOREACH(sp, &sptree[IPSEC_DIR_INBOUND], chain) {
 1245                 if (sp->state == IPSEC_SPSTATE_DEAD)
 1246                         continue;
 1247                 if (sp->id == id) {
 1248                         SP_ADDREF(sp);
 1249                         return sp;
 1250                 }
 1251         }
 1252 
 1253         LIST_FOREACH(sp, &sptree[IPSEC_DIR_OUTBOUND], chain) {
 1254                 if (sp->state == IPSEC_SPSTATE_DEAD)
 1255                         continue;
 1256                 if (sp->id == id) {
 1257                         SP_ADDREF(sp);
 1258                         return sp;
 1259                 }
 1260         }
 1261 
 1262         return NULL;
 1263 }
 1264 
 1265 struct secpolicy *
 1266 key_newsp(const char* where, int tag)
 1267 {
 1268         struct secpolicy *newsp = NULL;
 1269 
 1270         newsp = (struct secpolicy *)
 1271                 malloc(sizeof(struct secpolicy), M_SECA, M_NOWAIT|M_ZERO);
 1272         if (newsp) {
 1273                 newsp->refcnt = 1;
 1274                 newsp->req = NULL;
 1275         }
 1276 
 1277         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 1278                 printf("DP key_newsp from %s:%u return SP:%p\n",
 1279                         where, tag, newsp));
 1280         return newsp;
 1281 }
 1282 
 1283 /*
 1284  * create secpolicy structure from sadb_x_policy structure.
 1285  * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
 1286  * so must be set properly later.
 1287  */
 1288 struct secpolicy *
 1289 key_msg2sp(xpl0, len, error)
 1290         struct sadb_x_policy *xpl0;
 1291         size_t len;
 1292         int *error;
 1293 {
 1294         struct secpolicy *newsp;
 1295 
 1296         /* sanity check */
 1297         if (xpl0 == NULL)
 1298                 panic("key_msg2sp: NULL pointer was passed.\n");
 1299         if (len < sizeof(*xpl0))
 1300                 panic("key_msg2sp: invalid length.\n");
 1301         if (len != PFKEY_EXTLEN(xpl0)) {
 1302                 ipseclog((LOG_DEBUG, "key_msg2sp: Invalid msg length.\n"));
 1303                 *error = EINVAL;
 1304                 return NULL;
 1305         }
 1306 
 1307         if ((newsp = KEY_NEWSP()) == NULL) {
 1308                 *error = ENOBUFS;
 1309                 return NULL;
 1310         }
 1311 
 1312         newsp->spidx.dir = xpl0->sadb_x_policy_dir;
 1313         newsp->policy = xpl0->sadb_x_policy_type;
 1314 
 1315         /* check policy */
 1316         switch (xpl0->sadb_x_policy_type) {
 1317         case IPSEC_POLICY_DISCARD:
 1318         case IPSEC_POLICY_NONE:
 1319         case IPSEC_POLICY_ENTRUST:
 1320         case IPSEC_POLICY_BYPASS:
 1321                 newsp->req = NULL;
 1322                 break;
 1323 
 1324         case IPSEC_POLICY_IPSEC:
 1325             {
 1326                 int tlen;
 1327                 struct sadb_x_ipsecrequest *xisr;
 1328                 struct ipsecrequest **p_isr = &newsp->req;
 1329 
 1330                 /* validity check */
 1331                 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
 1332                         ipseclog((LOG_DEBUG,
 1333                             "key_msg2sp: Invalid msg length.\n"));
 1334                         KEY_FREESP(&newsp);
 1335                         *error = EINVAL;
 1336                         return NULL;
 1337                 }
 1338 
 1339                 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
 1340                 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
 1341 
 1342                 while (tlen > 0) {
 1343                         /* length check */
 1344                         if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
 1345                                 ipseclog((LOG_DEBUG, "key_msg2sp: "
 1346                                         "invalid ipsecrequest length.\n"));
 1347                                 KEY_FREESP(&newsp);
 1348                                 *error = EINVAL;
 1349                                 return NULL;
 1350                         }
 1351 
 1352                         /* allocate request buffer */
 1353                         KMALLOC(*p_isr, struct ipsecrequest *, sizeof(**p_isr));
 1354                         if ((*p_isr) == NULL) {
 1355                                 ipseclog((LOG_DEBUG,
 1356                                     "key_msg2sp: No more memory.\n"));
 1357                                 KEY_FREESP(&newsp);
 1358                                 *error = ENOBUFS;
 1359                                 return NULL;
 1360                         }
 1361                         bzero(*p_isr, sizeof(**p_isr));
 1362 
 1363                         /* set values */
 1364                         (*p_isr)->next = NULL;
 1365 
 1366                         switch (xisr->sadb_x_ipsecrequest_proto) {
 1367                         case IPPROTO_ESP:
 1368                         case IPPROTO_AH:
 1369                         case IPPROTO_IPCOMP:
 1370                                 break;
 1371                         default:
 1372                                 ipseclog((LOG_DEBUG,
 1373                                     "key_msg2sp: invalid proto type=%u\n",
 1374                                     xisr->sadb_x_ipsecrequest_proto));
 1375                                 KEY_FREESP(&newsp);
 1376                                 *error = EPROTONOSUPPORT;
 1377                                 return NULL;
 1378                         }
 1379                         (*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
 1380 
 1381                         switch (xisr->sadb_x_ipsecrequest_mode) {
 1382                         case IPSEC_MODE_TRANSPORT:
 1383                         case IPSEC_MODE_TUNNEL:
 1384                                 break;
 1385                         case IPSEC_MODE_ANY:
 1386                         default:
 1387                                 ipseclog((LOG_DEBUG,
 1388                                     "key_msg2sp: invalid mode=%u\n",
 1389                                     xisr->sadb_x_ipsecrequest_mode));
 1390                                 KEY_FREESP(&newsp);
 1391                                 *error = EINVAL;
 1392                                 return NULL;
 1393                         }
 1394                         (*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
 1395 
 1396                         switch (xisr->sadb_x_ipsecrequest_level) {
 1397                         case IPSEC_LEVEL_DEFAULT:
 1398                         case IPSEC_LEVEL_USE:
 1399                         case IPSEC_LEVEL_REQUIRE:
 1400                                 break;
 1401                         case IPSEC_LEVEL_UNIQUE:
 1402                                 /* validity check */
 1403                                 /*
 1404                                  * If range violation of reqid, kernel will
 1405                                  * update it, don't refuse it.
 1406                                  */
 1407                                 if (xisr->sadb_x_ipsecrequest_reqid
 1408                                                 > IPSEC_MANUAL_REQID_MAX) {
 1409                                         ipseclog((LOG_DEBUG,
 1410                                             "key_msg2sp: reqid=%d range "
 1411                                             "violation, updated by kernel.\n",
 1412                                             xisr->sadb_x_ipsecrequest_reqid));
 1413                                         xisr->sadb_x_ipsecrequest_reqid = 0;
 1414                                 }
 1415 
 1416                                 /* allocate new reqid id if reqid is zero. */
 1417                                 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
 1418                                         u_int32_t reqid;
 1419                                         if ((reqid = key_newreqid()) == 0) {
 1420                                                 KEY_FREESP(&newsp);
 1421                                                 *error = ENOBUFS;
 1422                                                 return NULL;
 1423                                         }
 1424                                         (*p_isr)->saidx.reqid = reqid;
 1425                                         xisr->sadb_x_ipsecrequest_reqid = reqid;
 1426                                 } else {
 1427                                 /* set it for manual keying. */
 1428                                         (*p_isr)->saidx.reqid =
 1429                                                 xisr->sadb_x_ipsecrequest_reqid;
 1430                                 }
 1431                                 break;
 1432 
 1433                         default:
 1434                                 ipseclog((LOG_DEBUG, "key_msg2sp: invalid level=%u\n",
 1435                                         xisr->sadb_x_ipsecrequest_level));
 1436                                 KEY_FREESP(&newsp);
 1437                                 *error = EINVAL;
 1438                                 return NULL;
 1439                         }
 1440                         (*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
 1441 
 1442                         /* set IP addresses if there */
 1443                         if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
 1444                                 struct sockaddr *paddr;
 1445 
 1446                                 paddr = (struct sockaddr *)(xisr + 1);
 1447 
 1448                                 /* validity check */
 1449                                 if (paddr->sa_len
 1450                                     > sizeof((*p_isr)->saidx.src)) {
 1451                                         ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
 1452                                                 "address length.\n"));
 1453                                         KEY_FREESP(&newsp);
 1454                                         *error = EINVAL;
 1455                                         return NULL;
 1456                                 }
 1457                                 bcopy(paddr, &(*p_isr)->saidx.src,
 1458                                         paddr->sa_len);
 1459 
 1460                                 paddr = (struct sockaddr *)((caddr_t)paddr
 1461                                                         + paddr->sa_len);
 1462 
 1463                                 /* validity check */
 1464                                 if (paddr->sa_len
 1465                                     > sizeof((*p_isr)->saidx.dst)) {
 1466                                         ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
 1467                                                 "address length.\n"));
 1468                                         KEY_FREESP(&newsp);
 1469                                         *error = EINVAL;
 1470                                         return NULL;
 1471                                 }
 1472                                 bcopy(paddr, &(*p_isr)->saidx.dst,
 1473                                         paddr->sa_len);
 1474                         }
 1475 
 1476                         (*p_isr)->sav = NULL;
 1477                         (*p_isr)->sp = newsp;
 1478 
 1479                         /* initialization for the next. */
 1480                         p_isr = &(*p_isr)->next;
 1481                         tlen -= xisr->sadb_x_ipsecrequest_len;
 1482 
 1483                         /* validity check */
 1484                         if (tlen < 0) {
 1485                                 ipseclog((LOG_DEBUG, "key_msg2sp: becoming tlen < 0.\n"));
 1486                                 KEY_FREESP(&newsp);
 1487                                 *error = EINVAL;
 1488                                 return NULL;
 1489                         }
 1490 
 1491                         xisr = (struct sadb_x_ipsecrequest *)((caddr_t)xisr
 1492                                          + xisr->sadb_x_ipsecrequest_len);
 1493                 }
 1494             }
 1495                 break;
 1496         default:
 1497                 ipseclog((LOG_DEBUG, "key_msg2sp: invalid policy type.\n"));
 1498                 KEY_FREESP(&newsp);
 1499                 *error = EINVAL;
 1500                 return NULL;
 1501         }
 1502 
 1503         *error = 0;
 1504         return newsp;
 1505 }
 1506 
 1507 static u_int32_t
 1508 key_newreqid()
 1509 {
 1510         static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
 1511 
 1512         auto_reqid = (auto_reqid == ~0
 1513                         ? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
 1514 
 1515         /* XXX should be unique check */
 1516 
 1517         return auto_reqid;
 1518 }
 1519 
 1520 /*
 1521  * copy secpolicy struct to sadb_x_policy structure indicated.
 1522  */
 1523 struct mbuf *
 1524 key_sp2msg(sp)
 1525         struct secpolicy *sp;
 1526 {
 1527         struct sadb_x_policy *xpl;
 1528         int tlen;
 1529         caddr_t p;
 1530         struct mbuf *m;
 1531 
 1532         /* sanity check. */
 1533         if (sp == NULL)
 1534                 panic("key_sp2msg: NULL pointer was passed.\n");
 1535 
 1536         tlen = key_getspreqmsglen(sp);
 1537 
 1538         m = key_alloc_mbuf(tlen);
 1539         if (!m || m->m_next) {  /*XXX*/
 1540                 if (m)
 1541                         m_freem(m);
 1542                 return NULL;
 1543         }
 1544 
 1545         m->m_len = tlen;
 1546         m->m_next = NULL;
 1547         xpl = mtod(m, struct sadb_x_policy *);
 1548         bzero(xpl, tlen);
 1549 
 1550         xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
 1551         xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
 1552         xpl->sadb_x_policy_type = sp->policy;
 1553         xpl->sadb_x_policy_dir = sp->spidx.dir;
 1554         xpl->sadb_x_policy_id = sp->id;
 1555         p = (caddr_t)xpl + sizeof(*xpl);
 1556 
 1557         /* if is the policy for ipsec ? */
 1558         if (sp->policy == IPSEC_POLICY_IPSEC) {
 1559                 struct sadb_x_ipsecrequest *xisr;
 1560                 struct ipsecrequest *isr;
 1561 
 1562                 for (isr = sp->req; isr != NULL; isr = isr->next) {
 1563 
 1564                         xisr = (struct sadb_x_ipsecrequest *)p;
 1565 
 1566                         xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
 1567                         xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
 1568                         xisr->sadb_x_ipsecrequest_level = isr->level;
 1569                         xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
 1570 
 1571                         p += sizeof(*xisr);
 1572                         bcopy(&isr->saidx.src, p, isr->saidx.src.sa.sa_len);
 1573                         p += isr->saidx.src.sa.sa_len;
 1574                         bcopy(&isr->saidx.dst, p, isr->saidx.dst.sa.sa_len);
 1575                         p += isr->saidx.src.sa.sa_len;
 1576 
 1577                         xisr->sadb_x_ipsecrequest_len =
 1578                                 PFKEY_ALIGN8(sizeof(*xisr)
 1579                                         + isr->saidx.src.sa.sa_len
 1580                                         + isr->saidx.dst.sa.sa_len);
 1581                 }
 1582         }
 1583 
 1584         return m;
 1585 }
 1586 
 1587 /* m will not be freed nor modified */
 1588 static struct mbuf *
 1589 #ifdef __STDC__
 1590 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
 1591         int ndeep, int nitem, ...)
 1592 #else
 1593 key_gather_mbuf(m, mhp, ndeep, nitem, va_alist)
 1594         struct mbuf *m;
 1595         const struct sadb_msghdr *mhp;
 1596         int ndeep;
 1597         int nitem;
 1598         va_dcl
 1599 #endif
 1600 {
 1601         va_list ap;
 1602         int idx;
 1603         int i;
 1604         struct mbuf *result = NULL, *n;
 1605         int len;
 1606 
 1607         if (m == NULL || mhp == NULL)
 1608                 panic("null pointer passed to key_gather");
 1609 
 1610         va_start(ap, nitem);
 1611         for (i = 0; i < nitem; i++) {
 1612                 idx = va_arg(ap, int);
 1613                 if (idx < 0 || idx > SADB_EXT_MAX)
 1614                         goto fail;
 1615                 /* don't attempt to pull empty extension */
 1616                 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
 1617                         continue;
 1618                 if (idx != SADB_EXT_RESERVED  &&
 1619                     (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
 1620                         continue;
 1621 
 1622                 if (idx == SADB_EXT_RESERVED) {
 1623                         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
 1624 #ifdef DIAGNOSTIC
 1625                         if (len > MHLEN)
 1626                                 panic("assumption failed");
 1627 #endif
 1628                         MGETHDR(n, M_DONTWAIT, MT_DATA);
 1629                         if (!n)
 1630                                 goto fail;
 1631                         n->m_len = len;
 1632                         n->m_next = NULL;
 1633                         m_copydata(m, 0, sizeof(struct sadb_msg),
 1634                             mtod(n, caddr_t));
 1635                 } else if (i < ndeep) {
 1636                         len = mhp->extlen[idx];
 1637                         n = key_alloc_mbuf(len);
 1638                         if (!n || n->m_next) {  /*XXX*/
 1639                                 if (n)
 1640                                         m_freem(n);
 1641                                 goto fail;
 1642                         }
 1643                         m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
 1644                             mtod(n, caddr_t));
 1645                 } else {
 1646                         n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
 1647                             M_DONTWAIT);
 1648                 }
 1649                 if (n == NULL)
 1650                         goto fail;
 1651 
 1652                 if (result)
 1653                         m_cat(result, n);
 1654                 else
 1655                         result = n;
 1656         }
 1657         va_end(ap);
 1658 
 1659         if ((result->m_flags & M_PKTHDR) != 0) {
 1660                 result->m_pkthdr.len = 0;
 1661                 for (n = result; n; n = n->m_next)
 1662                         result->m_pkthdr.len += n->m_len;
 1663         }
 1664 
 1665         return result;
 1666 
 1667 fail:
 1668         m_freem(result);
 1669         return NULL;
 1670 }
 1671 
 1672 /*
 1673  * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
 1674  * add an entry to SP database, when received
 1675  *   <base, address(SD), (lifetime(H),) policy>
 1676  * from the user(?).
 1677  * Adding to SP database,
 1678  * and send
 1679  *   <base, address(SD), (lifetime(H),) policy>
 1680  * to the socket which was send.
 1681  *
 1682  * SPDADD set a unique policy entry.
 1683  * SPDSETIDX like SPDADD without a part of policy requests.
 1684  * SPDUPDATE replace a unique policy entry.
 1685  *
 1686  * m will always be freed.
 1687  */
 1688 static int
 1689 key_spdadd(so, m, mhp)
 1690         struct socket *so;
 1691         struct mbuf *m;
 1692         const struct sadb_msghdr *mhp;
 1693 {
 1694         struct sadb_address *src0, *dst0;
 1695         struct sadb_x_policy *xpl0, *xpl;
 1696         struct sadb_lifetime *lft = NULL;
 1697         struct secpolicyindex spidx;
 1698         struct secpolicy *newsp;
 1699         int error;
 1700 
 1701         /* sanity check */
 1702         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 1703                 panic("key_spdadd: NULL pointer is passed.\n");
 1704 
 1705         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 1706             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
 1707             mhp->ext[SADB_X_EXT_POLICY] == NULL) {
 1708                 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
 1709                 return key_senderror(so, m, EINVAL);
 1710         }
 1711         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 1712             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
 1713             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
 1714                 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
 1715                 return key_senderror(so, m, EINVAL);
 1716         }
 1717         if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
 1718                 if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
 1719                         < sizeof(struct sadb_lifetime)) {
 1720                         ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
 1721                         return key_senderror(so, m, EINVAL);
 1722                 }
 1723                 lft = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
 1724         }
 1725 
 1726         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
 1727         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 1728         xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
 1729 
 1730         /* make secindex */
 1731         /* XXX boundary check against sa_len */
 1732         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
 1733                         src0 + 1,
 1734                         dst0 + 1,
 1735                         src0->sadb_address_prefixlen,
 1736                         dst0->sadb_address_prefixlen,
 1737                         src0->sadb_address_proto,
 1738                         &spidx);
 1739 
 1740         /* checking the direciton. */
 1741         switch (xpl0->sadb_x_policy_dir) {
 1742         case IPSEC_DIR_INBOUND:
 1743         case IPSEC_DIR_OUTBOUND:
 1744                 break;
 1745         default:
 1746                 ipseclog((LOG_DEBUG, "key_spdadd: Invalid SP direction.\n"));
 1747                 mhp->msg->sadb_msg_errno = EINVAL;
 1748                 return 0;
 1749         }
 1750 
 1751         /* check policy */
 1752         /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
 1753         if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
 1754          || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
 1755                 ipseclog((LOG_DEBUG, "key_spdadd: Invalid policy type.\n"));
 1756                 return key_senderror(so, m, EINVAL);
 1757         }
 1758 
 1759         /* policy requests are mandatory when action is ipsec. */
 1760         if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
 1761          && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
 1762          && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
 1763                 ipseclog((LOG_DEBUG, "key_spdadd: some policy requests part required.\n"));
 1764                 return key_senderror(so, m, EINVAL);
 1765         }
 1766 
 1767         /*
 1768          * checking there is SP already or not.
 1769          * SPDUPDATE doesn't depend on whether there is a SP or not.
 1770          * If the type is either SPDADD or SPDSETIDX AND a SP is found,
 1771          * then error.
 1772          */
 1773         newsp = key_getsp(&spidx);
 1774         if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
 1775                 if (newsp) {
 1776                         newsp->state = IPSEC_SPSTATE_DEAD;
 1777                         KEY_FREESP(&newsp);
 1778                 }
 1779         } else {
 1780                 if (newsp != NULL) {
 1781                         KEY_FREESP(&newsp);
 1782                         ipseclog((LOG_DEBUG, "key_spdadd: a SP entry exists already.\n"));
 1783                         return key_senderror(so, m, EEXIST);
 1784                 }
 1785         }
 1786 
 1787         /* allocation new SP entry */
 1788         if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
 1789                 return key_senderror(so, m, error);
 1790         }
 1791 
 1792         if ((newsp->id = key_getnewspid()) == 0) {
 1793                 KFREE(newsp);
 1794                 return key_senderror(so, m, ENOBUFS);
 1795         }
 1796 
 1797         /* XXX boundary check against sa_len */
 1798         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
 1799                         src0 + 1,
 1800                         dst0 + 1,
 1801                         src0->sadb_address_prefixlen,
 1802                         dst0->sadb_address_prefixlen,
 1803                         src0->sadb_address_proto,
 1804                         &newsp->spidx);
 1805 
 1806         /* sanity check on addr pair */
 1807         if (((struct sockaddr *)(src0 + 1))->sa_family !=
 1808                         ((struct sockaddr *)(dst0+ 1))->sa_family) {
 1809                 KFREE(newsp);
 1810                 return key_senderror(so, m, EINVAL);
 1811         }
 1812         if (((struct sockaddr *)(src0 + 1))->sa_len !=
 1813                         ((struct sockaddr *)(dst0+ 1))->sa_len) {
 1814                 KFREE(newsp);
 1815                 return key_senderror(so, m, EINVAL);
 1816         }
 1817 #if 1
 1818         if (newsp->req && newsp->req->saidx.src.sa.sa_family) {
 1819                 struct sockaddr *sa;
 1820                 sa = (struct sockaddr *)(src0 + 1);
 1821                 if (sa->sa_family != newsp->req->saidx.src.sa.sa_family) {
 1822                         KFREE(newsp);
 1823                         return key_senderror(so, m, EINVAL);
 1824                 }
 1825         }
 1826         if (newsp->req && newsp->req->saidx.dst.sa.sa_family) {
 1827                 struct sockaddr *sa;
 1828                 sa = (struct sockaddr *)(dst0 + 1);
 1829                 if (sa->sa_family != newsp->req->saidx.dst.sa.sa_family) {
 1830                         KFREE(newsp);
 1831                         return key_senderror(so, m, EINVAL);
 1832                 }
 1833         }
 1834 #endif
 1835 
 1836         newsp->created = time_second;
 1837         newsp->lastused = newsp->created;
 1838         newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
 1839         newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
 1840 
 1841         newsp->refcnt = 1;      /* do not reclaim until I say I do */
 1842         newsp->state = IPSEC_SPSTATE_ALIVE;
 1843         LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain);
 1844 
 1845         /* delete the entry in spacqtree */
 1846         if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
 1847                 struct secspacq *spacq;
 1848                 if ((spacq = key_getspacq(&spidx)) != NULL) {
 1849                         /* reset counter in order to deletion by timehandler. */
 1850                         spacq->created = time_second;
 1851                         spacq->count = 0;
 1852                 }
 1853         }
 1854 
 1855     {
 1856         struct mbuf *n, *mpolicy;
 1857         struct sadb_msg *newmsg;
 1858         int off;
 1859 
 1860         /* create new sadb_msg to reply. */
 1861         if (lft) {
 1862                 n = key_gather_mbuf(m, mhp, 2, 5, SADB_EXT_RESERVED,
 1863                     SADB_X_EXT_POLICY, SADB_EXT_LIFETIME_HARD,
 1864                     SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 1865         } else {
 1866                 n = key_gather_mbuf(m, mhp, 2, 4, SADB_EXT_RESERVED,
 1867                     SADB_X_EXT_POLICY,
 1868                     SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 1869         }
 1870         if (!n)
 1871                 return key_senderror(so, m, ENOBUFS);
 1872 
 1873         if (n->m_len < sizeof(*newmsg)) {
 1874                 n = m_pullup(n, sizeof(*newmsg));
 1875                 if (!n)
 1876                         return key_senderror(so, m, ENOBUFS);
 1877         }
 1878         newmsg = mtod(n, struct sadb_msg *);
 1879         newmsg->sadb_msg_errno = 0;
 1880         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 1881 
 1882         off = 0;
 1883         mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
 1884             sizeof(*xpl), &off);
 1885         if (mpolicy == NULL) {
 1886                 /* n is already freed */
 1887                 return key_senderror(so, m, ENOBUFS);
 1888         }
 1889         xpl = (struct sadb_x_policy *)(mtod(mpolicy, caddr_t) + off);
 1890         if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
 1891                 m_freem(n);
 1892                 return key_senderror(so, m, EINVAL);
 1893         }
 1894         xpl->sadb_x_policy_id = newsp->id;
 1895 
 1896         m_freem(m);
 1897         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 1898     }
 1899 }
 1900 
 1901 /*
 1902  * get new policy id.
 1903  * OUT:
 1904  *      0:      failure.
 1905  *      others: success.
 1906  */
 1907 static u_int32_t
 1908 key_getnewspid()
 1909 {
 1910         u_int32_t newid = 0;
 1911         int count = key_spi_trycnt;     /* XXX */
 1912         struct secpolicy *sp;
 1913 
 1914         /* when requesting to allocate spi ranged */
 1915         while (count--) {
 1916                 newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
 1917 
 1918                 if ((sp = key_getspbyid(newid)) == NULL)
 1919                         break;
 1920 
 1921                 KEY_FREESP(&sp);
 1922         }
 1923 
 1924         if (count == 0 || newid == 0) {
 1925                 ipseclog((LOG_DEBUG, "key_getnewspid: to allocate policy id is failed.\n"));
 1926                 return 0;
 1927         }
 1928 
 1929         return newid;
 1930 }
 1931 
 1932 /*
 1933  * SADB_SPDDELETE processing
 1934  * receive
 1935  *   <base, address(SD), policy(*)>
 1936  * from the user(?), and set SADB_SASTATE_DEAD,
 1937  * and send,
 1938  *   <base, address(SD), policy(*)>
 1939  * to the ikmpd.
 1940  * policy(*) including direction of policy.
 1941  *
 1942  * m will always be freed.
 1943  */
 1944 static int
 1945 key_spddelete(so, m, mhp)
 1946         struct socket *so;
 1947         struct mbuf *m;
 1948         const struct sadb_msghdr *mhp;
 1949 {
 1950         struct sadb_address *src0, *dst0;
 1951         struct sadb_x_policy *xpl0;
 1952         struct secpolicyindex spidx;
 1953         struct secpolicy *sp;
 1954 
 1955         /* sanity check */
 1956         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 1957                 panic("key_spddelete: NULL pointer is passed.\n");
 1958 
 1959         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 1960             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
 1961             mhp->ext[SADB_X_EXT_POLICY] == NULL) {
 1962                 ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
 1963                 return key_senderror(so, m, EINVAL);
 1964         }
 1965         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 1966             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
 1967             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
 1968                 ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
 1969                 return key_senderror(so, m, EINVAL);
 1970         }
 1971 
 1972         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
 1973         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 1974         xpl0 = (struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY];
 1975 
 1976         /* make secindex */
 1977         /* XXX boundary check against sa_len */
 1978         KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
 1979                         src0 + 1,
 1980                         dst0 + 1,
 1981                         src0->sadb_address_prefixlen,
 1982                         dst0->sadb_address_prefixlen,
 1983                         src0->sadb_address_proto,
 1984                         &spidx);
 1985 
 1986         /* checking the direciton. */
 1987         switch (xpl0->sadb_x_policy_dir) {
 1988         case IPSEC_DIR_INBOUND:
 1989         case IPSEC_DIR_OUTBOUND:
 1990                 break;
 1991         default:
 1992                 ipseclog((LOG_DEBUG, "key_spddelete: Invalid SP direction.\n"));
 1993                 return key_senderror(so, m, EINVAL);
 1994         }
 1995 
 1996         /* Is there SP in SPD ? */
 1997         if ((sp = key_getsp(&spidx)) == NULL) {
 1998                 ipseclog((LOG_DEBUG, "key_spddelete: no SP found.\n"));
 1999                 return key_senderror(so, m, EINVAL);
 2000         }
 2001 
 2002         /* save policy id to buffer to be returned. */
 2003         xpl0->sadb_x_policy_id = sp->id;
 2004 
 2005         sp->state = IPSEC_SPSTATE_DEAD;
 2006         KEY_FREESP(&sp);
 2007 
 2008     {
 2009         struct mbuf *n;
 2010         struct sadb_msg *newmsg;
 2011 
 2012         /* create new sadb_msg to reply. */
 2013         n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
 2014             SADB_X_EXT_POLICY, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 2015         if (!n)
 2016                 return key_senderror(so, m, ENOBUFS);
 2017 
 2018         newmsg = mtod(n, struct sadb_msg *);
 2019         newmsg->sadb_msg_errno = 0;
 2020         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 2021 
 2022         m_freem(m);
 2023         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 2024     }
 2025 }
 2026 
 2027 /*
 2028  * SADB_SPDDELETE2 processing
 2029  * receive
 2030  *   <base, policy(*)>
 2031  * from the user(?), and set SADB_SASTATE_DEAD,
 2032  * and send,
 2033  *   <base, policy(*)>
 2034  * to the ikmpd.
 2035  * policy(*) including direction of policy.
 2036  *
 2037  * m will always be freed.
 2038  */
 2039 static int
 2040 key_spddelete2(so, m, mhp)
 2041         struct socket *so;
 2042         struct mbuf *m;
 2043         const struct sadb_msghdr *mhp;
 2044 {
 2045         u_int32_t id;
 2046         struct secpolicy *sp;
 2047 
 2048         /* sanity check */
 2049         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 2050                 panic("key_spddelete2: NULL pointer is passed.\n");
 2051 
 2052         if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
 2053             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
 2054                 ipseclog((LOG_DEBUG, "key_spddelete2: invalid message is passed.\n"));
 2055                 key_senderror(so, m, EINVAL);
 2056                 return 0;
 2057         }
 2058 
 2059         id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
 2060 
 2061         /* Is there SP in SPD ? */
 2062         if ((sp = key_getspbyid(id)) == NULL) {
 2063                 ipseclog((LOG_DEBUG, "key_spddelete2: no SP found id:%u.\n", id));
 2064                 key_senderror(so, m, EINVAL);
 2065         }
 2066 
 2067         sp->state = IPSEC_SPSTATE_DEAD;
 2068         KEY_FREESP(&sp);
 2069 
 2070     {
 2071         struct mbuf *n, *nn;
 2072         struct sadb_msg *newmsg;
 2073         int off, len;
 2074 
 2075         /* create new sadb_msg to reply. */
 2076         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
 2077 
 2078         if (len > MCLBYTES)
 2079                 return key_senderror(so, m, ENOBUFS);
 2080         MGETHDR(n, M_DONTWAIT, MT_DATA);
 2081         if (n && len > MHLEN) {
 2082                 MCLGET(n, M_DONTWAIT);
 2083                 if ((n->m_flags & M_EXT) == 0) {
 2084                         m_freem(n);
 2085                         n = NULL;
 2086                 }
 2087         }
 2088         if (!n)
 2089                 return key_senderror(so, m, ENOBUFS);
 2090 
 2091         n->m_len = len;
 2092         n->m_next = NULL;
 2093         off = 0;
 2094 
 2095         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
 2096         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
 2097 
 2098 #ifdef DIAGNOSTIC
 2099         if (off != len)
 2100                 panic("length inconsistency in key_spddelete2");
 2101 #endif
 2102 
 2103         n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
 2104             mhp->extlen[SADB_X_EXT_POLICY], M_DONTWAIT);
 2105         if (!n->m_next) {
 2106                 m_freem(n);
 2107                 return key_senderror(so, m, ENOBUFS);
 2108         }
 2109 
 2110         n->m_pkthdr.len = 0;
 2111         for (nn = n; nn; nn = nn->m_next)
 2112                 n->m_pkthdr.len += nn->m_len;
 2113 
 2114         newmsg = mtod(n, struct sadb_msg *);
 2115         newmsg->sadb_msg_errno = 0;
 2116         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 2117 
 2118         m_freem(m);
 2119         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 2120     }
 2121 }
 2122 
 2123 /*
 2124  * SADB_X_GET processing
 2125  * receive
 2126  *   <base, policy(*)>
 2127  * from the user(?),
 2128  * and send,
 2129  *   <base, address(SD), policy>
 2130  * to the ikmpd.
 2131  * policy(*) including direction of policy.
 2132  *
 2133  * m will always be freed.
 2134  */
 2135 static int
 2136 key_spdget(so, m, mhp)
 2137         struct socket *so;
 2138         struct mbuf *m;
 2139         const struct sadb_msghdr *mhp;
 2140 {
 2141         u_int32_t id;
 2142         struct secpolicy *sp;
 2143         struct mbuf *n;
 2144 
 2145         /* sanity check */
 2146         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 2147                 panic("key_spdget: NULL pointer is passed.\n");
 2148 
 2149         if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
 2150             mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
 2151                 ipseclog((LOG_DEBUG, "key_spdget: invalid message is passed.\n"));
 2152                 return key_senderror(so, m, EINVAL);
 2153         }
 2154 
 2155         id = ((struct sadb_x_policy *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
 2156 
 2157         /* Is there SP in SPD ? */
 2158         if ((sp = key_getspbyid(id)) == NULL) {
 2159                 ipseclog((LOG_DEBUG, "key_spdget: no SP found id:%u.\n", id));
 2160                 return key_senderror(so, m, ENOENT);
 2161         }
 2162 
 2163         n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
 2164         if (n != NULL) {
 2165                 m_freem(m);
 2166                 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
 2167         } else
 2168                 return key_senderror(so, m, ENOBUFS);
 2169 }
 2170 
 2171 /*
 2172  * SADB_X_SPDACQUIRE processing.
 2173  * Acquire policy and SA(s) for a *OUTBOUND* packet.
 2174  * send
 2175  *   <base, policy(*)>
 2176  * to KMD, and expect to receive
 2177  *   <base> with SADB_X_SPDACQUIRE if error occured,
 2178  * or
 2179  *   <base, policy>
 2180  * with SADB_X_SPDUPDATE from KMD by PF_KEY.
 2181  * policy(*) is without policy requests.
 2182  *
 2183  *    0     : succeed
 2184  *    others: error number
 2185  */
 2186 int
 2187 key_spdacquire(sp)
 2188         struct secpolicy *sp;
 2189 {
 2190         struct mbuf *result = NULL, *m;
 2191         struct secspacq *newspacq;
 2192         int error;
 2193 
 2194         /* sanity check */
 2195         if (sp == NULL)
 2196                 panic("key_spdacquire: NULL pointer is passed.\n");
 2197         if (sp->req != NULL)
 2198                 panic("key_spdacquire: called but there is request.\n");
 2199         if (sp->policy != IPSEC_POLICY_IPSEC)
 2200                 panic("key_spdacquire: policy mismathed. IPsec is expected.\n");
 2201 
 2202         /* Get an entry to check whether sent message or not. */
 2203         if ((newspacq = key_getspacq(&sp->spidx)) != NULL) {
 2204                 if (key_blockacq_count < newspacq->count) {
 2205                         /* reset counter and do send message. */
 2206                         newspacq->count = 0;
 2207                 } else {
 2208                         /* increment counter and do nothing. */
 2209                         newspacq->count++;
 2210                         return 0;
 2211                 }
 2212         } else {
 2213                 /* make new entry for blocking to send SADB_ACQUIRE. */
 2214                 if ((newspacq = key_newspacq(&sp->spidx)) == NULL)
 2215                         return ENOBUFS;
 2216 
 2217                 /* add to acqtree */
 2218                 LIST_INSERT_HEAD(&spacqtree, newspacq, chain);
 2219         }
 2220 
 2221         /* create new sadb_msg to reply. */
 2222         m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
 2223         if (!m) {
 2224                 error = ENOBUFS;
 2225                 goto fail;
 2226         }
 2227         result = m;
 2228 
 2229         result->m_pkthdr.len = 0;
 2230         for (m = result; m; m = m->m_next)
 2231                 result->m_pkthdr.len += m->m_len;
 2232 
 2233         mtod(result, struct sadb_msg *)->sadb_msg_len =
 2234             PFKEY_UNIT64(result->m_pkthdr.len);
 2235 
 2236         return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
 2237 
 2238 fail:
 2239         if (result)
 2240                 m_freem(result);
 2241         return error;
 2242 }
 2243 
 2244 /*
 2245  * SADB_SPDFLUSH processing
 2246  * receive
 2247  *   <base>
 2248  * from the user, and free all entries in secpctree.
 2249  * and send,
 2250  *   <base>
 2251  * to the user.
 2252  * NOTE: what to do is only marking SADB_SASTATE_DEAD.
 2253  *
 2254  * m will always be freed.
 2255  */
 2256 static int
 2257 key_spdflush(so, m, mhp)
 2258         struct socket *so;
 2259         struct mbuf *m;
 2260         const struct sadb_msghdr *mhp;
 2261 {
 2262         struct sadb_msg *newmsg;
 2263         struct secpolicy *sp;
 2264         u_int dir;
 2265 
 2266         /* sanity check */
 2267         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 2268                 panic("key_spdflush: NULL pointer is passed.\n");
 2269 
 2270         if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
 2271                 return key_senderror(so, m, EINVAL);
 2272 
 2273         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
 2274                 LIST_FOREACH(sp, &sptree[dir], chain) {
 2275                         sp->state = IPSEC_SPSTATE_DEAD;
 2276                 }
 2277         }
 2278 
 2279         if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
 2280                 ipseclog((LOG_DEBUG, "key_spdflush: No more memory.\n"));
 2281                 return key_senderror(so, m, ENOBUFS);
 2282         }
 2283 
 2284         if (m->m_next)
 2285                 m_freem(m->m_next);
 2286         m->m_next = NULL;
 2287         m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
 2288         newmsg = mtod(m, struct sadb_msg *);
 2289         newmsg->sadb_msg_errno = 0;
 2290         newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
 2291 
 2292         return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
 2293 }
 2294 
 2295 /*
 2296  * SADB_SPDDUMP processing
 2297  * receive
 2298  *   <base>
 2299  * from the user, and dump all SP leaves
 2300  * and send,
 2301  *   <base> .....
 2302  * to the ikmpd.
 2303  *
 2304  * m will always be freed.
 2305  */
 2306 static int
 2307 key_spddump(so, m, mhp)
 2308         struct socket *so;
 2309         struct mbuf *m;
 2310         const struct sadb_msghdr *mhp;
 2311 {
 2312         struct secpolicy *sp;
 2313         int cnt;
 2314         u_int dir;
 2315         struct mbuf *n;
 2316 
 2317         /* sanity check */
 2318         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 2319                 panic("key_spddump: NULL pointer is passed.\n");
 2320 
 2321         /* search SPD entry and get buffer size. */
 2322         cnt = 0;
 2323         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
 2324                 LIST_FOREACH(sp, &sptree[dir], chain) {
 2325                         cnt++;
 2326                 }
 2327         }
 2328 
 2329         if (cnt == 0)
 2330                 return key_senderror(so, m, ENOENT);
 2331 
 2332         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
 2333                 LIST_FOREACH(sp, &sptree[dir], chain) {
 2334                         --cnt;
 2335                         n = key_setdumpsp(sp, SADB_X_SPDDUMP, cnt,
 2336                             mhp->msg->sadb_msg_pid);
 2337 
 2338                         if (n)
 2339                                 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
 2340                 }
 2341         }
 2342 
 2343         m_freem(m);
 2344         return 0;
 2345 }
 2346 
 2347 static struct mbuf *
 2348 key_setdumpsp(sp, type, seq, pid)
 2349         struct secpolicy *sp;
 2350         u_int8_t type;
 2351         u_int32_t seq, pid;
 2352 {
 2353         struct mbuf *result = NULL, *m;
 2354 
 2355         m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
 2356         if (!m)
 2357                 goto fail;
 2358         result = m;
 2359 
 2360         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
 2361             &sp->spidx.src.sa, sp->spidx.prefs,
 2362             sp->spidx.ul_proto);
 2363         if (!m)
 2364                 goto fail;
 2365         m_cat(result, m);
 2366 
 2367         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
 2368             &sp->spidx.dst.sa, sp->spidx.prefd,
 2369             sp->spidx.ul_proto);
 2370         if (!m)
 2371                 goto fail;
 2372         m_cat(result, m);
 2373 
 2374         m = key_sp2msg(sp);
 2375         if (!m)
 2376                 goto fail;
 2377         m_cat(result, m);
 2378 
 2379         if ((result->m_flags & M_PKTHDR) == 0)
 2380                 goto fail;
 2381 
 2382         if (result->m_len < sizeof(struct sadb_msg)) {
 2383                 result = m_pullup(result, sizeof(struct sadb_msg));
 2384                 if (result == NULL)
 2385                         goto fail;
 2386         }
 2387 
 2388         result->m_pkthdr.len = 0;
 2389         for (m = result; m; m = m->m_next)
 2390                 result->m_pkthdr.len += m->m_len;
 2391 
 2392         mtod(result, struct sadb_msg *)->sadb_msg_len =
 2393             PFKEY_UNIT64(result->m_pkthdr.len);
 2394 
 2395         return result;
 2396 
 2397 fail:
 2398         m_freem(result);
 2399         return NULL;
 2400 }
 2401 
 2402 /*
 2403  * get PFKEY message length for security policy and request.
 2404  */
 2405 static u_int
 2406 key_getspreqmsglen(sp)
 2407         struct secpolicy *sp;
 2408 {
 2409         u_int tlen;
 2410 
 2411         tlen = sizeof(struct sadb_x_policy);
 2412 
 2413         /* if is the policy for ipsec ? */
 2414         if (sp->policy != IPSEC_POLICY_IPSEC)
 2415                 return tlen;
 2416 
 2417         /* get length of ipsec requests */
 2418     {
 2419         struct ipsecrequest *isr;
 2420         int len;
 2421 
 2422         for (isr = sp->req; isr != NULL; isr = isr->next) {
 2423                 len = sizeof(struct sadb_x_ipsecrequest)
 2424                         + isr->saidx.src.sa.sa_len
 2425                         + isr->saidx.dst.sa.sa_len;
 2426 
 2427                 tlen += PFKEY_ALIGN8(len);
 2428         }
 2429     }
 2430 
 2431         return tlen;
 2432 }
 2433 
 2434 /*
 2435  * SADB_SPDEXPIRE processing
 2436  * send
 2437  *   <base, address(SD), lifetime(CH), policy>
 2438  * to KMD by PF_KEY.
 2439  *
 2440  * OUT: 0       : succeed
 2441  *      others  : error number
 2442  */
 2443 static int
 2444 key_spdexpire(sp)
 2445         struct secpolicy *sp;
 2446 {
 2447         int s;
 2448         struct mbuf *result = NULL, *m;
 2449         int len;
 2450         int error = -1;
 2451         struct sadb_lifetime *lt;
 2452 
 2453         /* XXX: Why do we lock ? */
 2454         s = splnet();   /*called from softclock()*/
 2455 
 2456         /* sanity check */
 2457         if (sp == NULL)
 2458                 panic("key_spdexpire: NULL pointer is passed.\n");
 2459 
 2460         /* set msg header */
 2461         m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
 2462         if (!m) {
 2463                 error = ENOBUFS;
 2464                 goto fail;
 2465         }
 2466         result = m;
 2467 
 2468         /* create lifetime extension (current and hard) */
 2469         len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
 2470         m = key_alloc_mbuf(len);
 2471         if (!m || m->m_next) {  /*XXX*/
 2472                 if (m)
 2473                         m_freem(m);
 2474                 error = ENOBUFS;
 2475                 goto fail;
 2476         }
 2477         bzero(mtod(m, caddr_t), len);
 2478         lt = mtod(m, struct sadb_lifetime *);
 2479         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
 2480         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
 2481         lt->sadb_lifetime_allocations = 0;
 2482         lt->sadb_lifetime_bytes = 0;
 2483         lt->sadb_lifetime_addtime = sp->created;
 2484         lt->sadb_lifetime_usetime = sp->lastused;
 2485         lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
 2486         lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
 2487         lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
 2488         lt->sadb_lifetime_allocations = 0;
 2489         lt->sadb_lifetime_bytes = 0;
 2490         lt->sadb_lifetime_addtime = sp->lifetime;
 2491         lt->sadb_lifetime_usetime = sp->validtime;
 2492         m_cat(result, m);
 2493 
 2494         /* set sadb_address for source */
 2495         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
 2496             &sp->spidx.src.sa,
 2497             sp->spidx.prefs, sp->spidx.ul_proto);
 2498         if (!m) {
 2499                 error = ENOBUFS;
 2500                 goto fail;
 2501         }
 2502         m_cat(result, m);
 2503 
 2504         /* set sadb_address for destination */
 2505         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
 2506             &sp->spidx.dst.sa,
 2507             sp->spidx.prefd, sp->spidx.ul_proto);
 2508         if (!m) {
 2509                 error = ENOBUFS;
 2510                 goto fail;
 2511         }
 2512         m_cat(result, m);
 2513 
 2514         /* set secpolicy */
 2515         m = key_sp2msg(sp);
 2516         if (!m) {
 2517                 error = ENOBUFS;
 2518                 goto fail;
 2519         }
 2520         m_cat(result, m);
 2521 
 2522         if ((result->m_flags & M_PKTHDR) == 0) {
 2523                 error = EINVAL;
 2524                 goto fail;
 2525         }
 2526 
 2527         if (result->m_len < sizeof(struct sadb_msg)) {
 2528                 result = m_pullup(result, sizeof(struct sadb_msg));
 2529                 if (result == NULL) {
 2530                         error = ENOBUFS;
 2531                         goto fail;
 2532                 }
 2533         }
 2534 
 2535         result->m_pkthdr.len = 0;
 2536         for (m = result; m; m = m->m_next)
 2537                 result->m_pkthdr.len += m->m_len;
 2538 
 2539         mtod(result, struct sadb_msg *)->sadb_msg_len =
 2540             PFKEY_UNIT64(result->m_pkthdr.len);
 2541 
 2542         return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
 2543 
 2544  fail:
 2545         if (result)
 2546                 m_freem(result);
 2547         splx(s);
 2548         return error;
 2549 }
 2550 
 2551 /* %%% SAD management */
 2552 /*
 2553  * allocating a memory for new SA head, and copy from the values of mhp.
 2554  * OUT: NULL    : failure due to the lack of memory.
 2555  *      others  : pointer to new SA head.
 2556  */
 2557 static struct secashead *
 2558 key_newsah(saidx)
 2559         struct secasindex *saidx;
 2560 {
 2561         struct secashead *newsah;
 2562 
 2563         KASSERT(saidx != NULL, ("key_newsaidx: null saidx"));
 2564 
 2565         newsah = (struct secashead *)
 2566                 malloc(sizeof(struct secashead), M_SECA, M_NOWAIT|M_ZERO);
 2567         if (newsah != NULL) {
 2568                 int i;
 2569                 for (i = 0; i < sizeof(newsah->savtree)/sizeof(newsah->savtree[0]); i++)
 2570                         LIST_INIT(&newsah->savtree[i]);
 2571                 newsah->saidx = *saidx;
 2572 
 2573                 /* add to saidxtree */
 2574                 newsah->state = SADB_SASTATE_MATURE;
 2575                 LIST_INSERT_HEAD(&sahtree, newsah, chain);
 2576         }
 2577         return(newsah);
 2578 }
 2579 
 2580 /*
 2581  * delete SA index and all SA registerd.
 2582  */
 2583 static void
 2584 key_delsah(sah)
 2585         struct secashead *sah;
 2586 {
 2587         struct secasvar *sav, *nextsav;
 2588         u_int stateidx, state;
 2589         int s;
 2590         int zombie = 0;
 2591 
 2592         /* sanity check */
 2593         if (sah == NULL)
 2594                 panic("key_delsah: NULL pointer is passed.\n");
 2595 
 2596         s = splnet();   /*called from softclock()*/
 2597 
 2598         /* searching all SA registerd in the secindex. */
 2599         for (stateidx = 0;
 2600              stateidx < _ARRAYLEN(saorder_state_any);
 2601              stateidx++) {
 2602 
 2603                 state = saorder_state_any[stateidx];
 2604                 for (sav = (struct secasvar *)LIST_FIRST(&sah->savtree[state]);
 2605                      sav != NULL;
 2606                      sav = nextsav) {
 2607 
 2608                         nextsav = LIST_NEXT(sav, chain);
 2609 
 2610                         if (sav->refcnt == 0) {
 2611                                 /* sanity check */
 2612                                 KEY_CHKSASTATE(state, sav->state, "key_delsah");
 2613                                 KEY_FREESAV(&sav);
 2614                         } else {
 2615                                 /* give up to delete this sa */
 2616                                 zombie++;
 2617                         }
 2618                 }
 2619         }
 2620 
 2621         /* don't delete sah only if there are savs. */
 2622         if (zombie) {
 2623                 splx(s);
 2624                 return;
 2625         }
 2626 
 2627         if (sah->sa_route.ro_rt) {
 2628                 RTFREE(sah->sa_route.ro_rt);
 2629                 sah->sa_route.ro_rt = (struct rtentry *)NULL;
 2630         }
 2631 
 2632         /* remove from tree of SA index */
 2633         if (__LIST_CHAINED(sah))
 2634                 LIST_REMOVE(sah, chain);
 2635 
 2636         KFREE(sah);
 2637 
 2638         splx(s);
 2639         return;
 2640 }
 2641 
 2642 /*
 2643  * allocating a new SA with LARVAL state.  key_add() and key_getspi() call,
 2644  * and copy the values of mhp into new buffer.
 2645  * When SAD message type is GETSPI:
 2646  *      to set sequence number from acq_seq++,
 2647  *      to set zero to SPI.
 2648  *      not to call key_setsava().
 2649  * OUT: NULL    : fail
 2650  *      others  : pointer to new secasvar.
 2651  *
 2652  * does not modify mbuf.  does not free mbuf on error.
 2653  */
 2654 static struct secasvar *
 2655 key_newsav(m, mhp, sah, errp, where, tag)
 2656         struct mbuf *m;
 2657         const struct sadb_msghdr *mhp;
 2658         struct secashead *sah;
 2659         int *errp;
 2660         const char* where;
 2661         int tag;
 2662 {
 2663         struct secasvar *newsav;
 2664         const struct sadb_sa *xsa;
 2665 
 2666         /* sanity check */
 2667         if (m == NULL || mhp == NULL || mhp->msg == NULL || sah == NULL)
 2668                 panic("key_newsa: NULL pointer is passed.\n");
 2669 
 2670         KMALLOC(newsav, struct secasvar *, sizeof(struct secasvar));
 2671         if (newsav == NULL) {
 2672                 ipseclog((LOG_DEBUG, "key_newsa: No more memory.\n"));
 2673                 *errp = ENOBUFS;
 2674                 goto done;
 2675         }
 2676         bzero((caddr_t)newsav, sizeof(struct secasvar));
 2677 
 2678         switch (mhp->msg->sadb_msg_type) {
 2679         case SADB_GETSPI:
 2680                 newsav->spi = 0;
 2681 
 2682 #ifdef IPSEC_DOSEQCHECK
 2683                 /* sync sequence number */
 2684                 if (mhp->msg->sadb_msg_seq == 0)
 2685                         newsav->seq =
 2686                                 (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
 2687                 else
 2688 #endif
 2689                         newsav->seq = mhp->msg->sadb_msg_seq;
 2690                 break;
 2691 
 2692         case SADB_ADD:
 2693                 /* sanity check */
 2694                 if (mhp->ext[SADB_EXT_SA] == NULL) {
 2695                         KFREE(newsav), newsav = NULL;
 2696                         ipseclog((LOG_DEBUG, "key_newsa: invalid message is passed.\n"));
 2697                         *errp = EINVAL;
 2698                         goto done;
 2699                 }
 2700                 xsa = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 2701                 newsav->spi = xsa->sadb_sa_spi;
 2702                 newsav->seq = mhp->msg->sadb_msg_seq;
 2703                 break;
 2704         default:
 2705                 KFREE(newsav), newsav = NULL;
 2706                 *errp = EINVAL;
 2707                 goto done;
 2708         }
 2709 
 2710         /* copy sav values */
 2711         if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
 2712                 *errp = key_setsaval(newsav, m, mhp);
 2713                 if (*errp) {
 2714                         KFREE(newsav), newsav = NULL;
 2715                         goto done;
 2716                 }
 2717         }
 2718 
 2719         /* reset created */
 2720         newsav->created = time_second;
 2721         newsav->pid = mhp->msg->sadb_msg_pid;
 2722 
 2723         /* add to satree */
 2724         newsav->sah = sah;
 2725         newsav->refcnt = 1;
 2726         newsav->state = SADB_SASTATE_LARVAL;
 2727         LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
 2728                         secasvar, chain);
 2729 done:
 2730         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 2731                 printf("DP key_newsav from %s:%u return SP:%p\n",
 2732                         where, tag, newsav));
 2733 
 2734         return newsav;
 2735 }
 2736 
 2737 /*
 2738  * free() SA variable entry.
 2739  */
 2740 static void
 2741 key_delsav(sav)
 2742         struct secasvar *sav;
 2743 {
 2744         KASSERT(sav != NULL, ("key_delsav: null sav"));
 2745         KASSERT(sav->refcnt == 0,
 2746                 ("key_delsav: reference count %u > 0", sav->refcnt));
 2747 
 2748         /* remove from SA header */
 2749         if (__LIST_CHAINED(sav))
 2750                 LIST_REMOVE(sav, chain);
 2751 
 2752         /*
 2753          * Cleanup xform state.  Note that zeroize'ing causes the
 2754          * keys to be cleared; otherwise we must do it ourself.
 2755          */
 2756         if (sav->tdb_xform != NULL) {
 2757                 sav->tdb_xform->xf_zeroize(sav);
 2758                 sav->tdb_xform = NULL;
 2759         } else {
 2760                 if (sav->key_auth != NULL)
 2761                         bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
 2762                 if (sav->key_enc != NULL)
 2763                         bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc));
 2764         }
 2765         if (sav->key_auth != NULL) {
 2766                 KFREE(sav->key_auth);
 2767                 sav->key_auth = NULL;
 2768         }
 2769         if (sav->key_enc != NULL) {
 2770                 KFREE(sav->key_enc);
 2771                 sav->key_enc = NULL;
 2772         }
 2773         if (sav->sched) {
 2774                 bzero(sav->sched, sav->schedlen);
 2775                 KFREE(sav->sched);
 2776                 sav->sched = NULL;
 2777         }
 2778         if (sav->replay != NULL) {
 2779                 KFREE(sav->replay);
 2780                 sav->replay = NULL;
 2781         }
 2782         if (sav->lft_c != NULL) {
 2783                 KFREE(sav->lft_c);
 2784                 sav->lft_c = NULL;
 2785         }
 2786         if (sav->lft_h != NULL) {
 2787                 KFREE(sav->lft_h);
 2788                 sav->lft_h = NULL;
 2789         }
 2790         if (sav->lft_s != NULL) {
 2791                 KFREE(sav->lft_s);
 2792                 sav->lft_s = NULL;
 2793         }
 2794         if (sav->iv != NULL) {
 2795                 KFREE(sav->iv);
 2796                 sav->iv = NULL;
 2797         }
 2798 
 2799         KFREE(sav);
 2800 
 2801         return;
 2802 }
 2803 
 2804 /*
 2805  * search SAD.
 2806  * OUT:
 2807  *      NULL    : not found
 2808  *      others  : found, pointer to a SA.
 2809  */
 2810 static struct secashead *
 2811 key_getsah(saidx)
 2812         struct secasindex *saidx;
 2813 {
 2814         struct secashead *sah;
 2815 
 2816         LIST_FOREACH(sah, &sahtree, chain) {
 2817                 if (sah->state == SADB_SASTATE_DEAD)
 2818                         continue;
 2819                 if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
 2820                         return sah;
 2821         }
 2822 
 2823         return NULL;
 2824 }
 2825 
 2826 /*
 2827  * check not to be duplicated SPI.
 2828  * NOTE: this function is too slow due to searching all SAD.
 2829  * OUT:
 2830  *      NULL    : not found
 2831  *      others  : found, pointer to a SA.
 2832  */
 2833 static struct secasvar *
 2834 key_checkspidup(saidx, spi)
 2835         struct secasindex *saidx;
 2836         u_int32_t spi;
 2837 {
 2838         struct secashead *sah;
 2839         struct secasvar *sav;
 2840 
 2841         /* check address family */
 2842         if (saidx->src.sa.sa_family != saidx->dst.sa.sa_family) {
 2843                 ipseclog((LOG_DEBUG, "key_checkspidup: address family mismatched.\n"));
 2844                 return NULL;
 2845         }
 2846 
 2847         /* check all SAD */
 2848         LIST_FOREACH(sah, &sahtree, chain) {
 2849                 if (!key_ismyaddr((struct sockaddr *)&sah->saidx.dst))
 2850                         continue;
 2851                 sav = key_getsavbyspi(sah, spi);
 2852                 if (sav != NULL)
 2853                         return sav;
 2854         }
 2855 
 2856         return NULL;
 2857 }
 2858 
 2859 /*
 2860  * search SAD litmited alive SA, protocol, SPI.
 2861  * OUT:
 2862  *      NULL    : not found
 2863  *      others  : found, pointer to a SA.
 2864  */
 2865 static struct secasvar *
 2866 key_getsavbyspi(sah, spi)
 2867         struct secashead *sah;
 2868         u_int32_t spi;
 2869 {
 2870         struct secasvar *sav;
 2871         u_int stateidx, state;
 2872 
 2873         /* search all status */
 2874         for (stateidx = 0;
 2875              stateidx < _ARRAYLEN(saorder_state_alive);
 2876              stateidx++) {
 2877 
 2878                 state = saorder_state_alive[stateidx];
 2879                 LIST_FOREACH(sav, &sah->savtree[state], chain) {
 2880 
 2881                         /* sanity check */
 2882                         if (sav->state != state) {
 2883                                 ipseclog((LOG_DEBUG, "key_getsavbyspi: "
 2884                                     "invalid sav->state (queue: %d SA: %d)\n",
 2885                                     state, sav->state));
 2886                                 continue;
 2887                         }
 2888 
 2889                         if (sav->spi == spi)
 2890                                 return sav;
 2891                 }
 2892         }
 2893 
 2894         return NULL;
 2895 }
 2896 
 2897 /*
 2898  * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
 2899  * You must update these if need.
 2900  * OUT: 0:      success.
 2901  *      !0:     failure.
 2902  *
 2903  * does not modify mbuf.  does not free mbuf on error.
 2904  */
 2905 static int
 2906 key_setsaval(sav, m, mhp)
 2907         struct secasvar *sav;
 2908         struct mbuf *m;
 2909         const struct sadb_msghdr *mhp;
 2910 {
 2911         int error = 0;
 2912 
 2913         /* sanity check */
 2914         if (m == NULL || mhp == NULL || mhp->msg == NULL)
 2915                 panic("key_setsaval: NULL pointer is passed.\n");
 2916 
 2917         /* initialization */
 2918         sav->replay = NULL;
 2919         sav->key_auth = NULL;
 2920         sav->key_enc = NULL;
 2921         sav->sched = NULL;
 2922         sav->schedlen = 0;
 2923         sav->iv = NULL;
 2924         sav->lft_c = NULL;
 2925         sav->lft_h = NULL;
 2926         sav->lft_s = NULL;
 2927         sav->tdb_xform = NULL;          /* transform */
 2928         sav->tdb_encalgxform = NULL;    /* encoding algorithm */
 2929         sav->tdb_authalgxform = NULL;   /* authentication algorithm */
 2930         sav->tdb_compalgxform = NULL;   /* compression algorithm */
 2931 
 2932         /* SA */
 2933         if (mhp->ext[SADB_EXT_SA] != NULL) {
 2934                 const struct sadb_sa *sa0;
 2935 
 2936                 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 2937                 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
 2938                         error = EINVAL;
 2939                         goto fail;
 2940                 }
 2941 
 2942                 sav->alg_auth = sa0->sadb_sa_auth;
 2943                 sav->alg_enc = sa0->sadb_sa_encrypt;
 2944                 sav->flags = sa0->sadb_sa_flags;
 2945 
 2946                 /* replay window */
 2947                 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
 2948                         sav->replay = (struct secreplay *)
 2949                                 malloc(sizeof(struct secreplay)+sa0->sadb_sa_replay, M_SECA, M_NOWAIT|M_ZERO);
 2950                         if (sav->replay == NULL) {
 2951                                 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
 2952                                 error = ENOBUFS;
 2953                                 goto fail;
 2954                         }
 2955                         if (sa0->sadb_sa_replay != 0)
 2956                                 sav->replay->bitmap = (caddr_t)(sav->replay+1);
 2957                         sav->replay->wsize = sa0->sadb_sa_replay;
 2958                 }
 2959         }
 2960 
 2961         /* Authentication keys */
 2962         if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
 2963                 const struct sadb_key *key0;
 2964                 int len;
 2965 
 2966                 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
 2967                 len = mhp->extlen[SADB_EXT_KEY_AUTH];
 2968 
 2969                 error = 0;
 2970                 if (len < sizeof(*key0)) {
 2971                         error = EINVAL;
 2972                         goto fail;
 2973                 }
 2974                 switch (mhp->msg->sadb_msg_satype) {
 2975                 case SADB_SATYPE_AH:
 2976                 case SADB_SATYPE_ESP:
 2977                 case SADB_X_SATYPE_TCPSIGNATURE:
 2978                         if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
 2979                             sav->alg_auth != SADB_X_AALG_NULL)
 2980                                 error = EINVAL;
 2981                         break;
 2982                 case SADB_X_SATYPE_IPCOMP:
 2983                 default:
 2984                         error = EINVAL;
 2985                         break;
 2986                 }
 2987                 if (error) {
 2988                         ipseclog((LOG_DEBUG, "key_setsaval: invalid key_auth values.\n"));
 2989                         goto fail;
 2990                 }
 2991 
 2992                 sav->key_auth = (struct sadb_key *)key_newbuf(key0, len);
 2993                 if (sav->key_auth == NULL) {
 2994                         ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
 2995                         error = ENOBUFS;
 2996                         goto fail;
 2997                 }
 2998         }
 2999 
 3000         /* Encryption key */
 3001         if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
 3002                 const struct sadb_key *key0;
 3003                 int len;
 3004 
 3005                 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
 3006                 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
 3007 
 3008                 error = 0;
 3009                 if (len < sizeof(*key0)) {
 3010                         error = EINVAL;
 3011                         goto fail;
 3012                 }
 3013                 switch (mhp->msg->sadb_msg_satype) {
 3014                 case SADB_SATYPE_ESP:
 3015                         if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
 3016                             sav->alg_enc != SADB_EALG_NULL) {
 3017                                 error = EINVAL;
 3018                                 break;
 3019                         }
 3020                         sav->key_enc = (struct sadb_key *)key_newbuf(key0, len);
 3021                         if (sav->key_enc == NULL) {
 3022                                 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
 3023                                 error = ENOBUFS;
 3024                                 goto fail;
 3025                         }
 3026                         break;
 3027                 case SADB_X_SATYPE_IPCOMP:
 3028                         if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
 3029                                 error = EINVAL;
 3030                         sav->key_enc = NULL;    /*just in case*/
 3031                         break;
 3032                 case SADB_SATYPE_AH:
 3033                 case SADB_X_SATYPE_TCPSIGNATURE:
 3034                 default:
 3035                         error = EINVAL;
 3036                         break;
 3037                 }
 3038                 if (error) {
 3039                         ipseclog((LOG_DEBUG, "key_setsatval: invalid key_enc value.\n"));
 3040                         goto fail;
 3041                 }
 3042         }
 3043 
 3044         /* set iv */
 3045         sav->ivlen = 0;
 3046 
 3047         switch (mhp->msg->sadb_msg_satype) {
 3048         case SADB_SATYPE_AH:
 3049                 error = xform_init(sav, XF_AH);
 3050                 break;
 3051         case SADB_SATYPE_ESP:
 3052                 error = xform_init(sav, XF_ESP);
 3053                 break;
 3054         case SADB_X_SATYPE_IPCOMP:
 3055                 error = xform_init(sav, XF_IPCOMP);
 3056                 break;
 3057         case SADB_X_SATYPE_TCPSIGNATURE:
 3058                 error = xform_init(sav, XF_TCPSIGNATURE);
 3059                 break;
 3060         }
 3061         if (error) {
 3062                 ipseclog((LOG_DEBUG,
 3063                         "key_setsaval: unable to initialize SA type %u.\n",
 3064                         mhp->msg->sadb_msg_satype));
 3065                 goto fail;
 3066         }
 3067 
 3068         /* reset created */
 3069         sav->created = time_second;
 3070 
 3071         /* make lifetime for CURRENT */
 3072         KMALLOC(sav->lft_c, struct sadb_lifetime *,
 3073             sizeof(struct sadb_lifetime));
 3074         if (sav->lft_c == NULL) {
 3075                 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
 3076                 error = ENOBUFS;
 3077                 goto fail;
 3078         }
 3079 
 3080         sav->lft_c->sadb_lifetime_len =
 3081             PFKEY_UNIT64(sizeof(struct sadb_lifetime));
 3082         sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
 3083         sav->lft_c->sadb_lifetime_allocations = 0;
 3084         sav->lft_c->sadb_lifetime_bytes = 0;
 3085         sav->lft_c->sadb_lifetime_addtime = time_second;
 3086         sav->lft_c->sadb_lifetime_usetime = 0;
 3087 
 3088         /* lifetimes for HARD and SOFT */
 3089     {
 3090         const struct sadb_lifetime *lft0;
 3091 
 3092         lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
 3093         if (lft0 != NULL) {
 3094                 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
 3095                         error = EINVAL;
 3096                         goto fail;
 3097                 }
 3098                 sav->lft_h = (struct sadb_lifetime *)key_newbuf(lft0,
 3099                     sizeof(*lft0));
 3100                 if (sav->lft_h == NULL) {
 3101                         ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
 3102                         error = ENOBUFS;
 3103                         goto fail;
 3104                 }
 3105                 /* to be initialize ? */
 3106         }
 3107 
 3108         lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
 3109         if (lft0 != NULL) {
 3110                 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
 3111                         error = EINVAL;
 3112                         goto fail;
 3113                 }
 3114                 sav->lft_s = (struct sadb_lifetime *)key_newbuf(lft0,
 3115                     sizeof(*lft0));
 3116                 if (sav->lft_s == NULL) {
 3117                         ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
 3118                         error = ENOBUFS;
 3119                         goto fail;
 3120                 }
 3121                 /* to be initialize ? */
 3122         }
 3123     }
 3124 
 3125         return 0;
 3126 
 3127  fail:
 3128         /* initialization */
 3129         if (sav->replay != NULL) {
 3130                 KFREE(sav->replay);
 3131                 sav->replay = NULL;
 3132         }
 3133         if (sav->key_auth != NULL) {
 3134                 KFREE(sav->key_auth);
 3135                 sav->key_auth = NULL;
 3136         }
 3137         if (sav->key_enc != NULL) {
 3138                 KFREE(sav->key_enc);
 3139                 sav->key_enc = NULL;
 3140         }
 3141         if (sav->sched) {
 3142                 KFREE(sav->sched);
 3143                 sav->sched = NULL;
 3144         }
 3145         if (sav->iv != NULL) {
 3146                 KFREE(sav->iv);
 3147                 sav->iv = NULL;
 3148         }
 3149         if (sav->lft_c != NULL) {
 3150                 KFREE(sav->lft_c);
 3151                 sav->lft_c = NULL;
 3152         }
 3153         if (sav->lft_h != NULL) {
 3154                 KFREE(sav->lft_h);
 3155                 sav->lft_h = NULL;
 3156         }
 3157         if (sav->lft_s != NULL) {
 3158                 KFREE(sav->lft_s);
 3159                 sav->lft_s = NULL;
 3160         }
 3161 
 3162         return error;
 3163 }
 3164 
 3165 /*
 3166  * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
 3167  * OUT: 0:      valid
 3168  *      other:  errno
 3169  */
 3170 static int
 3171 key_mature(sav)
 3172         struct secasvar *sav;
 3173 {
 3174         int error;
 3175 
 3176         /* check SPI value */
 3177         switch (sav->sah->saidx.proto) {
 3178         case IPPROTO_ESP:
 3179         case IPPROTO_AH:
 3180                 if (ntohl(sav->spi) >= 0 && ntohl(sav->spi) <= 255) {
 3181                         ipseclog((LOG_DEBUG,
 3182                             "key_mature: illegal range of SPI %u.\n",
 3183                             (u_int32_t)ntohl(sav->spi)));
 3184                         return EINVAL;
 3185                 }
 3186                 break;
 3187         }
 3188 
 3189         /* check satype */
 3190         switch (sav->sah->saidx.proto) {
 3191         case IPPROTO_ESP:
 3192                 /* check flags */
 3193                 if ((sav->flags & (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) ==
 3194                     (SADB_X_EXT_OLD|SADB_X_EXT_DERIV)) {
 3195                         ipseclog((LOG_DEBUG, "key_mature: "
 3196                             "invalid flag (derived) given to old-esp.\n"));
 3197                         return EINVAL;
 3198                 }
 3199                 error = xform_init(sav, XF_ESP);
 3200                 break;
 3201         case IPPROTO_AH:
 3202                 /* check flags */
 3203                 if (sav->flags & SADB_X_EXT_DERIV) {
 3204                         ipseclog((LOG_DEBUG, "key_mature: "
 3205                             "invalid flag (derived) given to AH SA.\n"));
 3206                         return EINVAL;
 3207                 }
 3208                 if (sav->alg_enc != SADB_EALG_NONE) {
 3209                         ipseclog((LOG_DEBUG, "key_mature: "
 3210                             "protocol and algorithm mismated.\n"));
 3211                         return(EINVAL);
 3212                 }
 3213                 error = xform_init(sav, XF_AH);
 3214                 break;
 3215         case IPPROTO_IPCOMP:
 3216                 if (sav->alg_auth != SADB_AALG_NONE) {
 3217                         ipseclog((LOG_DEBUG, "key_mature: "
 3218                                 "protocol and algorithm mismated.\n"));
 3219                         return(EINVAL);
 3220                 }
 3221                 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
 3222                  && ntohl(sav->spi) >= 0x10000) {
 3223                         ipseclog((LOG_DEBUG, "key_mature: invalid cpi for IPComp.\n"));
 3224                         return(EINVAL);
 3225                 }
 3226                 error = xform_init(sav, XF_IPCOMP);
 3227                 break;
 3228         case IPPROTO_TCP:
 3229                 if (sav->alg_enc != SADB_EALG_NONE) {
 3230                         ipseclog((LOG_DEBUG, "%s: protocol and algorithm "
 3231                                 "mismated.\n", __func__));
 3232                         return(EINVAL);
 3233                 }
 3234                 error = xform_init(sav, XF_TCPSIGNATURE);
 3235                 break;
 3236         default:
 3237                 ipseclog((LOG_DEBUG, "key_mature: Invalid satype.\n"));
 3238                 error = EPROTONOSUPPORT;
 3239                 break;
 3240         }
 3241         if (error == 0)
 3242                 key_sa_chgstate(sav, SADB_SASTATE_MATURE);
 3243         return (error);
 3244 }
 3245 
 3246 /*
 3247  * subroutine for SADB_GET and SADB_DUMP.
 3248  */
 3249 static struct mbuf *
 3250 key_setdumpsa(sav, type, satype, seq, pid)
 3251         struct secasvar *sav;
 3252         u_int8_t type, satype;
 3253         u_int32_t seq, pid;
 3254 {
 3255         struct mbuf *result = NULL, *tres = NULL, *m;
 3256         int l = 0;
 3257         int i;
 3258         void *p;
 3259         int dumporder[] = {
 3260                 SADB_EXT_SA, SADB_X_EXT_SA2,
 3261                 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
 3262                 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
 3263                 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
 3264                 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
 3265                 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
 3266         };
 3267 
 3268         m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
 3269         if (m == NULL)
 3270                 goto fail;
 3271         result = m;
 3272 
 3273         for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
 3274                 m = NULL;
 3275                 p = NULL;
 3276                 switch (dumporder[i]) {
 3277                 case SADB_EXT_SA:
 3278                         m = key_setsadbsa(sav);
 3279                         if (!m)
 3280                                 goto fail;
 3281                         break;
 3282 
 3283                 case SADB_X_EXT_SA2:
 3284                         m = key_setsadbxsa2(sav->sah->saidx.mode,
 3285                                         sav->replay ? sav->replay->count : 0,
 3286                                         sav->sah->saidx.reqid);
 3287                         if (!m)
 3288                                 goto fail;
 3289                         break;
 3290 
 3291                 case SADB_EXT_ADDRESS_SRC:
 3292                         m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
 3293                             &sav->sah->saidx.src.sa,
 3294                             FULLMASK, IPSEC_ULPROTO_ANY);
 3295                         if (!m)
 3296                                 goto fail;
 3297                         break;
 3298 
 3299                 case SADB_EXT_ADDRESS_DST:
 3300                         m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
 3301                             &sav->sah->saidx.dst.sa,
 3302                             FULLMASK, IPSEC_ULPROTO_ANY);
 3303                         if (!m)
 3304                                 goto fail;
 3305                         break;
 3306 
 3307                 case SADB_EXT_KEY_AUTH:
 3308                         if (!sav->key_auth)
 3309                                 continue;
 3310                         l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
 3311                         p = sav->key_auth;
 3312                         break;
 3313 
 3314                 case SADB_EXT_KEY_ENCRYPT:
 3315                         if (!sav->key_enc)
 3316                                 continue;
 3317                         l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
 3318                         p = sav->key_enc;
 3319                         break;
 3320 
 3321                 case SADB_EXT_LIFETIME_CURRENT:
 3322                         if (!sav->lft_c)
 3323                                 continue;
 3324                         l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
 3325                         p = sav->lft_c;
 3326                         break;
 3327 
 3328                 case SADB_EXT_LIFETIME_HARD:
 3329                         if (!sav->lft_h)
 3330                                 continue;
 3331                         l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
 3332                         p = sav->lft_h;
 3333                         break;
 3334 
 3335                 case SADB_EXT_LIFETIME_SOFT:
 3336                         if (!sav->lft_s)
 3337                                 continue;
 3338                         l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
 3339                         p = sav->lft_s;
 3340                         break;
 3341 
 3342                 case SADB_EXT_ADDRESS_PROXY:
 3343                 case SADB_EXT_IDENTITY_SRC:
 3344                 case SADB_EXT_IDENTITY_DST:
 3345                         /* XXX: should we brought from SPD ? */
 3346                 case SADB_EXT_SENSITIVITY:
 3347                 default:
 3348                         continue;
 3349                 }
 3350 
 3351                 if ((!m && !p) || (m && p))
 3352                         goto fail;
 3353                 if (p && tres) {
 3354                         M_PREPEND(tres, l, M_DONTWAIT);
 3355                         if (!tres)
 3356                                 goto fail;
 3357                         bcopy(p, mtod(tres, caddr_t), l);
 3358                         continue;
 3359                 }
 3360                 if (p) {
 3361                         m = key_alloc_mbuf(l);
 3362                         if (!m)
 3363                                 goto fail;
 3364                         m_copyback(m, 0, l, p);
 3365                 }
 3366 
 3367                 if (tres)
 3368                         m_cat(m, tres);
 3369                 tres = m;
 3370         }
 3371 
 3372         m_cat(result, tres);
 3373 
 3374         if (result->m_len < sizeof(struct sadb_msg)) {
 3375                 result = m_pullup(result, sizeof(struct sadb_msg));
 3376                 if (result == NULL)
 3377                         goto fail;
 3378         }
 3379 
 3380         result->m_pkthdr.len = 0;
 3381         for (m = result; m; m = m->m_next)
 3382                 result->m_pkthdr.len += m->m_len;
 3383 
 3384         mtod(result, struct sadb_msg *)->sadb_msg_len =
 3385             PFKEY_UNIT64(result->m_pkthdr.len);
 3386 
 3387         return result;
 3388 
 3389 fail:
 3390         m_freem(result);
 3391         m_freem(tres);
 3392         return NULL;
 3393 }
 3394 
 3395 /*
 3396  * set data into sadb_msg.
 3397  */
 3398 static struct mbuf *
 3399 key_setsadbmsg(type, tlen, satype, seq, pid, reserved)
 3400         u_int8_t type, satype;
 3401         u_int16_t tlen;
 3402         u_int32_t seq;
 3403         pid_t pid;
 3404         u_int16_t reserved;
 3405 {
 3406         struct mbuf *m;
 3407         struct sadb_msg *p;
 3408         int len;
 3409 
 3410         len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
 3411         if (len > MCLBYTES)
 3412                 return NULL;
 3413         MGETHDR(m, M_DONTWAIT, MT_DATA);
 3414         if (m && len > MHLEN) {
 3415                 MCLGET(m, M_DONTWAIT);
 3416                 if ((m->m_flags & M_EXT) == 0) {
 3417                         m_freem(m);
 3418                         m = NULL;
 3419                 }
 3420         }
 3421         if (!m)
 3422                 return NULL;
 3423         m->m_pkthdr.len = m->m_len = len;
 3424         m->m_next = NULL;
 3425 
 3426         p = mtod(m, struct sadb_msg *);
 3427 
 3428         bzero(p, len);
 3429         p->sadb_msg_version = PF_KEY_V2;
 3430         p->sadb_msg_type = type;
 3431         p->sadb_msg_errno = 0;
 3432         p->sadb_msg_satype = satype;
 3433         p->sadb_msg_len = PFKEY_UNIT64(tlen);
 3434         p->sadb_msg_reserved = reserved;
 3435         p->sadb_msg_seq = seq;
 3436         p->sadb_msg_pid = (u_int32_t)pid;
 3437 
 3438         return m;
 3439 }
 3440 
 3441 /*
 3442  * copy secasvar data into sadb_address.
 3443  */
 3444 static struct mbuf *
 3445 key_setsadbsa(sav)
 3446         struct secasvar *sav;
 3447 {
 3448         struct mbuf *m;
 3449         struct sadb_sa *p;
 3450         int len;
 3451 
 3452         len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
 3453         m = key_alloc_mbuf(len);
 3454         if (!m || m->m_next) {  /*XXX*/
 3455                 if (m)
 3456                         m_freem(m);
 3457                 return NULL;
 3458         }
 3459 
 3460         p = mtod(m, struct sadb_sa *);
 3461 
 3462         bzero(p, len);
 3463         p->sadb_sa_len = PFKEY_UNIT64(len);
 3464         p->sadb_sa_exttype = SADB_EXT_SA;
 3465         p->sadb_sa_spi = sav->spi;
 3466         p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
 3467         p->sadb_sa_state = sav->state;
 3468         p->sadb_sa_auth = sav->alg_auth;
 3469         p->sadb_sa_encrypt = sav->alg_enc;
 3470         p->sadb_sa_flags = sav->flags;
 3471 
 3472         return m;
 3473 }
 3474 
 3475 /*
 3476  * set data into sadb_address.
 3477  */
 3478 static struct mbuf *
 3479 key_setsadbaddr(exttype, saddr, prefixlen, ul_proto)
 3480         u_int16_t exttype;
 3481         const struct sockaddr *saddr;
 3482         u_int8_t prefixlen;
 3483         u_int16_t ul_proto;
 3484 {
 3485         struct mbuf *m;
 3486         struct sadb_address *p;
 3487         size_t len;
 3488 
 3489         len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
 3490             PFKEY_ALIGN8(saddr->sa_len);
 3491         m = key_alloc_mbuf(len);
 3492         if (!m || m->m_next) {  /*XXX*/
 3493                 if (m)
 3494                         m_freem(m);
 3495                 return NULL;
 3496         }
 3497 
 3498         p = mtod(m, struct sadb_address *);
 3499 
 3500         bzero(p, len);
 3501         p->sadb_address_len = PFKEY_UNIT64(len);
 3502         p->sadb_address_exttype = exttype;
 3503         p->sadb_address_proto = ul_proto;
 3504         if (prefixlen == FULLMASK) {
 3505                 switch (saddr->sa_family) {
 3506                 case AF_INET:
 3507                         prefixlen = sizeof(struct in_addr) << 3;
 3508                         break;
 3509                 case AF_INET6:
 3510                         prefixlen = sizeof(struct in6_addr) << 3;
 3511                         break;
 3512                 default:
 3513                         ; /*XXX*/
 3514                 }
 3515         }
 3516         p->sadb_address_prefixlen = prefixlen;
 3517         p->sadb_address_reserved = 0;
 3518 
 3519         bcopy(saddr,
 3520             mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
 3521             saddr->sa_len);
 3522 
 3523         return m;
 3524 }
 3525 
 3526 #if 0
 3527 /*
 3528  * set data into sadb_ident.
 3529  */
 3530 static struct mbuf *
 3531 key_setsadbident(exttype, idtype, string, stringlen, id)
 3532         u_int16_t exttype, idtype;
 3533         caddr_t string;
 3534         int stringlen;
 3535         u_int64_t id;
 3536 {
 3537         struct mbuf *m;
 3538         struct sadb_ident *p;
 3539         size_t len;
 3540 
 3541         len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
 3542         m = key_alloc_mbuf(len);
 3543         if (!m || m->m_next) {  /*XXX*/
 3544                 if (m)
 3545                         m_freem(m);
 3546                 return NULL;
 3547         }
 3548 
 3549         p = mtod(m, struct sadb_ident *);
 3550 
 3551         bzero(p, len);
 3552         p->sadb_ident_len = PFKEY_UNIT64(len);
 3553         p->sadb_ident_exttype = exttype;
 3554         p->sadb_ident_type = idtype;
 3555         p->sadb_ident_reserved = 0;
 3556         p->sadb_ident_id = id;
 3557 
 3558         bcopy(string,
 3559             mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
 3560             stringlen);
 3561 
 3562         return m;
 3563 }
 3564 #endif
 3565 
 3566 /*
 3567  * set data into sadb_x_sa2.
 3568  */
 3569 static struct mbuf *
 3570 key_setsadbxsa2(mode, seq, reqid)
 3571         u_int8_t mode;
 3572         u_int32_t seq, reqid;
 3573 {
 3574         struct mbuf *m;
 3575         struct sadb_x_sa2 *p;
 3576         size_t len;
 3577 
 3578         len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
 3579         m = key_alloc_mbuf(len);
 3580         if (!m || m->m_next) {  /*XXX*/
 3581                 if (m)
 3582                         m_freem(m);
 3583                 return NULL;
 3584         }
 3585 
 3586         p = mtod(m, struct sadb_x_sa2 *);
 3587 
 3588         bzero(p, len);
 3589         p->sadb_x_sa2_len = PFKEY_UNIT64(len);
 3590         p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
 3591         p->sadb_x_sa2_mode = mode;
 3592         p->sadb_x_sa2_reserved1 = 0;
 3593         p->sadb_x_sa2_reserved2 = 0;
 3594         p->sadb_x_sa2_sequence = seq;
 3595         p->sadb_x_sa2_reqid = reqid;
 3596 
 3597         return m;
 3598 }
 3599 
 3600 /*
 3601  * set data into sadb_x_policy
 3602  */
 3603 static struct mbuf *
 3604 key_setsadbxpolicy(type, dir, id)
 3605         u_int16_t type;
 3606         u_int8_t dir;
 3607         u_int32_t id;
 3608 {
 3609         struct mbuf *m;
 3610         struct sadb_x_policy *p;
 3611         size_t len;
 3612 
 3613         len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
 3614         m = key_alloc_mbuf(len);
 3615         if (!m || m->m_next) {  /*XXX*/
 3616                 if (m)
 3617                         m_freem(m);
 3618                 return NULL;
 3619         }
 3620 
 3621         p = mtod(m, struct sadb_x_policy *);
 3622 
 3623         bzero(p, len);
 3624         p->sadb_x_policy_len = PFKEY_UNIT64(len);
 3625         p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
 3626         p->sadb_x_policy_type = type;
 3627         p->sadb_x_policy_dir = dir;
 3628         p->sadb_x_policy_id = id;
 3629 
 3630         return m;
 3631 }
 3632 
 3633 /* %%% utilities */
 3634 /*
 3635  * copy a buffer into the new buffer allocated.
 3636  */
 3637 static void *
 3638 key_newbuf(src, len)
 3639         const void *src;
 3640         u_int len;
 3641 {
 3642         caddr_t new;
 3643 
 3644         KMALLOC(new, caddr_t, len);
 3645         if (new == NULL) {
 3646                 ipseclog((LOG_DEBUG, "key_newbuf: No more memory.\n"));
 3647                 return NULL;
 3648         }
 3649         bcopy(src, new, len);
 3650 
 3651         return new;
 3652 }
 3653 
 3654 /* compare my own address
 3655  * OUT: 1: true, i.e. my address.
 3656  *      0: false
 3657  */
 3658 int
 3659 key_ismyaddr(sa)
 3660         struct sockaddr *sa;
 3661 {
 3662 #ifdef INET
 3663         struct sockaddr_in *sin;
 3664         struct in_ifaddr *ia;
 3665 #endif
 3666 
 3667         /* sanity check */
 3668         if (sa == NULL)
 3669                 panic("key_ismyaddr: NULL pointer is passed.\n");
 3670 
 3671         switch (sa->sa_family) {
 3672 #ifdef INET
 3673         case AF_INET:
 3674                 sin = (struct sockaddr_in *)sa;
 3675                 for (ia = in_ifaddrhead.tqh_first; ia;
 3676                      ia = ia->ia_link.tqe_next)
 3677                 {
 3678                         if (sin->sin_family == ia->ia_addr.sin_family &&
 3679                             sin->sin_len == ia->ia_addr.sin_len &&
 3680                             sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
 3681                         {
 3682                                 return 1;
 3683                         }
 3684                 }
 3685                 break;
 3686 #endif
 3687 #ifdef INET6
 3688         case AF_INET6:
 3689                 return key_ismyaddr6((struct sockaddr_in6 *)sa);
 3690 #endif
 3691         }
 3692 
 3693         return 0;
 3694 }
 3695 
 3696 #ifdef INET6
 3697 /*
 3698  * compare my own address for IPv6.
 3699  * 1: ours
 3700  * 0: other
 3701  * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
 3702  */
 3703 #include <netinet6/in6_var.h>
 3704 
 3705 static int
 3706 key_ismyaddr6(sin6)
 3707         struct sockaddr_in6 *sin6;
 3708 {
 3709         struct in6_ifaddr *ia;
 3710         struct in6_multi *in6m;
 3711 
 3712         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
 3713                 if (key_sockaddrcmp((struct sockaddr *)&sin6,
 3714                     (struct sockaddr *)&ia->ia_addr, 0) == 0)
 3715                         return 1;
 3716 
 3717                 /*
 3718                  * XXX Multicast
 3719                  * XXX why do we care about multlicast here while we don't care
 3720                  * about IPv4 multicast??
 3721                  * XXX scope
 3722                  */
 3723                 in6m = NULL;
 3724                 IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
 3725                 if (in6m)
 3726                         return 1;
 3727         }
 3728 
 3729         /* loopback, just for safety */
 3730         if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
 3731                 return 1;
 3732 
 3733         return 0;
 3734 }
 3735 #endif /*INET6*/
 3736 
 3737 /*
 3738  * compare two secasindex structure.
 3739  * flag can specify to compare 2 saidxes.
 3740  * compare two secasindex structure without both mode and reqid.
 3741  * don't compare port.
 3742  * IN:  
 3743  *      saidx0: source, it can be in SAD.
 3744  *      saidx1: object.
 3745  * OUT: 
 3746  *      1 : equal
 3747  *      0 : not equal
 3748  */
 3749 static int
 3750 key_cmpsaidx(
 3751         const struct secasindex *saidx0,
 3752         const struct secasindex *saidx1,
 3753         int flag)
 3754 {
 3755         /* sanity */
 3756         if (saidx0 == NULL && saidx1 == NULL)
 3757                 return 1;
 3758 
 3759         if (saidx0 == NULL || saidx1 == NULL)
 3760                 return 0;
 3761 
 3762         if (saidx0->proto != saidx1->proto)
 3763                 return 0;
 3764 
 3765         if (flag == CMP_EXACTLY) {
 3766                 if (saidx0->mode != saidx1->mode)
 3767                         return 0;
 3768                 if (saidx0->reqid != saidx1->reqid)
 3769                         return 0;
 3770                 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.sa.sa_len) != 0 ||
 3771                     bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.sa.sa_len) != 0)
 3772                         return 0;
 3773         } else {
 3774 
 3775                 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
 3776                 if (flag == CMP_MODE_REQID
 3777                   ||flag == CMP_REQID) {
 3778                         /*
 3779                          * If reqid of SPD is non-zero, unique SA is required.
 3780                          * The result must be of same reqid in this case.
 3781                          */
 3782                         if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
 3783                                 return 0;
 3784                 }
 3785 
 3786                 if (flag == CMP_MODE_REQID) {
 3787                         if (saidx0->mode != IPSEC_MODE_ANY
 3788                          && saidx0->mode != saidx1->mode)
 3789                                 return 0;
 3790                 }
 3791 
 3792                 if (key_sockaddrcmp(&saidx0->src.sa, &saidx1->src.sa, 0) != 0) {
 3793                         return 0;
 3794                 }
 3795                 if (key_sockaddrcmp(&saidx0->dst.sa, &saidx1->dst.sa, 0) != 0) {
 3796                         return 0;
 3797                 }
 3798         }
 3799 
 3800         return 1;
 3801 }
 3802 
 3803 /*
 3804  * compare two secindex structure exactly.
 3805  * IN:
 3806  *      spidx0: source, it is often in SPD.
 3807  *      spidx1: object, it is often from PFKEY message.
 3808  * OUT:
 3809  *      1 : equal
 3810  *      0 : not equal
 3811  */
 3812 static int
 3813 key_cmpspidx_exactly(
 3814         struct secpolicyindex *spidx0,
 3815         struct secpolicyindex *spidx1)
 3816 {
 3817         /* sanity */
 3818         if (spidx0 == NULL && spidx1 == NULL)
 3819                 return 1;
 3820 
 3821         if (spidx0 == NULL || spidx1 == NULL)
 3822                 return 0;
 3823 
 3824         if (spidx0->prefs != spidx1->prefs
 3825          || spidx0->prefd != spidx1->prefd
 3826          || spidx0->ul_proto != spidx1->ul_proto)
 3827                 return 0;
 3828 
 3829         return key_sockaddrcmp(&spidx0->src.sa, &spidx1->src.sa, 1) == 0 &&
 3830                key_sockaddrcmp(&spidx0->dst.sa, &spidx1->dst.sa, 1) == 0;
 3831 }
 3832 
 3833 /*
 3834  * compare two secindex structure with mask.
 3835  * IN:
 3836  *      spidx0: source, it is often in SPD.
 3837  *      spidx1: object, it is often from IP header.
 3838  * OUT:
 3839  *      1 : equal
 3840  *      0 : not equal
 3841  */
 3842 static int
 3843 key_cmpspidx_withmask(
 3844         struct secpolicyindex *spidx0,
 3845         struct secpolicyindex *spidx1)
 3846 {
 3847         /* sanity */
 3848         if (spidx0 == NULL && spidx1 == NULL)
 3849                 return 1;
 3850 
 3851         if (spidx0 == NULL || spidx1 == NULL)
 3852                 return 0;
 3853 
 3854         if (spidx0->src.sa.sa_family != spidx1->src.sa.sa_family ||
 3855             spidx0->dst.sa.sa_family != spidx1->dst.sa.sa_family ||
 3856             spidx0->src.sa.sa_len != spidx1->src.sa.sa_len ||
 3857             spidx0->dst.sa.sa_len != spidx1->dst.sa.sa_len)
 3858                 return 0;
 3859 
 3860         /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
 3861         if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
 3862          && spidx0->ul_proto != spidx1->ul_proto)
 3863                 return 0;
 3864 
 3865         switch (spidx0->src.sa.sa_family) {
 3866         case AF_INET:
 3867                 if (spidx0->src.sin.sin_port != IPSEC_PORT_ANY
 3868                  && spidx0->src.sin.sin_port != spidx1->src.sin.sin_port)
 3869                         return 0;
 3870                 if (!key_bbcmp(&spidx0->src.sin.sin_addr,
 3871                     &spidx1->src.sin.sin_addr, spidx0->prefs))
 3872                         return 0;
 3873                 break;
 3874         case AF_INET6:
 3875                 if (spidx0->src.sin6.sin6_port != IPSEC_PORT_ANY
 3876                  && spidx0->src.sin6.sin6_port != spidx1->src.sin6.sin6_port)
 3877                         return 0;
 3878                 /*
 3879                  * scope_id check. if sin6_scope_id is 0, we regard it
 3880                  * as a wildcard scope, which matches any scope zone ID. 
 3881                  */
 3882                 if (spidx0->src.sin6.sin6_scope_id &&
 3883                     spidx1->src.sin6.sin6_scope_id &&
 3884                     spidx0->src.sin6.sin6_scope_id != spidx1->src.sin6.sin6_scope_id)
 3885                         return 0;
 3886                 if (!key_bbcmp(&spidx0->src.sin6.sin6_addr,
 3887                     &spidx1->src.sin6.sin6_addr, spidx0->prefs))
 3888                         return 0;
 3889                 break;
 3890         default:
 3891                 /* XXX */
 3892                 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.sa.sa_len) != 0)
 3893                         return 0;
 3894                 break;
 3895         }
 3896 
 3897         switch (spidx0->dst.sa.sa_family) {
 3898         case AF_INET:
 3899                 if (spidx0->dst.sin.sin_port != IPSEC_PORT_ANY
 3900                  && spidx0->dst.sin.sin_port != spidx1->dst.sin.sin_port)
 3901                         return 0;
 3902                 if (!key_bbcmp(&spidx0->dst.sin.sin_addr,
 3903                     &spidx1->dst.sin.sin_addr, spidx0->prefd))
 3904                         return 0;
 3905                 break;
 3906         case AF_INET6:
 3907                 if (spidx0->dst.sin6.sin6_port != IPSEC_PORT_ANY
 3908                  && spidx0->dst.sin6.sin6_port != spidx1->dst.sin6.sin6_port)
 3909                         return 0;
 3910                 /*
 3911                  * scope_id check. if sin6_scope_id is 0, we regard it
 3912                  * as a wildcard scope, which matches any scope zone ID. 
 3913                  */
 3914                 if (spidx0->src.sin6.sin6_scope_id &&
 3915                     spidx1->src.sin6.sin6_scope_id &&
 3916                     spidx0->dst.sin6.sin6_scope_id != spidx1->dst.sin6.sin6_scope_id)
 3917                         return 0;
 3918                 if (!key_bbcmp(&spidx0->dst.sin6.sin6_addr,
 3919                     &spidx1->dst.sin6.sin6_addr, spidx0->prefd))
 3920                         return 0;
 3921                 break;
 3922         default:
 3923                 /* XXX */
 3924                 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.sa.sa_len) != 0)
 3925                         return 0;
 3926                 break;
 3927         }
 3928 
 3929         /* XXX Do we check other field ?  e.g. flowinfo */
 3930 
 3931         return 1;
 3932 }
 3933 
 3934 /* returns 0 on match */
 3935 static int
 3936 key_sockaddrcmp(
 3937         const struct sockaddr *sa1,
 3938         const struct sockaddr *sa2,
 3939         int port)
 3940 {
 3941 #ifdef satosin
 3942 #undef satosin
 3943 #endif
 3944 #define satosin(s) ((const struct sockaddr_in *)s)
 3945 #ifdef satosin6
 3946 #undef satosin6
 3947 #endif
 3948 #define satosin6(s) ((const struct sockaddr_in6 *)s)
 3949         if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
 3950                 return 1;
 3951 
 3952         switch (sa1->sa_family) {
 3953         case AF_INET:
 3954                 if (sa1->sa_len != sizeof(struct sockaddr_in))
 3955                         return 1;
 3956                 if (satosin(sa1)->sin_addr.s_addr !=
 3957                     satosin(sa2)->sin_addr.s_addr) {
 3958                         return 1;
 3959                 }
 3960                 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
 3961                         return 1;
 3962                 break;
 3963         case AF_INET6:
 3964                 if (sa1->sa_len != sizeof(struct sockaddr_in6))
 3965                         return 1;       /*EINVAL*/
 3966                 if (satosin6(sa1)->sin6_scope_id !=
 3967                     satosin6(sa2)->sin6_scope_id) {
 3968                         return 1;
 3969                 }
 3970                 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
 3971                     &satosin6(sa2)->sin6_addr)) {
 3972                         return 1;
 3973                 }
 3974                 if (port &&
 3975                     satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
 3976                         return 1;
 3977                 }
 3978         default:
 3979                 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
 3980                         return 1;
 3981                 break;
 3982         }
 3983 
 3984         return 0;
 3985 #undef satosin
 3986 #undef satosin6
 3987 }
 3988 
 3989 /*
 3990  * compare two buffers with mask.
 3991  * IN:
 3992  *      addr1: source
 3993  *      addr2: object
 3994  *      bits:  Number of bits to compare
 3995  * OUT:
 3996  *      1 : equal
 3997  *      0 : not equal
 3998  */
 3999 static int
 4000 key_bbcmp(const void *a1, const void *a2, u_int bits)
 4001 {
 4002         const unsigned char *p1 = a1;
 4003         const unsigned char *p2 = a2;
 4004 
 4005         /* XXX: This could be considerably faster if we compare a word
 4006          * at a time, but it is complicated on LSB Endian machines */
 4007 
 4008         /* Handle null pointers */
 4009         if (p1 == NULL || p2 == NULL)
 4010                 return (p1 == p2);
 4011 
 4012         while (bits >= 8) {
 4013                 if (*p1++ != *p2++)
 4014                         return 0;
 4015                 bits -= 8;
 4016         }
 4017 
 4018         if (bits > 0) {
 4019                 u_int8_t mask = ~((1<<(8-bits))-1);
 4020                 if ((*p1 & mask) != (*p2 & mask))
 4021                         return 0;
 4022         }
 4023         return 1;       /* Match! */
 4024 }
 4025 
 4026 /*
 4027  * time handler.
 4028  * scanning SPD and SAD to check status for each entries,
 4029  * and do to remove or to expire.
 4030  * XXX: year 2038 problem may remain.
 4031  */
 4032 void
 4033 key_timehandler(void)
 4034 {
 4035         u_int dir;
 4036         int s;
 4037         time_t now = time_second;
 4038 
 4039         s = splnet();   /*called from softclock()*/
 4040 
 4041         /* SPD */
 4042     {
 4043         struct secpolicy *sp, *nextsp;
 4044 
 4045         for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
 4046                 for (sp = LIST_FIRST(&sptree[dir]);
 4047                      sp != NULL;
 4048                      sp = nextsp) {
 4049 
 4050                         nextsp = LIST_NEXT(sp, chain);
 4051 
 4052                         if (sp->state == IPSEC_SPSTATE_DEAD) {
 4053                                 KEY_FREESP(&sp);
 4054                                 continue;
 4055                         }
 4056 
 4057                         if (sp->lifetime == 0 && sp->validtime == 0)
 4058                                 continue;
 4059 
 4060                         /* the deletion will occur next time */
 4061                         if ((sp->lifetime && now - sp->created > sp->lifetime)
 4062                          || (sp->validtime && now - sp->lastused > sp->validtime)) {
 4063                                 sp->state = IPSEC_SPSTATE_DEAD;
 4064                                 key_spdexpire(sp);
 4065                                 continue;
 4066                         }
 4067                 }
 4068         }
 4069     }
 4070 
 4071         /* SAD */
 4072     {
 4073         struct secashead *sah, *nextsah;
 4074         struct secasvar *sav, *nextsav;
 4075 
 4076         for (sah = LIST_FIRST(&sahtree);
 4077              sah != NULL;
 4078              sah = nextsah) {
 4079 
 4080                 nextsah = LIST_NEXT(sah, chain);
 4081 
 4082                 /* if sah has been dead, then delete it and process next sah. */
 4083                 if (sah->state == SADB_SASTATE_DEAD) {
 4084                         key_delsah(sah);
 4085                         continue;
 4086                 }
 4087 
 4088                 /* if LARVAL entry doesn't become MATURE, delete it. */
 4089                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]);
 4090                      sav != NULL;
 4091                      sav = nextsav) {
 4092 
 4093                         nextsav = LIST_NEXT(sav, chain);
 4094 
 4095                         if (now - sav->created > key_larval_lifetime) {
 4096                                 KEY_FREESAV(&sav);
 4097                         }
 4098                 }
 4099 
 4100                 /*
 4101                  * check MATURE entry to start to send expire message
 4102                  * whether or not.
 4103                  */
 4104                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
 4105                      sav != NULL;
 4106                      sav = nextsav) {
 4107 
 4108                         nextsav = LIST_NEXT(sav, chain);
 4109 
 4110                         /* we don't need to check. */
 4111                         if (sav->lft_s == NULL)
 4112                                 continue;
 4113 
 4114                         /* sanity check */
 4115                         if (sav->lft_c == NULL) {
 4116                                 ipseclog((LOG_DEBUG,"key_timehandler: "
 4117                                         "There is no CURRENT time, why?\n"));
 4118                                 continue;
 4119                         }
 4120 
 4121                         /* check SOFT lifetime */
 4122                         if (sav->lft_s->sadb_lifetime_addtime != 0
 4123                          && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
 4124                                 /*
 4125                                  * check SA to be used whether or not.
 4126                                  * when SA hasn't been used, delete it.
 4127                                  */
 4128                                 if (sav->lft_c->sadb_lifetime_usetime == 0) {
 4129                                         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 4130                                         KEY_FREESAV(&sav);
 4131                                 } else {
 4132                                         key_sa_chgstate(sav, SADB_SASTATE_DYING);
 4133                                         /*
 4134                                          * XXX If we keep to send expire
 4135                                          * message in the status of
 4136                                          * DYING. Do remove below code.
 4137                                          */
 4138                                         key_expire(sav);
 4139                                 }
 4140                         }
 4141                         /* check SOFT lifetime by bytes */
 4142                         /*
 4143                          * XXX I don't know the way to delete this SA
 4144                          * when new SA is installed.  Caution when it's
 4145                          * installed too big lifetime by time.
 4146                          */
 4147                         else if (sav->lft_s->sadb_lifetime_bytes != 0
 4148                               && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
 4149 
 4150                                 key_sa_chgstate(sav, SADB_SASTATE_DYING);
 4151                                 /*
 4152                                  * XXX If we keep to send expire
 4153                                  * message in the status of
 4154                                  * DYING. Do remove below code.
 4155                                  */
 4156                                 key_expire(sav);
 4157                         }
 4158                 }
 4159 
 4160                 /* check DYING entry to change status to DEAD. */
 4161                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]);
 4162                      sav != NULL;
 4163                      sav = nextsav) {
 4164 
 4165                         nextsav = LIST_NEXT(sav, chain);
 4166 
 4167                         /* we don't need to check. */
 4168                         if (sav->lft_h == NULL)
 4169                                 continue;
 4170 
 4171                         /* sanity check */
 4172                         if (sav->lft_c == NULL) {
 4173                                 ipseclog((LOG_DEBUG, "key_timehandler: "
 4174                                         "There is no CURRENT time, why?\n"));
 4175                                 continue;
 4176                         }
 4177 
 4178                         if (sav->lft_h->sadb_lifetime_addtime != 0
 4179                          && now - sav->created > sav->lft_h->sadb_lifetime_addtime) {
 4180                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 4181                                 KEY_FREESAV(&sav);
 4182                         }
 4183 #if 0   /* XXX Should we keep to send expire message until HARD lifetime ? */
 4184                         else if (sav->lft_s != NULL
 4185                               && sav->lft_s->sadb_lifetime_addtime != 0
 4186                               && now - sav->created > sav->lft_s->sadb_lifetime_addtime) {
 4187                                 /*
 4188                                  * XXX: should be checked to be
 4189                                  * installed the valid SA.
 4190                                  */
 4191 
 4192                                 /*
 4193                                  * If there is no SA then sending
 4194                                  * expire message.
 4195                                  */
 4196                                 key_expire(sav);
 4197                         }
 4198 #endif
 4199                         /* check HARD lifetime by bytes */
 4200                         else if (sav->lft_h->sadb_lifetime_bytes != 0
 4201                               && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
 4202                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 4203                                 KEY_FREESAV(&sav);
 4204                         }
 4205                 }
 4206 
 4207                 /* delete entry in DEAD */
 4208                 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]);
 4209                      sav != NULL;
 4210                      sav = nextsav) {
 4211 
 4212                         nextsav = LIST_NEXT(sav, chain);
 4213 
 4214                         /* sanity check */
 4215                         if (sav->state != SADB_SASTATE_DEAD) {
 4216                                 ipseclog((LOG_DEBUG, "key_timehandler: "
 4217                                         "invalid sav->state "
 4218                                         "(queue: %d SA: %d): "
 4219                                         "kill it anyway\n",
 4220                                         SADB_SASTATE_DEAD, sav->state));
 4221                         }
 4222 
 4223                         /*
 4224                          * do not call key_freesav() here.
 4225                          * sav should already be freed, and sav->refcnt
 4226                          * shows other references to sav
 4227                          * (such as from SPD).
 4228                          */
 4229                 }
 4230         }
 4231     }
 4232 
 4233 #ifndef IPSEC_NONBLOCK_ACQUIRE
 4234         /* ACQ tree */
 4235     {
 4236         struct secacq *acq, *nextacq;
 4237 
 4238         for (acq = LIST_FIRST(&acqtree);
 4239              acq != NULL;
 4240              acq = nextacq) {
 4241 
 4242                 nextacq = LIST_NEXT(acq, chain);
 4243 
 4244                 if (now - acq->created > key_blockacq_lifetime
 4245                  && __LIST_CHAINED(acq)) {
 4246                         LIST_REMOVE(acq, chain);
 4247                         KFREE(acq);
 4248                 }
 4249         }
 4250     }
 4251 #endif
 4252 
 4253         /* SP ACQ tree */
 4254     {
 4255         struct secspacq *acq, *nextacq;
 4256 
 4257         for (acq = LIST_FIRST(&spacqtree);
 4258              acq != NULL;
 4259              acq = nextacq) {
 4260 
 4261                 nextacq = LIST_NEXT(acq, chain);
 4262 
 4263                 if (now - acq->created > key_blockacq_lifetime
 4264                  && __LIST_CHAINED(acq)) {
 4265                         LIST_REMOVE(acq, chain);
 4266                         KFREE(acq);
 4267                 }
 4268         }
 4269     }
 4270 
 4271         /* initialize random seed */
 4272         if (key_tick_init_random++ > key_int_random) {
 4273                 key_tick_init_random = 0;
 4274                 key_srandom();
 4275         }
 4276 
 4277 #ifndef IPSEC_DEBUG2
 4278         /* do exchange to tick time !! */
 4279         (void)timeout((void *)key_timehandler, (void *)0, hz);
 4280 #endif /* IPSEC_DEBUG2 */
 4281 
 4282         splx(s);
 4283         return;
 4284 }
 4285 
 4286 /*
 4287  * to initialize a seed for random()
 4288  */
 4289 static void
 4290 key_srandom()
 4291 {
 4292         srandom(time_second);
 4293 }
 4294 
 4295 u_long
 4296 key_random()
 4297 {
 4298         u_long value;
 4299 
 4300         key_randomfill(&value, sizeof(value));
 4301         return value;
 4302 }
 4303 
 4304 void
 4305 key_randomfill(p, l)
 4306         void *p;
 4307         size_t l;
 4308 {
 4309         size_t n;
 4310         u_long v;
 4311         static int warn = 1;
 4312 
 4313         n = 0;
 4314         n = (size_t)read_random(p, (u_int)l);
 4315         /* last resort */
 4316         while (n < l) {
 4317                 v = random();
 4318                 bcopy(&v, (u_int8_t *)p + n,
 4319                     l - n < sizeof(v) ? l - n : sizeof(v));
 4320                 n += sizeof(v);
 4321 
 4322                 if (warn) {
 4323                         printf("WARNING: pseudo-random number generator "
 4324                             "used for IPsec processing\n");
 4325                         warn = 0;
 4326                 }
 4327         }
 4328 }
 4329 
 4330 /*
 4331  * map SADB_SATYPE_* to IPPROTO_*.
 4332  * if satype == SADB_SATYPE then satype is mapped to ~0.
 4333  * OUT:
 4334  *      0: invalid satype.
 4335  */
 4336 static u_int16_t
 4337 key_satype2proto(satype)
 4338         u_int8_t satype;
 4339 {
 4340         switch (satype) {
 4341         case SADB_SATYPE_UNSPEC:
 4342                 return IPSEC_PROTO_ANY;
 4343         case SADB_SATYPE_AH:
 4344                 return IPPROTO_AH;
 4345         case SADB_SATYPE_ESP:
 4346                 return IPPROTO_ESP;
 4347         case SADB_X_SATYPE_IPCOMP:
 4348                 return IPPROTO_IPCOMP;
 4349         case SADB_X_SATYPE_TCPSIGNATURE:
 4350                 return IPPROTO_TCP;
 4351         default:
 4352                 return 0;
 4353         }
 4354         /* NOTREACHED */
 4355 }
 4356 
 4357 /*
 4358  * map IPPROTO_* to SADB_SATYPE_*
 4359  * OUT:
 4360  *      0: invalid protocol type.
 4361  */
 4362 static u_int8_t
 4363 key_proto2satype(proto)
 4364         u_int16_t proto;
 4365 {
 4366         switch (proto) {
 4367         case IPPROTO_AH:
 4368                 return SADB_SATYPE_AH;
 4369         case IPPROTO_ESP:
 4370                 return SADB_SATYPE_ESP;
 4371         case IPPROTO_IPCOMP:
 4372                 return SADB_X_SATYPE_IPCOMP;
 4373         case IPPROTO_TCP:
 4374                 return SADB_X_SATYPE_TCPSIGNATURE;
 4375         default:
 4376                 return 0;
 4377         }
 4378         /* NOTREACHED */
 4379 }
 4380 
 4381 /* %%% PF_KEY */
 4382 /*
 4383  * SADB_GETSPI processing is to receive
 4384  *      <base, (SA2), src address, dst address, (SPI range)>
 4385  * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
 4386  * tree with the status of LARVAL, and send
 4387  *      <base, SA(*), address(SD)>
 4388  * to the IKMPd.
 4389  *
 4390  * IN:  mhp: pointer to the pointer to each header.
 4391  * OUT: NULL if fail.
 4392  *      other if success, return pointer to the message to send.
 4393  */
 4394 static int
 4395 key_getspi(so, m, mhp)
 4396         struct socket *so;
 4397         struct mbuf *m;
 4398         const struct sadb_msghdr *mhp;
 4399 {
 4400         struct sadb_address *src0, *dst0;
 4401         struct secasindex saidx;
 4402         struct secashead *newsah;
 4403         struct secasvar *newsav;
 4404         u_int8_t proto;
 4405         u_int32_t spi;
 4406         u_int8_t mode;
 4407         u_int32_t reqid;
 4408         int error;
 4409 
 4410         /* sanity check */
 4411         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 4412                 panic("key_getspi: NULL pointer is passed.\n");
 4413 
 4414         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 4415             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
 4416                 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
 4417                 return key_senderror(so, m, EINVAL);
 4418         }
 4419         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 4420             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 4421                 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
 4422                 return key_senderror(so, m, EINVAL);
 4423         }
 4424         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
 4425                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
 4426                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
 4427         } else {
 4428                 mode = IPSEC_MODE_ANY;
 4429                 reqid = 0;
 4430         }
 4431 
 4432         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
 4433         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
 4434 
 4435         /* map satype to proto */
 4436         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 4437                 ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
 4438                 return key_senderror(so, m, EINVAL);
 4439         }
 4440 
 4441         /* make sure if port number is zero. */
 4442         switch (((struct sockaddr *)(src0 + 1))->sa_family) {
 4443         case AF_INET:
 4444                 if (((struct sockaddr *)(src0 + 1))->sa_len !=
 4445                     sizeof(struct sockaddr_in))
 4446                         return key_senderror(so, m, EINVAL);
 4447                 ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
 4448                 break;
 4449         case AF_INET6:
 4450                 if (((struct sockaddr *)(src0 + 1))->sa_len !=
 4451                     sizeof(struct sockaddr_in6))
 4452                         return key_senderror(so, m, EINVAL);
 4453                 ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
 4454                 break;
 4455         default:
 4456                 ; /*???*/
 4457         }
 4458         switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
 4459         case AF_INET:
 4460                 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
 4461                     sizeof(struct sockaddr_in))
 4462                         return key_senderror(so, m, EINVAL);
 4463                 ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
 4464                 break;
 4465         case AF_INET6:
 4466                 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
 4467                     sizeof(struct sockaddr_in6))
 4468                         return key_senderror(so, m, EINVAL);
 4469                 ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
 4470                 break;
 4471         default:
 4472                 ; /*???*/
 4473         }
 4474 
 4475         /* XXX boundary check against sa_len */
 4476         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
 4477 
 4478         /* SPI allocation */
 4479         spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
 4480                                &saidx);
 4481         if (spi == 0)
 4482                 return key_senderror(so, m, EINVAL);
 4483 
 4484         /* get a SA index */
 4485         if ((newsah = key_getsah(&saidx)) == NULL) {
 4486                 /* create a new SA index */
 4487                 if ((newsah = key_newsah(&saidx)) == NULL) {
 4488                         ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
 4489                         return key_senderror(so, m, ENOBUFS);
 4490                 }
 4491         }
 4492 
 4493         /* get a new SA */
 4494         /* XXX rewrite */
 4495         newsav = KEY_NEWSAV(m, mhp, newsah, &error);
 4496         if (newsav == NULL) {
 4497                 /* XXX don't free new SA index allocated in above. */
 4498                 return key_senderror(so, m, error);
 4499         }
 4500 
 4501         /* set spi */
 4502         newsav->spi = htonl(spi);
 4503 
 4504 #ifndef IPSEC_NONBLOCK_ACQUIRE
 4505         /* delete the entry in acqtree */
 4506         if (mhp->msg->sadb_msg_seq != 0) {
 4507                 struct secacq *acq;
 4508                 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
 4509                         /* reset counter in order to deletion by timehandler. */
 4510                         acq->created = time_second;
 4511                         acq->count = 0;
 4512                 }
 4513         }
 4514 #endif
 4515 
 4516     {
 4517         struct mbuf *n, *nn;
 4518         struct sadb_sa *m_sa;
 4519         struct sadb_msg *newmsg;
 4520         int off, len;
 4521 
 4522         /* create new sadb_msg to reply. */
 4523         len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
 4524             PFKEY_ALIGN8(sizeof(struct sadb_sa));
 4525         if (len > MCLBYTES)
 4526                 return key_senderror(so, m, ENOBUFS);
 4527 
 4528         MGETHDR(n, M_DONTWAIT, MT_DATA);
 4529         if (len > MHLEN) {
 4530                 MCLGET(n, M_DONTWAIT);
 4531                 if ((n->m_flags & M_EXT) == 0) {
 4532                         m_freem(n);
 4533                         n = NULL;
 4534                 }
 4535         }
 4536         if (!n)
 4537                 return key_senderror(so, m, ENOBUFS);
 4538 
 4539         n->m_len = len;
 4540         n->m_next = NULL;
 4541         off = 0;
 4542 
 4543         m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
 4544         off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
 4545 
 4546         m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
 4547         m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
 4548         m_sa->sadb_sa_exttype = SADB_EXT_SA;
 4549         m_sa->sadb_sa_spi = htonl(spi);
 4550         off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
 4551 
 4552 #ifdef DIAGNOSTIC
 4553         if (off != len)
 4554                 panic("length inconsistency in key_getspi");
 4555 #endif
 4556 
 4557         n->m_next = key_gather_mbuf(m, mhp, 0, 2, SADB_EXT_ADDRESS_SRC,
 4558             SADB_EXT_ADDRESS_DST);
 4559         if (!n->m_next) {
 4560                 m_freem(n);
 4561                 return key_senderror(so, m, ENOBUFS);
 4562         }
 4563 
 4564         if (n->m_len < sizeof(struct sadb_msg)) {
 4565                 n = m_pullup(n, sizeof(struct sadb_msg));
 4566                 if (n == NULL)
 4567                         return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
 4568         }
 4569 
 4570         n->m_pkthdr.len = 0;
 4571         for (nn = n; nn; nn = nn->m_next)
 4572                 n->m_pkthdr.len += nn->m_len;
 4573 
 4574         newmsg = mtod(n, struct sadb_msg *);
 4575         newmsg->sadb_msg_seq = newsav->seq;
 4576         newmsg->sadb_msg_errno = 0;
 4577         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 4578 
 4579         m_freem(m);
 4580         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
 4581     }
 4582 }
 4583 
 4584 /*
 4585  * allocating new SPI
 4586  * called by key_getspi().
 4587  * OUT:
 4588  *      0:      failure.
 4589  *      others: success.
 4590  */
 4591 static u_int32_t
 4592 key_do_getnewspi(spirange, saidx)
 4593         struct sadb_spirange *spirange;
 4594         struct secasindex *saidx;
 4595 {
 4596         u_int32_t newspi;
 4597         u_int32_t min, max;
 4598         int count = key_spi_trycnt;
 4599 
 4600         /* set spi range to allocate */
 4601         if (spirange != NULL) {
 4602                 min = spirange->sadb_spirange_min;
 4603                 max = spirange->sadb_spirange_max;
 4604         } else {
 4605                 min = key_spi_minval;
 4606                 max = key_spi_maxval;
 4607         }
 4608         /* IPCOMP needs 2-byte SPI */
 4609         if (saidx->proto == IPPROTO_IPCOMP) {
 4610                 u_int32_t t;
 4611                 if (min >= 0x10000)
 4612                         min = 0xffff;
 4613                 if (max >= 0x10000)
 4614                         max = 0xffff;
 4615                 if (min > max) {
 4616                         t = min; min = max; max = t;
 4617                 }
 4618         }
 4619 
 4620         if (min == max) {
 4621                 if (key_checkspidup(saidx, min) != NULL) {
 4622                         ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", min));
 4623                         return 0;
 4624                 }
 4625 
 4626                 count--; /* taking one cost. */
 4627                 newspi = min;
 4628 
 4629         } else {
 4630 
 4631                 /* init SPI */
 4632                 newspi = 0;
 4633 
 4634                 /* when requesting to allocate spi ranged */
 4635                 while (count--) {
 4636                         /* generate pseudo-random SPI value ranged. */
 4637                         newspi = min + (key_random() % (max - min + 1));
 4638 
 4639                         if (key_checkspidup(saidx, newspi) == NULL)
 4640                                 break;
 4641                 }
 4642 
 4643                 if (count == 0 || newspi == 0) {
 4644                         ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
 4645                         return 0;
 4646                 }
 4647         }
 4648 
 4649         /* statistics */
 4650         keystat.getspi_count =
 4651                 (keystat.getspi_count + key_spi_trycnt - count) / 2;
 4652 
 4653         return newspi;
 4654 }
 4655 
 4656 /*
 4657  * SADB_UPDATE processing
 4658  * receive
 4659  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
 4660  *       key(AE), (identity(SD),) (sensitivity)>
 4661  * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
 4662  * and send
 4663  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
 4664  *       (identity(SD),) (sensitivity)>
 4665  * to the ikmpd.
 4666  *
 4667  * m will always be freed.
 4668  */
 4669 static int
 4670 key_update(so, m, mhp)
 4671         struct socket *so;
 4672         struct mbuf *m;
 4673         const struct sadb_msghdr *mhp;
 4674 {
 4675         struct sadb_sa *sa0;
 4676         struct sadb_address *src0, *dst0;
 4677         struct secasindex saidx;
 4678         struct secashead *sah;
 4679         struct secasvar *sav;
 4680         u_int16_t proto;
 4681         u_int8_t mode;
 4682         u_int32_t reqid;
 4683         int error;
 4684 
 4685         /* sanity check */
 4686         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 4687                 panic("key_update: NULL pointer is passed.\n");
 4688 
 4689         /* map satype to proto */
 4690         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 4691                 ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
 4692                 return key_senderror(so, m, EINVAL);
 4693         }
 4694 
 4695         if (mhp->ext[SADB_EXT_SA] == NULL ||
 4696             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 4697             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
 4698             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
 4699              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
 4700             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
 4701              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
 4702             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
 4703              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
 4704             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
 4705              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
 4706                 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
 4707                 return key_senderror(so, m, EINVAL);
 4708         }
 4709         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
 4710             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 4711             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 4712                 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
 4713                 return key_senderror(so, m, EINVAL);
 4714         }
 4715         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
 4716                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
 4717                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
 4718         } else {
 4719                 mode = IPSEC_MODE_ANY;
 4720                 reqid = 0;
 4721         }
 4722         /* XXX boundary checking for other extensions */
 4723 
 4724         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 4725         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
 4726         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
 4727 
 4728         /* XXX boundary check against sa_len */
 4729         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
 4730 
 4731         /* get a SA header */
 4732         if ((sah = key_getsah(&saidx)) == NULL) {
 4733                 ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
 4734                 return key_senderror(so, m, ENOENT);
 4735         }
 4736 
 4737         /* set spidx if there */
 4738         /* XXX rewrite */
 4739         error = key_setident(sah, m, mhp);
 4740         if (error)
 4741                 return key_senderror(so, m, error);
 4742 
 4743         /* find a SA with sequence number. */
 4744 #ifdef IPSEC_DOSEQCHECK
 4745         if (mhp->msg->sadb_msg_seq != 0
 4746          && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
 4747                 ipseclog((LOG_DEBUG,
 4748                     "key_update: no larval SA with sequence %u exists.\n",
 4749                     mhp->msg->sadb_msg_seq));
 4750                 return key_senderror(so, m, ENOENT);
 4751         }
 4752 #else
 4753         if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
 4754                 ipseclog((LOG_DEBUG,
 4755                     "key_update: no such a SA found (spi:%u)\n",
 4756                     (u_int32_t)ntohl(sa0->sadb_sa_spi)));
 4757                 return key_senderror(so, m, EINVAL);
 4758         }
 4759 #endif
 4760 
 4761         /* validity check */
 4762         if (sav->sah->saidx.proto != proto) {
 4763                 ipseclog((LOG_DEBUG,
 4764                     "key_update: protocol mismatched (DB=%u param=%u)\n",
 4765                     sav->sah->saidx.proto, proto));
 4766                 return key_senderror(so, m, EINVAL);
 4767         }
 4768 #ifdef IPSEC_DOSEQCHECK
 4769         if (sav->spi != sa0->sadb_sa_spi) {
 4770                 ipseclog((LOG_DEBUG,
 4771                     "key_update: SPI mismatched (DB:%u param:%u)\n",
 4772                     (u_int32_t)ntohl(sav->spi),
 4773                     (u_int32_t)ntohl(sa0->sadb_sa_spi)));
 4774                 return key_senderror(so, m, EINVAL);
 4775         }
 4776 #endif
 4777         if (sav->pid != mhp->msg->sadb_msg_pid) {
 4778                 ipseclog((LOG_DEBUG,
 4779                     "key_update: pid mismatched (DB:%u param:%u)\n",
 4780                     sav->pid, mhp->msg->sadb_msg_pid));
 4781                 return key_senderror(so, m, EINVAL);
 4782         }
 4783 
 4784         /* copy sav values */
 4785         error = key_setsaval(sav, m, mhp);
 4786         if (error) {
 4787                 KEY_FREESAV(&sav);
 4788                 return key_senderror(so, m, error);
 4789         }
 4790 
 4791         /* check SA values to be mature. */
 4792         if ((mhp->msg->sadb_msg_errno = key_mature(sav)) != 0) {
 4793                 KEY_FREESAV(&sav);
 4794                 return key_senderror(so, m, 0);
 4795         }
 4796 
 4797     {
 4798         struct mbuf *n;
 4799 
 4800         /* set msg buf from mhp */
 4801         n = key_getmsgbuf_x1(m, mhp);
 4802         if (n == NULL) {
 4803                 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
 4804                 return key_senderror(so, m, ENOBUFS);
 4805         }
 4806 
 4807         m_freem(m);
 4808         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 4809     }
 4810 }
 4811 
 4812 /*
 4813  * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
 4814  * only called by key_update().
 4815  * OUT:
 4816  *      NULL    : not found
 4817  *      others  : found, pointer to a SA.
 4818  */
 4819 #ifdef IPSEC_DOSEQCHECK
 4820 static struct secasvar *
 4821 key_getsavbyseq(sah, seq)
 4822         struct secashead *sah;
 4823         u_int32_t seq;
 4824 {
 4825         struct secasvar *sav;
 4826         u_int state;
 4827 
 4828         state = SADB_SASTATE_LARVAL;
 4829 
 4830         /* search SAD with sequence number ? */
 4831         LIST_FOREACH(sav, &sah->savtree[state], chain) {
 4832 
 4833                 KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");
 4834 
 4835                 if (sav->seq == seq) {
 4836                         SA_ADDREF(sav);
 4837                         KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
 4838                                 printf("DP key_getsavbyseq cause "
 4839                                         "refcnt++:%d SA:%p\n",
 4840                                         sav->refcnt, sav));
 4841                         return sav;
 4842                 }
 4843         }
 4844 
 4845         return NULL;
 4846 }
 4847 #endif
 4848 
 4849 /*
 4850  * SADB_ADD processing
 4851  * add an entry to SA database, when received
 4852  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
 4853  *       key(AE), (identity(SD),) (sensitivity)>
 4854  * from the ikmpd,
 4855  * and send
 4856  *   <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
 4857  *       (identity(SD),) (sensitivity)>
 4858  * to the ikmpd.
 4859  *
 4860  * IGNORE identity and sensitivity messages.
 4861  *
 4862  * m will always be freed.
 4863  */
 4864 static int
 4865 key_add(so, m, mhp)
 4866         struct socket *so;
 4867         struct mbuf *m;
 4868         const struct sadb_msghdr *mhp;
 4869 {
 4870         struct sadb_sa *sa0;
 4871         struct sadb_address *src0, *dst0;
 4872         struct secasindex saidx;
 4873         struct secashead *newsah;
 4874         struct secasvar *newsav;
 4875         u_int16_t proto;
 4876         u_int8_t mode;
 4877         u_int32_t reqid;
 4878         int error;
 4879 
 4880         /* sanity check */
 4881         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 4882                 panic("key_add: NULL pointer is passed.\n");
 4883 
 4884         /* map satype to proto */
 4885         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 4886                 ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
 4887                 return key_senderror(so, m, EINVAL);
 4888         }
 4889 
 4890         if (mhp->ext[SADB_EXT_SA] == NULL ||
 4891             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 4892             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
 4893             (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
 4894              mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
 4895             (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
 4896              mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
 4897             (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
 4898              mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
 4899             (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
 4900              mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
 4901                 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
 4902                 return key_senderror(so, m, EINVAL);
 4903         }
 4904         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
 4905             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 4906             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 4907                 /* XXX need more */
 4908                 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
 4909                 return key_senderror(so, m, EINVAL);
 4910         }
 4911         if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
 4912                 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
 4913                 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
 4914         } else {
 4915                 mode = IPSEC_MODE_ANY;
 4916                 reqid = 0;
 4917         }
 4918 
 4919         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 4920         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
 4921         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 4922 
 4923         /* XXX boundary check against sa_len */
 4924         KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
 4925 
 4926         /* get a SA header */
 4927         if ((newsah = key_getsah(&saidx)) == NULL) {
 4928                 /* create a new SA header */
 4929                 if ((newsah = key_newsah(&saidx)) == NULL) {
 4930                         ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
 4931                         return key_senderror(so, m, ENOBUFS);
 4932                 }
 4933         }
 4934 
 4935         /* set spidx if there */
 4936         /* XXX rewrite */
 4937         error = key_setident(newsah, m, mhp);
 4938         if (error) {
 4939                 return key_senderror(so, m, error);
 4940         }
 4941 
 4942         /* create new SA entry. */
 4943         /* We can create new SA only if SPI is differenct. */
 4944         if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
 4945                 ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
 4946                 return key_senderror(so, m, EEXIST);
 4947         }
 4948         newsav = KEY_NEWSAV(m, mhp, newsah, &error);
 4949         if (newsav == NULL) {
 4950                 return key_senderror(so, m, error);
 4951         }
 4952 
 4953         /* check SA values to be mature. */
 4954         if ((error = key_mature(newsav)) != 0) {
 4955                 KEY_FREESAV(&newsav);
 4956                 return key_senderror(so, m, error);
 4957         }
 4958 
 4959         /*
 4960          * don't call key_freesav() here, as we would like to keep the SA
 4961          * in the database on success.
 4962          */
 4963 
 4964     {
 4965         struct mbuf *n;
 4966 
 4967         /* set msg buf from mhp */
 4968         n = key_getmsgbuf_x1(m, mhp);
 4969         if (n == NULL) {
 4970                 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
 4971                 return key_senderror(so, m, ENOBUFS);
 4972         }
 4973 
 4974         m_freem(m);
 4975         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 4976     }
 4977 }
 4978 
 4979 /* m is retained */
 4980 static int
 4981 key_setident(sah, m, mhp)
 4982         struct secashead *sah;
 4983         struct mbuf *m;
 4984         const struct sadb_msghdr *mhp;
 4985 {
 4986         const struct sadb_ident *idsrc, *iddst;
 4987         int idsrclen, iddstlen;
 4988 
 4989         /* sanity check */
 4990         if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 4991                 panic("key_setident: NULL pointer is passed.\n");
 4992 
 4993         /* don't make buffer if not there */
 4994         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
 4995             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
 4996                 sah->idents = NULL;
 4997                 sah->identd = NULL;
 4998                 return 0;
 4999         }
 5000         
 5001         if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
 5002             mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
 5003                 ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
 5004                 return EINVAL;
 5005         }
 5006 
 5007         idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
 5008         iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
 5009         idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
 5010         iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
 5011 
 5012         /* validity check */
 5013         if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
 5014                 ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
 5015                 return EINVAL;
 5016         }
 5017 
 5018         switch (idsrc->sadb_ident_type) {
 5019         case SADB_IDENTTYPE_PREFIX:
 5020         case SADB_IDENTTYPE_FQDN:
 5021         case SADB_IDENTTYPE_USERFQDN:
 5022         default:
 5023                 /* XXX do nothing */
 5024                 sah->idents = NULL;
 5025                 sah->identd = NULL;
 5026                 return 0;
 5027         }
 5028 
 5029         /* make structure */
 5030         KMALLOC(sah->idents, struct sadb_ident *, idsrclen);
 5031         if (sah->idents == NULL) {
 5032                 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
 5033                 return ENOBUFS;
 5034         }
 5035         KMALLOC(sah->identd, struct sadb_ident *, iddstlen);
 5036         if (sah->identd == NULL) {
 5037                 KFREE(sah->idents);
 5038                 sah->idents = NULL;
 5039                 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
 5040                 return ENOBUFS;
 5041         }
 5042         bcopy(idsrc, sah->idents, idsrclen);
 5043         bcopy(iddst, sah->identd, iddstlen);
 5044 
 5045         return 0;
 5046 }
 5047 
 5048 /*
 5049  * m will not be freed on return.
 5050  * it is caller's responsibility to free the result. 
 5051  */
 5052 static struct mbuf *
 5053 key_getmsgbuf_x1(m, mhp)
 5054         struct mbuf *m;
 5055         const struct sadb_msghdr *mhp;
 5056 {
 5057         struct mbuf *n;
 5058 
 5059         /* sanity check */
 5060         if (m == NULL || mhp == NULL || mhp->msg == NULL)
 5061                 panic("key_getmsgbuf_x1: NULL pointer is passed.\n");
 5062 
 5063         /* create new sadb_msg to reply. */
 5064         n = key_gather_mbuf(m, mhp, 1, 9, SADB_EXT_RESERVED,
 5065             SADB_EXT_SA, SADB_X_EXT_SA2,
 5066             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST,
 5067             SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
 5068             SADB_EXT_IDENTITY_SRC, SADB_EXT_IDENTITY_DST);
 5069         if (!n)
 5070                 return NULL;
 5071 
 5072         if (n->m_len < sizeof(struct sadb_msg)) {
 5073                 n = m_pullup(n, sizeof(struct sadb_msg));
 5074                 if (n == NULL)
 5075                         return NULL;
 5076         }
 5077         mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
 5078         mtod(n, struct sadb_msg *)->sadb_msg_len =
 5079             PFKEY_UNIT64(n->m_pkthdr.len);
 5080 
 5081         return n;
 5082 }
 5083 
 5084 static int key_delete_all __P((struct socket *, struct mbuf *,
 5085         const struct sadb_msghdr *, u_int16_t));
 5086 
 5087 /*
 5088  * SADB_DELETE processing
 5089  * receive
 5090  *   <base, SA(*), address(SD)>
 5091  * from the ikmpd, and set SADB_SASTATE_DEAD,
 5092  * and send,
 5093  *   <base, SA(*), address(SD)>
 5094  * to the ikmpd.
 5095  *
 5096  * m will always be freed.
 5097  */
 5098 static int
 5099 key_delete(so, m, mhp)
 5100         struct socket *so;
 5101         struct mbuf *m;
 5102         const struct sadb_msghdr *mhp;
 5103 {
 5104         struct sadb_sa *sa0;
 5105         struct sadb_address *src0, *dst0;
 5106         struct secasindex saidx;
 5107         struct secashead *sah;
 5108         struct secasvar *sav = NULL;
 5109         u_int16_t proto;
 5110 
 5111         /* sanity check */
 5112         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 5113                 panic("key_delete: NULL pointer is passed.\n");
 5114 
 5115         /* map satype to proto */
 5116         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 5117                 ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
 5118                 return key_senderror(so, m, EINVAL);
 5119         }
 5120 
 5121         if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 5122             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
 5123                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
 5124                 return key_senderror(so, m, EINVAL);
 5125         }
 5126 
 5127         if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 5128             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 5129                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
 5130                 return key_senderror(so, m, EINVAL);
 5131         }
 5132 
 5133         if (mhp->ext[SADB_EXT_SA] == NULL) {
 5134                 /*
 5135                  * Caller wants us to delete all non-LARVAL SAs
 5136                  * that match the src/dst.  This is used during
 5137                  * IKE INITIAL-CONTACT.
 5138                  */
 5139                 ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
 5140                 return key_delete_all(so, m, mhp, proto);
 5141         } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
 5142                 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
 5143                 return key_senderror(so, m, EINVAL);
 5144         }
 5145 
 5146         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 5147         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
 5148         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
 5149 
 5150         /* XXX boundary check against sa_len */
 5151         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
 5152 
 5153         /* get a SA header */
 5154         LIST_FOREACH(sah, &sahtree, chain) {
 5155                 if (sah->state == SADB_SASTATE_DEAD)
 5156                         continue;
 5157                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
 5158                         continue;
 5159 
 5160                 /* get a SA with SPI. */
 5161                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
 5162                 if (sav)
 5163                         break;
 5164         }
 5165         if (sah == NULL) {
 5166                 ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
 5167                 return key_senderror(so, m, ENOENT);
 5168         }
 5169 
 5170         key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 5171         KEY_FREESAV(&sav);
 5172 
 5173     {
 5174         struct mbuf *n;
 5175         struct sadb_msg *newmsg;
 5176 
 5177         /* create new sadb_msg to reply. */
 5178         n = key_gather_mbuf(m, mhp, 1, 4, SADB_EXT_RESERVED,
 5179             SADB_EXT_SA, SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 5180         if (!n)
 5181                 return key_senderror(so, m, ENOBUFS);
 5182 
 5183         if (n->m_len < sizeof(struct sadb_msg)) {
 5184                 n = m_pullup(n, sizeof(struct sadb_msg));
 5185                 if (n == NULL)
 5186                         return key_senderror(so, m, ENOBUFS);
 5187         }
 5188         newmsg = mtod(n, struct sadb_msg *);
 5189         newmsg->sadb_msg_errno = 0;
 5190         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 5191 
 5192         m_freem(m);
 5193         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 5194     }
 5195 }
 5196 
 5197 /*
 5198  * delete all SAs for src/dst.  Called from key_delete().
 5199  */
 5200 static int
 5201 key_delete_all(so, m, mhp, proto)
 5202         struct socket *so;
 5203         struct mbuf *m;
 5204         const struct sadb_msghdr *mhp;
 5205         u_int16_t proto;
 5206 {
 5207         struct sadb_address *src0, *dst0;
 5208         struct secasindex saidx;
 5209         struct secashead *sah;
 5210         struct secasvar *sav, *nextsav;
 5211         u_int stateidx, state;
 5212 
 5213         src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
 5214         dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
 5215 
 5216         /* XXX boundary check against sa_len */
 5217         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
 5218 
 5219         LIST_FOREACH(sah, &sahtree, chain) {
 5220                 if (sah->state == SADB_SASTATE_DEAD)
 5221                         continue;
 5222                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
 5223                         continue;
 5224 
 5225                 /* Delete all non-LARVAL SAs. */
 5226                 for (stateidx = 0;
 5227                      stateidx < _ARRAYLEN(saorder_state_alive);
 5228                      stateidx++) {
 5229                         state = saorder_state_alive[stateidx];
 5230                         if (state == SADB_SASTATE_LARVAL)
 5231                                 continue;
 5232                         for (sav = LIST_FIRST(&sah->savtree[state]);
 5233                              sav != NULL; sav = nextsav) {
 5234                                 nextsav = LIST_NEXT(sav, chain);
 5235                                 /* sanity check */
 5236                                 if (sav->state != state) {
 5237                                         ipseclog((LOG_DEBUG, "key_delete_all: "
 5238                                                "invalid sav->state "
 5239                                                "(queue: %d SA: %d)\n",
 5240                                                state, sav->state));
 5241                                         continue;
 5242                                 }
 5243                                 
 5244                                 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
 5245                                 KEY_FREESAV(&sav);
 5246                         }
 5247                 }
 5248         }
 5249     {
 5250         struct mbuf *n;
 5251         struct sadb_msg *newmsg;
 5252 
 5253         /* create new sadb_msg to reply. */
 5254         n = key_gather_mbuf(m, mhp, 1, 3, SADB_EXT_RESERVED,
 5255             SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST);
 5256         if (!n)
 5257                 return key_senderror(so, m, ENOBUFS);
 5258 
 5259         if (n->m_len < sizeof(struct sadb_msg)) {
 5260                 n = m_pullup(n, sizeof(struct sadb_msg));
 5261                 if (n == NULL)
 5262                         return key_senderror(so, m, ENOBUFS);
 5263         }
 5264         newmsg = mtod(n, struct sadb_msg *);
 5265         newmsg->sadb_msg_errno = 0;
 5266         newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
 5267 
 5268         m_freem(m);
 5269         return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
 5270     }
 5271 }
 5272 
 5273 /*
 5274  * SADB_GET processing
 5275  * receive
 5276  *   <base, SA(*), address(SD)>
 5277  * from the ikmpd, and get a SP and a SA to respond,
 5278  * and send,
 5279  *   <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
 5280  *       (identity(SD),) (sensitivity)>
 5281  * to the ikmpd.
 5282  *
 5283  * m will always be freed.
 5284  */
 5285 static int
 5286 key_get(so, m, mhp)
 5287         struct socket *so;
 5288         struct mbuf *m;
 5289         const struct sadb_msghdr *mhp;
 5290 {
 5291         struct sadb_sa *sa0;
 5292         struct sadb_address *src0, *dst0;
 5293         struct secasindex saidx;
 5294         struct secashead *sah;
 5295         struct secasvar *sav = NULL;
 5296         u_int16_t proto;
 5297 
 5298         /* sanity check */
 5299         if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
 5300                 panic("key_get: NULL pointer is passed.\n");
 5301 
 5302         /* map satype to proto */
 5303         if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
 5304                 ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
 5305                 return key_senderror(so, m, EINVAL);
 5306         }
 5307 
 5308         if (mhp->ext[SADB_EXT_SA] == NULL ||
 5309             mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
 5310             mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
 5311                 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
 5312                 return key_senderror(so, m, EINVAL);
 5313         }
 5314         if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
 5315             mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
 5316             mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
 5317                 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
 5318                 return key_senderror(so, m, EINVAL);
 5319         }
 5320 
 5321         sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
 5322         src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
 5323         dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
 5324 
 5325         /* XXX boundary check against sa_len */
 5326         KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
 5327 
 5328         /* get a SA header */
 5329         LIST_FOREACH(sah, &sahtree, chain) {
 5330                 if (sah->state == SADB_SASTATE_DEAD)
 5331                         continue;
 5332                 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
 5333                         continue;
 5334 
 5335                 /* get a SA with SPI. */
 5336                 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
 5337                 if (sav)
 5338                         break;
 5339         }
 5340         if (sah == NULL) {
 5341                 ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
 5342                 return key_senderror(so, m, ENOENT);
 5343         }
 5344 
 5345     {
 5346         struct mbuf *n;
 5347         u_int8_t satype;
 5348 
 5349         /* map proto to satype */
 5350         if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
 5351                 ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
 5352                 return key_senderror(so, m, EINVAL);
 5353         }
 5354 
 5355         /* create new sadb_msg to reply. */
 5356         n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
 5357             mhp->msg->sadb_msg_pid);
 5358         if (!n)
 5359                 return key_senderror(so, m, ENOBUFS);
 5360 
 5361         m_freem(m);
 5362         return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
 5363     }
 5364 }
 5365 
 5366 /* XXX make it sysctl-configurable? */
 5367 static void
 5368 key_getcomb_setlifetime(comb)
 5369         struct sadb_comb *comb;
 5370 {
 5371 
 5372         comb->sadb_comb_soft_allocations = 1;
 5373         comb->sadb_comb_hard_allocations = 1;
 5374         comb->sadb_comb_soft_bytes = 0;
 5375         comb->sadb_comb_hard_bytes = 0;
 5376         comb->sadb_comb_hard_addtime = 86400;   /* 1 day */
 5377         comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
 5378         comb->sadb_comb_soft_usetime = 28800;   /* 8 hours */
 5379         comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
 5380 }
 5381 
 5382 /*
 5383  * XXX reorder combinations by preference
 5384  * XXX no idea if the user wants ESP authentication or not
 5385  */
 5386 static struct mbuf *
 5387 key_getcomb_esp()
 5388 {
 5389         struct sadb_comb *comb;
 5390         struct enc_xform *algo;
 5391         struct mbuf *result = NULL, *m, *n;
 5392         int encmin;
 5393         int i, off, o;
 5394         int totlen;
 5395         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
 5396 
 5397         m = NULL;
 5398         for (i = 1; i <= SADB_EALG_MAX; i++) {
 5399                 algo = esp_algorithm_lookup(i);
 5400                 if (algo == NULL)
 5401                         continue;
 5402 
 5403                 /* discard algorithms with key size smaller than system min */
 5404                 if (_BITS(algo->maxkey) < ipsec_esp_keymin)
 5405                         continue;
 5406                 if (_BITS(algo->minkey) < ipsec_esp_keymin)
 5407                         encmin = ipsec_esp_keymin;
 5408                 else
 5409                         encmin = _BITS(algo->minkey);
 5410 
 5411                 if (ipsec_esp_auth)
 5412                         m = key_getcomb_ah();
 5413                 else {
 5414                         KASSERT(l <= MLEN,
 5415                                 ("key_getcomb_esp: l=%u > MLEN=%lu",
 5416                                 l, (u_long) MLEN));
 5417                         MGET(m, M_DONTWAIT, MT_DATA);
 5418                         if (m) {
 5419                                 M_ALIGN(m, l);
 5420                                 m->m_len = l;
 5421                                 m->m_next = NULL;
 5422                                 bzero(mtod(m, caddr_t), m->m_len);
 5423                         }
 5424                 }
 5425                 if (!m)
 5426                         goto fail;
 5427 
 5428                 totlen = 0;
 5429                 for (n = m; n; n = n->m_next)
 5430                         totlen += n->m_len;
 5431                 KASSERT((totlen % l) == 0,
 5432                         ("key_getcomb_esp: totlen=%u, l=%u", totlen, l));
 5433 
 5434                 for (off = 0; off < totlen; off += l) {
 5435                         n = m_pulldown(m, off, l, &o);
 5436                         if (!n) {
 5437                                 /* m is already freed */
 5438                                 goto fail;
 5439                         }
 5440                         comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
 5441                         bzero(comb, sizeof(*comb));
 5442                         key_getcomb_setlifetime(comb);
 5443                         comb->sadb_comb_encrypt = i;
 5444                         comb->sadb_comb_encrypt_minbits = encmin;
 5445                         comb->sadb_comb_encrypt_maxbits = _BITS(algo->maxkey);
 5446                 }
 5447 
 5448                 if (!result)
 5449                         result = m;
 5450                 else
 5451                         m_cat(result, m);
 5452         }
 5453 
 5454         return result;
 5455 
 5456  fail:
 5457         if (result)
 5458                 m_freem(result);
 5459         return NULL;
 5460 }
 5461 
 5462 static void
 5463 key_getsizes_ah(
 5464         const struct auth_hash *ah,
 5465         int alg,
 5466         u_int16_t* min,
 5467         u_int16_t* max)
 5468 {
 5469         *min = *max = ah->keysize;
 5470         if (ah->keysize == 0) {
 5471                 /*
 5472                  * Transform takes arbitrary key size but algorithm
 5473                  * key size is restricted.  Enforce this here.
 5474                  */
 5475                 switch (alg) {
 5476                 case SADB_X_AALG_MD5:   *min = *max = 16; break;
 5477                 case SADB_X_AALG_SHA:   *min = *max = 20; break;
 5478                 case SADB_X_AALG_NULL:  *min = 1; *max = 256; break;
 5479                 default:
 5480                         DPRINTF(("key_getsizes_ah: unknown AH algorithm %u\n",
 5481                                 alg));
 5482                         break;
 5483                 }
 5484         }
 5485 }
 5486 
 5487 /*
 5488  * XXX reorder combinations by preference
 5489  */
 5490 static struct mbuf *
 5491 key_getcomb_ah()
 5492 {
 5493         struct sadb_comb *comb;
 5494         struct auth_hash *algo;
 5495         struct mbuf *m;
 5496         u_int16_t minkeysize, maxkeysize;
 5497         int i;
 5498         const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
 5499 
 5500         m = NULL;
 5501         for (i = 1; i <= SADB_AALG_MAX; i++) {
 5502 #if 1
 5503                 /* we prefer HMAC algorithms, not old algorithms */
 5504                 if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
 5505                         continue;
 5506 #endif
 5507                 algo = ah_algorithm_lookup(i);
 5508                 if (!algo)
 5509                         continue;
 5510                 key_getsizes_ah(algo, i, &minkeysize, &maxkeysize);
 5511                 /* discard algorithms with key size smaller than system min */
 5512                 if (_BITS(minkeysize) < ipsec_ah_keymin)
 5513                         continue;
 5514 
 5515                 if (!m) {
 5516                         KASSERT(l <= MLEN,
 5517                                 ("key_getcomb_ah: l=%u > MLEN=%lu",
 5518                                 l, (u_long) MLEN));
 5519                         MGET(m, M_DONTWAIT, MT_DATA);
 5520                         if (m) {
 5521                                 M_ALIGN(m, l);
 5522                                 m->m_len = l;
 5523                                 m->m_next = NULL;
 5524                         }
 5525                 } else
 5526                         M_PREPEND(m, l, M_DONTWAIT);
 5527                 if (!m)
 5528                         return NULL;
 5529 
 5530                 comb = mtod(m, struct sadb_comb *);
 5531                 bzero(comb, sizeof(